1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "remoting/host/input_injector.h"
8 #include <ApplicationServices/ApplicationServices.h>
9 #include <Carbon/Carbon.h>
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/compiler_specific.h"
14 #include "base/location.h"
15 #include "base/mac/scoped_cftyperef.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/single_thread_task_runner.h"
18 #include "remoting/host/clipboard.h"
19 #include "remoting/proto/internal.pb.h"
20 #include "remoting/protocol/message_decoder.h"
21 #include "skia/ext/skia_utils_mac.h"
22 #include "third_party/skia/include/core/SkPoint.h"
23 #include "third_party/skia/include/core/SkRect.h"
24 #include "third_party/webrtc/modules/desktop_capture/mac/desktop_configuration.h"
25 #include "ui/base/keycodes/keycode_converter.h"
31 using protocol::ClipboardEvent;
32 using protocol::KeyEvent;
33 using protocol::MouseEvent;
35 // skia/ext/skia_utils_mac.h only defines CGRectToSkRect().
36 SkIRect CGRectToSkIRect(const CGRect& rect) {
38 gfx::CGRectToSkRect(rect).round(&result);
42 // A class to generate events on Mac.
43 class InputInjectorMac : public InputInjector {
45 explicit InputInjectorMac(
46 scoped_refptr<base::SingleThreadTaskRunner> task_runner);
47 virtual ~InputInjectorMac();
49 // ClipboardStub interface.
50 virtual void InjectClipboardEvent(const ClipboardEvent& event) OVERRIDE;
52 // InputStub interface.
53 virtual void InjectKeyEvent(const KeyEvent& event) OVERRIDE;
54 virtual void InjectMouseEvent(const MouseEvent& event) OVERRIDE;
56 // InputInjector interface.
58 scoped_ptr<protocol::ClipboardStub> client_clipboard) OVERRIDE;
61 // The actual implementation resides in InputInjectorMac::Core class.
62 class Core : public base::RefCountedThreadSafe<Core> {
64 explicit Core(scoped_refptr<base::SingleThreadTaskRunner> task_runner);
66 // Mirrors the ClipboardStub interface.
67 void InjectClipboardEvent(const ClipboardEvent& event);
69 // Mirrors the InputStub interface.
70 void InjectKeyEvent(const KeyEvent& event);
71 void InjectMouseEvent(const MouseEvent& event);
73 // Mirrors the InputInjector interface.
74 void Start(scoped_ptr<protocol::ClipboardStub> client_clipboard);
79 friend class base::RefCountedThreadSafe<Core>;
82 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
84 uint32 mouse_button_state_;
85 scoped_ptr<Clipboard> clipboard_;
87 DISALLOW_COPY_AND_ASSIGN(Core);
90 scoped_refptr<Core> core_;
92 DISALLOW_COPY_AND_ASSIGN(InputInjectorMac);
95 InputInjectorMac::InputInjectorMac(
96 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
97 core_ = new Core(task_runner);
100 InputInjectorMac::~InputInjectorMac() {
104 void InputInjectorMac::InjectClipboardEvent(const ClipboardEvent& event) {
105 core_->InjectClipboardEvent(event);
108 void InputInjectorMac::InjectKeyEvent(const KeyEvent& event) {
109 core_->InjectKeyEvent(event);
112 void InputInjectorMac::InjectMouseEvent(const MouseEvent& event) {
113 core_->InjectMouseEvent(event);
116 void InputInjectorMac::Start(
117 scoped_ptr<protocol::ClipboardStub> client_clipboard) {
118 core_->Start(client_clipboard.Pass());
121 InputInjectorMac::Core::Core(
122 scoped_refptr<base::SingleThreadTaskRunner> task_runner)
123 : task_runner_(task_runner),
124 mouse_button_state_(0),
125 clipboard_(Clipboard::Create()) {
126 // Ensure that local hardware events are not suppressed after injecting
127 // input events. This allows LocalInputMonitor to detect if the local mouse
128 // is being moved whilst a remote user is connected.
129 // This API is deprecated, but it is needed when using the deprecated
131 // If the non-deprecated injection APIs were used instead, the equivalent of
132 // this line would not be needed, as OS X defaults to _not_ suppressing local
133 // inputs in that case.
134 #pragma clang diagnostic push
135 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
136 CGSetLocalEventsSuppressionInterval(0.0);
137 #pragma clang diagnostic pop
140 void InputInjectorMac::Core::InjectClipboardEvent(const ClipboardEvent& event) {
141 if (!task_runner_->BelongsToCurrentThread()) {
142 task_runner_->PostTask(
143 FROM_HERE, base::Bind(&Core::InjectClipboardEvent, this, event));
147 // |clipboard_| will ignore unknown MIME-types, and verify the data's format.
148 clipboard_->InjectClipboardEvent(event);
151 void InputInjectorMac::Core::InjectKeyEvent(const KeyEvent& event) {
152 // HostEventDispatcher should filter events missing the pressed field.
153 if (!event.has_pressed() || !event.has_usb_keycode())
156 ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
157 int keycode = key_converter->UsbKeycodeToNativeKeycode(event.usb_keycode());
159 VLOG(3) << "Converting USB keycode: " << std::hex << event.usb_keycode()
160 << " to keycode: " << keycode << std::dec;
162 // If we couldn't determine the Mac virtual key code then ignore the event.
163 if (keycode == key_converter->InvalidNativeKeycode())
166 base::ScopedCFTypeRef<CGEventRef> eventRef(
167 CGEventCreateKeyboardEvent(NULL, keycode, event.pressed()));
170 // We only need to manually set CapsLock: Mac ignores NumLock.
171 // Modifier keys work correctly already via press/release event injection.
172 if (event.lock_states() & protocol::KeyEvent::LOCK_STATES_CAPSLOCK)
173 CGEventSetFlags(eventRef, kCGEventFlagMaskAlphaShift);
175 // Post the event to the current session.
176 CGEventPost(kCGSessionEventTap, eventRef);
180 void InputInjectorMac::Core::InjectMouseEvent(const MouseEvent& event) {
181 if (event.has_x() && event.has_y()) {
182 // On multi-monitor systems (0,0) refers to the top-left of the "main"
183 // display, whereas our coordinate scheme places (0,0) at the top-left of
184 // the bounding rectangle around all the displays, so we need to translate
187 // Set the mouse position assuming single-monitor.
188 mouse_pos_ = SkIPoint::Make(event.x(), event.y());
190 // Fetch the desktop configuration.
191 // TODO(wez): Optimize this out, or at least only enumerate displays in
192 // response to display-changed events. VideoFrameCapturer's VideoFrames
193 // could be augmented to include native cursor coordinates for use by
194 // MouseClampingFilter, removing the need for translation here.
195 webrtc::MacDesktopConfiguration desktop_config =
196 webrtc::MacDesktopConfiguration::GetCurrent(
197 webrtc::MacDesktopConfiguration::TopLeftOrigin);
199 // Translate the mouse position into desktop coordinates.
200 mouse_pos_ += SkIPoint::Make(desktop_config.pixel_bounds.left(),
201 desktop_config.pixel_bounds.top());
203 // Constrain the mouse position to the desktop coordinates.
204 mouse_pos_ = SkIPoint::Make(
205 std::max(desktop_config.pixel_bounds.left(),
206 std::min(desktop_config.pixel_bounds.right(), mouse_pos_.x())),
207 std::max(desktop_config.pixel_bounds.top(),
208 std::min(desktop_config.pixel_bounds.bottom(), mouse_pos_.y())));
210 // Convert from pixel to Density Independent Pixel coordinates.
211 mouse_pos_ = SkIPoint::Make(
212 SkScalarRound(mouse_pos_.x() / desktop_config.dip_to_pixel_scale),
213 SkScalarRound(mouse_pos_.y() / desktop_config.dip_to_pixel_scale));
215 VLOG(3) << "Moving mouse to " << mouse_pos_.x() << "," << mouse_pos_.y();
217 if (event.has_button() && event.has_button_down()) {
218 if (event.button() >= 1 && event.button() <= 3) {
219 VLOG(2) << "Button " << event.button()
220 << (event.button_down() ? " down" : " up");
221 int button_change = 1 << (event.button() - 1);
222 if (event.button_down())
223 mouse_button_state_ |= button_change;
225 mouse_button_state_ &= ~button_change;
227 VLOG(1) << "Unknown mouse button: " << event.button();
230 // We use the deprecated CGPostMouseEvent API because we receive low-level
231 // mouse events, whereas CGEventCreateMouseEvent is for injecting higher-level
232 // events. For example, the deprecated APIs will detect double-clicks or drags
233 // in a way that is consistent with how they would be generated using a local
234 // mouse, whereas the new APIs expect us to inject these higher-level events
236 CGPoint position = CGPointMake(mouse_pos_.x(), mouse_pos_.y());
238 LeftBit = 1 << (MouseEvent::BUTTON_LEFT - 1),
239 MiddleBit = 1 << (MouseEvent::BUTTON_MIDDLE - 1),
240 RightBit = 1 << (MouseEvent::BUTTON_RIGHT - 1)
242 #pragma clang diagnostic push
243 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
244 CGError error = CGPostMouseEvent(position, true, 3,
245 (mouse_button_state_ & LeftBit) != 0,
246 (mouse_button_state_ & RightBit) != 0,
247 (mouse_button_state_ & MiddleBit) != 0);
248 #pragma clang diagnostic pop
249 if (error != kCGErrorSuccess)
250 LOG(WARNING) << "CGPostMouseEvent error " << error;
252 if (event.has_wheel_delta_x() && event.has_wheel_delta_y()) {
253 int delta_x = static_cast<int>(event.wheel_delta_x());
254 int delta_y = static_cast<int>(event.wheel_delta_y());
255 base::ScopedCFTypeRef<CGEventRef> event(CGEventCreateScrollWheelEvent(
256 NULL, kCGScrollEventUnitPixel, 2, delta_y, delta_x));
258 CGEventPost(kCGSessionEventTap, event);
262 void InputInjectorMac::Core::Start(
263 scoped_ptr<protocol::ClipboardStub> client_clipboard) {
264 if (!task_runner_->BelongsToCurrentThread()) {
265 task_runner_->PostTask(
267 base::Bind(&Core::Start, this, base::Passed(&client_clipboard)));
271 clipboard_->Start(client_clipboard.Pass());
274 void InputInjectorMac::Core::Stop() {
275 if (!task_runner_->BelongsToCurrentThread()) {
276 task_runner_->PostTask(FROM_HERE, base::Bind(&Core::Stop, this));
283 InputInjectorMac::Core::~Core() {
288 scoped_ptr<InputInjector> InputInjector::Create(
289 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
290 scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) {
291 return scoped_ptr<InputInjector>(new InputInjectorMac(main_task_runner));
294 } // namespace remoting