Roll src/third_party/WebKit f36d5e0:68b67cd (svn 193299:193303)
[chromium-blink-merge.git] / remoting / host / input_injector_x11.cc
blob8fc725b0f7be7f9a855a8a5046ca641f62b1e881
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>
9 #include <X11/Xlib.h>
10 #include <X11/XKBlib.h>
12 #include <set>
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"
23 #endif
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"
30 namespace remoting {
32 namespace {
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,
41 KeySym key_sym,
42 uint32_t* keycode,
43 uint32_t* modifiers) {
44 *keycode = XKeysymToKeycode(display, key_sym);
46 const uint32_t kModifiersToTry[] = {
48 ShiftMask,
49 Mod2Mask,
50 Mod3Mask,
51 Mod4Mask,
52 ShiftMask | Mod2Mask,
53 ShiftMask | Mod3Mask,
54 ShiftMask | Mod4Mask,
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];
64 return true;
68 return false;
71 // Finds a keycode and set of modifiers that generate character with the
72 // specified |code_point|.
73 bool FindKeycodeForUnicode(Display* display,
74 uint32_t code_point,
75 uint32_t* keycode,
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)) {
83 return true;
87 return false;
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 {
96 public:
97 explicit InputInjectorX11(
98 scoped_refptr<base::SingleThreadTaskRunner> task_runner);
99 ~InputInjectorX11() override;
101 bool Init();
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;
115 private:
116 // The actual implementation resides in InputInjectorX11::Core class.
117 class Core : public base::RefCountedThreadSafe<Core> {
118 public:
119 explicit Core(scoped_refptr<base::SingleThreadTaskRunner> task_runner);
121 bool Init();
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);
134 void Stop();
136 private:
137 friend class base::RefCountedThreadSafe<Core>;
138 virtual ~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
145 // untouched.
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
153 // mapping.
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.
167 Display* display_;
168 Window root_window_;
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_;
181 #endif
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() {
201 core_->Stop();
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() {
245 CHECK(display_);
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";
253 return false;
256 // TODO(ajwong): Do we want to check the major/minor version at all for XTest?
257 int major = 0;
258 int minor = 0;
259 if (!XTestQueryExtension(display_, &test_event_base_, &test_error_base_,
260 &major, &minor)) {
261 LOG(ERROR) << "Server does not support XTest.";
262 return false;
264 InitMouseButtonMap();
265 return true;
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));
273 return;
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())
283 return;
285 if (!task_runner_->BelongsToCurrentThread()) {
286 task_runner_->PostTask(FROM_HERE,
287 base::Bind(&Core::InjectKeyEvent, this, event));
288 return;
291 int keycode =
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())
299 return;
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);
316 } else {
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);
326 XFlush(display_);
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));
333 return;
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) {
346 uint32_t code_point;
347 if (!base::ReadUnicodeCharacter(
348 text.c_str(), text.size(), &index, &code_point)) {
349 continue;
352 uint32_t keycode;
353 uint32_t modifiers;
354 if (!FindKeycodeForUnicode(display_, code_point, &keycode, &modifiers))
355 continue;
357 XkbLockModifiers(display_, XkbUseCoreKbd, modifiers, modifiers);
359 XTestFakeKeyEvent(display_, keycode, True, CurrentTime);
360 XTestFakeKeyEvent(display_, keycode, False, CurrentTime);
362 XkbLockModifiers(display_, XkbUseCoreKbd, modifiers, 0);
365 XFlush(display_);
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.";
381 return true;
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) {
393 if (button < 0) {
394 LOG(WARNING) << "Ignoring unmapped scroll wheel button";
395 return;
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));
408 return;
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(),
418 CurrentTime);
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());
433 #endif
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;
439 if (inject_motion) {
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(),
448 CurrentTime);
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();
457 return;
460 VLOG(3) << "Button " << event.button()
461 << " received, sending "
462 << (event.button_down() ? "down " : "up ")
463 << button_number;
464 XTestFakeButtonEvent(display_, button_number, event.button_down(),
465 CurrentTime);
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.
473 int ticks_y = 0;
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;
481 if (ticks_y != 0) {
482 InjectScrollWheelClicks(VerticalScrollWheelToX11ButtonNumber(ticks_y),
483 abs(ticks_y));
486 int ticks_x = 0;
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;
494 if (ticks_x != 0) {
495 InjectScrollWheelClicks(HorizontalScrollWheelToX11ButtonNumber(ticks_x),
496 abs(ticks_x));
499 XFlush(display_);
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(),
512 num_buttons);
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;
531 return;
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.
538 XID device_id = 0;
539 bool device_found = false;
540 int num_devices;
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;
548 device_found = true;
549 break;
552 XFreeDeviceList(devices);
554 if (!device_found) {
555 HOST_LOG << "Cannot find XTest device.";
556 return;
559 XDevice* device = XOpenDevice(display_, device_id);
560 if (!device) {
561 LOG(ERROR) << "Cannot open XTest device.";
562 return;
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(),
572 num_device_buttons);
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) {
581 switch (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:
592 default:
593 return -1;
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(
611 FROM_HERE,
612 base::Bind(&Core::Start, this, base::Passed(&client_clipboard)));
613 return;
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));
624 return;
627 clipboard_.reset();
630 } // namespace
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())
638 return nullptr;
639 return injector.Pass();
642 } // namespace remoting