Bug 1885565 - Part 2: Fix up parameter ordering and kDoc descriptions in NavigationBa...
[gecko.git] / widget / TextEvents.h
blob71d2e656e2f28b094370c592c297ebb99983f101
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef mozilla_TextEvents_h__
7 #define mozilla_TextEvents_h__
9 #include <stdint.h>
11 #include "mozilla/Assertions.h"
12 #include "mozilla/BasicEvents.h"
13 #include "mozilla/CheckedInt.h"
14 #include "mozilla/EventForwards.h" // for KeyNameIndex, temporarily
15 #include "mozilla/FontRange.h"
16 #include "mozilla/Maybe.h"
17 #include "mozilla/NativeKeyBindingsType.h"
18 #include "mozilla/OwningNonNull.h"
19 #include "mozilla/TextRange.h"
20 #include "mozilla/WritingModes.h"
21 #include "mozilla/dom/DataTransfer.h"
22 #include "mozilla/dom/KeyboardEventBinding.h"
23 #include "mozilla/dom/StaticRange.h"
24 #include "mozilla/widget/IMEData.h"
25 #include "mozilla/ipc/IPCForwards.h"
26 #include "nsCOMPtr.h"
27 #include "nsHashtablesFwd.h"
28 #include "nsISelectionListener.h"
29 #include "nsITransferable.h"
30 #include "nsRect.h"
31 #include "nsString.h"
32 #include "nsTArray.h"
34 class nsStringHashKey;
36 /******************************************************************************
37 * virtual keycode values
38 ******************************************************************************/
40 enum {
41 #define NS_DEFINE_VK(aDOMKeyName, aDOMKeyCode) NS_##aDOMKeyName = aDOMKeyCode,
42 #include "mozilla/VirtualKeyCodeList.h"
43 #undef NS_DEFINE_VK
44 NS_VK_UNKNOWN = 0xFF
47 namespace mozilla {
49 enum : uint32_t {
50 eKeyLocationStandard = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_STANDARD,
51 eKeyLocationLeft = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_LEFT,
52 eKeyLocationRight = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_RIGHT,
53 eKeyLocationNumpad = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_NUMPAD
56 const nsCString GetDOMKeyCodeName(uint32_t aKeyCode);
58 namespace dom {
59 class PBrowserParent;
60 class PBrowserChild;
61 } // namespace dom
62 namespace plugins {
63 class PPluginInstanceChild;
64 } // namespace plugins
66 enum class AccessKeyType {
67 // Handle access key for chrome.
68 eChrome,
69 // Handle access key for content.
70 eContent,
71 // Don't handle access key.
72 eNone
75 /******************************************************************************
76 * mozilla::AlternativeCharCode
78 * This stores alternative charCode values of a key event with some modifiers.
79 * The stored values proper for testing shortcut key or access key.
80 ******************************************************************************/
82 struct AlternativeCharCode {
83 AlternativeCharCode() = default;
84 AlternativeCharCode(uint32_t aUnshiftedCharCode, uint32_t aShiftedCharCode)
85 : mUnshiftedCharCode(aUnshiftedCharCode),
86 mShiftedCharCode(aShiftedCharCode) {}
88 uint32_t mUnshiftedCharCode = 0u;
89 uint32_t mShiftedCharCode = 0u;
91 bool operator==(const AlternativeCharCode& aOther) const {
92 return mUnshiftedCharCode == aOther.mUnshiftedCharCode &&
93 mShiftedCharCode == aOther.mShiftedCharCode;
95 bool operator!=(const AlternativeCharCode& aOther) const {
96 return !(*this == aOther);
100 /******************************************************************************
101 * mozilla::ShortcutKeyCandidate
103 * This stores a candidate of shortcut key combination.
104 ******************************************************************************/
106 struct ShortcutKeyCandidate {
107 enum class ShiftState : bool {
108 // Can ignore `Shift` modifier state when comparing the key combination.
109 // E.g., Ctrl + Shift + `:` in the US keyboard layout may match with
110 // Ctrl + `:` shortcut.
111 Ignorable,
112 // `Shift` modifier state should be respected. I.e., Ctrl + `;` in the US
113 // keyboard layout never matches with Ctrl + Shift + `;` shortcut.
114 MatchExactly,
117 enum class SkipIfEarlierHandlerDisabled : bool {
118 // Even if an earlier handler is disabled, this may match with another
119 // handler for avoiding inaccessible shortcut with the active keyboard
120 // layout.
122 // If an earlier handler (i.e., preferred handler) is disabled, this should
123 // not try to match. E.g., Ctrl + `-` in the French keyboard layout when
124 // the zoom level is the minimum value, it should not match with Ctrl + `6`
125 // shortcut (French keyboard layout introduces `-` when pressing Digit6 key
126 // without Shift, and Shift + Digit6 introduces `6`).
127 Yes,
130 ShortcutKeyCandidate() = default;
131 ShortcutKeyCandidate(
132 uint32_t aCharCode, ShiftState aShiftState,
133 SkipIfEarlierHandlerDisabled aSkipIfEarlierHandlerDisabled)
134 : mCharCode(aCharCode),
135 mShiftState(aShiftState),
136 mSkipIfEarlierHandlerDisabled(aSkipIfEarlierHandlerDisabled) {}
138 // The mCharCode value which must match keyboard shortcut definition.
139 uint32_t mCharCode = 0;
141 ShiftState mShiftState = ShiftState::MatchExactly;
142 SkipIfEarlierHandlerDisabled mSkipIfEarlierHandlerDisabled =
143 SkipIfEarlierHandlerDisabled::No;
146 /******************************************************************************
147 * mozilla::IgnoreModifierState
149 * This stores flags for modifiers that should be ignored when matching
150 * XBL handlers.
151 ******************************************************************************/
153 struct IgnoreModifierState {
154 // When mShift is true, Shift key state will be ignored.
155 bool mShift;
156 // When mMeta is true, Meta key state will be ignored.
157 bool mMeta;
159 IgnoreModifierState() : mShift(false), mMeta(false) {}
162 /******************************************************************************
163 * mozilla::WidgetKeyboardEvent
164 ******************************************************************************/
166 class WidgetKeyboardEvent final : public WidgetInputEvent {
167 private:
168 friend class dom::PBrowserParent;
169 friend class dom::PBrowserChild;
170 friend struct IPC::ParamTraits<WidgetKeyboardEvent>;
171 ALLOW_DEPRECATED_READPARAM
173 protected:
174 WidgetKeyboardEvent()
175 : mNativeKeyEvent(nullptr),
176 mKeyCode(0),
177 mCharCode(0),
178 mPseudoCharCode(0),
179 mLocation(eKeyLocationStandard),
180 mUniqueId(0),
181 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
182 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
183 mIsRepeat(false),
184 mIsComposing(false),
185 mIsSynthesizedByTIP(false),
186 mMaybeSkippableInRemoteProcess(true),
187 mUseLegacyKeyCodeAndCharCodeValues(false),
188 mEditCommandsForSingleLineEditorInitialized(false),
189 mEditCommandsForMultiLineEditorInitialized(false),
190 mEditCommandsForRichTextEditorInitialized(false) {}
192 public:
193 WidgetKeyboardEvent* AsKeyboardEvent() override { return this; }
195 WidgetKeyboardEvent(bool aIsTrusted, EventMessage aMessage,
196 nsIWidget* aWidget,
197 EventClassID aEventClassID = eKeyboardEventClass,
198 const WidgetEventTime* aTime = nullptr)
199 : WidgetInputEvent(aIsTrusted, aMessage, aWidget, aEventClassID, aTime),
200 mNativeKeyEvent(nullptr),
201 mKeyCode(0),
202 mCharCode(0),
203 mPseudoCharCode(0),
204 mLocation(eKeyLocationStandard),
205 mUniqueId(0),
206 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
207 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
208 mIsRepeat(false),
209 mIsComposing(false),
210 mIsSynthesizedByTIP(false),
211 mMaybeSkippableInRemoteProcess(true),
212 mUseLegacyKeyCodeAndCharCodeValues(false),
213 mEditCommandsForSingleLineEditorInitialized(false),
214 mEditCommandsForMultiLineEditorInitialized(false),
215 mEditCommandsForRichTextEditorInitialized(false) {}
217 // IsInputtingText() and IsInputtingLineBreak() are used to check if
218 // it should cause eKeyPress events even on web content.
219 // UI Events defines that "keypress" event should be fired "if and only if
220 // that key normally produces a character value".
221 // <https://www.w3.org/TR/uievents/#event-type-keypress>
222 // Additionally, for backward compatiblity with all existing browsers,
223 // there is a spec issue for Enter key press.
224 // <https://github.com/w3c/uievents/issues/183>
225 bool IsInputtingText() const {
226 // NOTE: On some keyboard layout, some characters are inputted with Control
227 // key or Alt key, but at that time, widget clears the modifier flag
228 // from eKeyPress event because our TextEditor won't handle eKeyPress
229 // events as inputting text (bug 1346832).
230 // NOTE: There are some complicated issues of our traditional behavior.
231 // -- On Windows, KeyboardLayout::WillDispatchKeyboardEvent() clears
232 // MODIFIER_ALT and MODIFIER_CONTROL of eKeyPress event if it
233 // should be treated as inputting a character because AltGr is
234 // represented with both Alt key and Ctrl key are pressed, and
235 // some keyboard layouts may produces a character with Ctrl key.
236 // -- On Linux, KeymapWrapper doesn't have this hack since perhaps,
237 // we don't have any bug reports that user cannot input proper
238 // character with Alt and/or Ctrl key.
239 // -- On macOS, IMEInputHandler::WillDispatchKeyboardEvent() clears
240 // MODIFIER_ALT and MDOFIEIR_CONTROL of eKeyPress event only when
241 // TextInputHandler::InsertText() has been called for the event.
242 // I.e., they are cleared only when an editor has focus (even if IME
243 // is disabled in password field or by |ime-mode: disabled;|) because
244 // TextInputHandler::InsertText() is called while
245 // TextInputHandler::HandleKeyDownEvent() calls interpretKeyEvents:
246 // to notify text input processor of Cocoa (including IME). In other
247 // words, when we need to disable IME completey when no editor has
248 // focus, we cannot call interpretKeyEvents:. So,
249 // TextInputHandler::InsertText() won't be called when no editor has
250 // focus so that neither MODIFIER_ALT nor MODIFIER_CONTROL is
251 // cleared. So, fortunately, altKey and ctrlKey values of "keypress"
252 // events are same as the other browsers only when no editor has
253 // focus.
254 // NOTE: As mentioned above, for compatibility with the other browsers on
255 // macOS, we should keep MODIFIER_ALT and MODIFIER_CONTROL flags of
256 // eKeyPress events when no editor has focus. However, Alt key,
257 // labeled "option" on keyboard for Mac, is AltGraph key on the other
258 // platforms. So, even if MODIFIER_ALT is set, we need to dispatch
259 // eKeyPress event even on web content unless mCharCode is 0.
260 // Therefore, we need to ignore MODIFIER_ALT flag here only on macOS.
261 return mMessage == eKeyPress && mCharCode &&
262 !(mModifiers & (
263 #ifndef XP_MACOSX
264 // So, ignore MODIFIER_ALT only on macOS since
265 // option key is used as AltGraph key on macOS.
266 MODIFIER_ALT |
267 #endif // #ifndef XP_MAXOSX
268 MODIFIER_CONTROL | MODIFIER_META));
271 bool IsInputtingLineBreak() const {
272 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
273 !(mModifiers & (MODIFIER_ALT | MODIFIER_CONTROL | MODIFIER_META));
277 * ShouldKeyPressEventBeFiredOnContent() should be called only when the
278 * instance is eKeyPress event. This returns true when the eKeyPress
279 * event should be fired even on content in the default event group.
281 bool ShouldKeyPressEventBeFiredOnContent() const {
282 MOZ_DIAGNOSTIC_ASSERT(mMessage == eKeyPress);
283 if (IsInputtingText() || IsInputtingLineBreak()) {
284 return true;
286 // Ctrl + Enter won't cause actual input in our editor.
287 // However, the other browsers fire keypress event in any platforms.
288 // So, for compatibility with them, we should fire keypress event for
289 // Ctrl + Enter too.
290 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
291 !(mModifiers & (MODIFIER_ALT | MODIFIER_META | MODIFIER_SHIFT));
294 WidgetEvent* Duplicate() const override {
295 MOZ_ASSERT(mClass == eKeyboardEventClass,
296 "Duplicate() must be overridden by sub class");
297 // Not copying widget, it is a weak reference.
298 WidgetKeyboardEvent* result = new WidgetKeyboardEvent(
299 false, mMessage, nullptr, eKeyboardEventClass, this);
300 result->AssignKeyEventData(*this, true);
301 result->mEditCommandsForSingleLineEditor =
302 mEditCommandsForSingleLineEditor.Clone();
303 result->mEditCommandsForMultiLineEditor =
304 mEditCommandsForMultiLineEditor.Clone();
305 result->mEditCommandsForRichTextEditor =
306 mEditCommandsForRichTextEditor.Clone();
307 result->mFlags = mFlags;
308 return result;
311 bool CanUserGestureActivateTarget() const {
312 // Printable keys, 'carriage return' and 'space' are supported user gestures
313 // for activating the document. However, if supported key is being pressed
314 // combining with other operation keys, such like alt, control ..etc., we
315 // won't activate the target for them because at that time user might
316 // interact with browser or window manager which doesn't necessarily
317 // demonstrate user's intent to play media.
318 const bool isCombiningWithOperationKeys = (IsControl() && !IsAltGraph()) ||
319 (IsAlt() && !IsAltGraph()) ||
320 IsMeta();
321 const bool isEnterOrSpaceKey =
322 mKeyNameIndex == KEY_NAME_INDEX_Enter || mKeyCode == NS_VK_SPACE;
323 return (PseudoCharCode() || isEnterOrSpaceKey) &&
324 (!isCombiningWithOperationKeys ||
325 // ctrl-c/ctrl-x/ctrl-v is quite common shortcut for clipboard
326 // operation.
327 // XXXedgar, we have to find a better way to handle browser keyboard
328 // shortcut for user activation, instead of just ignoring all
329 // combinations, see bug 1641171.
330 ((mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_C ||
331 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_V ||
332 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_X) &&
333 IsAccel()));
336 // Returns true if this event is likely an user activation for a link or
337 // a link-like button, where modifier keys are likely be used for controlling
338 // where the link is opened.
340 // This returns false if the keyboard event is more likely an user-defined
341 // shortcut key.
342 bool CanReflectModifiersToUserActivation() const {
343 MOZ_ASSERT(CanUserGestureActivateTarget(),
344 "Consumer should check CanUserGestureActivateTarget first");
345 // 'carriage return' and 'space' are supported user gestures for activating
346 // a link or a button.
347 // A button often behaves like a link, by calling window.open inside its
348 // event handler.
350 // Access keys can also activate links/buttons, but access keys have their
351 // own modifiers, and those modifiers are not appropriate for reflecting to
352 // the user activation nor controlling where the link is opened.
353 return mKeyNameIndex == KEY_NAME_INDEX_Enter || mKeyCode == NS_VK_SPACE;
356 [[nodiscard]] bool ShouldWorkAsSpaceKey() const {
357 if (mKeyCode == NS_VK_SPACE) {
358 return true;
360 // Additionally, if the code value is "Space" and the key is not mapped to
361 // a function key (i.e., not a printable key), we should treat it as space
362 // key because the active keyboard layout may input different character
363 // from the ASCII white space (U+0020). For example, NBSP (U+00A0).
364 return mKeyNameIndex == KEY_NAME_INDEX_USE_STRING &&
365 mCodeNameIndex == CODE_NAME_INDEX_Space;
369 * CanTreatAsUserInput() returns true if the key is pressed for perhaps
370 * doing something on the web app or our UI. This means that when this
371 * returns false, e.g., when user presses a modifier key, user is probably
372 * displeased by opening popup, entering fullscreen mode, etc. Therefore,
373 * only when this returns true, such reactions should be allowed.
375 bool CanTreatAsUserInput() const {
376 if (!IsTrusted()) {
377 return false;
379 switch (mKeyNameIndex) {
380 case KEY_NAME_INDEX_Escape:
381 // modifier keys:
382 case KEY_NAME_INDEX_Alt:
383 case KEY_NAME_INDEX_AltGraph:
384 case KEY_NAME_INDEX_CapsLock:
385 case KEY_NAME_INDEX_Control:
386 case KEY_NAME_INDEX_Fn:
387 case KEY_NAME_INDEX_FnLock:
388 case KEY_NAME_INDEX_Meta:
389 case KEY_NAME_INDEX_NumLock:
390 case KEY_NAME_INDEX_ScrollLock:
391 case KEY_NAME_INDEX_Shift:
392 case KEY_NAME_INDEX_Symbol:
393 case KEY_NAME_INDEX_SymbolLock:
394 // legacy modifier keys:
395 case KEY_NAME_INDEX_Hyper:
396 case KEY_NAME_INDEX_Super:
397 return false;
398 default:
399 return true;
404 * ShouldInteractionTimeRecorded() returns true if the handling time of
405 * the event should be recorded with the telemetry.
407 bool ShouldInteractionTimeRecorded() const {
408 // Let's record only when we can treat the instance is a user input.
409 return CanTreatAsUserInput();
412 // OS translated Unicode chars which are used for accesskey and accelkey
413 // handling. The handlers will try from first character to last character.
414 CopyableTArray<AlternativeCharCode> mAlternativeCharCodes;
415 // DOM KeyboardEvent.key only when mKeyNameIndex is KEY_NAME_INDEX_USE_STRING.
416 nsString mKeyValue;
417 // DOM KeyboardEvent.code only when mCodeNameIndex is
418 // CODE_NAME_INDEX_USE_STRING.
419 nsString mCodeValue;
421 // OS-specific native event can optionally be preserved.
422 // This is used to retrieve editing shortcut keys in the environment.
423 void* mNativeKeyEvent;
424 // A DOM keyCode value or 0. If a keypress event whose mCharCode is 0, this
425 // should be 0.
426 uint32_t mKeyCode;
427 // If the instance is a keypress event of a printable key, this is a UTF-16
428 // value of the key. Otherwise, 0. This value must not be a control
429 // character when some modifiers are active. Then, this value should be an
430 // unmodified value except Shift and AltGr.
431 uint32_t mCharCode;
432 // mPseudoCharCode is valid only when mMessage is an eKeyDown event.
433 // This stores mCharCode value of keypress event which is fired with same
434 // key value and same modifier state.
435 uint32_t mPseudoCharCode;
436 // One of eKeyLocation*
437 uint32_t mLocation;
438 // Unique id associated with a keydown / keypress event. It's ok if this wraps
439 // over long periods.
440 uint32_t mUniqueId;
442 // DOM KeyboardEvent.key
443 KeyNameIndex mKeyNameIndex;
444 // DOM KeyboardEvent.code
445 CodeNameIndex mCodeNameIndex;
447 // Indicates whether the event is generated by auto repeat or not.
448 // if this is keyup event, always false.
449 bool mIsRepeat;
450 // Indicates whether the event is generated during IME (or deadkey)
451 // composition. This is initialized by EventStateManager. So, key event
452 // dispatchers don't need to initialize this.
453 bool mIsComposing;
454 // Indicates whether the event is synthesized from Text Input Processor
455 // or an actual event from nsAppShell.
456 bool mIsSynthesizedByTIP;
457 // Indicates whether the event is skippable in remote process.
458 // Don't refer this member directly when you need to check this.
459 // Use CanSkipInRemoteProcess() instead.
460 bool mMaybeSkippableInRemoteProcess;
461 // Indicates whether the event should return legacy keyCode value and
462 // charCode value to web apps (one of them is always 0) or not, when it's
463 // an eKeyPress event.
464 bool mUseLegacyKeyCodeAndCharCodeValues;
466 bool CanSkipInRemoteProcess() const {
467 // If this is a repeat event (i.e., generated by auto-repeat feature of
468 // the platform), remove process may skip to handle it because of
469 // performances reasons.. However, if it's caused by odd keyboard utils,
470 // we should not ignore any key events even marked as repeated since
471 // generated key sequence may be important to input proper text. E.g.,
472 // "SinhalaTamil IME" on Windows emulates dead key like input with
473 // generating WM_KEYDOWN for VK_PACKET (inputting any Unicode characters
474 // without keyboard layout information) and VK_BACK (Backspace) to remove
475 // previous character(s) and those messages may be marked as "repeat" by
476 // their bug.
477 return mIsRepeat && mMaybeSkippableInRemoteProcess;
481 * If the key is an arrow key, and the current selection is in a vertical
482 * content, the caret should be moved to physically. However, arrow keys
483 * are mapped to logical move commands in horizontal content. Therefore,
484 * we need to check writing mode if and only if the key is an arrow key, and
485 * need to remap the command to logical command in vertical content if the
486 * writing mode at selection is vertical. These methods help to convert
487 * arrow keys in horizontal content to correspnding direction arrow keys
488 * in vertical content.
490 bool NeedsToRemapNavigationKey() const {
491 // TODO: Use mKeyNameIndex instead.
492 return mKeyCode >= NS_VK_LEFT && mKeyCode <= NS_VK_DOWN;
495 uint32_t GetRemappedKeyCode(const WritingMode& aWritingMode) const {
496 if (!aWritingMode.IsVertical()) {
497 return mKeyCode;
499 switch (mKeyCode) {
500 case NS_VK_LEFT:
501 return aWritingMode.IsVerticalLR() ? NS_VK_UP : NS_VK_DOWN;
502 case NS_VK_RIGHT:
503 return aWritingMode.IsVerticalLR() ? NS_VK_DOWN : NS_VK_UP;
504 case NS_VK_UP:
505 return NS_VK_LEFT;
506 case NS_VK_DOWN:
507 return NS_VK_RIGHT;
508 default:
509 return mKeyCode;
513 KeyNameIndex GetRemappedKeyNameIndex(const WritingMode& aWritingMode) const {
514 if (!aWritingMode.IsVertical()) {
515 return mKeyNameIndex;
517 uint32_t remappedKeyCode = GetRemappedKeyCode(aWritingMode);
518 if (remappedKeyCode == mKeyCode) {
519 return mKeyNameIndex;
521 switch (remappedKeyCode) {
522 case NS_VK_LEFT:
523 return KEY_NAME_INDEX_ArrowLeft;
524 case NS_VK_RIGHT:
525 return KEY_NAME_INDEX_ArrowRight;
526 case NS_VK_UP:
527 return KEY_NAME_INDEX_ArrowUp;
528 case NS_VK_DOWN:
529 return KEY_NAME_INDEX_ArrowDown;
530 default:
531 MOZ_ASSERT_UNREACHABLE("Add a case for the new remapped key");
532 return mKeyNameIndex;
537 * Retrieves all edit commands from mWidget. This shouldn't be called when
538 * the instance is an untrusted event, doesn't have widget or in non-chrome
539 * process.
541 * @param aWritingMode
542 * When writing mode of focused element is vertical, this
543 * will resolve some key's physical direction to logical
544 * direction. For doing it, this must be set to the
545 * writing mode at current selection. However, when there
546 * is no focused element and no selection ranges, this
547 * should be set to Nothing(). Using the result of
548 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
549 * is recommended.
551 MOZ_CAN_RUN_SCRIPT void InitAllEditCommands(
552 const Maybe<WritingMode>& aWritingMode);
555 * Retrieves edit commands from mWidget only for aType. This shouldn't be
556 * called when the instance is an untrusted event or doesn't have widget.
558 * @param aWritingMode
559 * When writing mode of focused element is vertical, this
560 * will resolve some key's physical direction to logical
561 * direction. For doing it, this must be set to the
562 * writing mode at current selection. However, when there
563 * is no focused element and no selection ranges, this
564 * should be set to Nothing(). Using the result of
565 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
566 * is recommended.
567 * @return false if some resource is not available to get
568 * commands unexpectedly. Otherwise, true even if
569 * retrieved command is nothing.
571 MOZ_CAN_RUN_SCRIPT bool InitEditCommandsFor(
572 NativeKeyBindingsType aType, const Maybe<WritingMode>& aWritingMode);
575 * PreventNativeKeyBindings() makes the instance to not cause any edit
576 * actions even if it matches with a native key binding.
578 void PreventNativeKeyBindings() {
579 mEditCommandsForSingleLineEditor.Clear();
580 mEditCommandsForMultiLineEditor.Clear();
581 mEditCommandsForRichTextEditor.Clear();
582 mEditCommandsForSingleLineEditorInitialized = true;
583 mEditCommandsForMultiLineEditorInitialized = true;
584 mEditCommandsForRichTextEditorInitialized = true;
588 * EditCommandsConstRef() returns reference to edit commands for aType.
590 const nsTArray<CommandInt>& EditCommandsConstRef(
591 NativeKeyBindingsType aType) const {
592 return const_cast<WidgetKeyboardEvent*>(this)->EditCommandsRef(aType);
596 * IsEditCommandsInitialized() returns true if edit commands for aType
597 * was already initialized. Otherwise, false.
599 bool IsEditCommandsInitialized(NativeKeyBindingsType aType) const {
600 return const_cast<WidgetKeyboardEvent*>(this)->IsEditCommandsInitializedRef(
601 aType);
605 * AreAllEditCommandsInitialized() returns true if edit commands for all
606 * types were already initialized. Otherwise, false.
608 bool AreAllEditCommandsInitialized() const {
609 return mEditCommandsForSingleLineEditorInitialized &&
610 mEditCommandsForMultiLineEditorInitialized &&
611 mEditCommandsForRichTextEditorInitialized;
615 * Execute edit commands for aType.
617 * @return true if the caller should do nothing anymore.
618 * false, otherwise.
620 typedef void (*DoCommandCallback)(Command, void*);
621 MOZ_CAN_RUN_SCRIPT bool ExecuteEditCommands(NativeKeyBindingsType aType,
622 DoCommandCallback aCallback,
623 void* aCallbackData);
625 // If the key should cause keypress events, this returns true.
626 // Otherwise, false.
627 bool ShouldCauseKeypressEvents() const;
629 // mCharCode value of non-eKeyPress events is always 0. However, if
630 // non-eKeyPress event has one or more alternative char code values,
631 // its first item should be the mCharCode value of following eKeyPress event.
632 // PseudoCharCode() returns mCharCode value for eKeyPress event,
633 // the first alternative char code value of non-eKeyPress event or 0.
634 uint32_t PseudoCharCode() const {
635 return mMessage == eKeyPress ? mCharCode : mPseudoCharCode;
637 void SetCharCode(uint32_t aCharCode) {
638 if (mMessage == eKeyPress) {
639 mCharCode = aCharCode;
640 } else {
641 mPseudoCharCode = aCharCode;
645 void GetDOMKeyName(nsAString& aKeyName) {
646 if (mKeyNameIndex == KEY_NAME_INDEX_USE_STRING) {
647 aKeyName = mKeyValue;
648 return;
650 GetDOMKeyName(mKeyNameIndex, aKeyName);
652 void GetDOMCodeName(nsAString& aCodeName) {
653 if (mCodeNameIndex == CODE_NAME_INDEX_USE_STRING) {
654 aCodeName = mCodeValue;
655 return;
657 GetDOMCodeName(mCodeNameIndex, aCodeName);
661 * GetFallbackKeyCodeOfPunctuationKey() returns a DOM keyCode value for
662 * aCodeNameIndex. This is keyCode value of the key when active keyboard
663 * layout is ANSI (US), JIS or ABNT keyboard layout (the latter 2 layouts
664 * are used only when ANSI doesn't have the key). The result is useful
665 * if the key doesn't produce ASCII character with active keyboard layout
666 * nor with alternative ASCII capable keyboard layout.
668 static uint32_t GetFallbackKeyCodeOfPunctuationKey(
669 CodeNameIndex aCodeNameIndex);
671 bool IsModifierKeyEvent() const {
672 return GetModifierForKeyName(mKeyNameIndex) != MODIFIER_NONE;
676 * Get the candidates for shortcut key.
678 * @param aCandidates [out] the candidate shortcut key combination list.
679 * the first item is most preferred.
681 void GetShortcutKeyCandidates(ShortcutKeyCandidateArray& aCandidates) const;
684 * Get the candidates for access key.
686 * @param aCandidates [out] the candidate access key list.
687 * the first item is most preferred.
689 void GetAccessKeyCandidates(nsTArray<uint32_t>& aCandidates) const;
692 * Check whether the modifiers match with chrome access key or
693 * content access key.
695 bool ModifiersMatchWithAccessKey(AccessKeyType aType) const;
698 * Return active modifiers which may match with access key.
699 * For example, even if Alt is access key modifier, then, when Control,
700 * CapseLock and NumLock are active, this returns only MODIFIER_CONTROL.
702 Modifiers ModifiersForAccessKeyMatching() const;
705 * Return access key modifiers.
707 static Modifiers AccessKeyModifiers(AccessKeyType aType);
709 static void Shutdown();
712 * ComputeLocationFromCodeValue() returns one of .mLocation value
713 * (eKeyLocation*) which is the most preferred value for the specified code
714 * value.
716 static uint32_t ComputeLocationFromCodeValue(CodeNameIndex aCodeNameIndex);
719 * ComputeKeyCodeFromKeyNameIndex() return a .mKeyCode value which can be
720 * mapped from the specified key value. Note that this returns 0 if the
721 * key name index is KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
722 * This means that this method is useful only for non-printable keys.
724 static uint32_t ComputeKeyCodeFromKeyNameIndex(KeyNameIndex aKeyNameIndex);
727 * ComputeCodeNameIndexFromKeyNameIndex() returns a code name index which
728 * is typically mapped to given key name index on the platform.
729 * Note that this returns CODE_NAME_INDEX_UNKNOWN if the key name index is
730 * KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
731 * This means that this method is useful only for non-printable keys.
733 * @param aKeyNameIndex A non-printable key name index.
734 * @param aLocation Should be one of location value. This is
735 * important when aKeyNameIndex may exist in
736 * both Numpad or Standard, or in both Left or
737 * Right. If this is nothing, this method
738 * returns Left or Standard position's code
739 * value.
741 static CodeNameIndex ComputeCodeNameIndexFromKeyNameIndex(
742 KeyNameIndex aKeyNameIndex, const Maybe<uint32_t>& aLocation);
745 * GetModifierForKeyName() returns a value of Modifier which is activated
746 * by the aKeyNameIndex.
748 static Modifier GetModifierForKeyName(KeyNameIndex aKeyNameIndex);
751 * IsLeftOrRightModiferKeyNameIndex() returns true if aKeyNameIndex is a
752 * modifier key which may be in Left and Right location.
754 static bool IsLeftOrRightModiferKeyNameIndex(KeyNameIndex aKeyNameIndex) {
755 switch (aKeyNameIndex) {
756 case KEY_NAME_INDEX_Alt:
757 case KEY_NAME_INDEX_Control:
758 case KEY_NAME_INDEX_Meta:
759 case KEY_NAME_INDEX_Shift:
760 return true;
761 default:
762 return false;
767 * IsLockableModifier() returns true if aKeyNameIndex is a lockable modifier
768 * key such as CapsLock and NumLock.
770 static bool IsLockableModifier(KeyNameIndex aKeyNameIndex);
772 static void GetDOMKeyName(KeyNameIndex aKeyNameIndex, nsAString& aKeyName);
773 static void GetDOMCodeName(CodeNameIndex aCodeNameIndex,
774 nsAString& aCodeName);
776 static KeyNameIndex GetKeyNameIndex(const nsAString& aKeyValue);
777 static CodeNameIndex GetCodeNameIndex(const nsAString& aCodeValue);
779 static const char* GetCommandStr(Command aCommand);
781 void AssignKeyEventData(const WidgetKeyboardEvent& aEvent,
782 bool aCopyTargets) {
783 AssignInputEventData(aEvent, aCopyTargets);
785 mKeyCode = aEvent.mKeyCode;
786 mCharCode = aEvent.mCharCode;
787 mPseudoCharCode = aEvent.mPseudoCharCode;
788 mLocation = aEvent.mLocation;
789 mAlternativeCharCodes = aEvent.mAlternativeCharCodes.Clone();
790 mIsRepeat = aEvent.mIsRepeat;
791 mIsComposing = aEvent.mIsComposing;
792 mKeyNameIndex = aEvent.mKeyNameIndex;
793 mCodeNameIndex = aEvent.mCodeNameIndex;
794 mKeyValue = aEvent.mKeyValue;
795 mCodeValue = aEvent.mCodeValue;
796 // Don't copy mNativeKeyEvent because it may be referred after its instance
797 // is destroyed.
798 mNativeKeyEvent = nullptr;
799 mUniqueId = aEvent.mUniqueId;
800 mIsSynthesizedByTIP = aEvent.mIsSynthesizedByTIP;
801 mMaybeSkippableInRemoteProcess = aEvent.mMaybeSkippableInRemoteProcess;
802 mUseLegacyKeyCodeAndCharCodeValues =
803 aEvent.mUseLegacyKeyCodeAndCharCodeValues;
805 // Don't copy mEditCommandsFor*Editor because it may require a lot of
806 // memory space. For example, if the event is dispatched but grabbed by
807 // a JS variable, they are not necessary anymore.
809 mEditCommandsForSingleLineEditorInitialized =
810 aEvent.mEditCommandsForSingleLineEditorInitialized;
811 mEditCommandsForMultiLineEditorInitialized =
812 aEvent.mEditCommandsForMultiLineEditorInitialized;
813 mEditCommandsForRichTextEditorInitialized =
814 aEvent.mEditCommandsForRichTextEditorInitialized;
817 void AssignCommands(const WidgetKeyboardEvent& aEvent) {
818 mEditCommandsForSingleLineEditorInitialized =
819 aEvent.mEditCommandsForSingleLineEditorInitialized;
820 if (mEditCommandsForSingleLineEditorInitialized) {
821 mEditCommandsForSingleLineEditor =
822 aEvent.mEditCommandsForSingleLineEditor.Clone();
823 } else {
824 mEditCommandsForSingleLineEditor.Clear();
826 mEditCommandsForMultiLineEditorInitialized =
827 aEvent.mEditCommandsForMultiLineEditorInitialized;
828 if (mEditCommandsForMultiLineEditorInitialized) {
829 mEditCommandsForMultiLineEditor =
830 aEvent.mEditCommandsForMultiLineEditor.Clone();
831 } else {
832 mEditCommandsForMultiLineEditor.Clear();
834 mEditCommandsForRichTextEditorInitialized =
835 aEvent.mEditCommandsForRichTextEditorInitialized;
836 if (mEditCommandsForRichTextEditorInitialized) {
837 mEditCommandsForRichTextEditor =
838 aEvent.mEditCommandsForRichTextEditor.Clone();
839 } else {
840 mEditCommandsForRichTextEditor.Clear();
844 private:
845 static const char16_t* const kKeyNames[];
846 static const char16_t* const kCodeNames[];
847 typedef nsTHashMap<nsStringHashKey, KeyNameIndex> KeyNameIndexHashtable;
848 typedef nsTHashMap<nsStringHashKey, CodeNameIndex> CodeNameIndexHashtable;
849 static KeyNameIndexHashtable* sKeyNameIndexHashtable;
850 static CodeNameIndexHashtable* sCodeNameIndexHashtable;
852 // mEditCommandsFor*Editor store edit commands. This should be initialized
853 // with InitEditCommandsFor().
854 // XXX Ideally, this should be array of Command rather than CommandInt.
855 // However, ParamTraits isn't aware of enum array.
856 CopyableTArray<CommandInt> mEditCommandsForSingleLineEditor;
857 CopyableTArray<CommandInt> mEditCommandsForMultiLineEditor;
858 CopyableTArray<CommandInt> mEditCommandsForRichTextEditor;
860 nsTArray<CommandInt>& EditCommandsRef(NativeKeyBindingsType aType) {
861 switch (aType) {
862 case NativeKeyBindingsType::SingleLineEditor:
863 return mEditCommandsForSingleLineEditor;
864 case NativeKeyBindingsType::MultiLineEditor:
865 return mEditCommandsForMultiLineEditor;
866 case NativeKeyBindingsType::RichTextEditor:
867 return mEditCommandsForRichTextEditor;
868 default:
869 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
870 "Invalid native key binding type");
874 // mEditCommandsFor*EditorInitialized are set to true when
875 // InitEditCommandsFor() initializes edit commands for the type.
876 bool mEditCommandsForSingleLineEditorInitialized;
877 bool mEditCommandsForMultiLineEditorInitialized;
878 bool mEditCommandsForRichTextEditorInitialized;
880 bool& IsEditCommandsInitializedRef(NativeKeyBindingsType aType) {
881 switch (aType) {
882 case NativeKeyBindingsType::SingleLineEditor:
883 return mEditCommandsForSingleLineEditorInitialized;
884 case NativeKeyBindingsType::MultiLineEditor:
885 return mEditCommandsForMultiLineEditorInitialized;
886 case NativeKeyBindingsType::RichTextEditor:
887 return mEditCommandsForRichTextEditorInitialized;
888 default:
889 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
890 "Invalid native key binding type");
895 /******************************************************************************
896 * mozilla::WidgetCompositionEvent
897 ******************************************************************************/
899 class WidgetCompositionEvent : public WidgetGUIEvent {
900 private:
901 friend class mozilla::dom::PBrowserParent;
902 friend class mozilla::dom::PBrowserChild;
903 ALLOW_DEPRECATED_READPARAM
905 WidgetCompositionEvent() : mOriginalMessage(eVoidEvent) {}
907 public:
908 virtual WidgetCompositionEvent* AsCompositionEvent() override { return this; }
910 WidgetCompositionEvent(bool aIsTrusted, EventMessage aMessage,
911 nsIWidget* aWidget,
912 const WidgetEventTime* aTime = nullptr)
913 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eCompositionEventClass,
914 aTime),
915 mNativeIMEContext(aWidget),
916 mOriginalMessage(eVoidEvent) {}
918 virtual WidgetEvent* Duplicate() const override {
919 MOZ_ASSERT(mClass == eCompositionEventClass,
920 "Duplicate() must be overridden by sub class");
921 // Not copying widget, it is a weak reference.
922 WidgetCompositionEvent* result =
923 new WidgetCompositionEvent(false, mMessage, nullptr, this);
924 result->AssignCompositionEventData(*this, true);
925 result->mFlags = mFlags;
926 return result;
929 // The composition string or the commit string. If the instance is a
930 // compositionstart event, this is initialized with selected text by
931 // TextComposition automatically.
932 nsString mData;
934 RefPtr<TextRangeArray> mRanges;
936 // mNativeIMEContext stores the native IME context which causes the
937 // composition event.
938 widget::NativeIMEContext mNativeIMEContext;
940 // If the instance is a clone of another event, mOriginalMessage stores
941 // the another event's mMessage.
942 EventMessage mOriginalMessage;
944 // Composition ID considered by TextComposition. If the event has not been
945 // handled by TextComposition yet, this is 0. And also if the event is for
946 // a composition synthesized in a content process, this is always 0.
947 uint32_t mCompositionId = 0;
949 void AssignCompositionEventData(const WidgetCompositionEvent& aEvent,
950 bool aCopyTargets) {
951 AssignGUIEventData(aEvent, aCopyTargets);
953 mData = aEvent.mData;
954 mOriginalMessage = aEvent.mOriginalMessage;
955 mRanges = aEvent.mRanges;
957 // Currently, we don't need to copy the other members because they are
958 // for internal use only (not available from JS).
961 bool IsComposing() const { return mRanges && mRanges->IsComposing(); }
963 uint32_t TargetClauseOffset() const {
964 return mRanges ? mRanges->TargetClauseOffset() : 0;
967 uint32_t TargetClauseLength() const {
968 uint32_t length = UINT32_MAX;
969 if (mRanges) {
970 length = mRanges->TargetClauseLength();
972 return length == UINT32_MAX ? mData.Length() : length;
975 uint32_t RangeCount() const { return mRanges ? mRanges->Length() : 0; }
977 bool CausesDOMTextEvent() const {
978 return mMessage == eCompositionChange || mMessage == eCompositionCommit ||
979 mMessage == eCompositionCommitAsIs;
982 bool CausesDOMCompositionEndEvent() const {
983 return mMessage == eCompositionEnd || mMessage == eCompositionCommit ||
984 mMessage == eCompositionCommitAsIs;
987 bool IsFollowedByCompositionEnd() const {
988 return IsFollowedByCompositionEnd(mOriginalMessage);
991 static bool IsFollowedByCompositionEnd(EventMessage aEventMessage) {
992 return aEventMessage == eCompositionCommit ||
993 aEventMessage == eCompositionCommitAsIs;
997 /******************************************************************************
998 * mozilla::WidgetQueryContentEvent
999 ******************************************************************************/
1001 class WidgetQueryContentEvent : public WidgetGUIEvent {
1002 private:
1003 friend class dom::PBrowserParent;
1004 friend class dom::PBrowserChild;
1005 ALLOW_DEPRECATED_READPARAM
1007 WidgetQueryContentEvent()
1008 : mUseNativeLineBreak(true),
1009 mWithFontRanges(false),
1010 mNeedsToFlushLayout(true) {
1011 MOZ_CRASH("WidgetQueryContentEvent is created without proper arguments");
1014 public:
1015 virtual WidgetQueryContentEvent* AsQueryContentEvent() override {
1016 return this;
1019 WidgetQueryContentEvent(bool aIsTrusted, EventMessage aMessage,
1020 nsIWidget* aWidget)
1021 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eQueryContentEventClass),
1022 mUseNativeLineBreak(true),
1023 mWithFontRanges(false),
1024 mNeedsToFlushLayout(true) {}
1026 WidgetQueryContentEvent(EventMessage aMessage,
1027 const WidgetQueryContentEvent& aOtherEvent)
1028 : WidgetGUIEvent(aOtherEvent.IsTrusted(), aMessage,
1029 const_cast<nsIWidget*>(aOtherEvent.mWidget.get()),
1030 eQueryContentEventClass),
1031 mUseNativeLineBreak(aOtherEvent.mUseNativeLineBreak),
1032 mWithFontRanges(false),
1033 mNeedsToFlushLayout(aOtherEvent.mNeedsToFlushLayout) {}
1035 WidgetEvent* Duplicate() const override {
1036 // This event isn't an internal event of any DOM event.
1037 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1038 "WidgetQueryContentEvent needs to support Duplicate()");
1039 MOZ_CRASH("WidgetQueryContentEvent doesn't support Duplicate()");
1042 struct Options final {
1043 bool mUseNativeLineBreak;
1044 bool mRelativeToInsertionPoint;
1046 explicit Options()
1047 : mUseNativeLineBreak(true), mRelativeToInsertionPoint(false) {}
1049 explicit Options(const WidgetQueryContentEvent& aEvent)
1050 : mUseNativeLineBreak(aEvent.mUseNativeLineBreak),
1051 mRelativeToInsertionPoint(aEvent.mInput.mRelativeToInsertionPoint) {}
1054 void Init(const Options& aOptions) {
1055 mUseNativeLineBreak = aOptions.mUseNativeLineBreak;
1056 mInput.mRelativeToInsertionPoint = aOptions.mRelativeToInsertionPoint;
1057 MOZ_ASSERT(mInput.IsValidEventMessage(mMessage));
1060 void InitForQueryTextContent(int64_t aOffset, uint32_t aLength,
1061 const Options& aOptions = Options()) {
1062 NS_ASSERTION(mMessage == eQueryTextContent, "wrong initializer is called");
1063 mInput.mOffset = aOffset;
1064 mInput.mLength = aLength;
1065 Init(aOptions);
1066 MOZ_ASSERT(mInput.IsValidOffset());
1069 void InitForQueryCaretRect(int64_t aOffset,
1070 const Options& aOptions = Options()) {
1071 NS_ASSERTION(mMessage == eQueryCaretRect, "wrong initializer is called");
1072 mInput.mOffset = aOffset;
1073 Init(aOptions);
1074 MOZ_ASSERT(mInput.IsValidOffset());
1077 void InitForQueryTextRect(int64_t aOffset, uint32_t aLength,
1078 const Options& aOptions = Options()) {
1079 NS_ASSERTION(mMessage == eQueryTextRect, "wrong initializer is called");
1080 mInput.mOffset = aOffset;
1081 mInput.mLength = aLength;
1082 Init(aOptions);
1083 MOZ_ASSERT(mInput.IsValidOffset());
1086 void InitForQuerySelectedText(SelectionType aSelectionType,
1087 const Options& aOptions = Options()) {
1088 MOZ_ASSERT(mMessage == eQuerySelectedText);
1089 MOZ_ASSERT(aSelectionType != SelectionType::eNone);
1090 mInput.mSelectionType = aSelectionType;
1091 Init(aOptions);
1094 void InitForQueryDOMWidgetHittest(
1095 const mozilla::LayoutDeviceIntPoint& aPoint) {
1096 NS_ASSERTION(mMessage == eQueryDOMWidgetHittest,
1097 "wrong initializer is called");
1098 mRefPoint = aPoint;
1101 void InitForQueryTextRectArray(uint32_t aOffset, uint32_t aLength,
1102 const Options& aOptions = Options()) {
1103 NS_ASSERTION(mMessage == eQueryTextRectArray,
1104 "wrong initializer is called");
1105 mInput.mOffset = aOffset;
1106 mInput.mLength = aLength;
1107 Init(aOptions);
1110 void RequestFontRanges() {
1111 MOZ_ASSERT(mMessage == eQueryTextContent);
1112 mWithFontRanges = true;
1115 bool Succeeded() const {
1116 if (mReply.isNothing()) {
1117 return false;
1119 switch (mMessage) {
1120 case eQueryTextContent:
1121 case eQueryTextRect:
1122 case eQueryCaretRect:
1123 return mReply->mOffsetAndData.isSome();
1124 default:
1125 return true;
1129 bool Failed() const { return !Succeeded(); }
1131 bool FoundSelection() const {
1132 MOZ_ASSERT(mMessage == eQuerySelectedText);
1133 return Succeeded() && mReply->mOffsetAndData.isSome();
1136 bool FoundChar() const {
1137 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1138 return Succeeded() && mReply->mOffsetAndData.isSome();
1141 bool FoundTentativeCaretOffset() const {
1142 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1143 return Succeeded() && mReply->mTentativeCaretOffset.isSome();
1146 bool DidNotFindSelection() const {
1147 MOZ_ASSERT(mMessage == eQuerySelectedText);
1148 return Failed() || mReply->mOffsetAndData.isNothing();
1151 bool DidNotFindChar() const {
1152 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1153 return Failed() || mReply->mOffsetAndData.isNothing();
1156 bool DidNotFindTentativeCaretOffset() const {
1157 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1158 return Failed() || mReply->mTentativeCaretOffset.isNothing();
1161 bool mUseNativeLineBreak;
1162 bool mWithFontRanges;
1163 bool mNeedsToFlushLayout;
1164 struct Input final {
1165 uint32_t EndOffset() const {
1166 CheckedInt<uint32_t> endOffset = CheckedInt<uint32_t>(mOffset) + mLength;
1167 return NS_WARN_IF(!endOffset.isValid()) ? UINT32_MAX : endOffset.value();
1170 int64_t mOffset;
1171 uint32_t mLength;
1172 SelectionType mSelectionType;
1173 // If mOffset is true, mOffset is relative to the start offset of
1174 // composition if there is, otherwise, the start of the first selection
1175 // range.
1176 bool mRelativeToInsertionPoint;
1178 Input()
1179 : mOffset(0),
1180 mLength(0),
1181 mSelectionType(SelectionType::eNormal),
1182 mRelativeToInsertionPoint(false) {}
1184 bool IsValidOffset() const {
1185 return mRelativeToInsertionPoint || mOffset >= 0;
1187 bool IsValidEventMessage(EventMessage aEventMessage) const {
1188 if (!mRelativeToInsertionPoint) {
1189 return true;
1191 switch (aEventMessage) {
1192 case eQueryTextContent:
1193 case eQueryCaretRect:
1194 case eQueryTextRect:
1195 return true;
1196 default:
1197 return false;
1200 bool MakeOffsetAbsolute(uint32_t aInsertionPointOffset) {
1201 if (NS_WARN_IF(!mRelativeToInsertionPoint)) {
1202 return true;
1204 mRelativeToInsertionPoint = false;
1205 // If mOffset + aInsertionPointOffset becomes negative value,
1206 // we should assume the absolute offset is 0.
1207 if (mOffset < 0 && -mOffset > aInsertionPointOffset) {
1208 mOffset = 0;
1209 return true;
1211 // Otherwise, we don't allow too large offset.
1212 CheckedInt<uint32_t> absOffset(mOffset + aInsertionPointOffset);
1213 if (NS_WARN_IF(!absOffset.isValid())) {
1214 mOffset = UINT32_MAX;
1215 return false;
1217 mOffset = absOffset.value();
1218 return true;
1220 } mInput;
1222 struct Reply final {
1223 EventMessage const mEventMessage;
1224 void* mContentsRoot = nullptr;
1225 Maybe<OffsetAndData<uint32_t>> mOffsetAndData;
1226 // mTentativeCaretOffset is used by only eQueryCharacterAtPoint.
1227 // This is the offset where caret would be if user clicked at the mRefPoint.
1228 Maybe<uint32_t> mTentativeCaretOffset;
1229 // mRect is used by eQueryTextRect, eQueryCaretRect, eQueryCharacterAtPoint
1230 // and eQueryEditorRect. The coordinates is system coordinates relative to
1231 // the top level widget of mFocusedWidget. E.g., if a <xul:panel> which
1232 // is owned by a window has focused editor, the offset of mRect is relative
1233 // to the owner window, not the <xul:panel>.
1234 mozilla::LayoutDeviceIntRect mRect;
1235 // The return widget has the caret. This is set at all query events.
1236 nsIWidget* mFocusedWidget = nullptr;
1237 // mozilla::WritingMode value at the end (focus) of the selection
1238 mozilla::WritingMode mWritingMode;
1239 // Used by eQuerySelectionAsTransferable
1240 nsCOMPtr<nsITransferable> mTransferable;
1241 // Used by eQueryTextContent with font ranges requested
1242 CopyableAutoTArray<mozilla::FontRange, 1> mFontRanges;
1243 // Used by eQueryTextRectArray
1244 CopyableTArray<mozilla::LayoutDeviceIntRect> mRectArray;
1245 // true if selection is reversed (end < start)
1246 bool mReversed = false;
1247 // true if DOM element under mouse belongs to widget
1248 bool mWidgetIsHit = false;
1249 // true if mContentRoot is focused editable content
1250 bool mIsEditableContent = false;
1252 Reply() = delete;
1253 explicit Reply(EventMessage aEventMessage) : mEventMessage(aEventMessage) {}
1255 // Don't allow to copy/move because of `mEventMessage`.
1256 Reply(const Reply& aOther) = delete;
1257 Reply(Reply&& aOther) = delete;
1258 Reply& operator=(const Reply& aOther) = delete;
1259 Reply& operator=(Reply&& aOther) = delete;
1261 MOZ_NEVER_INLINE_DEBUG uint32_t StartOffset() const {
1262 MOZ_ASSERT(mOffsetAndData.isSome());
1263 return mOffsetAndData->StartOffset();
1265 MOZ_NEVER_INLINE_DEBUG uint32_t EndOffset() const {
1266 MOZ_ASSERT(mOffsetAndData.isSome());
1267 return mOffsetAndData->EndOffset();
1269 MOZ_NEVER_INLINE_DEBUG uint32_t DataLength() const {
1270 MOZ_ASSERT(mOffsetAndData.isSome() ||
1271 mEventMessage == eQuerySelectedText);
1272 return mOffsetAndData.isSome() ? mOffsetAndData->Length() : 0;
1274 MOZ_NEVER_INLINE_DEBUG uint32_t AnchorOffset() const {
1275 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1276 MOZ_ASSERT(mOffsetAndData.isSome());
1277 return StartOffset() + (mReversed ? DataLength() : 0);
1280 MOZ_NEVER_INLINE_DEBUG uint32_t FocusOffset() const {
1281 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1282 MOZ_ASSERT(mOffsetAndData.isSome());
1283 return StartOffset() + (mReversed ? 0 : DataLength());
1286 const WritingMode& WritingModeRef() const {
1287 MOZ_ASSERT(mEventMessage == eQuerySelectedText ||
1288 mEventMessage == eQueryCaretRect ||
1289 mEventMessage == eQueryTextRect);
1290 MOZ_ASSERT(mOffsetAndData.isSome() ||
1291 mEventMessage == eQuerySelectedText);
1292 return mWritingMode;
1295 MOZ_NEVER_INLINE_DEBUG const nsString& DataRef() const {
1296 MOZ_ASSERT(mOffsetAndData.isSome() ||
1297 mEventMessage == eQuerySelectedText);
1298 return mOffsetAndData.isSome() ? mOffsetAndData->DataRef()
1299 : EmptyString();
1301 MOZ_NEVER_INLINE_DEBUG bool IsDataEmpty() const {
1302 MOZ_ASSERT(mOffsetAndData.isSome() ||
1303 mEventMessage == eQuerySelectedText);
1304 return mOffsetAndData.isSome() ? mOffsetAndData->IsDataEmpty() : true;
1306 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRange(uint32_t aOffset) const {
1307 MOZ_ASSERT(mOffsetAndData.isSome() ||
1308 mEventMessage == eQuerySelectedText);
1309 return mOffsetAndData.isSome() ? mOffsetAndData->IsOffsetInRange(aOffset)
1310 : false;
1312 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRangeOrEndOffset(
1313 uint32_t aOffset) const {
1314 MOZ_ASSERT(mOffsetAndData.isSome() ||
1315 mEventMessage == eQuerySelectedText);
1316 return mOffsetAndData.isSome()
1317 ? mOffsetAndData->IsOffsetInRangeOrEndOffset(aOffset)
1318 : false;
1320 MOZ_NEVER_INLINE_DEBUG void TruncateData(uint32_t aLength = 0) {
1321 MOZ_ASSERT(mOffsetAndData.isSome());
1322 mOffsetAndData->TruncateData(aLength);
1325 friend std::ostream& operator<<(std::ostream& aStream,
1326 const Reply& aReply) {
1327 aStream << "{ ";
1328 if (aReply.mEventMessage == eQuerySelectedText ||
1329 aReply.mEventMessage == eQueryTextContent ||
1330 aReply.mEventMessage == eQueryTextRect ||
1331 aReply.mEventMessage == eQueryCaretRect ||
1332 aReply.mEventMessage == eQueryCharacterAtPoint) {
1333 aStream << "mOffsetAndData=" << ToString(aReply.mOffsetAndData).c_str()
1334 << ", ";
1335 if (aReply.mEventMessage == eQueryCharacterAtPoint) {
1336 aStream << "mTentativeCaretOffset="
1337 << ToString(aReply.mTentativeCaretOffset).c_str() << ", ";
1340 if (aReply.mOffsetAndData.isSome() && aReply.mOffsetAndData->Length()) {
1341 if (aReply.mEventMessage == eQuerySelectedText) {
1342 aStream << ", mReversed=" << (aReply.mReversed ? "true" : "false");
1344 if (aReply.mEventMessage == eQuerySelectionAsTransferable) {
1345 aStream << ", mTransferable=0x" << aReply.mTransferable;
1348 if (aReply.mEventMessage == eQuerySelectedText ||
1349 aReply.mEventMessage == eQueryTextRect ||
1350 aReply.mEventMessage == eQueryCaretRect) {
1351 aStream << ", mWritingMode=" << ToString(aReply.mWritingMode).c_str();
1353 aStream << ", mContentsRoot=0x" << aReply.mContentsRoot
1354 << ", mIsEditableContent="
1355 << (aReply.mIsEditableContent ? "true" : "false")
1356 << ", mFocusedWidget=0x" << aReply.mFocusedWidget;
1357 if (aReply.mEventMessage == eQueryTextContent) {
1358 aStream << ", mFontRanges={ Length()=" << aReply.mFontRanges.Length()
1359 << " }";
1360 } else if (aReply.mEventMessage == eQueryTextRect ||
1361 aReply.mEventMessage == eQueryCaretRect ||
1362 aReply.mEventMessage == eQueryCharacterAtPoint) {
1363 aStream << ", mRect=" << ToString(aReply.mRect).c_str();
1364 } else if (aReply.mEventMessage == eQueryTextRectArray) {
1365 aStream << ", mRectArray={ Length()=" << aReply.mRectArray.Length()
1366 << " }";
1367 } else if (aReply.mEventMessage == eQueryDOMWidgetHittest) {
1368 aStream << ", mWidgetIsHit="
1369 << (aReply.mWidgetIsHit ? "true" : "false");
1371 return aStream << " }";
1375 void EmplaceReply() { mReply.emplace(mMessage); }
1376 Maybe<Reply> mReply;
1378 // values of mComputedScrollAction
1379 enum { SCROLL_ACTION_NONE, SCROLL_ACTION_LINE, SCROLL_ACTION_PAGE };
1382 /******************************************************************************
1383 * mozilla::WidgetSelectionEvent
1384 ******************************************************************************/
1386 class WidgetSelectionEvent : public WidgetGUIEvent {
1387 private:
1388 friend class mozilla::dom::PBrowserParent;
1389 friend class mozilla::dom::PBrowserChild;
1390 ALLOW_DEPRECATED_READPARAM
1392 WidgetSelectionEvent()
1393 : mOffset(0),
1394 mLength(0),
1395 mReversed(false),
1396 mExpandToClusterBoundary(true),
1397 mSucceeded(false),
1398 mUseNativeLineBreak(true),
1399 mReason(nsISelectionListener::NO_REASON) {}
1401 public:
1402 virtual WidgetSelectionEvent* AsSelectionEvent() override { return this; }
1404 WidgetSelectionEvent(bool aIsTrusted, EventMessage aMessage,
1405 nsIWidget* aWidget)
1406 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eSelectionEventClass),
1407 mOffset(0),
1408 mLength(0),
1409 mReversed(false),
1410 mExpandToClusterBoundary(true),
1411 mSucceeded(false),
1412 mUseNativeLineBreak(true),
1413 mReason(nsISelectionListener::NO_REASON) {}
1415 virtual WidgetEvent* Duplicate() const override {
1416 // This event isn't an internal event of any DOM event.
1417 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1418 "WidgetSelectionEvent needs to support Duplicate()");
1419 MOZ_CRASH("WidgetSelectionEvent doesn't support Duplicate()");
1420 return nullptr;
1423 // Start offset of selection
1424 uint32_t mOffset;
1425 // Length of selection
1426 uint32_t mLength;
1427 // Selection "anchor" should be in front
1428 bool mReversed;
1429 // Cluster-based or character-based
1430 bool mExpandToClusterBoundary;
1431 // true if setting selection succeeded.
1432 bool mSucceeded;
1433 // true if native line breaks are used for mOffset and mLength
1434 bool mUseNativeLineBreak;
1435 // Fennec provides eSetSelection reason codes for downstream
1436 // use in AccessibleCaret visibility logic.
1437 int16_t mReason;
1440 /******************************************************************************
1441 * mozilla::InternalEditorInputEvent
1442 ******************************************************************************/
1444 class InternalEditorInputEvent : public InternalUIEvent {
1445 private:
1446 InternalEditorInputEvent()
1447 : mData(VoidString()),
1448 mInputType(EditorInputType::eUnknown),
1449 mIsComposing(false) {}
1451 public:
1452 virtual InternalEditorInputEvent* AsEditorInputEvent() override {
1453 return this;
1456 InternalEditorInputEvent(bool aIsTrusted, EventMessage aMessage,
1457 nsIWidget* aWidget = nullptr,
1458 const WidgetEventTime* aTime = nullptr)
1459 : InternalUIEvent(aIsTrusted, aMessage, aWidget, eEditorInputEventClass,
1460 aTime),
1461 mData(VoidString()),
1462 mInputType(EditorInputType::eUnknown) {}
1464 virtual WidgetEvent* Duplicate() const override {
1465 MOZ_ASSERT(mClass == eEditorInputEventClass,
1466 "Duplicate() must be overridden by sub class");
1467 // Not copying widget, it is a weak reference.
1468 InternalEditorInputEvent* result =
1469 new InternalEditorInputEvent(false, mMessage, nullptr, this);
1470 result->AssignEditorInputEventData(*this, true);
1471 result->mFlags = mFlags;
1472 return result;
1475 nsString mData;
1476 RefPtr<dom::DataTransfer> mDataTransfer;
1477 OwningNonNullStaticRangeArray mTargetRanges;
1479 EditorInputType mInputType;
1481 bool mIsComposing;
1483 void AssignEditorInputEventData(const InternalEditorInputEvent& aEvent,
1484 bool aCopyTargets) {
1485 AssignUIEventData(aEvent, aCopyTargets);
1487 mData = aEvent.mData;
1488 mDataTransfer = aEvent.mDataTransfer;
1489 mTargetRanges = aEvent.mTargetRanges.Clone();
1490 mInputType = aEvent.mInputType;
1491 mIsComposing = aEvent.mIsComposing;
1494 void GetDOMInputTypeName(nsAString& aInputTypeName) {
1495 GetDOMInputTypeName(mInputType, aInputTypeName);
1497 static void GetDOMInputTypeName(EditorInputType aInputType,
1498 nsAString& aInputTypeName);
1499 static EditorInputType GetEditorInputType(const nsAString& aInputType);
1501 static void Shutdown();
1503 private:
1504 static const char16_t* const kInputTypeNames[];
1505 typedef nsTHashMap<nsStringHashKey, EditorInputType> InputTypeHashtable;
1506 static InputTypeHashtable* sInputTypeHashtable;
1509 } // namespace mozilla
1511 #endif // mozilla_TextEvents_h__