Bug 1776444 [wpt PR 34582] - Revert "Add TimedHTMLParserBudget to fieldtrial_testing_...
[gecko.git] / widget / TextEvents.h
blobe079c51dc6bde66dc2bac61820f17066eb5b7cbc
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 "nsCOMPtr.h"
26 #include "nsHashtablesFwd.h"
27 #include "nsISelectionListener.h"
28 #include "nsITransferable.h"
29 #include "nsRect.h"
30 #include "nsString.h"
31 #include "nsTArray.h"
33 class nsStringHashKey;
35 /******************************************************************************
36 * virtual keycode values
37 ******************************************************************************/
39 enum {
40 #define NS_DEFINE_VK(aDOMKeyName, aDOMKeyCode) NS_##aDOMKeyName = aDOMKeyCode,
41 #include "mozilla/VirtualKeyCodeList.h"
42 #undef NS_DEFINE_VK
43 NS_VK_UNKNOWN = 0xFF
46 namespace mozilla {
48 enum : uint32_t {
49 eKeyLocationStandard = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_STANDARD,
50 eKeyLocationLeft = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_LEFT,
51 eKeyLocationRight = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_RIGHT,
52 eKeyLocationNumpad = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_NUMPAD
55 const nsCString GetDOMKeyCodeName(uint32_t aKeyCode);
57 namespace dom {
58 class PBrowserParent;
59 class PBrowserChild;
60 } // namespace dom
61 namespace plugins {
62 class PPluginInstanceChild;
63 } // namespace plugins
65 enum class AccessKeyType {
66 // Handle access key for chrome.
67 eChrome,
68 // Handle access key for content.
69 eContent,
70 // Don't handle access key.
71 eNone
74 /******************************************************************************
75 * mozilla::AlternativeCharCode
77 * This stores alternative charCode values of a key event with some modifiers.
78 * The stored values proper for testing shortcut key or access key.
79 ******************************************************************************/
81 struct AlternativeCharCode {
82 AlternativeCharCode() : mUnshiftedCharCode(0), mShiftedCharCode(0) {}
83 AlternativeCharCode(uint32_t aUnshiftedCharCode, uint32_t aShiftedCharCode)
84 : mUnshiftedCharCode(aUnshiftedCharCode),
85 mShiftedCharCode(aShiftedCharCode) {}
86 uint32_t mUnshiftedCharCode;
87 uint32_t mShiftedCharCode;
90 /******************************************************************************
91 * mozilla::ShortcutKeyCandidate
93 * This stores a candidate of shortcut key combination.
94 ******************************************************************************/
96 struct ShortcutKeyCandidate {
97 ShortcutKeyCandidate() : mCharCode(0), mIgnoreShift(0) {}
98 ShortcutKeyCandidate(uint32_t aCharCode, bool aIgnoreShift)
99 : mCharCode(aCharCode), mIgnoreShift(aIgnoreShift) {}
100 // The mCharCode value which must match keyboard shortcut definition.
101 uint32_t mCharCode;
102 // true if Shift state can be ignored. Otherwise, Shift key state must
103 // match keyboard shortcut definition.
104 bool mIgnoreShift;
107 /******************************************************************************
108 * mozilla::IgnoreModifierState
110 * This stores flags for modifiers that should be ignored when matching
111 * XBL handlers.
112 ******************************************************************************/
114 struct IgnoreModifierState {
115 // When mShift is true, Shift key state will be ignored.
116 bool mShift;
117 // When mOS is true, OS key state will be ignored.
118 bool mOS;
120 IgnoreModifierState() : mShift(false), mOS(false) {}
123 /******************************************************************************
124 * mozilla::WidgetKeyboardEvent
125 ******************************************************************************/
127 class WidgetKeyboardEvent : public WidgetInputEvent {
128 private:
129 friend class dom::PBrowserParent;
130 friend class dom::PBrowserChild;
131 friend struct IPC::ParamTraits<WidgetKeyboardEvent>;
133 protected:
134 WidgetKeyboardEvent()
135 : mNativeKeyEvent(nullptr),
136 mKeyCode(0),
137 mCharCode(0),
138 mPseudoCharCode(0),
139 mLocation(eKeyLocationStandard),
140 mUniqueId(0),
141 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
142 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
143 mIsRepeat(false),
144 mIsComposing(false),
145 mIsSynthesizedByTIP(false),
146 mMaybeSkippableInRemoteProcess(true),
147 mUseLegacyKeyCodeAndCharCodeValues(false),
148 mEditCommandsForSingleLineEditorInitialized(false),
149 mEditCommandsForMultiLineEditorInitialized(false),
150 mEditCommandsForRichTextEditorInitialized(false) {}
152 public:
153 virtual WidgetKeyboardEvent* AsKeyboardEvent() override { return this; }
155 WidgetKeyboardEvent(bool aIsTrusted, EventMessage aMessage,
156 nsIWidget* aWidget,
157 EventClassID aEventClassID = eKeyboardEventClass)
158 : WidgetInputEvent(aIsTrusted, aMessage, aWidget, aEventClassID),
159 mNativeKeyEvent(nullptr),
160 mKeyCode(0),
161 mCharCode(0),
162 mPseudoCharCode(0),
163 mLocation(eKeyLocationStandard),
164 mUniqueId(0),
165 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
166 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
167 mIsRepeat(false),
168 mIsComposing(false),
169 mIsSynthesizedByTIP(false),
170 mMaybeSkippableInRemoteProcess(true),
171 mUseLegacyKeyCodeAndCharCodeValues(false),
172 mEditCommandsForSingleLineEditorInitialized(false),
173 mEditCommandsForMultiLineEditorInitialized(false),
174 mEditCommandsForRichTextEditorInitialized(false) {}
176 // IsInputtingText() and IsInputtingLineBreak() are used to check if
177 // it should cause eKeyPress events even on web content.
178 // UI Events defines that "keypress" event should be fired "if and only if
179 // that key normally produces a character value".
180 // <https://www.w3.org/TR/uievents/#event-type-keypress>
181 // Additionally, for backward compatiblity with all existing browsers,
182 // there is a spec issue for Enter key press.
183 // <https://github.com/w3c/uievents/issues/183>
184 bool IsInputtingText() const {
185 // NOTE: On some keyboard layout, some characters are inputted with Control
186 // key or Alt key, but at that time, widget clears the modifier flag
187 // from eKeyPress event because our TextEditor won't handle eKeyPress
188 // events as inputting text (bug 1346832).
189 // NOTE: There are some complicated issues of our traditional behavior.
190 // -- On Windows, KeyboardLayout::WillDispatchKeyboardEvent() clears
191 // MODIFIER_ALT and MODIFIER_CONTROL of eKeyPress event if it
192 // should be treated as inputting a character because AltGr is
193 // represented with both Alt key and Ctrl key are pressed, and
194 // some keyboard layouts may produces a character with Ctrl key.
195 // -- On Linux, KeymapWrapper doesn't have this hack since perhaps,
196 // we don't have any bug reports that user cannot input proper
197 // character with Alt and/or Ctrl key.
198 // -- On macOS, IMEInputHandler::WillDispatchKeyboardEvent() clears
199 // MODIFIER_ALT and MDOFIEIR_CONTROL of eKeyPress event only when
200 // TextInputHandler::InsertText() has been called for the event.
201 // I.e., they are cleared only when an editor has focus (even if IME
202 // is disabled in password field or by |ime-mode: disabled;|) because
203 // TextInputHandler::InsertText() is called while
204 // TextInputHandler::HandleKeyDownEvent() calls interpretKeyEvents:
205 // to notify text input processor of Cocoa (including IME). In other
206 // words, when we need to disable IME completey when no editor has
207 // focus, we cannot call interpretKeyEvents:. So,
208 // TextInputHandler::InsertText() won't be called when no editor has
209 // focus so that neither MODIFIER_ALT nor MODIFIER_CONTROL is
210 // cleared. So, fortunately, altKey and ctrlKey values of "keypress"
211 // events are same as the other browsers only when no editor has
212 // focus.
213 // NOTE: As mentioned above, for compatibility with the other browsers on
214 // macOS, we should keep MODIFIER_ALT and MODIFIER_CONTROL flags of
215 // eKeyPress events when no editor has focus. However, Alt key,
216 // labeled "option" on keyboard for Mac, is AltGraph key on the other
217 // platforms. So, even if MODIFIER_ALT is set, we need to dispatch
218 // eKeyPress event even on web content unless mCharCode is 0.
219 // Therefore, we need to ignore MODIFIER_ALT flag here only on macOS.
220 return mMessage == eKeyPress && mCharCode &&
221 !(mModifiers & (
222 #ifndef XP_MACOSX
223 // So, ignore MODIFIER_ALT only on macOS since
224 // option key is used as AltGraph key on macOS.
225 MODIFIER_ALT |
226 #endif // #ifndef XP_MAXOSX
227 MODIFIER_CONTROL | MODIFIER_META | MODIFIER_OS));
230 bool IsInputtingLineBreak() const {
231 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
232 !(mModifiers &
233 (MODIFIER_ALT | MODIFIER_CONTROL | MODIFIER_META | MODIFIER_OS));
237 * ShouldKeyPressEventBeFiredOnContent() should be called only when the
238 * instance is eKeyPress event. This returns true when the eKeyPress
239 * event should be fired even on content in the default event group.
241 bool ShouldKeyPressEventBeFiredOnContent() const {
242 MOZ_DIAGNOSTIC_ASSERT(mMessage == eKeyPress);
243 if (IsInputtingText() || IsInputtingLineBreak()) {
244 return true;
246 // Ctrl + Enter won't cause actual input in our editor.
247 // However, the other browsers fire keypress event in any platforms.
248 // So, for compatibility with them, we should fire keypress event for
249 // Ctrl + Enter too.
250 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
251 !(mModifiers &
252 (MODIFIER_ALT | MODIFIER_META | MODIFIER_OS | MODIFIER_SHIFT));
255 virtual WidgetEvent* Duplicate() const override {
256 MOZ_ASSERT(mClass == eKeyboardEventClass,
257 "Duplicate() must be overridden by sub class");
258 // Not copying widget, it is a weak reference.
259 WidgetKeyboardEvent* result =
260 new WidgetKeyboardEvent(false, mMessage, nullptr);
261 result->AssignKeyEventData(*this, true);
262 result->mEditCommandsForSingleLineEditor =
263 mEditCommandsForSingleLineEditor.Clone();
264 result->mEditCommandsForMultiLineEditor =
265 mEditCommandsForMultiLineEditor.Clone();
266 result->mEditCommandsForRichTextEditor =
267 mEditCommandsForRichTextEditor.Clone();
268 result->mFlags = mFlags;
269 return result;
272 bool CanUserGestureActivateTarget() const {
273 // Printable keys, 'carriage return' and 'space' are supported user gestures
274 // for activating the document. However, if supported key is being pressed
275 // combining with other operation keys, such like alt, control ..etc., we
276 // won't activate the target for them because at that time user might
277 // interact with browser or window manager which doesn't necessarily
278 // demonstrate user's intent to play media.
279 const bool isCombiningWithOperationKeys = (IsControl() && !IsAltGraph()) ||
280 (IsAlt() && !IsAltGraph()) ||
281 IsMeta() || IsOS();
282 const bool isEnterOrSpaceKey =
283 mKeyNameIndex == KEY_NAME_INDEX_Enter || mKeyCode == NS_VK_SPACE;
284 return (PseudoCharCode() || isEnterOrSpaceKey) &&
285 (!isCombiningWithOperationKeys ||
286 // ctrl-c/ctrl-x/ctrl-v is quite common shortcut for clipboard
287 // operation.
288 // XXXedgar, we have to find a better way to handle browser keyboard
289 // shortcut for user activation, instead of just ignoring all
290 // combinations, see bug 1641171.
291 ((mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_C ||
292 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_V ||
293 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_X) &&
294 IsAccel()));
298 * CanTreatAsUserInput() returns true if the key is pressed for perhaps
299 * doing something on the web app or our UI. This means that when this
300 * returns false, e.g., when user presses a modifier key, user is probably
301 * displeased by opening popup, entering fullscreen mode, etc. Therefore,
302 * only when this returns true, such reactions should be allowed.
304 bool CanTreatAsUserInput() const {
305 if (!IsTrusted()) {
306 return false;
308 switch (mKeyNameIndex) {
309 case KEY_NAME_INDEX_Escape:
310 // modifier keys:
311 case KEY_NAME_INDEX_Alt:
312 case KEY_NAME_INDEX_AltGraph:
313 case KEY_NAME_INDEX_CapsLock:
314 case KEY_NAME_INDEX_Control:
315 case KEY_NAME_INDEX_Fn:
316 case KEY_NAME_INDEX_FnLock:
317 case KEY_NAME_INDEX_Meta:
318 case KEY_NAME_INDEX_NumLock:
319 case KEY_NAME_INDEX_ScrollLock:
320 case KEY_NAME_INDEX_Shift:
321 case KEY_NAME_INDEX_Symbol:
322 case KEY_NAME_INDEX_SymbolLock:
323 // legacy modifier keys:
324 case KEY_NAME_INDEX_Hyper:
325 case KEY_NAME_INDEX_Super:
326 // obsolete modifier key:
327 case KEY_NAME_INDEX_OS:
328 return false;
329 default:
330 return true;
335 * ShouldInteractionTimeRecorded() returns true if the handling time of
336 * the event should be recorded with the telemetry.
338 bool ShouldInteractionTimeRecorded() const {
339 // Let's record only when we can treat the instance is a user input.
340 return CanTreatAsUserInput();
343 // OS translated Unicode chars which are used for accesskey and accelkey
344 // handling. The handlers will try from first character to last character.
345 CopyableTArray<AlternativeCharCode> mAlternativeCharCodes;
346 // DOM KeyboardEvent.key only when mKeyNameIndex is KEY_NAME_INDEX_USE_STRING.
347 nsString mKeyValue;
348 // DOM KeyboardEvent.code only when mCodeNameIndex is
349 // CODE_NAME_INDEX_USE_STRING.
350 nsString mCodeValue;
352 // OS-specific native event can optionally be preserved.
353 // This is used to retrieve editing shortcut keys in the environment.
354 void* mNativeKeyEvent;
355 // A DOM keyCode value or 0. If a keypress event whose mCharCode is 0, this
356 // should be 0.
357 uint32_t mKeyCode;
358 // If the instance is a keypress event of a printable key, this is a UTF-16
359 // value of the key. Otherwise, 0. This value must not be a control
360 // character when some modifiers are active. Then, this value should be an
361 // unmodified value except Shift and AltGr.
362 uint32_t mCharCode;
363 // mPseudoCharCode is valid only when mMessage is an eKeyDown event.
364 // This stores mCharCode value of keypress event which is fired with same
365 // key value and same modifier state.
366 uint32_t mPseudoCharCode;
367 // One of eKeyLocation*
368 uint32_t mLocation;
369 // Unique id associated with a keydown / keypress event. It's ok if this wraps
370 // over long periods.
371 uint32_t mUniqueId;
373 // DOM KeyboardEvent.key
374 KeyNameIndex mKeyNameIndex;
375 // DOM KeyboardEvent.code
376 CodeNameIndex mCodeNameIndex;
378 // Indicates whether the event is generated by auto repeat or not.
379 // if this is keyup event, always false.
380 bool mIsRepeat;
381 // Indicates whether the event is generated during IME (or deadkey)
382 // composition. This is initialized by EventStateManager. So, key event
383 // dispatchers don't need to initialize this.
384 bool mIsComposing;
385 // Indicates whether the event is synthesized from Text Input Processor
386 // or an actual event from nsAppShell.
387 bool mIsSynthesizedByTIP;
388 // Indicates whether the event is skippable in remote process.
389 // Don't refer this member directly when you need to check this.
390 // Use CanSkipInRemoteProcess() instead.
391 bool mMaybeSkippableInRemoteProcess;
392 // Indicates whether the event should return legacy keyCode value and
393 // charCode value to web apps (one of them is always 0) or not, when it's
394 // an eKeyPress event.
395 bool mUseLegacyKeyCodeAndCharCodeValues;
397 bool CanSkipInRemoteProcess() const {
398 // If this is a repeat event (i.e., generated by auto-repeat feature of
399 // the platform), remove process may skip to handle it because of
400 // performances reasons.. However, if it's caused by odd keyboard utils,
401 // we should not ignore any key events even marked as repeated since
402 // generated key sequence may be important to input proper text. E.g.,
403 // "SinhalaTamil IME" on Windows emulates dead key like input with
404 // generating WM_KEYDOWN for VK_PACKET (inputting any Unicode characters
405 // without keyboard layout information) and VK_BACK (Backspace) to remove
406 // previous character(s) and those messages may be marked as "repeat" by
407 // their bug.
408 return mIsRepeat && mMaybeSkippableInRemoteProcess;
412 * If the key is an arrow key, and the current selection is in a vertical
413 * content, the caret should be moved to physically. However, arrow keys
414 * are mapped to logical move commands in horizontal content. Therefore,
415 * we need to check writing mode if and only if the key is an arrow key, and
416 * need to remap the command to logical command in vertical content if the
417 * writing mode at selection is vertical. These methods help to convert
418 * arrow keys in horizontal content to correspnding direction arrow keys
419 * in vertical content.
421 bool NeedsToRemapNavigationKey() const {
422 // TODO: Use mKeyNameIndex instead.
423 return mKeyCode >= NS_VK_LEFT && mKeyCode <= NS_VK_DOWN;
426 uint32_t GetRemappedKeyCode(const WritingMode& aWritingMode) const {
427 if (!aWritingMode.IsVertical()) {
428 return mKeyCode;
430 switch (mKeyCode) {
431 case NS_VK_LEFT:
432 return aWritingMode.IsVerticalLR() ? NS_VK_UP : NS_VK_DOWN;
433 case NS_VK_RIGHT:
434 return aWritingMode.IsVerticalLR() ? NS_VK_DOWN : NS_VK_UP;
435 case NS_VK_UP:
436 return NS_VK_LEFT;
437 case NS_VK_DOWN:
438 return NS_VK_RIGHT;
439 default:
440 return mKeyCode;
444 KeyNameIndex GetRemappedKeyNameIndex(const WritingMode& aWritingMode) const {
445 if (!aWritingMode.IsVertical()) {
446 return mKeyNameIndex;
448 uint32_t remappedKeyCode = GetRemappedKeyCode(aWritingMode);
449 if (remappedKeyCode == mKeyCode) {
450 return mKeyNameIndex;
452 switch (remappedKeyCode) {
453 case NS_VK_LEFT:
454 return KEY_NAME_INDEX_ArrowLeft;
455 case NS_VK_RIGHT:
456 return KEY_NAME_INDEX_ArrowRight;
457 case NS_VK_UP:
458 return KEY_NAME_INDEX_ArrowUp;
459 case NS_VK_DOWN:
460 return KEY_NAME_INDEX_ArrowDown;
461 default:
462 MOZ_ASSERT_UNREACHABLE("Add a case for the new remapped key");
463 return mKeyNameIndex;
468 * Retrieves all edit commands from mWidget. This shouldn't be called when
469 * the instance is an untrusted event, doesn't have widget or in non-chrome
470 * process.
472 * @param aWritingMode
473 * When writing mode of focused element is vertical, this
474 * will resolve some key's physical direction to logical
475 * direction. For doing it, this must be set to the
476 * writing mode at current selection. However, when there
477 * is no focused element and no selection ranges, this
478 * should be set to Nothing(). Using the result of
479 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
480 * is recommended.
482 MOZ_CAN_RUN_SCRIPT void InitAllEditCommands(
483 const Maybe<WritingMode>& aWritingMode);
486 * Retrieves edit commands from mWidget only for aType. This shouldn't be
487 * called when the instance is an untrusted event or doesn't have widget.
489 * @param aWritingMode
490 * When writing mode of focused element is vertical, this
491 * will resolve some key's physical direction to logical
492 * direction. For doing it, this must be set to the
493 * writing mode at current selection. However, when there
494 * is no focused element and no selection ranges, this
495 * should be set to Nothing(). Using the result of
496 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
497 * is recommended.
498 * @return false if some resource is not available to get
499 * commands unexpectedly. Otherwise, true even if
500 * retrieved command is nothing.
502 MOZ_CAN_RUN_SCRIPT bool InitEditCommandsFor(
503 NativeKeyBindingsType aType, const Maybe<WritingMode>& aWritingMode);
506 * PreventNativeKeyBindings() makes the instance to not cause any edit
507 * actions even if it matches with a native key binding.
509 void PreventNativeKeyBindings() {
510 mEditCommandsForSingleLineEditor.Clear();
511 mEditCommandsForMultiLineEditor.Clear();
512 mEditCommandsForRichTextEditor.Clear();
513 mEditCommandsForSingleLineEditorInitialized = true;
514 mEditCommandsForMultiLineEditorInitialized = true;
515 mEditCommandsForRichTextEditorInitialized = true;
519 * EditCommandsConstRef() returns reference to edit commands for aType.
521 const nsTArray<CommandInt>& EditCommandsConstRef(
522 NativeKeyBindingsType aType) const {
523 return const_cast<WidgetKeyboardEvent*>(this)->EditCommandsRef(aType);
527 * IsEditCommandsInitialized() returns true if edit commands for aType
528 * was already initialized. Otherwise, false.
530 bool IsEditCommandsInitialized(NativeKeyBindingsType aType) const {
531 return const_cast<WidgetKeyboardEvent*>(this)->IsEditCommandsInitializedRef(
532 aType);
536 * AreAllEditCommandsInitialized() returns true if edit commands for all
537 * types were already initialized. Otherwise, false.
539 bool AreAllEditCommandsInitialized() const {
540 return mEditCommandsForSingleLineEditorInitialized &&
541 mEditCommandsForMultiLineEditorInitialized &&
542 mEditCommandsForRichTextEditorInitialized;
546 * Execute edit commands for aType.
548 * @return true if the caller should do nothing anymore.
549 * false, otherwise.
551 typedef void (*DoCommandCallback)(Command, void*);
552 MOZ_CAN_RUN_SCRIPT bool ExecuteEditCommands(NativeKeyBindingsType aType,
553 DoCommandCallback aCallback,
554 void* aCallbackData);
556 // If the key should cause keypress events, this returns true.
557 // Otherwise, false.
558 bool ShouldCauseKeypressEvents() const;
560 // mCharCode value of non-eKeyPress events is always 0. However, if
561 // non-eKeyPress event has one or more alternative char code values,
562 // its first item should be the mCharCode value of following eKeyPress event.
563 // PseudoCharCode() returns mCharCode value for eKeyPress event,
564 // the first alternative char code value of non-eKeyPress event or 0.
565 uint32_t PseudoCharCode() const {
566 return mMessage == eKeyPress ? mCharCode : mPseudoCharCode;
568 void SetCharCode(uint32_t aCharCode) {
569 if (mMessage == eKeyPress) {
570 mCharCode = aCharCode;
571 } else {
572 mPseudoCharCode = aCharCode;
576 void GetDOMKeyName(nsAString& aKeyName) {
577 if (mKeyNameIndex == KEY_NAME_INDEX_USE_STRING) {
578 aKeyName = mKeyValue;
579 return;
581 GetDOMKeyName(mKeyNameIndex, aKeyName);
583 void GetDOMCodeName(nsAString& aCodeName) {
584 if (mCodeNameIndex == CODE_NAME_INDEX_USE_STRING) {
585 aCodeName = mCodeValue;
586 return;
588 GetDOMCodeName(mCodeNameIndex, aCodeName);
592 * GetFallbackKeyCodeOfPunctuationKey() returns a DOM keyCode value for
593 * aCodeNameIndex. This is keyCode value of the key when active keyboard
594 * layout is ANSI (US), JIS or ABNT keyboard layout (the latter 2 layouts
595 * are used only when ANSI doesn't have the key). The result is useful
596 * if the key doesn't produce ASCII character with active keyboard layout
597 * nor with alternative ASCII capable keyboard layout.
599 static uint32_t GetFallbackKeyCodeOfPunctuationKey(
600 CodeNameIndex aCodeNameIndex);
602 bool IsModifierKeyEvent() const {
603 return GetModifierForKeyName(mKeyNameIndex) != MODIFIER_NONE;
607 * Get the candidates for shortcut key.
609 * @param aCandidates [out] the candidate shortcut key combination list.
610 * the first item is most preferred.
612 void GetShortcutKeyCandidates(ShortcutKeyCandidateArray& aCandidates) const;
615 * Get the candidates for access key.
617 * @param aCandidates [out] the candidate access key list.
618 * the first item is most preferred.
620 void GetAccessKeyCandidates(nsTArray<uint32_t>& aCandidates) const;
623 * Check whether the modifiers match with chrome access key or
624 * content access key.
626 bool ModifiersMatchWithAccessKey(AccessKeyType aType) const;
629 * Return active modifiers which may match with access key.
630 * For example, even if Alt is access key modifier, then, when Control,
631 * CapseLock and NumLock are active, this returns only MODIFIER_CONTROL.
633 Modifiers ModifiersForAccessKeyMatching() const;
636 * Return access key modifiers.
638 static Modifiers AccessKeyModifiers(AccessKeyType aType);
640 static void Shutdown();
643 * ComputeLocationFromCodeValue() returns one of .mLocation value
644 * (eKeyLocation*) which is the most preferred value for the specified code
645 * value.
647 static uint32_t ComputeLocationFromCodeValue(CodeNameIndex aCodeNameIndex);
650 * ComputeKeyCodeFromKeyNameIndex() return a .mKeyCode value which can be
651 * mapped from the specified key value. Note that this returns 0 if the
652 * key name index is KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
653 * This means that this method is useful only for non-printable keys.
655 static uint32_t ComputeKeyCodeFromKeyNameIndex(KeyNameIndex aKeyNameIndex);
658 * ComputeCodeNameIndexFromKeyNameIndex() returns a code name index which
659 * is typically mapped to given key name index on the platform.
660 * Note that this returns CODE_NAME_INDEX_UNKNOWN if the key name index is
661 * KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
662 * This means that this method is useful only for non-printable keys.
664 * @param aKeyNameIndex A non-printable key name index.
665 * @param aLocation Should be one of location value. This is
666 * important when aKeyNameIndex may exist in
667 * both Numpad or Standard, or in both Left or
668 * Right. If this is nothing, this method
669 * returns Left or Standard position's code
670 * value.
672 static CodeNameIndex ComputeCodeNameIndexFromKeyNameIndex(
673 KeyNameIndex aKeyNameIndex, const Maybe<uint32_t>& aLocation);
676 * GetModifierForKeyName() returns a value of Modifier which is activated
677 * by the aKeyNameIndex.
679 static Modifier GetModifierForKeyName(KeyNameIndex aKeyNameIndex);
682 * IsLeftOrRightModiferKeyNameIndex() returns true if aKeyNameIndex is a
683 * modifier key which may be in Left and Right location.
685 static bool IsLeftOrRightModiferKeyNameIndex(KeyNameIndex aKeyNameIndex) {
686 switch (aKeyNameIndex) {
687 case KEY_NAME_INDEX_Alt:
688 case KEY_NAME_INDEX_Control:
689 case KEY_NAME_INDEX_Meta:
690 case KEY_NAME_INDEX_OS:
691 case KEY_NAME_INDEX_Shift:
692 return true;
693 default:
694 return false;
699 * IsLockableModifier() returns true if aKeyNameIndex is a lockable modifier
700 * key such as CapsLock and NumLock.
702 static bool IsLockableModifier(KeyNameIndex aKeyNameIndex);
704 static void GetDOMKeyName(KeyNameIndex aKeyNameIndex, nsAString& aKeyName);
705 static void GetDOMCodeName(CodeNameIndex aCodeNameIndex,
706 nsAString& aCodeName);
708 static KeyNameIndex GetKeyNameIndex(const nsAString& aKeyValue);
709 static CodeNameIndex GetCodeNameIndex(const nsAString& aCodeValue);
711 static const char* GetCommandStr(Command aCommand);
713 void AssignKeyEventData(const WidgetKeyboardEvent& aEvent,
714 bool aCopyTargets) {
715 AssignInputEventData(aEvent, aCopyTargets);
717 mKeyCode = aEvent.mKeyCode;
718 mCharCode = aEvent.mCharCode;
719 mPseudoCharCode = aEvent.mPseudoCharCode;
720 mLocation = aEvent.mLocation;
721 mAlternativeCharCodes = aEvent.mAlternativeCharCodes.Clone();
722 mIsRepeat = aEvent.mIsRepeat;
723 mIsComposing = aEvent.mIsComposing;
724 mKeyNameIndex = aEvent.mKeyNameIndex;
725 mCodeNameIndex = aEvent.mCodeNameIndex;
726 mKeyValue = aEvent.mKeyValue;
727 mCodeValue = aEvent.mCodeValue;
728 // Don't copy mNativeKeyEvent because it may be referred after its instance
729 // is destroyed.
730 mNativeKeyEvent = nullptr;
731 mUniqueId = aEvent.mUniqueId;
732 mIsSynthesizedByTIP = aEvent.mIsSynthesizedByTIP;
733 mMaybeSkippableInRemoteProcess = aEvent.mMaybeSkippableInRemoteProcess;
734 mUseLegacyKeyCodeAndCharCodeValues =
735 aEvent.mUseLegacyKeyCodeAndCharCodeValues;
737 // Don't copy mEditCommandsFor*Editor because it may require a lot of
738 // memory space. For example, if the event is dispatched but grabbed by
739 // a JS variable, they are not necessary anymore.
741 mEditCommandsForSingleLineEditorInitialized =
742 aEvent.mEditCommandsForSingleLineEditorInitialized;
743 mEditCommandsForMultiLineEditorInitialized =
744 aEvent.mEditCommandsForMultiLineEditorInitialized;
745 mEditCommandsForRichTextEditorInitialized =
746 aEvent.mEditCommandsForRichTextEditorInitialized;
749 void AssignCommands(const WidgetKeyboardEvent& aEvent) {
750 mEditCommandsForSingleLineEditorInitialized =
751 aEvent.mEditCommandsForSingleLineEditorInitialized;
752 if (mEditCommandsForSingleLineEditorInitialized) {
753 mEditCommandsForSingleLineEditor =
754 aEvent.mEditCommandsForSingleLineEditor.Clone();
755 } else {
756 mEditCommandsForSingleLineEditor.Clear();
758 mEditCommandsForMultiLineEditorInitialized =
759 aEvent.mEditCommandsForMultiLineEditorInitialized;
760 if (mEditCommandsForMultiLineEditorInitialized) {
761 mEditCommandsForMultiLineEditor =
762 aEvent.mEditCommandsForMultiLineEditor.Clone();
763 } else {
764 mEditCommandsForMultiLineEditor.Clear();
766 mEditCommandsForRichTextEditorInitialized =
767 aEvent.mEditCommandsForRichTextEditorInitialized;
768 if (mEditCommandsForRichTextEditorInitialized) {
769 mEditCommandsForRichTextEditor =
770 aEvent.mEditCommandsForRichTextEditor.Clone();
771 } else {
772 mEditCommandsForRichTextEditor.Clear();
776 private:
777 static const char16_t* const kKeyNames[];
778 static const char16_t* const kCodeNames[];
779 typedef nsTHashMap<nsStringHashKey, KeyNameIndex> KeyNameIndexHashtable;
780 typedef nsTHashMap<nsStringHashKey, CodeNameIndex> CodeNameIndexHashtable;
781 static KeyNameIndexHashtable* sKeyNameIndexHashtable;
782 static CodeNameIndexHashtable* sCodeNameIndexHashtable;
784 // mEditCommandsFor*Editor store edit commands. This should be initialized
785 // with InitEditCommandsFor().
786 // XXX Ideally, this should be array of Command rather than CommandInt.
787 // However, ParamTraits isn't aware of enum array.
788 CopyableTArray<CommandInt> mEditCommandsForSingleLineEditor;
789 CopyableTArray<CommandInt> mEditCommandsForMultiLineEditor;
790 CopyableTArray<CommandInt> mEditCommandsForRichTextEditor;
792 nsTArray<CommandInt>& EditCommandsRef(NativeKeyBindingsType aType) {
793 switch (aType) {
794 case NativeKeyBindingsType::SingleLineEditor:
795 return mEditCommandsForSingleLineEditor;
796 case NativeKeyBindingsType::MultiLineEditor:
797 return mEditCommandsForMultiLineEditor;
798 case NativeKeyBindingsType::RichTextEditor:
799 return mEditCommandsForRichTextEditor;
800 default:
801 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
802 "Invalid native key binding type");
806 // mEditCommandsFor*EditorInitialized are set to true when
807 // InitEditCommandsFor() initializes edit commands for the type.
808 bool mEditCommandsForSingleLineEditorInitialized;
809 bool mEditCommandsForMultiLineEditorInitialized;
810 bool mEditCommandsForRichTextEditorInitialized;
812 bool& IsEditCommandsInitializedRef(NativeKeyBindingsType aType) {
813 switch (aType) {
814 case NativeKeyBindingsType::SingleLineEditor:
815 return mEditCommandsForSingleLineEditorInitialized;
816 case NativeKeyBindingsType::MultiLineEditor:
817 return mEditCommandsForMultiLineEditorInitialized;
818 case NativeKeyBindingsType::RichTextEditor:
819 return mEditCommandsForRichTextEditorInitialized;
820 default:
821 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
822 "Invalid native key binding type");
827 /******************************************************************************
828 * mozilla::WidgetCompositionEvent
829 ******************************************************************************/
831 class WidgetCompositionEvent : public WidgetGUIEvent {
832 private:
833 friend class mozilla::dom::PBrowserParent;
834 friend class mozilla::dom::PBrowserChild;
836 WidgetCompositionEvent() : mOriginalMessage(eVoidEvent) {}
838 public:
839 virtual WidgetCompositionEvent* AsCompositionEvent() override { return this; }
841 WidgetCompositionEvent(bool aIsTrusted, EventMessage aMessage,
842 nsIWidget* aWidget)
843 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eCompositionEventClass),
844 mNativeIMEContext(aWidget),
845 mOriginalMessage(eVoidEvent) {}
847 virtual WidgetEvent* Duplicate() const override {
848 MOZ_ASSERT(mClass == eCompositionEventClass,
849 "Duplicate() must be overridden by sub class");
850 // Not copying widget, it is a weak reference.
851 WidgetCompositionEvent* result =
852 new WidgetCompositionEvent(false, mMessage, nullptr);
853 result->AssignCompositionEventData(*this, true);
854 result->mFlags = mFlags;
855 return result;
858 // The composition string or the commit string. If the instance is a
859 // compositionstart event, this is initialized with selected text by
860 // TextComposition automatically.
861 nsString mData;
863 RefPtr<TextRangeArray> mRanges;
865 // mNativeIMEContext stores the native IME context which causes the
866 // composition event.
867 widget::NativeIMEContext mNativeIMEContext;
869 // If the instance is a clone of another event, mOriginalMessage stores
870 // the another event's mMessage.
871 EventMessage mOriginalMessage;
873 void AssignCompositionEventData(const WidgetCompositionEvent& aEvent,
874 bool aCopyTargets) {
875 AssignGUIEventData(aEvent, aCopyTargets);
877 mData = aEvent.mData;
878 mOriginalMessage = aEvent.mOriginalMessage;
879 mRanges = aEvent.mRanges;
881 // Currently, we don't need to copy the other members because they are
882 // for internal use only (not available from JS).
885 bool IsComposing() const { return mRanges && mRanges->IsComposing(); }
887 uint32_t TargetClauseOffset() const {
888 return mRanges ? mRanges->TargetClauseOffset() : 0;
891 uint32_t TargetClauseLength() const {
892 uint32_t length = UINT32_MAX;
893 if (mRanges) {
894 length = mRanges->TargetClauseLength();
896 return length == UINT32_MAX ? mData.Length() : length;
899 uint32_t RangeCount() const { return mRanges ? mRanges->Length() : 0; }
901 bool CausesDOMTextEvent() const {
902 return mMessage == eCompositionChange || mMessage == eCompositionCommit ||
903 mMessage == eCompositionCommitAsIs;
906 bool CausesDOMCompositionEndEvent() const {
907 return mMessage == eCompositionEnd || mMessage == eCompositionCommit ||
908 mMessage == eCompositionCommitAsIs;
911 bool IsFollowedByCompositionEnd() const {
912 return IsFollowedByCompositionEnd(mOriginalMessage);
915 static bool IsFollowedByCompositionEnd(EventMessage aEventMessage) {
916 return aEventMessage == eCompositionCommit ||
917 aEventMessage == eCompositionCommitAsIs;
921 /******************************************************************************
922 * mozilla::WidgetQueryContentEvent
923 ******************************************************************************/
925 class WidgetQueryContentEvent : public WidgetGUIEvent {
926 private:
927 friend class dom::PBrowserParent;
928 friend class dom::PBrowserChild;
930 WidgetQueryContentEvent()
931 : mUseNativeLineBreak(true),
932 mWithFontRanges(false),
933 mNeedsToFlushLayout(true) {
934 MOZ_CRASH("WidgetQueryContentEvent is created without proper arguments");
937 public:
938 virtual WidgetQueryContentEvent* AsQueryContentEvent() override {
939 return this;
942 WidgetQueryContentEvent(bool aIsTrusted, EventMessage aMessage,
943 nsIWidget* aWidget)
944 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eQueryContentEventClass),
945 mUseNativeLineBreak(true),
946 mWithFontRanges(false),
947 mNeedsToFlushLayout(true) {}
949 WidgetQueryContentEvent(EventMessage aMessage,
950 const WidgetQueryContentEvent& aOtherEvent)
951 : WidgetGUIEvent(aOtherEvent.IsTrusted(), aMessage,
952 const_cast<nsIWidget*>(aOtherEvent.mWidget.get()),
953 eQueryContentEventClass),
954 mUseNativeLineBreak(aOtherEvent.mUseNativeLineBreak),
955 mWithFontRanges(false),
956 mNeedsToFlushLayout(aOtherEvent.mNeedsToFlushLayout) {}
958 virtual WidgetEvent* Duplicate() const override {
959 // This event isn't an internal event of any DOM event.
960 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
961 "WidgetQueryContentEvent needs to support Duplicate()");
962 MOZ_CRASH("WidgetQueryContentEvent doesn't support Duplicate()");
965 struct Options final {
966 bool mUseNativeLineBreak;
967 bool mRelativeToInsertionPoint;
969 explicit Options()
970 : mUseNativeLineBreak(true), mRelativeToInsertionPoint(false) {}
972 explicit Options(const WidgetQueryContentEvent& aEvent)
973 : mUseNativeLineBreak(aEvent.mUseNativeLineBreak),
974 mRelativeToInsertionPoint(aEvent.mInput.mRelativeToInsertionPoint) {}
977 void Init(const Options& aOptions) {
978 mUseNativeLineBreak = aOptions.mUseNativeLineBreak;
979 mInput.mRelativeToInsertionPoint = aOptions.mRelativeToInsertionPoint;
980 MOZ_ASSERT(mInput.IsValidEventMessage(mMessage));
983 void InitForQueryTextContent(int64_t aOffset, uint32_t aLength,
984 const Options& aOptions = Options()) {
985 NS_ASSERTION(mMessage == eQueryTextContent, "wrong initializer is called");
986 mInput.mOffset = aOffset;
987 mInput.mLength = aLength;
988 Init(aOptions);
989 MOZ_ASSERT(mInput.IsValidOffset());
992 void InitForQueryCaretRect(int64_t aOffset,
993 const Options& aOptions = Options()) {
994 NS_ASSERTION(mMessage == eQueryCaretRect, "wrong initializer is called");
995 mInput.mOffset = aOffset;
996 Init(aOptions);
997 MOZ_ASSERT(mInput.IsValidOffset());
1000 void InitForQueryTextRect(int64_t aOffset, uint32_t aLength,
1001 const Options& aOptions = Options()) {
1002 NS_ASSERTION(mMessage == eQueryTextRect, "wrong initializer is called");
1003 mInput.mOffset = aOffset;
1004 mInput.mLength = aLength;
1005 Init(aOptions);
1006 MOZ_ASSERT(mInput.IsValidOffset());
1009 void InitForQuerySelectedText(SelectionType aSelectionType,
1010 const Options& aOptions = Options()) {
1011 MOZ_ASSERT(mMessage == eQuerySelectedText);
1012 MOZ_ASSERT(aSelectionType != SelectionType::eNone);
1013 mInput.mSelectionType = aSelectionType;
1014 Init(aOptions);
1017 void InitForQueryDOMWidgetHittest(
1018 const mozilla::LayoutDeviceIntPoint& aPoint) {
1019 NS_ASSERTION(mMessage == eQueryDOMWidgetHittest,
1020 "wrong initializer is called");
1021 mRefPoint = aPoint;
1024 void InitForQueryTextRectArray(uint32_t aOffset, uint32_t aLength,
1025 const Options& aOptions = Options()) {
1026 NS_ASSERTION(mMessage == eQueryTextRectArray,
1027 "wrong initializer is called");
1028 mInput.mOffset = aOffset;
1029 mInput.mLength = aLength;
1030 Init(aOptions);
1033 bool NeedsToFlushLayout() const { return mNeedsToFlushLayout; }
1035 void RequestFontRanges() {
1036 MOZ_ASSERT(mMessage == eQueryTextContent);
1037 mWithFontRanges = true;
1040 bool Succeeded() const {
1041 if (mReply.isNothing()) {
1042 return false;
1044 switch (mMessage) {
1045 case eQueryTextContent:
1046 case eQueryTextRect:
1047 case eQueryCaretRect:
1048 return mReply->mOffsetAndData.isSome();
1049 default:
1050 return true;
1054 bool Failed() const { return !Succeeded(); }
1056 bool FoundSelection() const {
1057 MOZ_ASSERT(mMessage == eQuerySelectedText);
1058 return Succeeded() && mReply->mOffsetAndData.isSome();
1061 bool FoundChar() const {
1062 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1063 return Succeeded() && mReply->mOffsetAndData.isSome();
1066 bool FoundTentativeCaretOffset() const {
1067 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1068 return Succeeded() && mReply->mTentativeCaretOffset.isSome();
1071 bool DidNotFindSelection() const {
1072 MOZ_ASSERT(mMessage == eQuerySelectedText);
1073 return Failed() || mReply->mOffsetAndData.isNothing();
1076 bool DidNotFindChar() const {
1077 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1078 return Failed() || mReply->mOffsetAndData.isNothing();
1081 bool DidNotFindTentativeCaretOffset() const {
1082 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1083 return Failed() || mReply->mTentativeCaretOffset.isNothing();
1086 bool mUseNativeLineBreak;
1087 bool mWithFontRanges;
1088 bool mNeedsToFlushLayout;
1089 struct Input final {
1090 uint32_t EndOffset() const {
1091 CheckedInt<uint32_t> endOffset = CheckedInt<uint32_t>(mOffset) + mLength;
1092 return NS_WARN_IF(!endOffset.isValid()) ? UINT32_MAX : endOffset.value();
1095 int64_t mOffset;
1096 uint32_t mLength;
1097 SelectionType mSelectionType;
1098 // If mOffset is true, mOffset is relative to the start offset of
1099 // composition if there is, otherwise, the start of the first selection
1100 // range.
1101 bool mRelativeToInsertionPoint;
1103 Input()
1104 : mOffset(0),
1105 mLength(0),
1106 mSelectionType(SelectionType::eNormal),
1107 mRelativeToInsertionPoint(false) {}
1109 bool IsValidOffset() const {
1110 return mRelativeToInsertionPoint || mOffset >= 0;
1112 bool IsValidEventMessage(EventMessage aEventMessage) const {
1113 if (!mRelativeToInsertionPoint) {
1114 return true;
1116 switch (aEventMessage) {
1117 case eQueryTextContent:
1118 case eQueryCaretRect:
1119 case eQueryTextRect:
1120 return true;
1121 default:
1122 return false;
1125 bool MakeOffsetAbsolute(uint32_t aInsertionPointOffset) {
1126 if (NS_WARN_IF(!mRelativeToInsertionPoint)) {
1127 return true;
1129 mRelativeToInsertionPoint = false;
1130 // If mOffset + aInsertionPointOffset becomes negative value,
1131 // we should assume the absolute offset is 0.
1132 if (mOffset < 0 && -mOffset > aInsertionPointOffset) {
1133 mOffset = 0;
1134 return true;
1136 // Otherwise, we don't allow too large offset.
1137 CheckedInt<uint32_t> absOffset(mOffset + aInsertionPointOffset);
1138 if (NS_WARN_IF(!absOffset.isValid())) {
1139 mOffset = UINT32_MAX;
1140 return false;
1142 mOffset = absOffset.value();
1143 return true;
1145 } mInput;
1147 struct Reply final {
1148 EventMessage const mEventMessage;
1149 void* mContentsRoot = nullptr;
1150 Maybe<OffsetAndData<uint32_t>> mOffsetAndData;
1151 // mTentativeCaretOffset is used by only eQueryCharacterAtPoint.
1152 // This is the offset where caret would be if user clicked at the mRefPoint.
1153 Maybe<uint32_t> mTentativeCaretOffset;
1154 // mRect is used by eQueryTextRect, eQueryCaretRect, eQueryCharacterAtPoint
1155 // and eQueryEditorRect. The coordinates is system coordinates relative to
1156 // the top level widget of mFocusedWidget. E.g., if a <xul:panel> which
1157 // is owned by a window has focused editor, the offset of mRect is relative
1158 // to the owner window, not the <xul:panel>.
1159 mozilla::LayoutDeviceIntRect mRect;
1160 // The return widget has the caret. This is set at all query events.
1161 nsIWidget* mFocusedWidget = nullptr;
1162 // mozilla::WritingMode value at the end (focus) of the selection
1163 mozilla::WritingMode mWritingMode;
1164 // Used by eQuerySelectionAsTransferable
1165 nsCOMPtr<nsITransferable> mTransferable;
1166 // Used by eQueryTextContent with font ranges requested
1167 CopyableAutoTArray<mozilla::FontRange, 1> mFontRanges;
1168 // Used by eQueryTextRectArray
1169 CopyableTArray<mozilla::LayoutDeviceIntRect> mRectArray;
1170 // true if selection is reversed (end < start)
1171 bool mReversed = false;
1172 // true if DOM element under mouse belongs to widget
1173 bool mWidgetIsHit = false;
1174 // true if mContentRoot is focused editable content
1175 bool mIsEditableContent = false;
1177 Reply() = delete;
1178 explicit Reply(EventMessage aEventMessage) : mEventMessage(aEventMessage) {}
1180 // Don't allow to copy/move because of `mEventMessage`.
1181 Reply(const Reply& aOther) = delete;
1182 Reply(Reply&& aOther) = delete;
1183 Reply& operator=(const Reply& aOther) = delete;
1184 Reply& operator=(Reply&& aOther) = delete;
1186 MOZ_NEVER_INLINE_DEBUG uint32_t StartOffset() const {
1187 MOZ_ASSERT(mOffsetAndData.isSome());
1188 return mOffsetAndData->StartOffset();
1190 MOZ_NEVER_INLINE_DEBUG uint32_t EndOffset() const {
1191 MOZ_ASSERT(mOffsetAndData.isSome());
1192 return mOffsetAndData->EndOffset();
1194 MOZ_NEVER_INLINE_DEBUG uint32_t DataLength() const {
1195 MOZ_ASSERT(mOffsetAndData.isSome() ||
1196 mEventMessage == eQuerySelectedText);
1197 return mOffsetAndData.isSome() ? mOffsetAndData->Length() : 0;
1199 MOZ_NEVER_INLINE_DEBUG uint32_t AnchorOffset() const {
1200 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1201 MOZ_ASSERT(mOffsetAndData.isSome());
1202 return StartOffset() + (mReversed ? DataLength() : 0);
1205 MOZ_NEVER_INLINE_DEBUG uint32_t FocusOffset() const {
1206 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1207 MOZ_ASSERT(mOffsetAndData.isSome());
1208 return StartOffset() + (mReversed ? 0 : DataLength());
1211 const WritingMode& WritingModeRef() const {
1212 MOZ_ASSERT(mEventMessage == eQuerySelectedText ||
1213 mEventMessage == eQueryCaretRect ||
1214 mEventMessage == eQueryTextRect);
1215 MOZ_ASSERT(mOffsetAndData.isSome() ||
1216 mEventMessage == eQuerySelectedText);
1217 return mWritingMode;
1220 MOZ_NEVER_INLINE_DEBUG const nsString& DataRef() const {
1221 MOZ_ASSERT(mOffsetAndData.isSome() ||
1222 mEventMessage == eQuerySelectedText);
1223 return mOffsetAndData.isSome() ? mOffsetAndData->DataRef()
1224 : EmptyString();
1226 MOZ_NEVER_INLINE_DEBUG bool IsDataEmpty() const {
1227 MOZ_ASSERT(mOffsetAndData.isSome() ||
1228 mEventMessage == eQuerySelectedText);
1229 return mOffsetAndData.isSome() ? mOffsetAndData->IsDataEmpty() : true;
1231 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRange(uint32_t aOffset) const {
1232 MOZ_ASSERT(mOffsetAndData.isSome() ||
1233 mEventMessage == eQuerySelectedText);
1234 return mOffsetAndData.isSome() ? mOffsetAndData->IsOffsetInRange(aOffset)
1235 : false;
1237 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRangeOrEndOffset(
1238 uint32_t aOffset) const {
1239 MOZ_ASSERT(mOffsetAndData.isSome() ||
1240 mEventMessage == eQuerySelectedText);
1241 return mOffsetAndData.isSome()
1242 ? mOffsetAndData->IsOffsetInRangeOrEndOffset(aOffset)
1243 : false;
1245 MOZ_NEVER_INLINE_DEBUG void TruncateData(uint32_t aLength = 0) {
1246 MOZ_ASSERT(mOffsetAndData.isSome());
1247 mOffsetAndData->TruncateData(aLength);
1250 friend std::ostream& operator<<(std::ostream& aStream,
1251 const Reply& aReply) {
1252 aStream << "{ ";
1253 if (aReply.mEventMessage == eQuerySelectedText ||
1254 aReply.mEventMessage == eQueryTextContent ||
1255 aReply.mEventMessage == eQueryTextRect ||
1256 aReply.mEventMessage == eQueryCaretRect ||
1257 aReply.mEventMessage == eQueryCharacterAtPoint) {
1258 aStream << "mOffsetAndData=" << ToString(aReply.mOffsetAndData).c_str()
1259 << ", ";
1260 if (aReply.mEventMessage == eQueryCharacterAtPoint) {
1261 aStream << "mTentativeCaretOffset="
1262 << ToString(aReply.mTentativeCaretOffset).c_str() << ", ";
1265 if (aReply.mOffsetAndData.isSome() && aReply.mOffsetAndData->Length()) {
1266 if (aReply.mEventMessage == eQuerySelectedText) {
1267 aStream << ", mReversed=" << (aReply.mReversed ? "true" : "false");
1269 if (aReply.mEventMessage == eQuerySelectionAsTransferable) {
1270 aStream << ", mTransferable=0x" << aReply.mTransferable;
1273 if (aReply.mEventMessage == eQuerySelectedText ||
1274 aReply.mEventMessage == eQueryTextRect ||
1275 aReply.mEventMessage == eQueryCaretRect) {
1276 aStream << ", mWritingMode=" << ToString(aReply.mWritingMode).c_str();
1278 aStream << ", mContentsRoot=0x" << aReply.mContentsRoot
1279 << ", mIsEditableContent="
1280 << (aReply.mIsEditableContent ? "true" : "false")
1281 << ", mFocusedWidget=0x" << aReply.mFocusedWidget;
1282 if (aReply.mEventMessage == eQueryTextContent) {
1283 aStream << ", mFontRanges={ Length()=" << aReply.mFontRanges.Length()
1284 << " }";
1285 } else if (aReply.mEventMessage == eQueryTextRect ||
1286 aReply.mEventMessage == eQueryCaretRect ||
1287 aReply.mEventMessage == eQueryCharacterAtPoint) {
1288 aStream << ", mRect=" << ToString(aReply.mRect).c_str();
1289 } else if (aReply.mEventMessage == eQueryTextRectArray) {
1290 aStream << ", mRectArray={ Length()=" << aReply.mRectArray.Length()
1291 << " }";
1292 } else if (aReply.mEventMessage == eQueryDOMWidgetHittest) {
1293 aStream << ", mWidgetIsHit="
1294 << (aReply.mWidgetIsHit ? "true" : "false");
1296 return aStream << " }";
1300 void EmplaceReply() { mReply.emplace(mMessage); }
1301 Maybe<Reply> mReply;
1303 // values of mComputedScrollAction
1304 enum { SCROLL_ACTION_NONE, SCROLL_ACTION_LINE, SCROLL_ACTION_PAGE };
1307 /******************************************************************************
1308 * mozilla::WidgetSelectionEvent
1309 ******************************************************************************/
1311 class WidgetSelectionEvent : public WidgetGUIEvent {
1312 private:
1313 friend class mozilla::dom::PBrowserParent;
1314 friend class mozilla::dom::PBrowserChild;
1316 WidgetSelectionEvent()
1317 : mOffset(0),
1318 mLength(0),
1319 mReversed(false),
1320 mExpandToClusterBoundary(true),
1321 mSucceeded(false),
1322 mUseNativeLineBreak(true),
1323 mReason(nsISelectionListener::NO_REASON) {}
1325 public:
1326 virtual WidgetSelectionEvent* AsSelectionEvent() override { return this; }
1328 WidgetSelectionEvent(bool aIsTrusted, EventMessage aMessage,
1329 nsIWidget* aWidget)
1330 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eSelectionEventClass),
1331 mOffset(0),
1332 mLength(0),
1333 mReversed(false),
1334 mExpandToClusterBoundary(true),
1335 mSucceeded(false),
1336 mUseNativeLineBreak(true),
1337 mReason(nsISelectionListener::NO_REASON) {}
1339 virtual WidgetEvent* Duplicate() const override {
1340 // This event isn't an internal event of any DOM event.
1341 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1342 "WidgetSelectionEvent needs to support Duplicate()");
1343 MOZ_CRASH("WidgetSelectionEvent doesn't support Duplicate()");
1344 return nullptr;
1347 // Start offset of selection
1348 uint32_t mOffset;
1349 // Length of selection
1350 uint32_t mLength;
1351 // Selection "anchor" should be in front
1352 bool mReversed;
1353 // Cluster-based or character-based
1354 bool mExpandToClusterBoundary;
1355 // true if setting selection succeeded.
1356 bool mSucceeded;
1357 // true if native line breaks are used for mOffset and mLength
1358 bool mUseNativeLineBreak;
1359 // Fennec provides eSetSelection reason codes for downstream
1360 // use in AccessibleCaret visibility logic.
1361 int16_t mReason;
1364 /******************************************************************************
1365 * mozilla::InternalEditorInputEvent
1366 ******************************************************************************/
1368 class InternalEditorInputEvent : public InternalUIEvent {
1369 private:
1370 InternalEditorInputEvent()
1371 : mData(VoidString()),
1372 mInputType(EditorInputType::eUnknown),
1373 mIsComposing(false) {}
1375 public:
1376 virtual InternalEditorInputEvent* AsEditorInputEvent() override {
1377 return this;
1380 InternalEditorInputEvent(bool aIsTrusted, EventMessage aMessage,
1381 nsIWidget* aWidget = nullptr)
1382 : InternalUIEvent(aIsTrusted, aMessage, aWidget, eEditorInputEventClass),
1383 mData(VoidString()),
1384 mInputType(EditorInputType::eUnknown) {}
1386 virtual WidgetEvent* Duplicate() const override {
1387 MOZ_ASSERT(mClass == eEditorInputEventClass,
1388 "Duplicate() must be overridden by sub class");
1389 // Not copying widget, it is a weak reference.
1390 InternalEditorInputEvent* result =
1391 new InternalEditorInputEvent(false, mMessage, nullptr);
1392 result->AssignEditorInputEventData(*this, true);
1393 result->mFlags = mFlags;
1394 return result;
1397 nsString mData;
1398 RefPtr<dom::DataTransfer> mDataTransfer;
1399 OwningNonNullStaticRangeArray mTargetRanges;
1401 EditorInputType mInputType;
1403 bool mIsComposing;
1405 void AssignEditorInputEventData(const InternalEditorInputEvent& aEvent,
1406 bool aCopyTargets) {
1407 AssignUIEventData(aEvent, aCopyTargets);
1409 mData = aEvent.mData;
1410 mDataTransfer = aEvent.mDataTransfer;
1411 mTargetRanges = aEvent.mTargetRanges.Clone();
1412 mInputType = aEvent.mInputType;
1413 mIsComposing = aEvent.mIsComposing;
1416 void GetDOMInputTypeName(nsAString& aInputTypeName) {
1417 GetDOMInputTypeName(mInputType, aInputTypeName);
1419 static void GetDOMInputTypeName(EditorInputType aInputType,
1420 nsAString& aInputTypeName);
1421 static EditorInputType GetEditorInputType(const nsAString& aInputType);
1423 static void Shutdown();
1425 private:
1426 static const char16_t* const kInputTypeNames[];
1427 typedef nsTHashMap<nsStringHashKey, EditorInputType> InputTypeHashtable;
1428 static InputTypeHashtable* sInputTypeHashtable;
1431 } // namespace mozilla
1433 #endif // mozilla_TextEvents_h__