1 // Copyright 2013 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 "media/base/user_input_monitor.h"
7 #include <sys/select.h>
10 #include <X11/keysymdef.h>
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/location.h"
17 #include "base/logging.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/message_loop/message_pump_libevent.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/synchronization/lock.h"
22 #include "media/base/keyboard_event_counter.h"
23 #include "third_party/skia/include/core/SkPoint.h"
24 #include "ui/events/keycodes/keyboard_code_conversion_x.h"
26 // These includes need to be later than dictated by the style guide due to
27 // Xlib header pollution, specifically the min, max, and Status macros.
28 #include <X11/XKBlib.h>
29 #include <X11/Xlibint.h>
30 #include <X11/extensions/record.h>
35 // This is the actual implementation of event monitoring. It's separated from
36 // UserInputMonitorLinux since it needs to be deleted on the IO thread.
37 class UserInputMonitorLinuxCore
38 : public base::MessagePumpLibevent::Watcher
,
39 public base::SupportsWeakPtr
<UserInputMonitorLinuxCore
>,
40 public base::MessageLoop::DestructionObserver
{
47 explicit UserInputMonitorLinuxCore(
48 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
49 const scoped_refptr
<UserInputMonitor::MouseListenerList
>&
51 virtual ~UserInputMonitorLinuxCore();
53 // DestructionObserver overrides.
54 virtual void WillDestroyCurrentMessageLoop() OVERRIDE
;
56 size_t GetKeyPressCount() const;
57 void StartMonitor(EventType type
);
58 void StopMonitor(EventType type
);
61 // base::MessagePumpLibevent::Watcher interface.
62 virtual void OnFileCanReadWithoutBlocking(int fd
) OVERRIDE
;
63 virtual void OnFileCanWriteWithoutBlocking(int fd
) OVERRIDE
;
65 // Processes key and mouse events.
66 void ProcessXEvent(xEvent
* event
);
67 static void ProcessReply(XPointer self
, XRecordInterceptData
* data
);
69 scoped_refptr
<base::SingleThreadTaskRunner
> io_task_runner_
;
70 scoped_refptr
<ObserverListThreadSafe
<UserInputMonitor::MouseEventListener
> >
74 // The following members should only be accessed on the IO thread.
76 base::MessagePumpLibevent::FileDescriptorWatcher controller_
;
77 Display
* x_control_display_
;
78 Display
* x_record_display_
;
79 XRecordRange
* x_record_range_
[2];
80 XRecordContext x_record_context_
;
81 KeyboardEventCounter counter_
;
83 DISALLOW_COPY_AND_ASSIGN(UserInputMonitorLinuxCore
);
86 class UserInputMonitorLinux
: public UserInputMonitor
{
88 explicit UserInputMonitorLinux(
89 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
);
90 virtual ~UserInputMonitorLinux();
92 // Public UserInputMonitor overrides.
93 virtual size_t GetKeyPressCount() const OVERRIDE
;
96 // Private UserInputMonitor overrides.
97 virtual void StartKeyboardMonitoring() OVERRIDE
;
98 virtual void StopKeyboardMonitoring() OVERRIDE
;
99 virtual void StartMouseMonitoring() OVERRIDE
;
100 virtual void StopMouseMonitoring() OVERRIDE
;
102 scoped_refptr
<base::SingleThreadTaskRunner
> io_task_runner_
;
103 UserInputMonitorLinuxCore
* core_
;
105 DISALLOW_COPY_AND_ASSIGN(UserInputMonitorLinux
);
108 UserInputMonitorLinuxCore::UserInputMonitorLinuxCore(
109 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
110 const scoped_refptr
<UserInputMonitor::MouseListenerList
>& mouse_listeners
)
111 : io_task_runner_(io_task_runner
),
112 mouse_listeners_(mouse_listeners
),
113 x_control_display_(NULL
),
114 x_record_display_(NULL
),
115 x_record_context_(0) {
116 x_record_range_
[0] = NULL
;
117 x_record_range_
[1] = NULL
;
120 UserInputMonitorLinuxCore::~UserInputMonitorLinuxCore() {
121 DCHECK(!x_control_display_
);
122 DCHECK(!x_record_display_
);
123 DCHECK(!x_record_range_
[0]);
124 DCHECK(!x_record_range_
[1]);
125 DCHECK(!x_record_context_
);
128 void UserInputMonitorLinuxCore::WillDestroyCurrentMessageLoop() {
129 DCHECK(io_task_runner_
->BelongsToCurrentThread());
130 StopMonitor(MOUSE_EVENT
);
131 StopMonitor(KEYBOARD_EVENT
);
134 size_t UserInputMonitorLinuxCore::GetKeyPressCount() const {
135 return counter_
.GetKeyPressCount();
138 void UserInputMonitorLinuxCore::StartMonitor(EventType type
) {
139 DCHECK(io_task_runner_
->BelongsToCurrentThread());
141 if (type
== KEYBOARD_EVENT
)
144 // TODO(jamiewalch): We should pass the display in. At that point, since
145 // XRecord needs a private connection to the X Server for its data channel
146 // and both channels are used from a separate thread, we'll need to duplicate
147 // them with something like the following:
148 // XOpenDisplay(DisplayString(display));
149 if (!x_control_display_
)
150 x_control_display_
= XOpenDisplay(NULL
);
152 if (!x_record_display_
)
153 x_record_display_
= XOpenDisplay(NULL
);
155 if (!x_control_display_
|| !x_record_display_
) {
156 LOG(ERROR
) << "Couldn't open X display";
161 int xr_opcode
, xr_event
, xr_error
;
162 if (!XQueryExtension(
163 x_control_display_
, "RECORD", &xr_opcode
, &xr_event
, &xr_error
)) {
164 LOG(ERROR
) << "X Record extension not available.";
169 if (!x_record_range_
[type
])
170 x_record_range_
[type
] = XRecordAllocRange();
172 if (!x_record_range_
[type
]) {
173 LOG(ERROR
) << "XRecordAllocRange failed.";
178 if (type
== MOUSE_EVENT
) {
179 x_record_range_
[type
]->device_events
.first
= MotionNotify
;
180 x_record_range_
[type
]->device_events
.last
= MotionNotify
;
182 DCHECK_EQ(KEYBOARD_EVENT
, type
);
183 x_record_range_
[type
]->device_events
.first
= KeyPress
;
184 x_record_range_
[type
]->device_events
.last
= KeyRelease
;
187 if (x_record_context_
) {
188 XRecordDisableContext(x_control_display_
, x_record_context_
);
189 XFlush(x_control_display_
);
190 XRecordFreeContext(x_record_display_
, x_record_context_
);
191 x_record_context_
= 0;
193 XRecordRange
** record_range_to_use
=
194 (x_record_range_
[0] && x_record_range_
[1]) ? x_record_range_
195 : &x_record_range_
[type
];
196 int number_of_ranges
= (x_record_range_
[0] && x_record_range_
[1]) ? 2 : 1;
198 XRecordClientSpec client_spec
= XRecordAllClients
;
199 x_record_context_
= XRecordCreateContext(x_record_display_
,
205 if (!x_record_context_
) {
206 LOG(ERROR
) << "XRecordCreateContext failed.";
211 if (!XRecordEnableContextAsync(x_record_display_
,
213 &UserInputMonitorLinuxCore::ProcessReply
,
214 reinterpret_cast<XPointer
>(this))) {
215 LOG(ERROR
) << "XRecordEnableContextAsync failed.";
220 if (!x_record_range_
[0] || !x_record_range_
[1]) {
221 // Register OnFileCanReadWithoutBlocking() to be called every time there is
222 // something to read from |x_record_display_|.
223 base::MessageLoopForIO
* message_loop
= base::MessageLoopForIO::current();
225 message_loop
->WatchFileDescriptor(ConnectionNumber(x_record_display_
),
227 base::MessageLoopForIO::WATCH_READ
,
231 LOG(ERROR
) << "Failed to create X record task.";
236 // Start observing message loop destruction if we start monitoring the first
238 base::MessageLoop::current()->AddDestructionObserver(this);
241 // Fetch pending events if any.
242 OnFileCanReadWithoutBlocking(ConnectionNumber(x_record_display_
));
245 void UserInputMonitorLinuxCore::StopMonitor(EventType type
) {
246 DCHECK(io_task_runner_
->BelongsToCurrentThread());
248 if (x_record_range_
[type
]) {
249 XFree(x_record_range_
[type
]);
250 x_record_range_
[type
] = NULL
;
252 if (x_record_range_
[0] || x_record_range_
[1])
255 // Context must be disabled via the control channel because we can't send
256 // any X protocol traffic over the data channel while it's recording.
257 if (x_record_context_
) {
258 XRecordDisableContext(x_control_display_
, x_record_context_
);
259 XFlush(x_control_display_
);
260 XRecordFreeContext(x_record_display_
, x_record_context_
);
261 x_record_context_
= 0;
263 controller_
.StopWatchingFileDescriptor();
265 if (x_record_display_
) {
266 XCloseDisplay(x_record_display_
);
267 x_record_display_
= NULL
;
269 if (x_control_display_
) {
270 XCloseDisplay(x_control_display_
);
271 x_control_display_
= NULL
;
273 // Stop observing message loop destruction if no event is being monitored.
274 base::MessageLoop::current()->RemoveDestructionObserver(this);
277 void UserInputMonitorLinuxCore::OnFileCanReadWithoutBlocking(int fd
) {
278 DCHECK(io_task_runner_
->BelongsToCurrentThread());
280 // Fetch pending events if any.
281 while (XPending(x_record_display_
)) {
282 XNextEvent(x_record_display_
, &event
);
286 void UserInputMonitorLinuxCore::OnFileCanWriteWithoutBlocking(int fd
) {
290 void UserInputMonitorLinuxCore::ProcessXEvent(xEvent
* event
) {
291 DCHECK(io_task_runner_
->BelongsToCurrentThread());
292 if (event
->u
.u
.type
== MotionNotify
) {
293 SkIPoint
position(SkIPoint::Make(event
->u
.keyButtonPointer
.rootX
,
294 event
->u
.keyButtonPointer
.rootY
));
295 mouse_listeners_
->Notify(
296 &UserInputMonitor::MouseEventListener::OnMouseMoved
, position
);
299 if (event
->u
.u
.type
== KeyPress
) {
300 type
= ui::ET_KEY_PRESSED
;
301 } else if (event
->u
.u
.type
== KeyRelease
) {
302 type
= ui::ET_KEY_RELEASED
;
309 XkbKeycodeToKeysym(x_control_display_
, event
->u
.u
.detail
, 0, 0);
310 ui::KeyboardCode key_code
= ui::KeyboardCodeFromXKeysym(key_sym
);
311 counter_
.OnKeyboardEvent(type
, key_code
);
316 void UserInputMonitorLinuxCore::ProcessReply(XPointer self
,
317 XRecordInterceptData
* data
) {
318 if (data
->category
== XRecordFromServer
) {
319 xEvent
* event
= reinterpret_cast<xEvent
*>(data
->data
);
320 reinterpret_cast<UserInputMonitorLinuxCore
*>(self
)->ProcessXEvent(event
);
322 XRecordFreeData(data
);
326 // Implementation of UserInputMonitorLinux.
329 UserInputMonitorLinux::UserInputMonitorLinux(
330 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
)
331 : io_task_runner_(io_task_runner
),
332 core_(new UserInputMonitorLinuxCore(io_task_runner
, mouse_listeners())) {}
334 UserInputMonitorLinux::~UserInputMonitorLinux() {
335 if (!io_task_runner_
->DeleteSoon(FROM_HERE
, core_
))
339 size_t UserInputMonitorLinux::GetKeyPressCount() const {
340 return core_
->GetKeyPressCount();
343 void UserInputMonitorLinux::StartKeyboardMonitoring() {
344 io_task_runner_
->PostTask(
346 base::Bind(&UserInputMonitorLinuxCore::StartMonitor
,
348 UserInputMonitorLinuxCore::KEYBOARD_EVENT
));
351 void UserInputMonitorLinux::StopKeyboardMonitoring() {
352 io_task_runner_
->PostTask(
354 base::Bind(&UserInputMonitorLinuxCore::StopMonitor
,
356 UserInputMonitorLinuxCore::KEYBOARD_EVENT
));
359 void UserInputMonitorLinux::StartMouseMonitoring() {
360 io_task_runner_
->PostTask(FROM_HERE
,
361 base::Bind(&UserInputMonitorLinuxCore::StartMonitor
,
363 UserInputMonitorLinuxCore::MOUSE_EVENT
));
366 void UserInputMonitorLinux::StopMouseMonitoring() {
367 io_task_runner_
->PostTask(FROM_HERE
,
368 base::Bind(&UserInputMonitorLinuxCore::StopMonitor
,
370 UserInputMonitorLinuxCore::MOUSE_EVENT
));
375 scoped_ptr
<UserInputMonitor
> UserInputMonitor::Create(
376 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
377 const scoped_refptr
<base::SingleThreadTaskRunner
>& ui_task_runner
) {
378 return scoped_ptr
<UserInputMonitor
>(
379 new UserInputMonitorLinux(io_task_runner
));