Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(73)

Side by Side Diff: media/base/user_input_monitor_linux.cc

Issue 21183002: Adding key press detection in the browser process. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 7 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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.
4
5 #include "media/base/user_input_monitor.h"
6
7 #include <sys/select.h>
8 #include <unistd.h>
9 #define XK_MISCELLANY
10 #include <X11/keysymdef.h>
11
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/memory/weak_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/message_loop/message_pump_libevent.h"
21 #include "base/posix/eintr_wrapper.h"
22 #include "base/single_thread_task_runner.h"
23 #include "base/threading/non_thread_safe.h"
24 #include "third_party/skia/include/core/SkPoint.h"
25 #include "ui/base/keycodes/keyboard_code_conversion_x.h"
26
27 // These includes need to be later than dictated by the style guide due to
28 // Xlib header pollution, specifically the min, max, and Status macros.
29 #include <X11/XKBlib.h>
30 #include <X11/Xlibint.h>
31 #include <X11/extensions/record.h>
32
33 namespace media {
34
35 namespace {
36
37 class UserInputMonitorLinux : public base::NonThreadSafe,
38 public UserInputMonitor {
39 public:
40 UserInputMonitorLinux(
41 const scoped_refptr<base::SingleThreadTaskRunner>& input_task_runner);
42 virtual ~UserInputMonitorLinux();
43
44 private:
45 enum EventType {
46 MOUSE_EVENT = 0,
47 KEYBOARD_EVENT = 1
48 };
49
50 // The actual implementation resides in UserInputMonitorLinux::Core class.
51 // Must be called on the input_task_runner thread.
52 class Core : public base::RefCountedThreadSafe<Core>,
53 public base::MessagePumpLibevent::Watcher {
54 public:
55 typedef const base::Callback<void(const SkIPoint&)> MouseCallback;
56 typedef base::Callback<void(ui::EventType event, ui::KeyboardCode key_code)>
57 KeyboardCallback;
58 Core(const MouseCallback& mouse_callback,
59 const KeyboardCallback& keyboard_callback);
60
61 void StartMonitor(EventType type);
62 void StopMonitor(EventType type);
63
64 private:
65 friend class base::RefCountedThreadSafe<Core>;
66 virtual ~Core();
67
68 // base::MessagePumpLibevent::Watcher interface.
69 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
70 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE;
71
72 // Processes key and mouse events.
73 void ProcessXEvent(xEvent* event);
74 static void ProcessReply(XPointer self, XRecordInterceptData* data);
75
76 // Used to receive base::MessagePumpLibevent::Watcher events.
77 base::MessagePumpLibevent::FileDescriptorWatcher controller_;
78
79 Display* display_;
80 Display* x_record_display_;
81 XRecordRange* x_record_range_[2];
82 XRecordContext x_record_context_;
83 base::Callback<void(const SkIPoint&)> mouse_callback_;
84 base::Callback<void(ui::EventType event, ui::KeyboardCode key_code)>
85 keyboard_callback_;
86
87 DISALLOW_COPY_AND_ASSIGN(Core);
88 };
89
90 virtual void StartMonitorMouse() OVERRIDE;
91 virtual void StopMonitorMouse() OVERRIDE;
92 virtual void StartMonitorKeyboard() OVERRIDE;
93 virtual void StopMonitorKeyboard() OVERRIDE;
94
95 void OnMouseEvent(const SkIPoint& position);
96 void OnKeyboardEvent(ui::EventType event, ui::KeyboardCode key_code);
97
98 void SetOrVerifyCallingThread();
99
100 // Task runner on which monitoring is started and callbacks are called.
101 scoped_refptr<base::SingleThreadTaskRunner> callback_task_runner_;
102 // Task runner on which X Window events are received.
103 scoped_refptr<base::SingleThreadTaskRunner> input_task_runner_;
104 scoped_refptr<Core> core_;
105
106 DISALLOW_COPY_AND_ASSIGN(UserInputMonitorLinux);
107 };
108
109 UserInputMonitorLinux::UserInputMonitorLinux(
110 const scoped_refptr<base::SingleThreadTaskRunner>& input_task_runner)
111 : input_task_runner_(input_task_runner),
112 core_(new Core(base::Bind(&UserInputMonitorLinux::OnMouseEvent,
113 base::Unretained(this)),
114 base::Bind(&UserInputMonitorLinux::OnKeyboardEvent,
115 base::Unretained(this)))) {}
116
117 UserInputMonitorLinux::~UserInputMonitorLinux() {}
118
119 void UserInputMonitorLinux::StartMonitorMouse() {
120 SetOrVerifyCallingThread();
121 input_task_runner_->PostTask(
122 FROM_HERE, base::Bind(&Core::StartMonitor, core_.get(), MOUSE_EVENT));
123 }
124
125 void UserInputMonitorLinux::StopMonitorMouse() {
126 SetOrVerifyCallingThread();
127 input_task_runner_->PostTask(
128 FROM_HERE, base::Bind(&Core::StopMonitor, core_.get(), MOUSE_EVENT));
129 }
130
131 void UserInputMonitorLinux::StartMonitorKeyboard() {
132 SetOrVerifyCallingThread();
133 input_task_runner_->PostTask(
134 FROM_HERE, base::Bind(&Core::StartMonitor, core_.get(), KEYBOARD_EVENT));
135 }
136
137 void UserInputMonitorLinux::StopMonitorKeyboard() {
138 SetOrVerifyCallingThread();
139 input_task_runner_->PostTask(
140 FROM_HERE, base::Bind(&Core::StopMonitor, core_.get(), KEYBOARD_EVENT));
141 }
142
143 void UserInputMonitorLinux::OnMouseEvent(const SkIPoint& position) {
144 if (!callback_task_runner_->BelongsToCurrentThread()) {
145 callback_task_runner_->PostTask(
146 FROM_HERE,
147 base::Bind(&UserInputMonitorLinux::OnMouseEvent,
148 base::Unretained(this),
149 position));
150 return;
151 }
152 UserInputMonitor::OnMouseEvent(position);
153 }
154
155 void UserInputMonitorLinux::OnKeyboardEvent(ui::EventType event,
156 ui::KeyboardCode key_code) {
157 if (!callback_task_runner_->BelongsToCurrentThread()) {
158 callback_task_runner_->PostTask(
159 FROM_HERE,
160 base::Bind(&UserInputMonitorLinux::OnKeyboardEvent,
161 base::Unretained(this),
162 event,
163 key_code));
164 return;
165 }
166 UserInputMonitor::OnKeyboardEvent(event, key_code);
167 }
168
169 void UserInputMonitorLinux::SetOrVerifyCallingThread() {
DaleCurtis 2013/08/10 00:13:12 Instead of trying to do this, which feels a bit sk
jiayl 2013/08/10 00:37:56 If it's not done here, it needs to be done in the
Sergey Ulanov 2013/08/10 00:48:19 It would mean that the clients of this interface h
DaleCurtis 2013/08/10 00:57:51 Since UserInputMonitor is owned by BrowserMainLoop
jiayl 2013/08/12 19:05:59 Is there any problem with using ObserverList with
170 if (!callback_task_runner_) {
171 callback_task_runner_ = base::MessageLoopProxy::current();
172 return;
173 }
174 CHECK(callback_task_runner_->BelongsToCurrentThread());
Sergey Ulanov 2013/08/10 00:48:19 it's more common to use DCHECKs for thread checks.
175 }
176
177 UserInputMonitorLinux::Core::Core(const MouseCallback& mouse_callback,
178 const KeyboardCallback& keyboard_callback)
179 : display_(NULL),
180 x_record_display_(NULL),
181 x_record_context_(0),
182 mouse_callback_(mouse_callback),
183 keyboard_callback_(keyboard_callback) {
184 x_record_range_[0] = NULL;
185 x_record_range_[1] = NULL;
186 }
187
188 UserInputMonitorLinux::Core::~Core() {
189 DCHECK(!display_);
190 DCHECK(!x_record_display_);
191 DCHECK(!x_record_range_[0]);
192 DCHECK(!x_record_range_[1]);
193 DCHECK(!x_record_context_);
194 }
195
196 void UserInputMonitorLinux::Core::StartMonitor(EventType type) {
197 DCHECK(base::MessageLoopForIO::current());
198 // TODO(jamiewalch): We should pass the display in. At that point, since
199 // XRecord needs a private connection to the X Server for its data channel
200 // and both channels are used from a separate thread, we'll need to duplicate
201 // them with something like the following:
202 // XOpenDisplay(DisplayString(display));
203 if (!display_)
204 display_ = XOpenDisplay(NULL);
205
206 if (!x_record_display_)
207 x_record_display_ = XOpenDisplay(NULL);
208
209 if (!display_ || !x_record_display_) {
210 LOG(ERROR) << "Couldn't open X display";
211 return;
212 }
213
214 int xr_opcode, xr_event, xr_error;
215 if (!XQueryExtension(display_, "RECORD", &xr_opcode, &xr_event, &xr_error)) {
216 LOG(ERROR) << "X Record extension not available.";
217 return;
218 }
219
220 if (!x_record_range_[type])
221 x_record_range_[type] = XRecordAllocRange();
222
223 if (!x_record_range_[type]) {
224 LOG(ERROR) << "XRecordAllocRange failed.";
225 return;
226 }
227 if (type == MOUSE_EVENT) {
228 x_record_range_[type]->device_events.first = MotionNotify;
229 x_record_range_[type]->device_events.last = MotionNotify;
230 } else {
231 DCHECK_EQ(KEYBOARD_EVENT, type);
232 x_record_range_[type]->device_events.first = KeyPress;
233 x_record_range_[type]->device_events.last = KeyRelease;
234 }
235
236 if (x_record_context_) {
237 XRecordDisableContext(display_, x_record_context_);
238 XFlush(display_);
239 XRecordFreeContext(x_record_display_, x_record_context_);
240 x_record_context_ = 0;
241 }
242 XRecordRange** record_range_to_use =
243 (x_record_range_[0] && x_record_range_[1]) ? x_record_range_
244 : &x_record_range_[type];
245 int number_of_ranges = (x_record_range_[0] && x_record_range_[1]) ? 2 : 1;
246
247 XRecordClientSpec client_spec = XRecordAllClients;
248 x_record_context_ = XRecordCreateContext(x_record_display_,
249 0,
250 &client_spec,
251 1,
252 record_range_to_use,
253 number_of_ranges);
254 if (!x_record_context_) {
255 LOG(ERROR) << "XRecordCreateContext failed.";
256 return;
257 }
258
259 if (!XRecordEnableContextAsync(x_record_display_,
260 x_record_context_,
261 &Core::ProcessReply,
262 reinterpret_cast<XPointer>(this))) {
263 LOG(ERROR) << "XRecordEnableContextAsync failed.";
264 return;
265 }
266
267 if (!x_record_range_[0] || !x_record_range_[1]) {
268 // Register OnFileCanReadWithoutBlocking() to be called every time there is
269 // something to read from |x_record_display_|.
270 base::MessageLoopForIO* message_loop = base::MessageLoopForIO::current();
DaleCurtis 2013/08/10 00:13:12 ?? just use io_loop_ ?
jiayl 2013/08/10 00:37:56 Core doesn't have a member as io_loop_. It's alway
Sergey Ulanov 2013/08/10 00:48:19 Also, only ForIO version of MessageLoop has WatchF
271 int result =
272 message_loop->WatchFileDescriptor(ConnectionNumber(x_record_display_),
273 true,
274 base::MessageLoopForIO::WATCH_READ,
275 &controller_,
276 this);
277 if (!result) {
278 LOG(ERROR) << "Failed to create X record task.";
279 return;
280 }
281 }
282
283 // Fetch pending events if any.
284 while (XPending(x_record_display_)) {
285 XEvent ev;
286 XNextEvent(x_record_display_, &ev);
287 }
288 }
289
290 void UserInputMonitorLinux::Core::StopMonitor(EventType type) {
291 DCHECK(base::MessageLoopForIO::current());
292
293 if (x_record_range_[type]) {
294 XFree(x_record_range_[type]);
295 x_record_range_[type] = NULL;
296 }
297 if (x_record_range_[0] || x_record_range_[1])
298 return;
299
300 // Context must be disabled via the control channel because we can't send
301 // any X protocol traffic over the data channel while it's recording.
302 if (x_record_context_) {
303 XRecordDisableContext(display_, x_record_context_);
304 XFlush(display_);
305 XRecordFreeContext(x_record_display_, x_record_context_);
306 x_record_context_ = 0;
307
308 controller_.StopWatchingFileDescriptor();
309 if (x_record_display_) {
310 XCloseDisplay(x_record_display_);
311 x_record_display_ = NULL;
312 }
313 if (display_) {
314 XCloseDisplay(display_);
315 display_ = NULL;
316 }
317 }
318 }
319
320 void UserInputMonitorLinux::Core::OnFileCanReadWithoutBlocking(int fd) {
321 DCHECK(base::MessageLoopForIO::current());
322
323 // Fetch pending events if any.
324 while (XPending(x_record_display_)) {
325 XEvent ev;
326 XNextEvent(x_record_display_, &ev);
327 }
328 }
329
330 void UserInputMonitorLinux::Core::OnFileCanWriteWithoutBlocking(int fd) {
331 NOTREACHED();
332 }
333
334 void UserInputMonitorLinux::Core::ProcessXEvent(xEvent* event) {
335 if (event->u.u.type == MotionNotify) {
336 SkIPoint position(SkIPoint::Make(event->u.keyButtonPointer.rootX,
337 event->u.keyButtonPointer.rootY));
338 mouse_callback_.Run(position);
339 } else {
340 ui::EventType type;
341 if (event->u.u.type == KeyPress) {
342 type = ui::ET_KEY_PRESSED;
343 } else if (event->u.u.type == KeyRelease) {
344 type = ui::ET_KEY_RELEASED;
345 } else {
346 NOTREACHED();
347 }
348
349 KeySym key_sym = XkbKeycodeToKeysym(display_, event->u.u.detail, 0, 0);
350 ui::KeyboardCode key_code = ui::KeyboardCodeFromXKeysym(key_sym);
351 keyboard_callback_.Run(type, key_code);
352 }
353 }
354
355 // static
356 void UserInputMonitorLinux::Core::ProcessReply(XPointer self,
357 XRecordInterceptData* data) {
358 if (data->category == XRecordFromServer) {
359 xEvent* event = reinterpret_cast<xEvent*>(data->data);
360 reinterpret_cast<Core*>(self)->ProcessXEvent(event);
361 }
362 XRecordFreeData(data);
363 }
364
365 } // namespace
366
367 scoped_ptr<UserInputMonitor> UserInputMonitor::Create(
368 const scoped_refptr<base::SingleThreadTaskRunner>& input_task_runner,
369 const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) {
370 return scoped_ptr<UserInputMonitor>(
371 new UserInputMonitorLinux(input_task_runner));
372 }
373
374 } // namespace media
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698