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"
7 #include <X11/extensions/XInput.h>
8 #include <X11/extensions/XTest.h>
10 #include <X11/XKBlib.h>
14 #include "base/basictypes.h"
15 #include "base/bind.h"
16 #include "base/compiler_specific.h"
17 #include "base/location.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/strings/utf_string_conversion_utils.h"
20 #include "remoting/base/logging.h"
21 #if defined(OS_CHROMEOS)
22 #include "remoting/host/chromeos/point_transformer.h"
24 #include "remoting/host/clipboard.h"
25 #include "remoting/host/linux/unicode_to_keysym.h"
26 #include "remoting/proto/internal.pb.h"
27 #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
28 #include "ui/events/keycodes/dom4/keycode_converter.h"
34 using protocol::ClipboardEvent
;
35 using protocol::KeyEvent
;
36 using protocol::TextEvent
;
37 using protocol::MouseEvent
;
38 using protocol::TouchEvent
;
40 bool FindKeycodeForKeySym(Display
* display
,
43 uint32_t* modifiers
) {
44 *keycode
= XKeysymToKeycode(display
, key_sym
);
46 const uint32_t kModifiersToTry
[] = {
57 // TODO(sergeyu): Is there a better way to find modifiers state?
58 for (size_t i
= 0; i
< arraysize(kModifiersToTry
); ++i
) {
59 unsigned long key_sym_with_mods
;
60 if (XkbLookupKeySym(display
, *keycode
, kModifiersToTry
[i
], nullptr,
61 &key_sym_with_mods
) &&
62 key_sym_with_mods
== key_sym
) {
63 *modifiers
= kModifiersToTry
[i
];
71 // Finds a keycode and set of modifiers that generate character with the
72 // specified |code_point|.
73 bool FindKeycodeForUnicode(Display
* display
,
76 uint32_t* modifiers
) {
77 std::vector
<uint32_t> keysyms
;
78 GetKeySymsForUnicode(code_point
, &keysyms
);
80 for (std::vector
<uint32_t>::iterator it
= keysyms
.begin();
81 it
!= keysyms
.end(); ++it
) {
82 if (FindKeycodeForKeySym(display
, *it
, keycode
, modifiers
)) {
90 // Pixel-to-wheel-ticks conversion ratio used by GTK.
91 // From third_party/WebKit/Source/web/gtk/WebInputEventFactory.cpp .
92 const float kWheelTicksPerPixel
= 3.0f
/ 160.0f
;
94 // A class to generate events on X11.
95 class InputInjectorX11
: public InputInjector
{
97 explicit InputInjectorX11(
98 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
);
99 ~InputInjectorX11() override
;
103 // Clipboard stub interface.
104 void InjectClipboardEvent(const ClipboardEvent
& event
) override
;
106 // InputStub interface.
107 void InjectKeyEvent(const KeyEvent
& event
) override
;
108 void InjectTextEvent(const TextEvent
& event
) override
;
109 void InjectMouseEvent(const MouseEvent
& event
) override
;
110 void InjectTouchEvent(const TouchEvent
& event
) override
;
112 // InputInjector interface.
113 void Start(scoped_ptr
<protocol::ClipboardStub
> client_clipboard
) override
;
116 // The actual implementation resides in InputInjectorX11::Core class.
117 class Core
: public base::RefCountedThreadSafe
<Core
> {
119 explicit Core(scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
);
123 // Mirrors the ClipboardStub interface.
124 void InjectClipboardEvent(const ClipboardEvent
& event
);
126 // Mirrors the InputStub interface.
127 void InjectKeyEvent(const KeyEvent
& event
);
128 void InjectTextEvent(const TextEvent
& event
);
129 void InjectMouseEvent(const MouseEvent
& event
);
131 // Mirrors the InputInjector interface.
132 void Start(scoped_ptr
<protocol::ClipboardStub
> client_clipboard
);
137 friend class base::RefCountedThreadSafe
<Core
>;
140 void InitClipboard();
142 // Queries whether keyboard auto-repeat is globally enabled. This is used
143 // to decide whether to temporarily disable then restore this setting. If
144 // auto-repeat has already been disabled, this class should leave it
146 bool IsAutoRepeatEnabled();
148 // Enables or disables keyboard auto-repeat globally.
149 void SetAutoRepeatEnabled(bool enabled
);
151 void InjectScrollWheelClicks(int button
, int count
);
152 // Compensates for global button mappings and resets the XTest device
154 void InitMouseButtonMap();
155 int MouseButtonToX11ButtonNumber(MouseEvent::MouseButton button
);
156 int HorizontalScrollWheelToX11ButtonNumber(int dx
);
157 int VerticalScrollWheelToX11ButtonNumber(int dy
);
159 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
161 std::set
<int> pressed_keys_
;
162 webrtc::DesktopVector latest_mouse_position_
;
163 float wheel_ticks_x_
;
164 float wheel_ticks_y_
;
166 // X11 graphics context.
170 int test_event_base_
;
171 int test_error_base_
;
173 // Number of buttons we support.
174 // Left, Right, Middle, VScroll Up/Down, HScroll Left/Right.
175 static const int kNumPointerButtons
= 7;
177 int pointer_button_map_
[kNumPointerButtons
];
179 #if defined(OS_CHROMEOS)
180 PointTransformer point_transformer_
;
183 scoped_ptr
<Clipboard
> clipboard_
;
185 bool saved_auto_repeat_enabled_
;
187 DISALLOW_COPY_AND_ASSIGN(Core
);
190 scoped_refptr
<Core
> core_
;
192 DISALLOW_COPY_AND_ASSIGN(InputInjectorX11
);
195 InputInjectorX11::InputInjectorX11(
196 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
) {
197 core_
= new Core(task_runner
);
200 InputInjectorX11::~InputInjectorX11() {
204 bool InputInjectorX11::Init() {
205 return core_
->Init();
208 void InputInjectorX11::InjectClipboardEvent(const ClipboardEvent
& event
) {
209 core_
->InjectClipboardEvent(event
);
212 void InputInjectorX11::InjectKeyEvent(const KeyEvent
& event
) {
213 core_
->InjectKeyEvent(event
);
216 void InputInjectorX11::InjectTextEvent(const TextEvent
& event
) {
217 core_
->InjectTextEvent(event
);
220 void InputInjectorX11::InjectMouseEvent(const MouseEvent
& event
) {
221 core_
->InjectMouseEvent(event
);
224 void InputInjectorX11::InjectTouchEvent(const TouchEvent
& event
) {
225 NOTIMPLEMENTED() << "Raw touch event injection not implemented for X11.";
228 void InputInjectorX11::Start(
229 scoped_ptr
<protocol::ClipboardStub
> client_clipboard
) {
230 core_
->Start(client_clipboard
.Pass());
233 InputInjectorX11::Core::Core(
234 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
)
235 : task_runner_(task_runner
),
236 latest_mouse_position_(-1, -1),
237 wheel_ticks_x_(0.0f
),
238 wheel_ticks_y_(0.0f
),
239 display_(XOpenDisplay(nullptr)),
240 root_window_(BadValue
),
241 saved_auto_repeat_enabled_(false) {
244 bool InputInjectorX11::Core::Init() {
247 if (!task_runner_
->BelongsToCurrentThread())
248 task_runner_
->PostTask(FROM_HERE
, base::Bind(&Core::InitClipboard
, this));
250 root_window_
= RootWindow(display_
, DefaultScreen(display_
));
251 if (root_window_
== BadValue
) {
252 LOG(ERROR
) << "Unable to get the root window";
256 // TODO(ajwong): Do we want to check the major/minor version at all for XTest?
259 if (!XTestQueryExtension(display_
, &test_event_base_
, &test_error_base_
,
261 LOG(ERROR
) << "Server does not support XTest.";
264 InitMouseButtonMap();
268 void InputInjectorX11::Core::InjectClipboardEvent(
269 const ClipboardEvent
& event
) {
270 if (!task_runner_
->BelongsToCurrentThread()) {
271 task_runner_
->PostTask(
272 FROM_HERE
, base::Bind(&Core::InjectClipboardEvent
, this, event
));
276 // |clipboard_| will ignore unknown MIME-types, and verify the data's format.
277 clipboard_
->InjectClipboardEvent(event
);
280 void InputInjectorX11::Core::InjectKeyEvent(const KeyEvent
& event
) {
281 // HostEventDispatcher should filter events missing the pressed field.
282 if (!event
.has_pressed() || !event
.has_usb_keycode())
285 if (!task_runner_
->BelongsToCurrentThread()) {
286 task_runner_
->PostTask(FROM_HERE
,
287 base::Bind(&Core::InjectKeyEvent
, this, event
));
292 ui::KeycodeConverter::UsbKeycodeToNativeKeycode(event
.usb_keycode());
294 VLOG(3) << "Converting USB keycode: " << std::hex
<< event
.usb_keycode()
295 << " to keycode: " << keycode
<< std::dec
;
297 // Ignore events which can't be mapped.
298 if (keycode
== ui::KeycodeConverter::InvalidNativeKeycode())
301 if (event
.pressed()) {
302 if (pressed_keys_
.find(keycode
) != pressed_keys_
.end()) {
303 // Key is already held down, so lift the key up to ensure this repeated
304 // press takes effect.
305 XTestFakeKeyEvent(display_
, keycode
, False
, CurrentTime
);
308 if (pressed_keys_
.empty()) {
309 // Disable auto-repeat, if necessary, to avoid triggering auto-repeat
310 // if network congestion delays the key-up event from the client.
311 saved_auto_repeat_enabled_
= IsAutoRepeatEnabled();
312 if (saved_auto_repeat_enabled_
)
313 SetAutoRepeatEnabled(false);
315 pressed_keys_
.insert(keycode
);
317 pressed_keys_
.erase(keycode
);
318 if (pressed_keys_
.empty()) {
319 // Re-enable auto-repeat, if necessary, when all keys are released.
320 if (saved_auto_repeat_enabled_
)
321 SetAutoRepeatEnabled(true);
325 XTestFakeKeyEvent(display_
, keycode
, event
.pressed(), CurrentTime
);
329 void InputInjectorX11::Core::InjectTextEvent(const TextEvent
& event
) {
330 if (!task_runner_
->BelongsToCurrentThread()) {
331 task_runner_
->PostTask(FROM_HERE
,
332 base::Bind(&Core::InjectTextEvent
, this, event
));
336 // Release all keys before injecting text event. This is necessary to avoid
337 // any interference with the currently pressed keys. E.g. if Shift is pressed
338 // when TextEvent is received.
339 for (int key
: pressed_keys_
) {
340 XTestFakeKeyEvent(display_
, key
, False
, CurrentTime
);
342 pressed_keys_
.clear();
344 const std::string text
= event
.text();
345 for (int32 index
= 0; index
< static_cast<int32
>(text
.size()); ++index
) {
347 if (!base::ReadUnicodeCharacter(
348 text
.c_str(), text
.size(), &index
, &code_point
)) {
354 if (!FindKeycodeForUnicode(display_
, code_point
, &keycode
, &modifiers
))
357 XkbLockModifiers(display_
, XkbUseCoreKbd
, modifiers
, modifiers
);
359 XTestFakeKeyEvent(display_
, keycode
, True
, CurrentTime
);
360 XTestFakeKeyEvent(display_
, keycode
, False
, CurrentTime
);
362 XkbLockModifiers(display_
, XkbUseCoreKbd
, modifiers
, 0);
368 InputInjectorX11::Core::~Core() {
369 CHECK(pressed_keys_
.empty());
372 void InputInjectorX11::Core::InitClipboard() {
373 DCHECK(task_runner_
->BelongsToCurrentThread());
374 clipboard_
= Clipboard::Create();
377 bool InputInjectorX11::Core::IsAutoRepeatEnabled() {
378 XKeyboardState state
;
379 if (!XGetKeyboardControl(display_
, &state
)) {
380 LOG(ERROR
) << "Failed to get keyboard auto-repeat status, assuming ON.";
383 return state
.global_auto_repeat
== AutoRepeatModeOn
;
386 void InputInjectorX11::Core::SetAutoRepeatEnabled(bool mode
) {
387 XKeyboardControl control
;
388 control
.auto_repeat_mode
= mode
? AutoRepeatModeOn
: AutoRepeatModeOff
;
389 XChangeKeyboardControl(display_
, KBAutoRepeatMode
, &control
);
392 void InputInjectorX11::Core::InjectScrollWheelClicks(int button
, int count
) {
394 LOG(WARNING
) << "Ignoring unmapped scroll wheel button";
397 for (int i
= 0; i
< count
; i
++) {
398 // Generate a button-down and a button-up to simulate a wheel click.
399 XTestFakeButtonEvent(display_
, button
, true, CurrentTime
);
400 XTestFakeButtonEvent(display_
, button
, false, CurrentTime
);
404 void InputInjectorX11::Core::InjectMouseEvent(const MouseEvent
& event
) {
405 if (!task_runner_
->BelongsToCurrentThread()) {
406 task_runner_
->PostTask(FROM_HERE
,
407 base::Bind(&Core::InjectMouseEvent
, this, event
));
411 if (event
.has_delta_x() &&
412 event
.has_delta_y() &&
413 (event
.delta_x() != 0 || event
.delta_y() != 0)) {
414 latest_mouse_position_
.set(-1, -1);
415 VLOG(3) << "Moving mouse by " << event
.delta_x() << "," << event
.delta_y();
416 XTestFakeRelativeMotionEvent(display_
,
417 event
.delta_x(), event
.delta_y(),
420 } else if (event
.has_x() && event
.has_y()) {
421 // Injecting a motion event immediately before a button release results in
422 // a MotionNotify even if the mouse position hasn't changed, which confuses
423 // apps which assume MotionNotify implies movement. See crbug.com/138075.
424 bool inject_motion
= true;
425 webrtc::DesktopVector
new_mouse_position(event
.x(), event
.y());
426 #if defined(OS_CHROMEOS)
427 // Interim hack to handle display rotation on Chrome OS.
428 // TODO(kelvin): Remove this when Chrome OS has completely migrated to
429 // Ozone (crbug.com/439287).
430 gfx::PointF screen_location
= point_transformer_
.ToScreenCoordinates(
431 gfx::PointF(event
.x(), event
.y()));
432 new_mouse_position
.set(screen_location
.x(), screen_location
.y());
434 if (event
.has_button() && event
.has_button_down() && !event
.button_down()) {
435 if (new_mouse_position
.equals(latest_mouse_position_
))
436 inject_motion
= false;
440 latest_mouse_position_
.set(std::max(0, new_mouse_position
.x()),
441 std::max(0, new_mouse_position
.y()));
443 VLOG(3) << "Moving mouse to " << latest_mouse_position_
.x()
444 << "," << latest_mouse_position_
.y();
445 XTestFakeMotionEvent(display_
, DefaultScreen(display_
),
446 latest_mouse_position_
.x(),
447 latest_mouse_position_
.y(),
452 if (event
.has_button() && event
.has_button_down()) {
453 int button_number
= MouseButtonToX11ButtonNumber(event
.button());
455 if (button_number
< 0) {
456 LOG(WARNING
) << "Ignoring unknown button type: " << event
.button();
460 VLOG(3) << "Button " << event
.button()
461 << " received, sending "
462 << (event
.button_down() ? "down " : "up ")
464 XTestFakeButtonEvent(display_
, button_number
, event
.button_down(),
468 // Older client plugins always send scroll events in pixels, which
469 // must be accumulated host-side. Recent client plugins send both
470 // pixels and ticks with every scroll event, allowing the host to
471 // choose the best model on a per-platform basis. Since we can only
472 // inject ticks on Linux, use them if available.
474 if (event
.has_wheel_ticks_y()) {
475 ticks_y
= event
.wheel_ticks_y();
476 } else if (event
.has_wheel_delta_y()) {
477 wheel_ticks_y_
+= event
.wheel_delta_y() * kWheelTicksPerPixel
;
478 ticks_y
= static_cast<int>(wheel_ticks_y_
);
479 wheel_ticks_y_
-= ticks_y
;
482 InjectScrollWheelClicks(VerticalScrollWheelToX11ButtonNumber(ticks_y
),
487 if (event
.has_wheel_ticks_x()) {
488 ticks_x
= event
.wheel_ticks_x();
489 } else if (event
.has_wheel_delta_x()) {
490 wheel_ticks_x_
+= event
.wheel_delta_x() * kWheelTicksPerPixel
;
491 ticks_x
= static_cast<int>(wheel_ticks_x_
);
492 wheel_ticks_x_
-= ticks_x
;
495 InjectScrollWheelClicks(HorizontalScrollWheelToX11ButtonNumber(ticks_x
),
502 void InputInjectorX11::Core::InitMouseButtonMap() {
503 // TODO(rmsousa): Run this on global/device mapping change events.
505 // Do not touch global pointer mapping, since this may affect the local user.
506 // Instead, try to work around it by reversing the mapping.
507 // Note that if a user has a global mapping that completely disables a button
508 // (by assigning 0 to it), we won't be able to inject it.
509 int num_buttons
= XGetPointerMapping(display_
, nullptr, 0);
510 scoped_ptr
<unsigned char[]> pointer_mapping(new unsigned char[num_buttons
]);
511 num_buttons
= XGetPointerMapping(display_
, pointer_mapping
.get(),
513 for (int i
= 0; i
< kNumPointerButtons
; i
++) {
514 pointer_button_map_
[i
] = -1;
516 for (int i
= 0; i
< num_buttons
; i
++) {
517 // Reverse the mapping.
518 if (pointer_mapping
[i
] > 0 && pointer_mapping
[i
] <= kNumPointerButtons
)
519 pointer_button_map_
[pointer_mapping
[i
] - 1] = i
+ 1;
521 for (int i
= 0; i
< kNumPointerButtons
; i
++) {
522 if (pointer_button_map_
[i
] == -1)
523 LOG(ERROR
) << "Global pointer mapping does not support button " << i
+ 1;
526 int opcode
, event
, error
;
527 if (!XQueryExtension(display_
, "XInputExtension", &opcode
, &event
, &error
)) {
528 // If XInput is not available, we're done. But it would be very unusual to
529 // have a server that supports XTest but not XInput, so log it as an error.
530 LOG(ERROR
) << "X Input extension not available: " << error
;
534 // Make sure the XTEST XInput pointer device mapping is trivial. It should be
535 // safe to reset this mapping, as it won't affect the user's local devices.
536 // In fact, the reason why we do this is because an old gnome-settings-daemon
537 // may have mistakenly applied left-handed preferences to the XTEST device.
539 bool device_found
= false;
541 XDeviceInfo
* devices
;
542 devices
= XListInputDevices(display_
, &num_devices
);
543 for (int i
= 0; i
< num_devices
; i
++) {
544 XDeviceInfo
* device_info
= &devices
[i
];
545 if (device_info
->use
== IsXExtensionPointer
&&
546 strcmp(device_info
->name
, "Virtual core XTEST pointer") == 0) {
547 device_id
= device_info
->id
;
552 XFreeDeviceList(devices
);
555 HOST_LOG
<< "Cannot find XTest device.";
559 XDevice
* device
= XOpenDevice(display_
, device_id
);
561 LOG(ERROR
) << "Cannot open XTest device.";
565 int num_device_buttons
=
566 XGetDeviceButtonMapping(display_
, device
, nullptr, 0);
567 scoped_ptr
<unsigned char[]> button_mapping(new unsigned char[num_buttons
]);
568 for (int i
= 0; i
< num_device_buttons
; i
++) {
569 button_mapping
[i
] = i
+ 1;
571 error
= XSetDeviceButtonMapping(display_
, device
, button_mapping
.get(),
573 if (error
!= Success
)
574 LOG(ERROR
) << "Failed to set XTest device button mapping: " << error
;
576 XCloseDevice(display_
, device
);
579 int InputInjectorX11::Core::MouseButtonToX11ButtonNumber(
580 MouseEvent::MouseButton button
) {
582 case MouseEvent::BUTTON_LEFT
:
583 return pointer_button_map_
[0];
585 case MouseEvent::BUTTON_RIGHT
:
586 return pointer_button_map_
[2];
588 case MouseEvent::BUTTON_MIDDLE
:
589 return pointer_button_map_
[1];
591 case MouseEvent::BUTTON_UNDEFINED
:
597 int InputInjectorX11::Core::HorizontalScrollWheelToX11ButtonNumber(int dx
) {
598 return (dx
> 0 ? pointer_button_map_
[5] : pointer_button_map_
[6]);
601 int InputInjectorX11::Core::VerticalScrollWheelToX11ButtonNumber(int dy
) {
602 // Positive y-values are wheel scroll-up events (button 4), negative y-values
603 // are wheel scroll-down events (button 5).
604 return (dy
> 0 ? pointer_button_map_
[3] : pointer_button_map_
[4]);
607 void InputInjectorX11::Core::Start(
608 scoped_ptr
<protocol::ClipboardStub
> client_clipboard
) {
609 if (!task_runner_
->BelongsToCurrentThread()) {
610 task_runner_
->PostTask(
612 base::Bind(&Core::Start
, this, base::Passed(&client_clipboard
)));
616 InitMouseButtonMap();
618 clipboard_
->Start(client_clipboard
.Pass());
621 void InputInjectorX11::Core::Stop() {
622 if (!task_runner_
->BelongsToCurrentThread()) {
623 task_runner_
->PostTask(FROM_HERE
, base::Bind(&Core::Stop
, this));
632 scoped_ptr
<InputInjector
> InputInjector::Create(
633 scoped_refptr
<base::SingleThreadTaskRunner
> main_task_runner
,
634 scoped_refptr
<base::SingleThreadTaskRunner
> ui_task_runner
) {
635 scoped_ptr
<InputInjectorX11
> injector(
636 new InputInjectorX11(main_task_runner
));
637 if (!injector
->Init())
639 return injector
.Pass();
642 } // namespace remoting