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

Side by Side Diff: ui/views/widget/desktop_aura/desktop_keyboard_capture_win.cc

Issue 297123002: API proposal for chrome.app.window to intercept all keys. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Update based on Ananta's cr comments Created 6 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 (c) 2014 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 "ui/views/widget/desktop_aura/desktop_keyboard_capture_win.h"
6
7 #include <map>
8
9 #include "base/containers/scoped_ptr_hash_map.h"
10 #include "base/logging.h"
11 #include "base/macros.h"
12 #include "base/memory/singleton.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/message_loop/message_pump_win.h"
15
16 namespace {
17 // Some helper routines used to construct keyboard event.
18
19 // Return true of WPARAM corresponds to a UP keyboard event.
20 bool IsKeyUp(WPARAM w_param) {
21 return (w_param == WM_KEYUP) || (w_param == WM_SYSKEYUP);
22 }
23
24 // Check if the given bit is set.
25 bool IsBitSet(ULONG value, ULONG mask) {
26 return ((value & mask) != 0);
27 }
28
29 // Return the location independent keycode corresponding to given keycode (e.g.
30 // return shift when left/right shift is pressed). This is needed as low level
31 // hooks get location information which is not returned as part of normal window
32 // keyboard events.
33 DWORD RemoveLocationOnKeycode(DWORD vk_code) {
34 // Virtual keycode from low level hook include location while window messages
35 // does not. So convert them to be without location.
36 switch (vk_code) {
37 case VK_LSHIFT:
38 case VK_RSHIFT:
39 return VK_SHIFT;
40 case VK_LCONTROL:
41 case VK_RCONTROL:
42 return VK_CONTROL;
43 case VK_LMENU:
44 case VK_RMENU:
45 return VK_MENU;
46 }
47 return vk_code;
48 }
49
50 // Construct LPARAM corresponding to the given low level hook callback
51 // structure.
52 LPARAM GetLParamFromHookStruct(WPARAM w_param, KBDLLHOOKSTRUCT* hook_struct) {
53 ULONG key_state = 0;
54 // There is no way to get repeat count so always set it to 1.
55 key_state = 1;
56
57 // Scan code.
58 key_state |= (hook_struct->scanCode & 0xFF) << 16;
59
60 // Extended key when the event is received as part window event and so skip
61 // it.
62
63 // Context code.
64 key_state |= IsBitSet(hook_struct->flags, LLKHF_ALTDOWN) << 29;
65
66 // Previous key state - set to 1 for KEYUP events.
67 key_state |= IsKeyUp(w_param) << 30;
68
69 // Transition state.
70 key_state |= IsBitSet(hook_struct->flags, LLKHF_UP) << 31;
71
72 return static_cast<LPARAM>(key_state);
73 }
74
75 // List of key state that we want to save.
76 int keys_to_save[] = {VK_SHIFT, VK_CONTROL, VK_MENU};
77
78 // Make sure that we are not going to run out of bits saving the state.
79 C_ASSERT((arraysize(keys_to_save) * 2) <= (sizeof(WPARAM) * 8));
80
81 // Save keyboard state to WPARAM so it can be restored later before the keyboard
82 // message is processed in the main thread. This is necessary for
83 // GetKeyboardState() to work as keyboard state will be different by the time
84 // main thread processes the message.
85 WPARAM SaveKeyboardState() {
86 WPARAM value = 0;
87
88 for (int index = 0; index < arraysize(keys_to_save); index++) {
89 value <<= 2;
90 SHORT key_state = GetAsyncKeyState(keys_to_save[index]);
91 value |= ((IsBitSet(key_state, 0x8000) ? 0x2 : 0) |
92 (IsBitSet(key_state, 0x1) ? 0x1 : 0));
93 }
94 return value;
95 }
96
97 // Restore keyboard state based on saved values.
98 bool RestoreKeyboardState(WPARAM w_param) {
99 const int kKeyboardStateLength = 256;
100 BYTE keyboard_state[kKeyboardStateLength];
101 if (!GetKeyboardState(keyboard_state)) {
102 DVLOG(ERROR) << "Error getting keyboard state";
103 return false;
104 }
105
106 // restore in the reverse order of what was saved so we have the right bit for
107 // each key that was saved.
108 for (int index = arraysize(keys_to_save) - 1; index >= 0; index--) {
109 int key = keys_to_save[index];
110 keyboard_state[key] =
111 (IsBitSet(w_param, 0x2) ? 0x80 : 0) | (IsBitSet(w_param, 0x1) ? 1 : 0);
112 w_param >>= 2;
113 }
114
115 if (!SetKeyboardState(keyboard_state)) {
116 DVLOG(ERROR) << "Error setting keyboard state";
117 return false;
118 }
119
120 return true;
121 }
122
123 // Data corresponding to keyboard event.
124 struct KeyboardEventInfo {
125 UINT message_id;
126 WPARAM event_w_param;
127 LPARAM event_l_param;
128 WPARAM keyboard_state_to_restore;
129 };
130
131 // Maintains low level registration for a window.
132 class KeyboardInterceptRegistration {
133 public:
134 KeyboardInterceptRegistration();
135
136 // Are there any keyboard events queued.
137 bool IsKeyboardEventQueueEmpty();
138
139 // Insert keyboard event in the queue.
140 void QueueKeyboardEvent(const KeyboardEventInfo& info);
141
142 KeyboardEventInfo DequeueKeyboardEvent();
143
144 private:
145 std::queue<KeyboardEventInfo> keyboard_events_;
146
147 DISALLOW_COPY_AND_ASSIGN(KeyboardInterceptRegistration);
148 };
149
150 // Implements low level hook and manages registration for all the windows.
151 class LowLevelHookHandler {
152 public:
153 // Request all keyboard events to be routed to the given window.
154 void Register(HWND window_handle);
155
156 // Release the request for all keyboard events.
157 void Deregister(HWND window_handle);
158
159 // Get singleton instance.
160 static LowLevelHookHandler* GetInstance();
161
162 private:
163 // Private constructor/destructor so it is accessible only
164 // DefaultSingletonTraits.
165 friend struct DefaultSingletonTraits<LowLevelHookHandler>;
166 LowLevelHookHandler();
167
168 ~LowLevelHookHandler();
169
170 // Low level keyboard hook processing related functions.
171 // Hook callback called from the OS.
172 static LRESULT CALLBACK
173 KeyboardHook(int code, WPARAM w_param, LPARAM l_param);
174
175 // Low level keyboard hook handler.
176 LRESULT HandleKeyboardHook(int code, WPARAM w_param, LPARAM l_param);
177
178 // Message filter to set keyboard state based on private message.
179 static LRESULT CALLBACK
180 MessageFilterHook(int code, WPARAM w_param, LPARAM l_param);
181
182 // Message filter handler.
183 LRESULT HandleMessageFilterHook(int code, WPARAM w_param, LPARAM l_param);
184
185 bool EnableHooks();
186 void DisableHooks();
187
188 // Hook handle for window message to set keyboard state based on private
189 // message.
190 HHOOK message_filter_hook_;
191
192 // Hook handle for low level keyboard hook.
193 HHOOK keyboard_hook_;
194
195 // Private window message to set keyboard state for the thread.
196 UINT restore_keyboard_state_message_id_;
197
198 // Private message to inject keyboard event after current injected message is
199 // processed.
200 UINT inject_keyboard_event_message_id_;
201
202 // There is no lock protecting this list as the low level hook callbacks are
203 // executed on same thread that registered the hook and there is only one
204 // thread
205 // that execute all view code in browser.
206 base::ScopedPtrHashMap<HWND, KeyboardInterceptRegistration> registrations_;
207 };
208
209 KeyboardInterceptRegistration::KeyboardInterceptRegistration() {
210 }
211
212 bool KeyboardInterceptRegistration::IsKeyboardEventQueueEmpty() {
213 return keyboard_events_.empty();
214 }
215
216 void KeyboardInterceptRegistration::QueueKeyboardEvent(
217 const KeyboardEventInfo& info) {
218 keyboard_events_.push(info);
219 }
220
221 KeyboardEventInfo KeyboardInterceptRegistration::DequeueKeyboardEvent() {
222 KeyboardEventInfo info = keyboard_events_.front();
223 keyboard_events_.pop();
224 return info;
225 }
226
227 LowLevelHookHandler::LowLevelHookHandler()
228 : message_filter_hook_(NULL),
229 keyboard_hook_(NULL),
230 restore_keyboard_state_message_id_(0),
231 inject_keyboard_event_message_id_(0) {
232 restore_keyboard_state_message_id_ =
233 RegisterWindowMessage(L"chrome:restore_keyboard_state");
234 inject_keyboard_event_message_id_ =
235 RegisterWindowMessage(L"chrome:inject_keyboard_event");
236 }
237
238 LowLevelHookHandler::~LowLevelHookHandler() {
239 DisableHooks();
240 }
241
242 // static
243 LRESULT CALLBACK
244 LowLevelHookHandler::KeyboardHook(int code, WPARAM w_param, LPARAM l_param) {
245 return GetInstance()->HandleKeyboardHook(code, w_param, l_param);
246 }
247
248 // static
249 LRESULT CALLBACK LowLevelHookHandler::MessageFilterHook(int code,
250 WPARAM w_param,
251 LPARAM l_param) {
252 return GetInstance()->HandleMessageFilterHook(code, w_param, l_param);
253 }
254
255 // static
256 LowLevelHookHandler* LowLevelHookHandler::GetInstance() {
257 return Singleton<LowLevelHookHandler,
258 DefaultSingletonTraits<LowLevelHookHandler> >::get();
259 }
260
261 void LowLevelHookHandler::Register(HWND window_handle) {
262 if (registrations_.contains(window_handle))
263 return;
264
265 if (!EnableHooks())
266 return;
267
268 scoped_ptr<KeyboardInterceptRegistration> registration(
269 new KeyboardInterceptRegistration());
270 registrations_.add(window_handle, registration.Pass());
271 }
272
273 void LowLevelHookHandler::Deregister(HWND window_handle) {
274 registrations_.erase(window_handle);
275 if (registrations_.empty())
276 DisableHooks();
277
278 DVLOG(1) << "Keyboard hook unregistered for handle = " << window_handle;
279 }
280
281 bool LowLevelHookHandler::EnableHooks() {
282 // Make sure that hook is set from main thread as it has to be valid for
283 // the lifetime of the registration.
284 DCHECK(base::MessageLoopForUI::IsCurrent());
285
286 if (message_filter_hook_)
287 return true;
288
289 DCHECK(keyboard_hook_ == NULL) << "Keyboard hook already registered";
290
291 keyboard_hook_ = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHook, NULL, 0);
292 if (keyboard_hook_ == NULL) {
293 DVLOG(ERROR) << "Error calling SetWindowsHookEx() - GLE = "
294 << GetLastError();
295 return false;
296 }
297
298 message_filter_hook_ = SetWindowsHookEx(
299 WH_MSGFILTER, MessageFilterHook, NULL, GetCurrentThreadId());
300 if (message_filter_hook_ == NULL) {
301 DVLOG(ERROR) << "Error calling SetWindowsHookEx() to set message hook, "
302 << "gle = " << GetLastError();
303 return false;
304 }
305 return true;
306 }
307
308 void LowLevelHookHandler::DisableHooks() {
309 if (keyboard_hook_ != NULL) {
310 UnhookWindowsHookEx(keyboard_hook_);
311 keyboard_hook_ = NULL;
312 }
313
314 if (message_filter_hook_ != NULL) {
315 UnhookWindowsHookEx(message_filter_hook_);
316 message_filter_hook_ = NULL;
317 }
318 }
319
320 LRESULT
321 LowLevelHookHandler::HandleMessageFilterHook(int code,
322 WPARAM w_param,
323 LPARAM l_param) {
324 // Ignore if not called from main message loop.
325 if (code != base::MessagePumpForUI::kMessageFilterCode)
326 return CallNextHookEx(NULL, code, w_param, l_param);
327
328 MSG* msg = reinterpret_cast<MSG*>(l_param);
329 if (msg->message == restore_keyboard_state_message_id_) {
330 RestoreKeyboardState(msg->wParam);
331 return true;
332 } else if (msg->message == inject_keyboard_event_message_id_) {
333 KeyboardInterceptRegistration* registration = registrations_.get(msg->hwnd);
334 if (registration) {
335 // Post keyboard state and key event to main thread for processing.
336 KeyboardEventInfo event_info = registration->DequeueKeyboardEvent();
337 PostMessage(msg->hwnd,
338 restore_keyboard_state_message_id_,
339 event_info.keyboard_state_to_restore,
340 static_cast<LPARAM>(0));
341
342 PostMessage(msg->hwnd,
343 event_info.message_id,
344 event_info.event_w_param,
345 event_info.event_l_param);
346
347 if (!registration->IsKeyboardEventQueueEmpty()) {
348 // Post another inject keyboard event if there are more key events to
349 // process after the current injected event is processed.
350 PostMessage(msg->hwnd,
351 inject_keyboard_event_message_id_,
352 static_cast<WPARAM>(0),
353 static_cast<LPARAM>(0));
354 }
355
356 return true;
357 }
358 }
359
360 return CallNextHookEx(NULL, code, w_param, l_param);
361 }
362
363 LRESULT
364 LowLevelHookHandler::HandleKeyboardHook(int code,
365 WPARAM w_param,
366 LPARAM l_param) {
367 HWND current_active_window = GetActiveWindow();
ananta 2014/08/12 19:43:26 Shouldn't you be using GetFocus here?. GetFocus re
Sriram 2014/08/12 22:26:35 Done.
368
369 if (code >= 0) {
370 KeyboardInterceptRegistration* registration =
371 registrations_.get(current_active_window);
372 if (registration) {
373 // Save keyboard state to queue and post message to handle keyboard event
374 // if the queue is not empty. It is done this way as keyboard state should
375 // be preserved until char event corresponding to the keyboard event is
376 // handled (so correct alt/shift/control key state is set). Also
377 // SendMessage() cannot be used as it would bypass both message loop
378 // delegates and TransalateMessage() calls (which will inserts char
379 // events).
380 PKBDLLHOOKSTRUCT hook_struct =
381 reinterpret_cast<PKBDLLHOOKSTRUCT>(l_param);
382
383 KeyboardEventInfo event_info = {0};
384 event_info.message_id = w_param;
385 event_info.event_w_param = RemoveLocationOnKeycode(hook_struct->vkCode);
386 event_info.event_l_param = GetLParamFromHookStruct(w_param, hook_struct);
387 event_info.keyboard_state_to_restore = SaveKeyboardState();
388
389 bool should_queue_inject_event =
390 registration->IsKeyboardEventQueueEmpty();
391
392 registration->QueueKeyboardEvent(event_info);
393 if (should_queue_inject_event) {
394 PostMessage(current_active_window,
395 inject_keyboard_event_message_id_,
396 static_cast<WPARAM>(0),
397 static_cast<LPARAM>(0));
398 }
399 return 1;
400 }
401 }
402
403 return CallNextHookEx(NULL, code, w_param, l_param);
404 }
405
406 } // namespace
407
408 namespace views {
409
410 DesktopKeyboardCaptureWin::DesktopKeyboardCaptureWin(HWND window_handle)
411 : window_handle_(window_handle) {
412 LowLevelHookHandler::GetInstance()->Register(window_handle_);
413 }
414
415 DesktopKeyboardCaptureWin::~DesktopKeyboardCaptureWin() {
416 LowLevelHookHandler::GetInstance()->Deregister(window_handle_);
417 }
418
419 } // namespace views
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698