Bug 1793579 [wpt PR 36253] - Set empty string for reflection of IDREF attributes...
[gecko.git] / widget / TextEvents.h
blob1cc87be1830586aae2de269d635d01f6cec9b946
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 final : 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 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 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()));
297 [[nodiscard]] bool ShouldWorkAsSpaceKey() const {
298 if (mKeyCode == NS_VK_SPACE) {
299 return true;
301 // Additionally, if the code value is "Space" and the key is not mapped to
302 // a function key (i.e., not a printable key), we should treat it as space
303 // key because the active keyboard layout may input different character
304 // from the ASCII white space (U+0020). For example, NBSP (U+00A0).
305 return mKeyNameIndex == KEY_NAME_INDEX_USE_STRING &&
306 mCodeNameIndex == CODE_NAME_INDEX_Space;
310 * CanTreatAsUserInput() returns true if the key is pressed for perhaps
311 * doing something on the web app or our UI. This means that when this
312 * returns false, e.g., when user presses a modifier key, user is probably
313 * displeased by opening popup, entering fullscreen mode, etc. Therefore,
314 * only when this returns true, such reactions should be allowed.
316 bool CanTreatAsUserInput() const {
317 if (!IsTrusted()) {
318 return false;
320 switch (mKeyNameIndex) {
321 case KEY_NAME_INDEX_Escape:
322 // modifier keys:
323 case KEY_NAME_INDEX_Alt:
324 case KEY_NAME_INDEX_AltGraph:
325 case KEY_NAME_INDEX_CapsLock:
326 case KEY_NAME_INDEX_Control:
327 case KEY_NAME_INDEX_Fn:
328 case KEY_NAME_INDEX_FnLock:
329 case KEY_NAME_INDEX_Meta:
330 case KEY_NAME_INDEX_NumLock:
331 case KEY_NAME_INDEX_ScrollLock:
332 case KEY_NAME_INDEX_Shift:
333 case KEY_NAME_INDEX_Symbol:
334 case KEY_NAME_INDEX_SymbolLock:
335 // legacy modifier keys:
336 case KEY_NAME_INDEX_Hyper:
337 case KEY_NAME_INDEX_Super:
338 // obsolete modifier key:
339 case KEY_NAME_INDEX_OS:
340 return false;
341 default:
342 return true;
347 * ShouldInteractionTimeRecorded() returns true if the handling time of
348 * the event should be recorded with the telemetry.
350 bool ShouldInteractionTimeRecorded() const {
351 // Let's record only when we can treat the instance is a user input.
352 return CanTreatAsUserInput();
355 // OS translated Unicode chars which are used for accesskey and accelkey
356 // handling. The handlers will try from first character to last character.
357 CopyableTArray<AlternativeCharCode> mAlternativeCharCodes;
358 // DOM KeyboardEvent.key only when mKeyNameIndex is KEY_NAME_INDEX_USE_STRING.
359 nsString mKeyValue;
360 // DOM KeyboardEvent.code only when mCodeNameIndex is
361 // CODE_NAME_INDEX_USE_STRING.
362 nsString mCodeValue;
364 // OS-specific native event can optionally be preserved.
365 // This is used to retrieve editing shortcut keys in the environment.
366 void* mNativeKeyEvent;
367 // A DOM keyCode value or 0. If a keypress event whose mCharCode is 0, this
368 // should be 0.
369 uint32_t mKeyCode;
370 // If the instance is a keypress event of a printable key, this is a UTF-16
371 // value of the key. Otherwise, 0. This value must not be a control
372 // character when some modifiers are active. Then, this value should be an
373 // unmodified value except Shift and AltGr.
374 uint32_t mCharCode;
375 // mPseudoCharCode is valid only when mMessage is an eKeyDown event.
376 // This stores mCharCode value of keypress event which is fired with same
377 // key value and same modifier state.
378 uint32_t mPseudoCharCode;
379 // One of eKeyLocation*
380 uint32_t mLocation;
381 // Unique id associated with a keydown / keypress event. It's ok if this wraps
382 // over long periods.
383 uint32_t mUniqueId;
385 // DOM KeyboardEvent.key
386 KeyNameIndex mKeyNameIndex;
387 // DOM KeyboardEvent.code
388 CodeNameIndex mCodeNameIndex;
390 // Indicates whether the event is generated by auto repeat or not.
391 // if this is keyup event, always false.
392 bool mIsRepeat;
393 // Indicates whether the event is generated during IME (or deadkey)
394 // composition. This is initialized by EventStateManager. So, key event
395 // dispatchers don't need to initialize this.
396 bool mIsComposing;
397 // Indicates whether the event is synthesized from Text Input Processor
398 // or an actual event from nsAppShell.
399 bool mIsSynthesizedByTIP;
400 // Indicates whether the event is skippable in remote process.
401 // Don't refer this member directly when you need to check this.
402 // Use CanSkipInRemoteProcess() instead.
403 bool mMaybeSkippableInRemoteProcess;
404 // Indicates whether the event should return legacy keyCode value and
405 // charCode value to web apps (one of them is always 0) or not, when it's
406 // an eKeyPress event.
407 bool mUseLegacyKeyCodeAndCharCodeValues;
409 bool CanSkipInRemoteProcess() const {
410 // If this is a repeat event (i.e., generated by auto-repeat feature of
411 // the platform), remove process may skip to handle it because of
412 // performances reasons.. However, if it's caused by odd keyboard utils,
413 // we should not ignore any key events even marked as repeated since
414 // generated key sequence may be important to input proper text. E.g.,
415 // "SinhalaTamil IME" on Windows emulates dead key like input with
416 // generating WM_KEYDOWN for VK_PACKET (inputting any Unicode characters
417 // without keyboard layout information) and VK_BACK (Backspace) to remove
418 // previous character(s) and those messages may be marked as "repeat" by
419 // their bug.
420 return mIsRepeat && mMaybeSkippableInRemoteProcess;
424 * If the key is an arrow key, and the current selection is in a vertical
425 * content, the caret should be moved to physically. However, arrow keys
426 * are mapped to logical move commands in horizontal content. Therefore,
427 * we need to check writing mode if and only if the key is an arrow key, and
428 * need to remap the command to logical command in vertical content if the
429 * writing mode at selection is vertical. These methods help to convert
430 * arrow keys in horizontal content to correspnding direction arrow keys
431 * in vertical content.
433 bool NeedsToRemapNavigationKey() const {
434 // TODO: Use mKeyNameIndex instead.
435 return mKeyCode >= NS_VK_LEFT && mKeyCode <= NS_VK_DOWN;
438 uint32_t GetRemappedKeyCode(const WritingMode& aWritingMode) const {
439 if (!aWritingMode.IsVertical()) {
440 return mKeyCode;
442 switch (mKeyCode) {
443 case NS_VK_LEFT:
444 return aWritingMode.IsVerticalLR() ? NS_VK_UP : NS_VK_DOWN;
445 case NS_VK_RIGHT:
446 return aWritingMode.IsVerticalLR() ? NS_VK_DOWN : NS_VK_UP;
447 case NS_VK_UP:
448 return NS_VK_LEFT;
449 case NS_VK_DOWN:
450 return NS_VK_RIGHT;
451 default:
452 return mKeyCode;
456 KeyNameIndex GetRemappedKeyNameIndex(const WritingMode& aWritingMode) const {
457 if (!aWritingMode.IsVertical()) {
458 return mKeyNameIndex;
460 uint32_t remappedKeyCode = GetRemappedKeyCode(aWritingMode);
461 if (remappedKeyCode == mKeyCode) {
462 return mKeyNameIndex;
464 switch (remappedKeyCode) {
465 case NS_VK_LEFT:
466 return KEY_NAME_INDEX_ArrowLeft;
467 case NS_VK_RIGHT:
468 return KEY_NAME_INDEX_ArrowRight;
469 case NS_VK_UP:
470 return KEY_NAME_INDEX_ArrowUp;
471 case NS_VK_DOWN:
472 return KEY_NAME_INDEX_ArrowDown;
473 default:
474 MOZ_ASSERT_UNREACHABLE("Add a case for the new remapped key");
475 return mKeyNameIndex;
480 * Retrieves all edit commands from mWidget. This shouldn't be called when
481 * the instance is an untrusted event, doesn't have widget or in non-chrome
482 * process.
484 * @param aWritingMode
485 * When writing mode of focused element is vertical, this
486 * will resolve some key's physical direction to logical
487 * direction. For doing it, this must be set to the
488 * writing mode at current selection. However, when there
489 * is no focused element and no selection ranges, this
490 * should be set to Nothing(). Using the result of
491 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
492 * is recommended.
494 MOZ_CAN_RUN_SCRIPT void InitAllEditCommands(
495 const Maybe<WritingMode>& aWritingMode);
498 * Retrieves edit commands from mWidget only for aType. This shouldn't be
499 * called when the instance is an untrusted event or doesn't have widget.
501 * @param aWritingMode
502 * When writing mode of focused element is vertical, this
503 * will resolve some key's physical direction to logical
504 * direction. For doing it, this must be set to the
505 * writing mode at current selection. However, when there
506 * is no focused element and no selection ranges, this
507 * should be set to Nothing(). Using the result of
508 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
509 * is recommended.
510 * @return false if some resource is not available to get
511 * commands unexpectedly. Otherwise, true even if
512 * retrieved command is nothing.
514 MOZ_CAN_RUN_SCRIPT bool InitEditCommandsFor(
515 NativeKeyBindingsType aType, const Maybe<WritingMode>& aWritingMode);
518 * PreventNativeKeyBindings() makes the instance to not cause any edit
519 * actions even if it matches with a native key binding.
521 void PreventNativeKeyBindings() {
522 mEditCommandsForSingleLineEditor.Clear();
523 mEditCommandsForMultiLineEditor.Clear();
524 mEditCommandsForRichTextEditor.Clear();
525 mEditCommandsForSingleLineEditorInitialized = true;
526 mEditCommandsForMultiLineEditorInitialized = true;
527 mEditCommandsForRichTextEditorInitialized = true;
531 * EditCommandsConstRef() returns reference to edit commands for aType.
533 const nsTArray<CommandInt>& EditCommandsConstRef(
534 NativeKeyBindingsType aType) const {
535 return const_cast<WidgetKeyboardEvent*>(this)->EditCommandsRef(aType);
539 * IsEditCommandsInitialized() returns true if edit commands for aType
540 * was already initialized. Otherwise, false.
542 bool IsEditCommandsInitialized(NativeKeyBindingsType aType) const {
543 return const_cast<WidgetKeyboardEvent*>(this)->IsEditCommandsInitializedRef(
544 aType);
548 * AreAllEditCommandsInitialized() returns true if edit commands for all
549 * types were already initialized. Otherwise, false.
551 bool AreAllEditCommandsInitialized() const {
552 return mEditCommandsForSingleLineEditorInitialized &&
553 mEditCommandsForMultiLineEditorInitialized &&
554 mEditCommandsForRichTextEditorInitialized;
558 * Execute edit commands for aType.
560 * @return true if the caller should do nothing anymore.
561 * false, otherwise.
563 typedef void (*DoCommandCallback)(Command, void*);
564 MOZ_CAN_RUN_SCRIPT bool ExecuteEditCommands(NativeKeyBindingsType aType,
565 DoCommandCallback aCallback,
566 void* aCallbackData);
568 // If the key should cause keypress events, this returns true.
569 // Otherwise, false.
570 bool ShouldCauseKeypressEvents() const;
572 // mCharCode value of non-eKeyPress events is always 0. However, if
573 // non-eKeyPress event has one or more alternative char code values,
574 // its first item should be the mCharCode value of following eKeyPress event.
575 // PseudoCharCode() returns mCharCode value for eKeyPress event,
576 // the first alternative char code value of non-eKeyPress event or 0.
577 uint32_t PseudoCharCode() const {
578 return mMessage == eKeyPress ? mCharCode : mPseudoCharCode;
580 void SetCharCode(uint32_t aCharCode) {
581 if (mMessage == eKeyPress) {
582 mCharCode = aCharCode;
583 } else {
584 mPseudoCharCode = aCharCode;
588 void GetDOMKeyName(nsAString& aKeyName) {
589 if (mKeyNameIndex == KEY_NAME_INDEX_USE_STRING) {
590 aKeyName = mKeyValue;
591 return;
593 GetDOMKeyName(mKeyNameIndex, aKeyName);
595 void GetDOMCodeName(nsAString& aCodeName) {
596 if (mCodeNameIndex == CODE_NAME_INDEX_USE_STRING) {
597 aCodeName = mCodeValue;
598 return;
600 GetDOMCodeName(mCodeNameIndex, aCodeName);
604 * GetFallbackKeyCodeOfPunctuationKey() returns a DOM keyCode value for
605 * aCodeNameIndex. This is keyCode value of the key when active keyboard
606 * layout is ANSI (US), JIS or ABNT keyboard layout (the latter 2 layouts
607 * are used only when ANSI doesn't have the key). The result is useful
608 * if the key doesn't produce ASCII character with active keyboard layout
609 * nor with alternative ASCII capable keyboard layout.
611 static uint32_t GetFallbackKeyCodeOfPunctuationKey(
612 CodeNameIndex aCodeNameIndex);
614 bool IsModifierKeyEvent() const {
615 return GetModifierForKeyName(mKeyNameIndex) != MODIFIER_NONE;
619 * Get the candidates for shortcut key.
621 * @param aCandidates [out] the candidate shortcut key combination list.
622 * the first item is most preferred.
624 void GetShortcutKeyCandidates(ShortcutKeyCandidateArray& aCandidates) const;
627 * Get the candidates for access key.
629 * @param aCandidates [out] the candidate access key list.
630 * the first item is most preferred.
632 void GetAccessKeyCandidates(nsTArray<uint32_t>& aCandidates) const;
635 * Check whether the modifiers match with chrome access key or
636 * content access key.
638 bool ModifiersMatchWithAccessKey(AccessKeyType aType) const;
641 * Return active modifiers which may match with access key.
642 * For example, even if Alt is access key modifier, then, when Control,
643 * CapseLock and NumLock are active, this returns only MODIFIER_CONTROL.
645 Modifiers ModifiersForAccessKeyMatching() const;
648 * Return access key modifiers.
650 static Modifiers AccessKeyModifiers(AccessKeyType aType);
652 static void Shutdown();
655 * ComputeLocationFromCodeValue() returns one of .mLocation value
656 * (eKeyLocation*) which is the most preferred value for the specified code
657 * value.
659 static uint32_t ComputeLocationFromCodeValue(CodeNameIndex aCodeNameIndex);
662 * ComputeKeyCodeFromKeyNameIndex() return a .mKeyCode value which can be
663 * mapped from the specified key value. Note that this returns 0 if the
664 * key name index is KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
665 * This means that this method is useful only for non-printable keys.
667 static uint32_t ComputeKeyCodeFromKeyNameIndex(KeyNameIndex aKeyNameIndex);
670 * ComputeCodeNameIndexFromKeyNameIndex() returns a code name index which
671 * is typically mapped to given key name index on the platform.
672 * Note that this returns CODE_NAME_INDEX_UNKNOWN if the key name index is
673 * KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
674 * This means that this method is useful only for non-printable keys.
676 * @param aKeyNameIndex A non-printable key name index.
677 * @param aLocation Should be one of location value. This is
678 * important when aKeyNameIndex may exist in
679 * both Numpad or Standard, or in both Left or
680 * Right. If this is nothing, this method
681 * returns Left or Standard position's code
682 * value.
684 static CodeNameIndex ComputeCodeNameIndexFromKeyNameIndex(
685 KeyNameIndex aKeyNameIndex, const Maybe<uint32_t>& aLocation);
688 * GetModifierForKeyName() returns a value of Modifier which is activated
689 * by the aKeyNameIndex.
691 static Modifier GetModifierForKeyName(KeyNameIndex aKeyNameIndex);
694 * IsLeftOrRightModiferKeyNameIndex() returns true if aKeyNameIndex is a
695 * modifier key which may be in Left and Right location.
697 static bool IsLeftOrRightModiferKeyNameIndex(KeyNameIndex aKeyNameIndex) {
698 switch (aKeyNameIndex) {
699 case KEY_NAME_INDEX_Alt:
700 case KEY_NAME_INDEX_Control:
701 case KEY_NAME_INDEX_Meta:
702 case KEY_NAME_INDEX_OS:
703 case KEY_NAME_INDEX_Shift:
704 return true;
705 default:
706 return false;
711 * IsLockableModifier() returns true if aKeyNameIndex is a lockable modifier
712 * key such as CapsLock and NumLock.
714 static bool IsLockableModifier(KeyNameIndex aKeyNameIndex);
716 static void GetDOMKeyName(KeyNameIndex aKeyNameIndex, nsAString& aKeyName);
717 static void GetDOMCodeName(CodeNameIndex aCodeNameIndex,
718 nsAString& aCodeName);
720 static KeyNameIndex GetKeyNameIndex(const nsAString& aKeyValue);
721 static CodeNameIndex GetCodeNameIndex(const nsAString& aCodeValue);
723 static const char* GetCommandStr(Command aCommand);
725 void AssignKeyEventData(const WidgetKeyboardEvent& aEvent,
726 bool aCopyTargets) {
727 AssignInputEventData(aEvent, aCopyTargets);
729 mKeyCode = aEvent.mKeyCode;
730 mCharCode = aEvent.mCharCode;
731 mPseudoCharCode = aEvent.mPseudoCharCode;
732 mLocation = aEvent.mLocation;
733 mAlternativeCharCodes = aEvent.mAlternativeCharCodes.Clone();
734 mIsRepeat = aEvent.mIsRepeat;
735 mIsComposing = aEvent.mIsComposing;
736 mKeyNameIndex = aEvent.mKeyNameIndex;
737 mCodeNameIndex = aEvent.mCodeNameIndex;
738 mKeyValue = aEvent.mKeyValue;
739 mCodeValue = aEvent.mCodeValue;
740 // Don't copy mNativeKeyEvent because it may be referred after its instance
741 // is destroyed.
742 mNativeKeyEvent = nullptr;
743 mUniqueId = aEvent.mUniqueId;
744 mIsSynthesizedByTIP = aEvent.mIsSynthesizedByTIP;
745 mMaybeSkippableInRemoteProcess = aEvent.mMaybeSkippableInRemoteProcess;
746 mUseLegacyKeyCodeAndCharCodeValues =
747 aEvent.mUseLegacyKeyCodeAndCharCodeValues;
749 // Don't copy mEditCommandsFor*Editor because it may require a lot of
750 // memory space. For example, if the event is dispatched but grabbed by
751 // a JS variable, they are not necessary anymore.
753 mEditCommandsForSingleLineEditorInitialized =
754 aEvent.mEditCommandsForSingleLineEditorInitialized;
755 mEditCommandsForMultiLineEditorInitialized =
756 aEvent.mEditCommandsForMultiLineEditorInitialized;
757 mEditCommandsForRichTextEditorInitialized =
758 aEvent.mEditCommandsForRichTextEditorInitialized;
761 void AssignCommands(const WidgetKeyboardEvent& aEvent) {
762 mEditCommandsForSingleLineEditorInitialized =
763 aEvent.mEditCommandsForSingleLineEditorInitialized;
764 if (mEditCommandsForSingleLineEditorInitialized) {
765 mEditCommandsForSingleLineEditor =
766 aEvent.mEditCommandsForSingleLineEditor.Clone();
767 } else {
768 mEditCommandsForSingleLineEditor.Clear();
770 mEditCommandsForMultiLineEditorInitialized =
771 aEvent.mEditCommandsForMultiLineEditorInitialized;
772 if (mEditCommandsForMultiLineEditorInitialized) {
773 mEditCommandsForMultiLineEditor =
774 aEvent.mEditCommandsForMultiLineEditor.Clone();
775 } else {
776 mEditCommandsForMultiLineEditor.Clear();
778 mEditCommandsForRichTextEditorInitialized =
779 aEvent.mEditCommandsForRichTextEditorInitialized;
780 if (mEditCommandsForRichTextEditorInitialized) {
781 mEditCommandsForRichTextEditor =
782 aEvent.mEditCommandsForRichTextEditor.Clone();
783 } else {
784 mEditCommandsForRichTextEditor.Clear();
788 private:
789 static const char16_t* const kKeyNames[];
790 static const char16_t* const kCodeNames[];
791 typedef nsTHashMap<nsStringHashKey, KeyNameIndex> KeyNameIndexHashtable;
792 typedef nsTHashMap<nsStringHashKey, CodeNameIndex> CodeNameIndexHashtable;
793 static KeyNameIndexHashtable* sKeyNameIndexHashtable;
794 static CodeNameIndexHashtable* sCodeNameIndexHashtable;
796 // mEditCommandsFor*Editor store edit commands. This should be initialized
797 // with InitEditCommandsFor().
798 // XXX Ideally, this should be array of Command rather than CommandInt.
799 // However, ParamTraits isn't aware of enum array.
800 CopyableTArray<CommandInt> mEditCommandsForSingleLineEditor;
801 CopyableTArray<CommandInt> mEditCommandsForMultiLineEditor;
802 CopyableTArray<CommandInt> mEditCommandsForRichTextEditor;
804 nsTArray<CommandInt>& EditCommandsRef(NativeKeyBindingsType aType) {
805 switch (aType) {
806 case NativeKeyBindingsType::SingleLineEditor:
807 return mEditCommandsForSingleLineEditor;
808 case NativeKeyBindingsType::MultiLineEditor:
809 return mEditCommandsForMultiLineEditor;
810 case NativeKeyBindingsType::RichTextEditor:
811 return mEditCommandsForRichTextEditor;
812 default:
813 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
814 "Invalid native key binding type");
818 // mEditCommandsFor*EditorInitialized are set to true when
819 // InitEditCommandsFor() initializes edit commands for the type.
820 bool mEditCommandsForSingleLineEditorInitialized;
821 bool mEditCommandsForMultiLineEditorInitialized;
822 bool mEditCommandsForRichTextEditorInitialized;
824 bool& IsEditCommandsInitializedRef(NativeKeyBindingsType aType) {
825 switch (aType) {
826 case NativeKeyBindingsType::SingleLineEditor:
827 return mEditCommandsForSingleLineEditorInitialized;
828 case NativeKeyBindingsType::MultiLineEditor:
829 return mEditCommandsForMultiLineEditorInitialized;
830 case NativeKeyBindingsType::RichTextEditor:
831 return mEditCommandsForRichTextEditorInitialized;
832 default:
833 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
834 "Invalid native key binding type");
839 /******************************************************************************
840 * mozilla::WidgetCompositionEvent
841 ******************************************************************************/
843 class WidgetCompositionEvent : public WidgetGUIEvent {
844 private:
845 friend class mozilla::dom::PBrowserParent;
846 friend class mozilla::dom::PBrowserChild;
848 WidgetCompositionEvent() : mOriginalMessage(eVoidEvent) {}
850 public:
851 virtual WidgetCompositionEvent* AsCompositionEvent() override { return this; }
853 WidgetCompositionEvent(bool aIsTrusted, EventMessage aMessage,
854 nsIWidget* aWidget)
855 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eCompositionEventClass),
856 mNativeIMEContext(aWidget),
857 mOriginalMessage(eVoidEvent) {}
859 virtual WidgetEvent* Duplicate() const override {
860 MOZ_ASSERT(mClass == eCompositionEventClass,
861 "Duplicate() must be overridden by sub class");
862 // Not copying widget, it is a weak reference.
863 WidgetCompositionEvent* result =
864 new WidgetCompositionEvent(false, mMessage, nullptr);
865 result->AssignCompositionEventData(*this, true);
866 result->mFlags = mFlags;
867 return result;
870 // The composition string or the commit string. If the instance is a
871 // compositionstart event, this is initialized with selected text by
872 // TextComposition automatically.
873 nsString mData;
875 RefPtr<TextRangeArray> mRanges;
877 // mNativeIMEContext stores the native IME context which causes the
878 // composition event.
879 widget::NativeIMEContext mNativeIMEContext;
881 // If the instance is a clone of another event, mOriginalMessage stores
882 // the another event's mMessage.
883 EventMessage mOriginalMessage;
885 void AssignCompositionEventData(const WidgetCompositionEvent& aEvent,
886 bool aCopyTargets) {
887 AssignGUIEventData(aEvent, aCopyTargets);
889 mData = aEvent.mData;
890 mOriginalMessage = aEvent.mOriginalMessage;
891 mRanges = aEvent.mRanges;
893 // Currently, we don't need to copy the other members because they are
894 // for internal use only (not available from JS).
897 bool IsComposing() const { return mRanges && mRanges->IsComposing(); }
899 uint32_t TargetClauseOffset() const {
900 return mRanges ? mRanges->TargetClauseOffset() : 0;
903 uint32_t TargetClauseLength() const {
904 uint32_t length = UINT32_MAX;
905 if (mRanges) {
906 length = mRanges->TargetClauseLength();
908 return length == UINT32_MAX ? mData.Length() : length;
911 uint32_t RangeCount() const { return mRanges ? mRanges->Length() : 0; }
913 bool CausesDOMTextEvent() const {
914 return mMessage == eCompositionChange || mMessage == eCompositionCommit ||
915 mMessage == eCompositionCommitAsIs;
918 bool CausesDOMCompositionEndEvent() const {
919 return mMessage == eCompositionEnd || mMessage == eCompositionCommit ||
920 mMessage == eCompositionCommitAsIs;
923 bool IsFollowedByCompositionEnd() const {
924 return IsFollowedByCompositionEnd(mOriginalMessage);
927 static bool IsFollowedByCompositionEnd(EventMessage aEventMessage) {
928 return aEventMessage == eCompositionCommit ||
929 aEventMessage == eCompositionCommitAsIs;
933 /******************************************************************************
934 * mozilla::WidgetQueryContentEvent
935 ******************************************************************************/
937 class WidgetQueryContentEvent : public WidgetGUIEvent {
938 private:
939 friend class dom::PBrowserParent;
940 friend class dom::PBrowserChild;
942 WidgetQueryContentEvent()
943 : mUseNativeLineBreak(true),
944 mWithFontRanges(false),
945 mNeedsToFlushLayout(true) {
946 MOZ_CRASH("WidgetQueryContentEvent is created without proper arguments");
949 public:
950 virtual WidgetQueryContentEvent* AsQueryContentEvent() override {
951 return this;
954 WidgetQueryContentEvent(bool aIsTrusted, EventMessage aMessage,
955 nsIWidget* aWidget)
956 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eQueryContentEventClass),
957 mUseNativeLineBreak(true),
958 mWithFontRanges(false),
959 mNeedsToFlushLayout(true) {}
961 WidgetQueryContentEvent(EventMessage aMessage,
962 const WidgetQueryContentEvent& aOtherEvent)
963 : WidgetGUIEvent(aOtherEvent.IsTrusted(), aMessage,
964 const_cast<nsIWidget*>(aOtherEvent.mWidget.get()),
965 eQueryContentEventClass),
966 mUseNativeLineBreak(aOtherEvent.mUseNativeLineBreak),
967 mWithFontRanges(false),
968 mNeedsToFlushLayout(aOtherEvent.mNeedsToFlushLayout) {}
970 virtual WidgetEvent* Duplicate() const override {
971 // This event isn't an internal event of any DOM event.
972 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
973 "WidgetQueryContentEvent needs to support Duplicate()");
974 MOZ_CRASH("WidgetQueryContentEvent doesn't support Duplicate()");
977 struct Options final {
978 bool mUseNativeLineBreak;
979 bool mRelativeToInsertionPoint;
981 explicit Options()
982 : mUseNativeLineBreak(true), mRelativeToInsertionPoint(false) {}
984 explicit Options(const WidgetQueryContentEvent& aEvent)
985 : mUseNativeLineBreak(aEvent.mUseNativeLineBreak),
986 mRelativeToInsertionPoint(aEvent.mInput.mRelativeToInsertionPoint) {}
989 void Init(const Options& aOptions) {
990 mUseNativeLineBreak = aOptions.mUseNativeLineBreak;
991 mInput.mRelativeToInsertionPoint = aOptions.mRelativeToInsertionPoint;
992 MOZ_ASSERT(mInput.IsValidEventMessage(mMessage));
995 void InitForQueryTextContent(int64_t aOffset, uint32_t aLength,
996 const Options& aOptions = Options()) {
997 NS_ASSERTION(mMessage == eQueryTextContent, "wrong initializer is called");
998 mInput.mOffset = aOffset;
999 mInput.mLength = aLength;
1000 Init(aOptions);
1001 MOZ_ASSERT(mInput.IsValidOffset());
1004 void InitForQueryCaretRect(int64_t aOffset,
1005 const Options& aOptions = Options()) {
1006 NS_ASSERTION(mMessage == eQueryCaretRect, "wrong initializer is called");
1007 mInput.mOffset = aOffset;
1008 Init(aOptions);
1009 MOZ_ASSERT(mInput.IsValidOffset());
1012 void InitForQueryTextRect(int64_t aOffset, uint32_t aLength,
1013 const Options& aOptions = Options()) {
1014 NS_ASSERTION(mMessage == eQueryTextRect, "wrong initializer is called");
1015 mInput.mOffset = aOffset;
1016 mInput.mLength = aLength;
1017 Init(aOptions);
1018 MOZ_ASSERT(mInput.IsValidOffset());
1021 void InitForQuerySelectedText(SelectionType aSelectionType,
1022 const Options& aOptions = Options()) {
1023 MOZ_ASSERT(mMessage == eQuerySelectedText);
1024 MOZ_ASSERT(aSelectionType != SelectionType::eNone);
1025 mInput.mSelectionType = aSelectionType;
1026 Init(aOptions);
1029 void InitForQueryDOMWidgetHittest(
1030 const mozilla::LayoutDeviceIntPoint& aPoint) {
1031 NS_ASSERTION(mMessage == eQueryDOMWidgetHittest,
1032 "wrong initializer is called");
1033 mRefPoint = aPoint;
1036 void InitForQueryTextRectArray(uint32_t aOffset, uint32_t aLength,
1037 const Options& aOptions = Options()) {
1038 NS_ASSERTION(mMessage == eQueryTextRectArray,
1039 "wrong initializer is called");
1040 mInput.mOffset = aOffset;
1041 mInput.mLength = aLength;
1042 Init(aOptions);
1045 bool NeedsToFlushLayout() const { return mNeedsToFlushLayout; }
1047 void RequestFontRanges() {
1048 MOZ_ASSERT(mMessage == eQueryTextContent);
1049 mWithFontRanges = true;
1052 bool Succeeded() const {
1053 if (mReply.isNothing()) {
1054 return false;
1056 switch (mMessage) {
1057 case eQueryTextContent:
1058 case eQueryTextRect:
1059 case eQueryCaretRect:
1060 return mReply->mOffsetAndData.isSome();
1061 default:
1062 return true;
1066 bool Failed() const { return !Succeeded(); }
1068 bool FoundSelection() const {
1069 MOZ_ASSERT(mMessage == eQuerySelectedText);
1070 return Succeeded() && mReply->mOffsetAndData.isSome();
1073 bool FoundChar() const {
1074 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1075 return Succeeded() && mReply->mOffsetAndData.isSome();
1078 bool FoundTentativeCaretOffset() const {
1079 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1080 return Succeeded() && mReply->mTentativeCaretOffset.isSome();
1083 bool DidNotFindSelection() const {
1084 MOZ_ASSERT(mMessage == eQuerySelectedText);
1085 return Failed() || mReply->mOffsetAndData.isNothing();
1088 bool DidNotFindChar() const {
1089 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1090 return Failed() || mReply->mOffsetAndData.isNothing();
1093 bool DidNotFindTentativeCaretOffset() const {
1094 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1095 return Failed() || mReply->mTentativeCaretOffset.isNothing();
1098 bool mUseNativeLineBreak;
1099 bool mWithFontRanges;
1100 bool mNeedsToFlushLayout;
1101 struct Input final {
1102 uint32_t EndOffset() const {
1103 CheckedInt<uint32_t> endOffset = CheckedInt<uint32_t>(mOffset) + mLength;
1104 return NS_WARN_IF(!endOffset.isValid()) ? UINT32_MAX : endOffset.value();
1107 int64_t mOffset;
1108 uint32_t mLength;
1109 SelectionType mSelectionType;
1110 // If mOffset is true, mOffset is relative to the start offset of
1111 // composition if there is, otherwise, the start of the first selection
1112 // range.
1113 bool mRelativeToInsertionPoint;
1115 Input()
1116 : mOffset(0),
1117 mLength(0),
1118 mSelectionType(SelectionType::eNormal),
1119 mRelativeToInsertionPoint(false) {}
1121 bool IsValidOffset() const {
1122 return mRelativeToInsertionPoint || mOffset >= 0;
1124 bool IsValidEventMessage(EventMessage aEventMessage) const {
1125 if (!mRelativeToInsertionPoint) {
1126 return true;
1128 switch (aEventMessage) {
1129 case eQueryTextContent:
1130 case eQueryCaretRect:
1131 case eQueryTextRect:
1132 return true;
1133 default:
1134 return false;
1137 bool MakeOffsetAbsolute(uint32_t aInsertionPointOffset) {
1138 if (NS_WARN_IF(!mRelativeToInsertionPoint)) {
1139 return true;
1141 mRelativeToInsertionPoint = false;
1142 // If mOffset + aInsertionPointOffset becomes negative value,
1143 // we should assume the absolute offset is 0.
1144 if (mOffset < 0 && -mOffset > aInsertionPointOffset) {
1145 mOffset = 0;
1146 return true;
1148 // Otherwise, we don't allow too large offset.
1149 CheckedInt<uint32_t> absOffset(mOffset + aInsertionPointOffset);
1150 if (NS_WARN_IF(!absOffset.isValid())) {
1151 mOffset = UINT32_MAX;
1152 return false;
1154 mOffset = absOffset.value();
1155 return true;
1157 } mInput;
1159 struct Reply final {
1160 EventMessage const mEventMessage;
1161 void* mContentsRoot = nullptr;
1162 Maybe<OffsetAndData<uint32_t>> mOffsetAndData;
1163 // mTentativeCaretOffset is used by only eQueryCharacterAtPoint.
1164 // This is the offset where caret would be if user clicked at the mRefPoint.
1165 Maybe<uint32_t> mTentativeCaretOffset;
1166 // mRect is used by eQueryTextRect, eQueryCaretRect, eQueryCharacterAtPoint
1167 // and eQueryEditorRect. The coordinates is system coordinates relative to
1168 // the top level widget of mFocusedWidget. E.g., if a <xul:panel> which
1169 // is owned by a window has focused editor, the offset of mRect is relative
1170 // to the owner window, not the <xul:panel>.
1171 mozilla::LayoutDeviceIntRect mRect;
1172 // The return widget has the caret. This is set at all query events.
1173 nsIWidget* mFocusedWidget = nullptr;
1174 // mozilla::WritingMode value at the end (focus) of the selection
1175 mozilla::WritingMode mWritingMode;
1176 // Used by eQuerySelectionAsTransferable
1177 nsCOMPtr<nsITransferable> mTransferable;
1178 // Used by eQueryTextContent with font ranges requested
1179 CopyableAutoTArray<mozilla::FontRange, 1> mFontRanges;
1180 // Used by eQueryTextRectArray
1181 CopyableTArray<mozilla::LayoutDeviceIntRect> mRectArray;
1182 // true if selection is reversed (end < start)
1183 bool mReversed = false;
1184 // true if DOM element under mouse belongs to widget
1185 bool mWidgetIsHit = false;
1186 // true if mContentRoot is focused editable content
1187 bool mIsEditableContent = false;
1189 Reply() = delete;
1190 explicit Reply(EventMessage aEventMessage) : mEventMessage(aEventMessage) {}
1192 // Don't allow to copy/move because of `mEventMessage`.
1193 Reply(const Reply& aOther) = delete;
1194 Reply(Reply&& aOther) = delete;
1195 Reply& operator=(const Reply& aOther) = delete;
1196 Reply& operator=(Reply&& aOther) = delete;
1198 MOZ_NEVER_INLINE_DEBUG uint32_t StartOffset() const {
1199 MOZ_ASSERT(mOffsetAndData.isSome());
1200 return mOffsetAndData->StartOffset();
1202 MOZ_NEVER_INLINE_DEBUG uint32_t EndOffset() const {
1203 MOZ_ASSERT(mOffsetAndData.isSome());
1204 return mOffsetAndData->EndOffset();
1206 MOZ_NEVER_INLINE_DEBUG uint32_t DataLength() const {
1207 MOZ_ASSERT(mOffsetAndData.isSome() ||
1208 mEventMessage == eQuerySelectedText);
1209 return mOffsetAndData.isSome() ? mOffsetAndData->Length() : 0;
1211 MOZ_NEVER_INLINE_DEBUG uint32_t AnchorOffset() const {
1212 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1213 MOZ_ASSERT(mOffsetAndData.isSome());
1214 return StartOffset() + (mReversed ? DataLength() : 0);
1217 MOZ_NEVER_INLINE_DEBUG uint32_t FocusOffset() const {
1218 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1219 MOZ_ASSERT(mOffsetAndData.isSome());
1220 return StartOffset() + (mReversed ? 0 : DataLength());
1223 const WritingMode& WritingModeRef() const {
1224 MOZ_ASSERT(mEventMessage == eQuerySelectedText ||
1225 mEventMessage == eQueryCaretRect ||
1226 mEventMessage == eQueryTextRect);
1227 MOZ_ASSERT(mOffsetAndData.isSome() ||
1228 mEventMessage == eQuerySelectedText);
1229 return mWritingMode;
1232 MOZ_NEVER_INLINE_DEBUG const nsString& DataRef() const {
1233 MOZ_ASSERT(mOffsetAndData.isSome() ||
1234 mEventMessage == eQuerySelectedText);
1235 return mOffsetAndData.isSome() ? mOffsetAndData->DataRef()
1236 : EmptyString();
1238 MOZ_NEVER_INLINE_DEBUG bool IsDataEmpty() const {
1239 MOZ_ASSERT(mOffsetAndData.isSome() ||
1240 mEventMessage == eQuerySelectedText);
1241 return mOffsetAndData.isSome() ? mOffsetAndData->IsDataEmpty() : true;
1243 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRange(uint32_t aOffset) const {
1244 MOZ_ASSERT(mOffsetAndData.isSome() ||
1245 mEventMessage == eQuerySelectedText);
1246 return mOffsetAndData.isSome() ? mOffsetAndData->IsOffsetInRange(aOffset)
1247 : false;
1249 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRangeOrEndOffset(
1250 uint32_t aOffset) const {
1251 MOZ_ASSERT(mOffsetAndData.isSome() ||
1252 mEventMessage == eQuerySelectedText);
1253 return mOffsetAndData.isSome()
1254 ? mOffsetAndData->IsOffsetInRangeOrEndOffset(aOffset)
1255 : false;
1257 MOZ_NEVER_INLINE_DEBUG void TruncateData(uint32_t aLength = 0) {
1258 MOZ_ASSERT(mOffsetAndData.isSome());
1259 mOffsetAndData->TruncateData(aLength);
1262 friend std::ostream& operator<<(std::ostream& aStream,
1263 const Reply& aReply) {
1264 aStream << "{ ";
1265 if (aReply.mEventMessage == eQuerySelectedText ||
1266 aReply.mEventMessage == eQueryTextContent ||
1267 aReply.mEventMessage == eQueryTextRect ||
1268 aReply.mEventMessage == eQueryCaretRect ||
1269 aReply.mEventMessage == eQueryCharacterAtPoint) {
1270 aStream << "mOffsetAndData=" << ToString(aReply.mOffsetAndData).c_str()
1271 << ", ";
1272 if (aReply.mEventMessage == eQueryCharacterAtPoint) {
1273 aStream << "mTentativeCaretOffset="
1274 << ToString(aReply.mTentativeCaretOffset).c_str() << ", ";
1277 if (aReply.mOffsetAndData.isSome() && aReply.mOffsetAndData->Length()) {
1278 if (aReply.mEventMessage == eQuerySelectedText) {
1279 aStream << ", mReversed=" << (aReply.mReversed ? "true" : "false");
1281 if (aReply.mEventMessage == eQuerySelectionAsTransferable) {
1282 aStream << ", mTransferable=0x" << aReply.mTransferable;
1285 if (aReply.mEventMessage == eQuerySelectedText ||
1286 aReply.mEventMessage == eQueryTextRect ||
1287 aReply.mEventMessage == eQueryCaretRect) {
1288 aStream << ", mWritingMode=" << ToString(aReply.mWritingMode).c_str();
1290 aStream << ", mContentsRoot=0x" << aReply.mContentsRoot
1291 << ", mIsEditableContent="
1292 << (aReply.mIsEditableContent ? "true" : "false")
1293 << ", mFocusedWidget=0x" << aReply.mFocusedWidget;
1294 if (aReply.mEventMessage == eQueryTextContent) {
1295 aStream << ", mFontRanges={ Length()=" << aReply.mFontRanges.Length()
1296 << " }";
1297 } else if (aReply.mEventMessage == eQueryTextRect ||
1298 aReply.mEventMessage == eQueryCaretRect ||
1299 aReply.mEventMessage == eQueryCharacterAtPoint) {
1300 aStream << ", mRect=" << ToString(aReply.mRect).c_str();
1301 } else if (aReply.mEventMessage == eQueryTextRectArray) {
1302 aStream << ", mRectArray={ Length()=" << aReply.mRectArray.Length()
1303 << " }";
1304 } else if (aReply.mEventMessage == eQueryDOMWidgetHittest) {
1305 aStream << ", mWidgetIsHit="
1306 << (aReply.mWidgetIsHit ? "true" : "false");
1308 return aStream << " }";
1312 void EmplaceReply() { mReply.emplace(mMessage); }
1313 Maybe<Reply> mReply;
1315 // values of mComputedScrollAction
1316 enum { SCROLL_ACTION_NONE, SCROLL_ACTION_LINE, SCROLL_ACTION_PAGE };
1319 /******************************************************************************
1320 * mozilla::WidgetSelectionEvent
1321 ******************************************************************************/
1323 class WidgetSelectionEvent : public WidgetGUIEvent {
1324 private:
1325 friend class mozilla::dom::PBrowserParent;
1326 friend class mozilla::dom::PBrowserChild;
1328 WidgetSelectionEvent()
1329 : mOffset(0),
1330 mLength(0),
1331 mReversed(false),
1332 mExpandToClusterBoundary(true),
1333 mSucceeded(false),
1334 mUseNativeLineBreak(true),
1335 mReason(nsISelectionListener::NO_REASON) {}
1337 public:
1338 virtual WidgetSelectionEvent* AsSelectionEvent() override { return this; }
1340 WidgetSelectionEvent(bool aIsTrusted, EventMessage aMessage,
1341 nsIWidget* aWidget)
1342 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eSelectionEventClass),
1343 mOffset(0),
1344 mLength(0),
1345 mReversed(false),
1346 mExpandToClusterBoundary(true),
1347 mSucceeded(false),
1348 mUseNativeLineBreak(true),
1349 mReason(nsISelectionListener::NO_REASON) {}
1351 virtual WidgetEvent* Duplicate() const override {
1352 // This event isn't an internal event of any DOM event.
1353 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1354 "WidgetSelectionEvent needs to support Duplicate()");
1355 MOZ_CRASH("WidgetSelectionEvent doesn't support Duplicate()");
1356 return nullptr;
1359 // Start offset of selection
1360 uint32_t mOffset;
1361 // Length of selection
1362 uint32_t mLength;
1363 // Selection "anchor" should be in front
1364 bool mReversed;
1365 // Cluster-based or character-based
1366 bool mExpandToClusterBoundary;
1367 // true if setting selection succeeded.
1368 bool mSucceeded;
1369 // true if native line breaks are used for mOffset and mLength
1370 bool mUseNativeLineBreak;
1371 // Fennec provides eSetSelection reason codes for downstream
1372 // use in AccessibleCaret visibility logic.
1373 int16_t mReason;
1376 /******************************************************************************
1377 * mozilla::InternalEditorInputEvent
1378 ******************************************************************************/
1380 class InternalEditorInputEvent : public InternalUIEvent {
1381 private:
1382 InternalEditorInputEvent()
1383 : mData(VoidString()),
1384 mInputType(EditorInputType::eUnknown),
1385 mIsComposing(false) {}
1387 public:
1388 virtual InternalEditorInputEvent* AsEditorInputEvent() override {
1389 return this;
1392 InternalEditorInputEvent(bool aIsTrusted, EventMessage aMessage,
1393 nsIWidget* aWidget = nullptr)
1394 : InternalUIEvent(aIsTrusted, aMessage, aWidget, eEditorInputEventClass),
1395 mData(VoidString()),
1396 mInputType(EditorInputType::eUnknown) {}
1398 virtual WidgetEvent* Duplicate() const override {
1399 MOZ_ASSERT(mClass == eEditorInputEventClass,
1400 "Duplicate() must be overridden by sub class");
1401 // Not copying widget, it is a weak reference.
1402 InternalEditorInputEvent* result =
1403 new InternalEditorInputEvent(false, mMessage, nullptr);
1404 result->AssignEditorInputEventData(*this, true);
1405 result->mFlags = mFlags;
1406 return result;
1409 nsString mData;
1410 RefPtr<dom::DataTransfer> mDataTransfer;
1411 OwningNonNullStaticRangeArray mTargetRanges;
1413 EditorInputType mInputType;
1415 bool mIsComposing;
1417 void AssignEditorInputEventData(const InternalEditorInputEvent& aEvent,
1418 bool aCopyTargets) {
1419 AssignUIEventData(aEvent, aCopyTargets);
1421 mData = aEvent.mData;
1422 mDataTransfer = aEvent.mDataTransfer;
1423 mTargetRanges = aEvent.mTargetRanges.Clone();
1424 mInputType = aEvent.mInputType;
1425 mIsComposing = aEvent.mIsComposing;
1428 void GetDOMInputTypeName(nsAString& aInputTypeName) {
1429 GetDOMInputTypeName(mInputType, aInputTypeName);
1431 static void GetDOMInputTypeName(EditorInputType aInputType,
1432 nsAString& aInputTypeName);
1433 static EditorInputType GetEditorInputType(const nsAString& aInputType);
1435 static void Shutdown();
1437 private:
1438 static const char16_t* const kInputTypeNames[];
1439 typedef nsTHashMap<nsStringHashKey, EditorInputType> InputTypeHashtable;
1440 static InputTypeHashtable* sInputTypeHashtable;
1443 } // namespace mozilla
1445 #endif // mozilla_TextEvents_h__