File: KeyboardEventManager.cpp

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (464 lines) | stat: -rw-r--r-- 16,325 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "KeyboardEventManager.h"

#include "core/dom/DocumentUserGestureToken.h"
#include "core/dom/Element.h"
#include "core/editing/Editor.h"
#include "core/events/KeyboardEvent.h"
#include "core/html/HTMLDialogElement.h"
#include "core/input/EventHandler.h"
#include "core/input/EventHandlingUtil.h"
#include "core/input/InputDeviceCapabilities.h"
#include "core/input/ScrollManager.h"
#include "core/layout/LayoutObject.h"
#include "core/layout/LayoutTextControlSingleLine.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/page/ChromeClient.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
#include "core/page/SpatialNavigation.h"
#include "platform/KeyboardCodes.h"
#include "platform/UserGestureIndicator.h"
#include "platform/WindowsKeyboardCodes.h"
#include "public/platform/WebInputEvent.h"

#if OS(WIN)
#include <windows.h>
#elif OS(MACOSX)
#import <Carbon/Carbon.h>
#endif

namespace blink {

namespace {

#if OS(WIN)
static const unsigned short HIGHBITMASKSHORT = 0x8000;
#endif

const int kVKeyProcessKey = 229;

WebFocusType focusDirectionForKey(KeyboardEvent* event) {
  if (event->ctrlKey() || event->metaKey() || event->shiftKey())
    return WebFocusTypeNone;

  WebFocusType retVal = WebFocusTypeNone;
  if (event->key() == "ArrowDown")
    retVal = WebFocusTypeDown;
  else if (event->key() == "ArrowUp")
    retVal = WebFocusTypeUp;
  else if (event->key() == "ArrowLeft")
    retVal = WebFocusTypeLeft;
  else if (event->key() == "ArrowRight")
    retVal = WebFocusTypeRight;
  return retVal;
}

bool mapKeyCodeForScroll(int keyCode,
                         PlatformEvent::Modifiers modifiers,
                         ScrollDirection* scrollDirection,
                         ScrollGranularity* scrollGranularity) {
  if (modifiers & PlatformEvent::ShiftKey || modifiers & PlatformEvent::MetaKey)
    return false;

  if (modifiers & PlatformEvent::AltKey) {
    // Alt-Up/Down should behave like PageUp/Down on Mac.  (Note that Alt-keys
    // on other platforms are suppressed due to isSystemKey being set.)
    if (keyCode == VKEY_UP)
      keyCode = VKEY_PRIOR;
    else if (keyCode == VKEY_DOWN)
      keyCode = VKEY_NEXT;
    else
      return false;
  }

  if (modifiers & PlatformEvent::CtrlKey) {
    // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
    // key combinations which affect scrolling.
    if (keyCode != VKEY_HOME && keyCode != VKEY_END)
      return false;
  }

  switch (keyCode) {
    case VKEY_LEFT:
      *scrollDirection = ScrollLeftIgnoringWritingMode;
      *scrollGranularity = ScrollByLine;
      break;
    case VKEY_RIGHT:
      *scrollDirection = ScrollRightIgnoringWritingMode;
      *scrollGranularity = ScrollByLine;
      break;
    case VKEY_UP:
      *scrollDirection = ScrollUpIgnoringWritingMode;
      *scrollGranularity = ScrollByLine;
      break;
    case VKEY_DOWN:
      *scrollDirection = ScrollDownIgnoringWritingMode;
      *scrollGranularity = ScrollByLine;
      break;
    case VKEY_HOME:
      *scrollDirection = ScrollUpIgnoringWritingMode;
      *scrollGranularity = ScrollByDocument;
      break;
    case VKEY_END:
      *scrollDirection = ScrollDownIgnoringWritingMode;
      *scrollGranularity = ScrollByDocument;
      break;
    case VKEY_PRIOR:  // page up
      *scrollDirection = ScrollUpIgnoringWritingMode;
      *scrollGranularity = ScrollByPage;
      break;
    case VKEY_NEXT:  // page down
      *scrollDirection = ScrollDownIgnoringWritingMode;
      *scrollGranularity = ScrollByPage;
      break;
    default:
      return false;
  }

  return true;
}

}  // namespace

KeyboardEventManager::KeyboardEventManager(LocalFrame& frame,
                                           ScrollManager& scrollManager)
    : m_frame(frame), m_scrollManager(scrollManager) {}

DEFINE_TRACE(KeyboardEventManager) {
  visitor->trace(m_frame);
  visitor->trace(m_scrollManager);
}

bool KeyboardEventManager::handleAccessKey(const WebKeyboardEvent& evt) {
  // FIXME: Ignoring the state of Shift key is what neither IE nor Firefox do.
  // IE matches lower and upper case access keys regardless of Shift key state -
  // but if both upper and lower case variants are present in a document, the
  // correct element is matched based on Shift key state.  Firefox only matches
  // an access key if Shift is not pressed, and does that case-insensitively.
  DCHECK(!(kAccessKeyModifiers & WebInputEvent::ShiftKey));
  if ((evt.modifiers() & (WebKeyboardEvent::KeyModifiers &
                          ~WebInputEvent::ShiftKey)) != kAccessKeyModifiers)
    return false;
  String key = String(evt.unmodifiedText);
  Element* elem = m_frame->document()->getElementByAccessKey(key.lower());
  if (!elem)
    return false;
  elem->accessKeyAction(false);
  return true;
}

WebInputEventResult KeyboardEventManager::keyEvent(
    const WebKeyboardEvent& initialKeyEvent) {
  m_frame->chromeClient().clearToolTip(*m_frame);

  if (initialKeyEvent.windowsKeyCode == VK_CAPITAL)
    capsLockStateMayHaveChanged();

  if (m_scrollManager->middleClickAutoscrollInProgress()) {
    DCHECK(RuntimeEnabledFeatures::middleClickAutoscrollEnabled());
    // If a key is pressed while the middleClickAutoscroll is in progress then
    // we want to stop.
    if (initialKeyEvent.type() == WebInputEvent::KeyDown ||
        initialKeyEvent.type() == WebInputEvent::RawKeyDown)
      m_scrollManager->stopAutoscroll();

    // If we were in panscroll mode, we swallow the key event
    return WebInputEventResult::HandledSuppressed;
  }

  // Check for cases where we are too early for events -- possible unmatched key
  // up from pressing return in the location bar.
  Node* node = eventTargetNodeForDocument(m_frame->document());
  if (!node)
    return WebInputEventResult::NotHandled;

  UserGestureIndicator gestureIndicator(
      DocumentUserGestureToken::create(m_frame->document()));

  // In IE, access keys are special, they are handled after default keydown
  // processing, but cannot be canceled - this is hard to match.  On Mac OS X,
  // we process them before dispatching keydown, as the default keydown handler
  // implements Emacs key bindings, which may conflict with access keys. Then we
  // dispatch keydown, but suppress its default handling.
  // On Windows, WebKit explicitly calls handleAccessKey() instead of
  // dispatching a keypress event for WM_SYSCHAR messages.  Other platforms
  // currently match either Mac or Windows behavior, depending on whether they
  // send combined KeyDown events.
  bool matchedAnAccessKey = false;
  if (initialKeyEvent.type() == WebInputEvent::KeyDown)
    matchedAnAccessKey = handleAccessKey(initialKeyEvent);

  // FIXME: it would be fair to let an input method handle KeyUp events before
  // DOM dispatch.
  if (initialKeyEvent.type() == WebInputEvent::KeyUp ||
      initialKeyEvent.type() == WebInputEvent::Char) {
    KeyboardEvent* domEvent = KeyboardEvent::create(
        initialKeyEvent, m_frame->document()->domWindow());

    return EventHandlingUtil::toWebInputEventResult(
        node->dispatchEvent(domEvent));
  }

  WebKeyboardEvent keyDownEvent = initialKeyEvent;
  if (keyDownEvent.type() != WebInputEvent::RawKeyDown)
    keyDownEvent.setType(WebInputEvent::RawKeyDown);
  KeyboardEvent* keydown =
      KeyboardEvent::create(keyDownEvent, m_frame->document()->domWindow());
  if (matchedAnAccessKey)
    keydown->setDefaultPrevented(true);
  keydown->setTarget(node);

  DispatchEventResult dispatchResult = node->dispatchEvent(keydown);
  if (dispatchResult != DispatchEventResult::NotCanceled)
    return EventHandlingUtil::toWebInputEventResult(dispatchResult);
  // If frame changed as a result of keydown dispatch, then return early to
  // avoid sending a subsequent keypress message to the new frame.
  bool changedFocusedFrame =
      m_frame->page() &&
      m_frame != m_frame->page()->focusController().focusedOrMainFrame();
  if (changedFocusedFrame)
    return WebInputEventResult::HandledSystem;

  if (initialKeyEvent.type() == WebInputEvent::RawKeyDown)
    return WebInputEventResult::NotHandled;

  // Focus may have changed during keydown handling, so refetch node.
  // But if we are dispatching a fake backward compatibility keypress, then we
  // pretend that the keypress happened on the original node.
  node = eventTargetNodeForDocument(m_frame->document());
  if (!node)
    return WebInputEventResult::NotHandled;

#if OS(MACOSX)
  // According to NSEvents.h, OpenStep reserves the range 0xF700-0xF8FF for
  // function keys. However, some actual private use characters happen to be
  // in this range, e.g. the Apple logo (Option+Shift+K). 0xF7FF is an
  // arbitrary cut-off.
  if (initialKeyEvent.text[0U] >= 0xF700 &&
      initialKeyEvent.text[0U] <= 0xF7FF) {
    return WebInputEventResult::NotHandled;
  }
#endif

  WebKeyboardEvent keyPressEvent = initialKeyEvent;
  keyPressEvent.setType(WebInputEvent::Char);
  if (keyPressEvent.text[0] == 0)
    return WebInputEventResult::NotHandled;
  KeyboardEvent* keypress =
      KeyboardEvent::create(keyPressEvent, m_frame->document()->domWindow());
  keypress->setTarget(node);
  return EventHandlingUtil::toWebInputEventResult(
      node->dispatchEvent(keypress));
}

void KeyboardEventManager::capsLockStateMayHaveChanged() {
  if (Element* element = m_frame->document()->focusedElement()) {
    if (LayoutObject* r = element->layoutObject()) {
      if (r->isTextField())
        toLayoutTextControlSingleLine(r)->capsLockStateMayHaveChanged();
    }
  }
}

void KeyboardEventManager::defaultKeyboardEventHandler(
    KeyboardEvent* event,
    Node* possibleFocusedNode) {
  if (event->type() == EventTypeNames::keydown) {
    m_frame->editor().handleKeyboardEvent(event);
    if (event->defaultHandled())
      return;

    // Do not perform the default action when inside a IME composition context.
    // TODO(dtapuska): Replace this with isComposing support. crbug.com/625686
    if (event->keyCode() == kVKeyProcessKey)
      return;
    if (event->key() == "Tab") {
      defaultTabEventHandler(event);
    } else if (event->key() == "Backspace") {
      defaultBackspaceEventHandler(event);
    } else if (event->key() == "Escape") {
      defaultEscapeEventHandler(event);
    } else {
      defaultArrowEventHandler(event, possibleFocusedNode);
    }
  }
  if (event->type() == EventTypeNames::keypress) {
    m_frame->editor().handleKeyboardEvent(event);
    if (event->defaultHandled())
      return;
    if (event->charCode() == ' ')
      defaultSpaceEventHandler(event, possibleFocusedNode);
  }
}

void KeyboardEventManager::defaultSpaceEventHandler(KeyboardEvent* event,
                                                    Node* possibleFocusedNode) {
  DCHECK_EQ(event->type(), EventTypeNames::keypress);

  if (event->ctrlKey() || event->metaKey() || event->altKey())
    return;

  ScrollDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward
                                                : ScrollBlockDirectionForward;

  // FIXME: enable scroll customization in this case. See crbug.com/410974.
  if (m_scrollManager->logicalScroll(direction, ScrollByPage, nullptr,
                                     possibleFocusedNode)) {
    event->setDefaultHandled();
    return;
  }
}

void KeyboardEventManager::defaultBackspaceEventHandler(KeyboardEvent* event) {
  DCHECK_EQ(event->type(), EventTypeNames::keydown);

  if (!RuntimeEnabledFeatures::backspaceDefaultHandlerEnabled())
    return;

  if (event->ctrlKey() || event->metaKey() || event->altKey())
    return;

  if (!m_frame->editor().behavior().shouldNavigateBackOnBackspace())
    return;
  UseCounter::count(m_frame->document(), UseCounter::BackspaceNavigatedBack);
  if (m_frame->page()->chromeClient().hadFormInteraction())
    UseCounter::count(m_frame->document(),
                      UseCounter::BackspaceNavigatedBackAfterFormInteraction);
  bool handledEvent = m_frame->loader().client()->navigateBackForward(
      event->shiftKey() ? 1 : -1);
  if (handledEvent)
    event->setDefaultHandled();
}

void KeyboardEventManager::defaultArrowEventHandler(KeyboardEvent* event,
                                                    Node* possibleFocusedNode) {
  DCHECK_EQ(event->type(), EventTypeNames::keydown);

  Page* page = m_frame->page();
  if (!page)
    return;

  WebFocusType type = focusDirectionForKey(event);
  if (type != WebFocusTypeNone && isSpatialNavigationEnabled(m_frame) &&
      !m_frame->document()->inDesignMode()) {
    if (page->focusController().advanceFocus(type)) {
      event->setDefaultHandled();
      return;
    }
  }

  if (event->keyEvent() && event->keyEvent()->isSystemKey)
    return;

  ScrollDirection scrollDirection;
  ScrollGranularity scrollGranularity;
  if (!mapKeyCodeForScroll(event->keyCode(), event->modifiers(),
                           &scrollDirection, &scrollGranularity))
    return;

  if (m_scrollManager->bubblingScroll(scrollDirection, scrollGranularity,
                                      nullptr, possibleFocusedNode)) {
    event->setDefaultHandled();
    return;
  }
}

void KeyboardEventManager::defaultTabEventHandler(KeyboardEvent* event) {
  DCHECK_EQ(event->type(), EventTypeNames::keydown);

  // We should only advance focus on tabs if no special modifier keys are held
  // down.
  if (event->ctrlKey() || event->metaKey())
    return;

#if !OS(MACOSX)
  // Option-Tab is a shortcut based on a system-wide preference on Mac but
  // should be ignored on all other platforms.
  if (event->altKey())
    return;
#endif

  Page* page = m_frame->page();
  if (!page)
    return;
  if (!page->tabKeyCyclesThroughElements())
    return;

  WebFocusType focusType =
      event->shiftKey() ? WebFocusTypeBackward : WebFocusTypeForward;

  // Tabs can be used in design mode editing.
  if (m_frame->document()->inDesignMode())
    return;

  if (page->focusController().advanceFocus(focusType,
                                           m_frame->document()
                                               ->domWindow()
                                               ->getInputDeviceCapabilities()
                                               ->firesTouchEvents(false)))
    event->setDefaultHandled();
}

void KeyboardEventManager::defaultEscapeEventHandler(KeyboardEvent* event) {
  if (HTMLDialogElement* dialog = m_frame->document()->activeModalDialog())
    dialog->dispatchEvent(Event::createCancelable(EventTypeNames::cancel));
}

static OverrideCapsLockState s_overrideCapsLockState;

void KeyboardEventManager::setCurrentCapsLockState(
    OverrideCapsLockState state) {
  s_overrideCapsLockState = state;
}

bool KeyboardEventManager::currentCapsLockState() {
  switch (s_overrideCapsLockState) {
    case OverrideCapsLockState::Default:
#if OS(WIN)
      // FIXME: Does this even work inside the sandbox?
      return GetKeyState(VK_CAPITAL) & 1;
#elif OS(MACOSX)
      return GetCurrentKeyModifiers() & alphaLock;
#else
      NOTIMPLEMENTED();
      return false;
#endif
    case OverrideCapsLockState::On:
      return true;
    case OverrideCapsLockState::Off:
    default:
      return false;
  }
}

WebInputEvent::Modifiers KeyboardEventManager::getCurrentModifierState() {
  unsigned modifiers = 0;
#if OS(WIN)
  if (GetKeyState(VK_SHIFT) & HIGHBITMASKSHORT)
    modifiers |= WebInputEvent::ShiftKey;
  if (GetKeyState(VK_CONTROL) & HIGHBITMASKSHORT)
    modifiers |= WebInputEvent::ControlKey;
  if (GetKeyState(VK_MENU) & HIGHBITMASKSHORT)
    modifiers |= WebInputEvent::AltKey;
#elif OS(MACOSX)
  UInt32 currentModifiers = GetCurrentKeyModifiers();
  if (currentModifiers & ::shiftKey)
    modifiers |= WebInputEvent::ShiftKey;
  if (currentModifiers & ::controlKey)
    modifiers |= WebInputEvent::ControlKey;
  if (currentModifiers & ::optionKey)
    modifiers |= WebInputEvent::AltKey;
  if (currentModifiers & ::cmdKey)
    modifiers |= WebInputEvent::MetaKey;
#else
  // TODO(crbug.com/538289): Implement on other platforms.
  return static_cast<WebInputEvent::Modifiers>(0);
#endif
  return static_cast<WebInputEvent::Modifiers>(modifiers);
}

}  // namespace blink