Backed out changeset 8aaffdf63d09 (bug 1920575) for causing bc failures on browser_si...
[gecko.git] / widget / TextEvents.h
bloba775dd84c41a81cd9fcb9dd3f4a3ef891ef9fc21
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef mozilla_TextEvents_h__
7 #define mozilla_TextEvents_h__
9 #include <stdint.h>
11 #include "mozilla/Assertions.h"
12 #include "mozilla/BasicEvents.h"
13 #include "mozilla/CheckedInt.h"
14 #include "mozilla/EventForwards.h" // for KeyNameIndex, temporarily
15 #include "mozilla/FontRange.h"
16 #include "mozilla/Maybe.h"
17 #include "mozilla/NativeKeyBindingsType.h"
18 #include "mozilla/OwningNonNull.h"
19 #include "mozilla/TextRange.h"
20 #include "mozilla/WritingModes.h"
21 #include "mozilla/dom/DataTransfer.h"
22 #include "mozilla/dom/KeyboardEventBinding.h"
23 #include "mozilla/dom/StaticRange.h"
24 #include "mozilla/widget/IMEData.h"
25 #include "mozilla/ipc/IPCForwards.h"
26 #include "nsCOMPtr.h"
27 #include "nsHashtablesFwd.h"
28 #include "nsIFrame.h"
29 #include "nsISelectionListener.h"
30 #include "nsITransferable.h"
31 #include "nsRect.h"
32 #include "nsString.h"
33 #include "nsTArray.h"
35 class nsStringHashKey;
37 /******************************************************************************
38 * virtual keycode values
39 ******************************************************************************/
41 enum {
42 #define NS_DEFINE_VK(aDOMKeyName, aDOMKeyCode) NS_##aDOMKeyName = aDOMKeyCode,
43 #include "mozilla/VirtualKeyCodeList.h"
44 #undef NS_DEFINE_VK
45 NS_VK_UNKNOWN = 0xFF
48 namespace mozilla {
50 enum : uint32_t {
51 eKeyLocationStandard = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_STANDARD,
52 eKeyLocationLeft = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_LEFT,
53 eKeyLocationRight = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_RIGHT,
54 eKeyLocationNumpad = dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_NUMPAD
57 const nsCString GetDOMKeyCodeName(uint32_t aKeyCode);
59 namespace dom {
60 class PBrowserParent;
61 class PBrowserChild;
62 } // namespace dom
63 namespace plugins {
64 class PPluginInstanceChild;
65 } // namespace plugins
67 enum class AccessKeyType {
68 // Handle access key for chrome.
69 eChrome,
70 // Handle access key for content.
71 eContent,
72 // Don't handle access key.
73 eNone
76 /******************************************************************************
77 * mozilla::AlternativeCharCode
79 * This stores alternative charCode values of a key event with some modifiers.
80 * The stored values proper for testing shortcut key or access key.
81 ******************************************************************************/
83 struct AlternativeCharCode {
84 AlternativeCharCode() = default;
85 AlternativeCharCode(uint32_t aUnshiftedCharCode, uint32_t aShiftedCharCode)
86 : mUnshiftedCharCode(aUnshiftedCharCode),
87 mShiftedCharCode(aShiftedCharCode) {}
89 uint32_t mUnshiftedCharCode = 0u;
90 uint32_t mShiftedCharCode = 0u;
92 bool operator==(const AlternativeCharCode& aOther) const {
93 return mUnshiftedCharCode == aOther.mUnshiftedCharCode &&
94 mShiftedCharCode == aOther.mShiftedCharCode;
96 bool operator!=(const AlternativeCharCode& aOther) const {
97 return !(*this == aOther);
101 /******************************************************************************
102 * mozilla::ShortcutKeyCandidate
104 * This stores a candidate of shortcut key combination.
105 ******************************************************************************/
107 struct ShortcutKeyCandidate {
108 enum class ShiftState : bool {
109 // Can ignore `Shift` modifier state when comparing the key combination.
110 // E.g., Ctrl + Shift + `:` in the US keyboard layout may match with
111 // Ctrl + `:` shortcut.
112 Ignorable,
113 // `Shift` modifier state should be respected. I.e., Ctrl + `;` in the US
114 // keyboard layout never matches with Ctrl + Shift + `;` shortcut.
115 MatchExactly,
118 enum class SkipIfEarlierHandlerDisabled : bool {
119 // Even if an earlier handler is disabled, this may match with another
120 // handler for avoiding inaccessible shortcut with the active keyboard
121 // layout.
123 // If an earlier handler (i.e., preferred handler) is disabled, this should
124 // not try to match. E.g., Ctrl + `-` in the French keyboard layout when
125 // the zoom level is the minimum value, it should not match with Ctrl + `6`
126 // shortcut (French keyboard layout introduces `-` when pressing Digit6 key
127 // without Shift, and Shift + Digit6 introduces `6`).
128 Yes,
131 ShortcutKeyCandidate() = default;
132 ShortcutKeyCandidate(
133 uint32_t aCharCode, ShiftState aShiftState,
134 SkipIfEarlierHandlerDisabled aSkipIfEarlierHandlerDisabled)
135 : mCharCode(aCharCode),
136 mShiftState(aShiftState),
137 mSkipIfEarlierHandlerDisabled(aSkipIfEarlierHandlerDisabled) {}
139 // The mCharCode value which must match keyboard shortcut definition.
140 uint32_t mCharCode = 0;
142 ShiftState mShiftState = ShiftState::MatchExactly;
143 SkipIfEarlierHandlerDisabled mSkipIfEarlierHandlerDisabled =
144 SkipIfEarlierHandlerDisabled::No;
147 /******************************************************************************
148 * mozilla::IgnoreModifierState
150 * This stores flags for modifiers that should be ignored when matching
151 * XBL handlers.
152 ******************************************************************************/
154 struct IgnoreModifierState {
155 // When mShift is true, Shift key state will be ignored.
156 bool mShift;
157 // When mMeta is true, Meta key state will be ignored.
158 bool mMeta;
160 IgnoreModifierState() : mShift(false), mMeta(false) {}
163 /******************************************************************************
164 * mozilla::WidgetKeyboardEvent
165 ******************************************************************************/
167 class WidgetKeyboardEvent final : public WidgetInputEvent {
168 private:
169 friend class dom::PBrowserParent;
170 friend class dom::PBrowserChild;
171 friend struct IPC::ParamTraits<WidgetKeyboardEvent>;
172 ALLOW_DEPRECATED_READPARAM
174 protected:
175 WidgetKeyboardEvent()
176 : mNativeKeyEvent(nullptr),
177 mKeyCode(0),
178 mCharCode(0),
179 mPseudoCharCode(0),
180 mLocation(eKeyLocationStandard),
181 mUniqueId(0),
182 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
183 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
184 mIsRepeat(false),
185 mIsComposing(false),
186 mIsSynthesizedByTIP(false),
187 mMaybeSkippableInRemoteProcess(true),
188 mUseLegacyKeyCodeAndCharCodeValues(false),
189 mEditCommandsForSingleLineEditorInitialized(false),
190 mEditCommandsForMultiLineEditorInitialized(false),
191 mEditCommandsForRichTextEditorInitialized(false) {}
193 public:
194 WidgetKeyboardEvent* AsKeyboardEvent() override { return this; }
196 WidgetKeyboardEvent(bool aIsTrusted, EventMessage aMessage,
197 nsIWidget* aWidget,
198 EventClassID aEventClassID = eKeyboardEventClass,
199 const WidgetEventTime* aTime = nullptr)
200 : WidgetInputEvent(aIsTrusted, aMessage, aWidget, aEventClassID, aTime),
201 mNativeKeyEvent(nullptr),
202 mKeyCode(0),
203 mCharCode(0),
204 mPseudoCharCode(0),
205 mLocation(eKeyLocationStandard),
206 mUniqueId(0),
207 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
208 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
209 mIsRepeat(false),
210 mIsComposing(false),
211 mIsSynthesizedByTIP(false),
212 mMaybeSkippableInRemoteProcess(true),
213 mUseLegacyKeyCodeAndCharCodeValues(false),
214 mEditCommandsForSingleLineEditorInitialized(false),
215 mEditCommandsForMultiLineEditorInitialized(false),
216 mEditCommandsForRichTextEditorInitialized(false) {}
218 // IsInputtingText() and IsInputtingLineBreak() are used to check if
219 // it should cause eKeyPress events even on web content.
220 // UI Events defines that "keypress" event should be fired "if and only if
221 // that key normally produces a character value".
222 // <https://www.w3.org/TR/uievents/#event-type-keypress>
223 // Additionally, for backward compatiblity with all existing browsers,
224 // there is a spec issue for Enter key press.
225 // <https://github.com/w3c/uievents/issues/183>
226 bool IsInputtingText() const {
227 // NOTE: On some keyboard layout, some characters are inputted with Control
228 // key or Alt key, but at that time, widget clears the modifier flag
229 // from eKeyPress event because our TextEditor won't handle eKeyPress
230 // events as inputting text (bug 1346832).
231 // NOTE: There are some complicated issues of our traditional behavior.
232 // -- On Windows, KeyboardLayout::WillDispatchKeyboardEvent() clears
233 // MODIFIER_ALT and MODIFIER_CONTROL of eKeyPress event if it
234 // should be treated as inputting a character because AltGr is
235 // represented with both Alt key and Ctrl key are pressed, and
236 // some keyboard layouts may produces a character with Ctrl key.
237 // -- On Linux, KeymapWrapper doesn't have this hack since perhaps,
238 // we don't have any bug reports that user cannot input proper
239 // character with Alt and/or Ctrl key.
240 // -- On macOS, IMEInputHandler::WillDispatchKeyboardEvent() clears
241 // MODIFIER_ALT and MDOFIEIR_CONTROL of eKeyPress event only when
242 // TextInputHandler::InsertText() has been called for the event.
243 // I.e., they are cleared only when an editor has focus (even if IME
244 // is disabled in password field or by |ime-mode: disabled;|) because
245 // TextInputHandler::InsertText() is called while
246 // TextInputHandler::HandleKeyDownEvent() calls interpretKeyEvents:
247 // to notify text input processor of Cocoa (including IME). In other
248 // words, when we need to disable IME completey when no editor has
249 // focus, we cannot call interpretKeyEvents:. So,
250 // TextInputHandler::InsertText() won't be called when no editor has
251 // focus so that neither MODIFIER_ALT nor MODIFIER_CONTROL is
252 // cleared. So, fortunately, altKey and ctrlKey values of "keypress"
253 // events are same as the other browsers only when no editor has
254 // focus.
255 // NOTE: As mentioned above, for compatibility with the other browsers on
256 // macOS, we should keep MODIFIER_ALT and MODIFIER_CONTROL flags of
257 // eKeyPress events when no editor has focus. However, Alt key,
258 // labeled "option" on keyboard for Mac, is AltGraph key on the other
259 // platforms. So, even if MODIFIER_ALT is set, we need to dispatch
260 // eKeyPress event even on web content unless mCharCode is 0.
261 // Therefore, we need to ignore MODIFIER_ALT flag here only on macOS.
262 return mMessage == eKeyPress && mCharCode &&
263 !(mModifiers & (
264 #ifndef XP_MACOSX
265 // So, ignore MODIFIER_ALT only on macOS since
266 // option key is used as AltGraph key on macOS.
267 MODIFIER_ALT |
268 #endif // #ifndef XP_MAXOSX
269 MODIFIER_CONTROL | MODIFIER_META));
272 bool IsInputtingLineBreak() const {
273 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
274 !(mModifiers & (MODIFIER_ALT | MODIFIER_CONTROL | MODIFIER_META));
278 * ShouldKeyPressEventBeFiredOnContent() should be called only when the
279 * instance is eKeyPress event. This returns true when the eKeyPress
280 * event should be fired even on content in the default event group.
282 bool ShouldKeyPressEventBeFiredOnContent() const {
283 MOZ_DIAGNOSTIC_ASSERT(mMessage == eKeyPress);
284 if (IsInputtingText() || IsInputtingLineBreak()) {
285 return true;
287 // Ctrl + Enter won't cause actual input in our editor.
288 // However, the other browsers fire keypress event in any platforms.
289 // So, for compatibility with them, we should fire keypress event for
290 // Ctrl + Enter too.
291 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
292 !(mModifiers & (MODIFIER_ALT | MODIFIER_META | MODIFIER_SHIFT));
295 WidgetEvent* Duplicate() const override {
296 MOZ_ASSERT(mClass == eKeyboardEventClass,
297 "Duplicate() must be overridden by sub class");
298 // Not copying widget, it is a weak reference.
299 WidgetKeyboardEvent* result = new WidgetKeyboardEvent(
300 false, mMessage, nullptr, eKeyboardEventClass, this);
301 result->AssignKeyEventData(*this, true);
302 result->mEditCommandsForSingleLineEditor =
303 mEditCommandsForSingleLineEditor.Clone();
304 result->mEditCommandsForMultiLineEditor =
305 mEditCommandsForMultiLineEditor.Clone();
306 result->mEditCommandsForRichTextEditor =
307 mEditCommandsForRichTextEditor.Clone();
308 result->mFlags = mFlags;
309 return result;
312 bool CanUserGestureActivateTarget() const {
313 // Printable keys, 'carriage return' and 'space' are supported user gestures
314 // for activating the document. However, if supported key is being pressed
315 // combining with other operation keys, such like alt, control ..etc., we
316 // won't activate the target for them because at that time user might
317 // interact with browser or window manager which doesn't necessarily
318 // demonstrate user's intent to play media.
319 const bool isCombiningWithOperationKeys = (IsControl() && !IsAltGraph()) ||
320 (IsAlt() && !IsAltGraph()) ||
321 IsMeta();
322 const bool isEnterOrSpaceKey =
323 mKeyNameIndex == KEY_NAME_INDEX_Enter || mKeyCode == NS_VK_SPACE;
324 return (PseudoCharCode() || isEnterOrSpaceKey) &&
325 (!isCombiningWithOperationKeys ||
326 // ctrl-c/ctrl-x/ctrl-v is quite common shortcut for clipboard
327 // operation.
328 // XXXedgar, we have to find a better way to handle browser keyboard
329 // shortcut for user activation, instead of just ignoring all
330 // combinations, see bug 1641171.
331 ((mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_C ||
332 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_V ||
333 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_X) &&
334 IsAccel()));
337 // Returns true if this event is likely an user activation for a link or
338 // a link-like button, where modifier keys are likely be used for controlling
339 // where the link is opened.
341 // This returns false if the keyboard event is more likely an user-defined
342 // shortcut key.
343 bool CanReflectModifiersToUserActivation() const {
344 MOZ_ASSERT(CanUserGestureActivateTarget(),
345 "Consumer should check CanUserGestureActivateTarget first");
346 // 'carriage return' and 'space' are supported user gestures for activating
347 // a link or a button.
348 // A button often behaves like a link, by calling window.open inside its
349 // event handler.
351 // Access keys can also activate links/buttons, but access keys have their
352 // own modifiers, and those modifiers are not appropriate for reflecting to
353 // the user activation nor controlling where the link is opened.
354 return mKeyNameIndex == KEY_NAME_INDEX_Enter || mKeyCode == NS_VK_SPACE;
357 [[nodiscard]] bool ShouldWorkAsSpaceKey() const {
358 if (mKeyCode == NS_VK_SPACE) {
359 return true;
361 // Additionally, if the code value is "Space" and the key is not mapped to
362 // a function key (i.e., not a printable key), we should treat it as space
363 // key because the active keyboard layout may input different character
364 // from the ASCII white space (U+0020). For example, NBSP (U+00A0).
365 return mKeyNameIndex == KEY_NAME_INDEX_USE_STRING &&
366 mCodeNameIndex == CODE_NAME_INDEX_Space;
370 * CanTreatAsUserInput() returns true if the key is pressed for perhaps
371 * doing something on the web app or our UI. This means that when this
372 * returns false, e.g., when user presses a modifier key, user is probably
373 * displeased by opening popup, entering fullscreen mode, etc. Therefore,
374 * only when this returns true, such reactions should be allowed.
376 bool CanTreatAsUserInput() const {
377 if (!IsTrusted()) {
378 return false;
380 switch (mKeyNameIndex) {
381 case KEY_NAME_INDEX_Escape:
382 // modifier keys:
383 case KEY_NAME_INDEX_Alt:
384 case KEY_NAME_INDEX_AltGraph:
385 case KEY_NAME_INDEX_CapsLock:
386 case KEY_NAME_INDEX_Control:
387 case KEY_NAME_INDEX_Fn:
388 case KEY_NAME_INDEX_FnLock:
389 case KEY_NAME_INDEX_Meta:
390 case KEY_NAME_INDEX_NumLock:
391 case KEY_NAME_INDEX_ScrollLock:
392 case KEY_NAME_INDEX_Shift:
393 case KEY_NAME_INDEX_Symbol:
394 case KEY_NAME_INDEX_SymbolLock:
395 // legacy modifier keys:
396 case KEY_NAME_INDEX_Hyper:
397 case KEY_NAME_INDEX_Super:
398 return false;
399 default:
400 return true;
405 * ShouldInteractionTimeRecorded() returns true if the handling time of
406 * the event should be recorded with the telemetry.
408 bool ShouldInteractionTimeRecorded() const {
409 // Let's record only when we can treat the instance is a user input.
410 return CanTreatAsUserInput();
413 // OS translated Unicode chars which are used for accesskey and accelkey
414 // handling. The handlers will try from first character to last character.
415 CopyableTArray<AlternativeCharCode> mAlternativeCharCodes;
416 // DOM KeyboardEvent.key only when mKeyNameIndex is KEY_NAME_INDEX_USE_STRING.
417 nsString mKeyValue;
418 // DOM KeyboardEvent.code only when mCodeNameIndex is
419 // CODE_NAME_INDEX_USE_STRING.
420 nsString mCodeValue;
422 // OS-specific native event can optionally be preserved.
423 // This is used to retrieve editing shortcut keys in the environment.
424 void* mNativeKeyEvent;
425 // A DOM keyCode value or 0. If a keypress event whose mCharCode is 0, this
426 // should be 0.
427 uint32_t mKeyCode;
428 // If the instance is a keypress event of a printable key, this is a UTF-16
429 // value of the key. Otherwise, 0. This value must not be a control
430 // character when some modifiers are active. Then, this value should be an
431 // unmodified value except Shift and AltGr.
432 uint32_t mCharCode;
433 // mPseudoCharCode is valid only when mMessage is an eKeyDown event.
434 // This stores mCharCode value of keypress event which is fired with same
435 // key value and same modifier state.
436 uint32_t mPseudoCharCode;
437 // One of eKeyLocation*
438 uint32_t mLocation;
439 // Unique id associated with a keydown / keypress event. It's ok if this wraps
440 // over long periods.
441 uint32_t mUniqueId;
443 // DOM KeyboardEvent.key
444 KeyNameIndex mKeyNameIndex;
445 // DOM KeyboardEvent.code
446 CodeNameIndex mCodeNameIndex;
448 // Indicates whether the event is generated by auto repeat or not.
449 // if this is keyup event, always false.
450 bool mIsRepeat;
451 // Indicates whether the event is generated during IME (or deadkey)
452 // composition. This is initialized by EventStateManager. So, key event
453 // dispatchers don't need to initialize this.
454 bool mIsComposing;
455 // Indicates whether the event is synthesized from Text Input Processor
456 // or an actual event from nsAppShell.
457 bool mIsSynthesizedByTIP;
458 // Indicates whether the event is skippable in remote process.
459 // Don't refer this member directly when you need to check this.
460 // Use CanSkipInRemoteProcess() instead.
461 bool mMaybeSkippableInRemoteProcess;
462 // Indicates whether the event should return legacy keyCode value and
463 // charCode value to web apps (one of them is always 0) or not, when it's
464 // an eKeyPress event.
465 bool mUseLegacyKeyCodeAndCharCodeValues;
467 bool CanSkipInRemoteProcess() const {
468 // If this is a repeat event (i.e., generated by auto-repeat feature of
469 // the platform), remove process may skip to handle it because of
470 // performances reasons.. However, if it's caused by odd keyboard utils,
471 // we should not ignore any key events even marked as repeated since
472 // generated key sequence may be important to input proper text. E.g.,
473 // "SinhalaTamil IME" on Windows emulates dead key like input with
474 // generating WM_KEYDOWN for VK_PACKET (inputting any Unicode characters
475 // without keyboard layout information) and VK_BACK (Backspace) to remove
476 // previous character(s) and those messages may be marked as "repeat" by
477 // their bug.
478 return mIsRepeat && mMaybeSkippableInRemoteProcess;
482 * If the key is an arrow key, and the current selection is in a vertical
483 * content, the caret should be moved to physically. However, arrow keys
484 * are mapped to logical move commands in horizontal content. Therefore,
485 * we need to check writing mode if and only if the key is an arrow key, and
486 * need to remap the command to logical command in vertical content if the
487 * writing mode at selection is vertical. These methods help to convert
488 * arrow keys in horizontal content to correspnding direction arrow keys
489 * in vertical content.
491 bool NeedsToRemapNavigationKey() const {
492 // TODO: Use mKeyNameIndex instead.
493 return mKeyCode >= NS_VK_LEFT && mKeyCode <= NS_VK_DOWN;
496 uint32_t GetRemappedKeyCode(const WritingMode& aWritingMode) const {
497 if (!aWritingMode.IsVertical()) {
498 return mKeyCode;
500 switch (mKeyCode) {
501 case NS_VK_LEFT:
502 return aWritingMode.IsVerticalLR() ? NS_VK_UP : NS_VK_DOWN;
503 case NS_VK_RIGHT:
504 return aWritingMode.IsVerticalLR() ? NS_VK_DOWN : NS_VK_UP;
505 case NS_VK_UP:
506 return NS_VK_LEFT;
507 case NS_VK_DOWN:
508 return NS_VK_RIGHT;
509 default:
510 return mKeyCode;
514 KeyNameIndex GetRemappedKeyNameIndex(const WritingMode& aWritingMode) const {
515 if (!aWritingMode.IsVertical()) {
516 return mKeyNameIndex;
518 uint32_t remappedKeyCode = GetRemappedKeyCode(aWritingMode);
519 if (remappedKeyCode == mKeyCode) {
520 return mKeyNameIndex;
522 switch (remappedKeyCode) {
523 case NS_VK_LEFT:
524 return KEY_NAME_INDEX_ArrowLeft;
525 case NS_VK_RIGHT:
526 return KEY_NAME_INDEX_ArrowRight;
527 case NS_VK_UP:
528 return KEY_NAME_INDEX_ArrowUp;
529 case NS_VK_DOWN:
530 return KEY_NAME_INDEX_ArrowDown;
531 default:
532 MOZ_ASSERT_UNREACHABLE("Add a case for the new remapped key");
533 return mKeyNameIndex;
538 * Retrieves all edit commands from mWidget. This shouldn't be called when
539 * the instance is an untrusted event, doesn't have widget or in non-chrome
540 * process.
542 * @param aWritingMode
543 * When writing mode of focused element is vertical, this
544 * will resolve some key's physical direction to logical
545 * direction. For doing it, this must be set to the
546 * writing mode at current selection. However, when there
547 * is no focused element and no selection ranges, this
548 * should be set to Nothing(). Using the result of
549 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
550 * is recommended.
552 MOZ_CAN_RUN_SCRIPT void InitAllEditCommands(
553 const Maybe<WritingMode>& aWritingMode);
556 * Retrieves edit commands from mWidget only for aType. This shouldn't be
557 * called when the instance is an untrusted event or doesn't have widget.
559 * @param aWritingMode
560 * When writing mode of focused element is vertical, this
561 * will resolve some key's physical direction to logical
562 * direction. For doing it, this must be set to the
563 * writing mode at current selection. However, when there
564 * is no focused element and no selection ranges, this
565 * should be set to Nothing(). Using the result of
566 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
567 * is recommended.
568 * @return false if some resource is not available to get
569 * commands unexpectedly. Otherwise, true even if
570 * retrieved command is nothing.
572 MOZ_CAN_RUN_SCRIPT bool InitEditCommandsFor(
573 NativeKeyBindingsType aType, const Maybe<WritingMode>& aWritingMode);
576 * PreventNativeKeyBindings() makes the instance to not cause any edit
577 * actions even if it matches with a native key binding.
579 void PreventNativeKeyBindings() {
580 mEditCommandsForSingleLineEditor.Clear();
581 mEditCommandsForMultiLineEditor.Clear();
582 mEditCommandsForRichTextEditor.Clear();
583 mEditCommandsForSingleLineEditorInitialized = true;
584 mEditCommandsForMultiLineEditorInitialized = true;
585 mEditCommandsForRichTextEditorInitialized = true;
589 * EditCommandsConstRef() returns reference to edit commands for aType.
591 const nsTArray<CommandInt>& EditCommandsConstRef(
592 NativeKeyBindingsType aType) const {
593 return const_cast<WidgetKeyboardEvent*>(this)->EditCommandsRef(aType);
597 * IsEditCommandsInitialized() returns true if edit commands for aType
598 * was already initialized. Otherwise, false.
600 bool IsEditCommandsInitialized(NativeKeyBindingsType aType) const {
601 return const_cast<WidgetKeyboardEvent*>(this)->IsEditCommandsInitializedRef(
602 aType);
606 * AreAllEditCommandsInitialized() returns true if edit commands for all
607 * types were already initialized. Otherwise, false.
609 bool AreAllEditCommandsInitialized() const {
610 return mEditCommandsForSingleLineEditorInitialized &&
611 mEditCommandsForMultiLineEditorInitialized &&
612 mEditCommandsForRichTextEditorInitialized;
616 * Execute edit commands for aType.
618 * @return true if the caller should do nothing anymore.
619 * false, otherwise.
621 typedef void (*DoCommandCallback)(Command, void*);
622 MOZ_CAN_RUN_SCRIPT bool ExecuteEditCommands(NativeKeyBindingsType aType,
623 DoCommandCallback aCallback,
624 void* aCallbackData);
626 // If the key should cause keypress events, this returns true.
627 // Otherwise, false.
628 bool ShouldCauseKeypressEvents() const;
630 // mCharCode value of non-eKeyPress events is always 0. However, if
631 // non-eKeyPress event has one or more alternative char code values,
632 // its first item should be the mCharCode value of following eKeyPress event.
633 // PseudoCharCode() returns mCharCode value for eKeyPress event,
634 // the first alternative char code value of non-eKeyPress event or 0.
635 uint32_t PseudoCharCode() const {
636 return mMessage == eKeyPress ? mCharCode : mPseudoCharCode;
638 void SetCharCode(uint32_t aCharCode) {
639 if (mMessage == eKeyPress) {
640 mCharCode = aCharCode;
641 } else {
642 mPseudoCharCode = aCharCode;
646 void GetDOMKeyName(nsAString& aKeyName) {
647 if (mKeyNameIndex == KEY_NAME_INDEX_USE_STRING) {
648 aKeyName = mKeyValue;
649 return;
651 GetDOMKeyName(mKeyNameIndex, aKeyName);
653 void GetDOMCodeName(nsAString& aCodeName) {
654 if (mCodeNameIndex == CODE_NAME_INDEX_USE_STRING) {
655 aCodeName = mCodeValue;
656 return;
658 GetDOMCodeName(mCodeNameIndex, aCodeName);
662 * GetFallbackKeyCodeOfPunctuationKey() returns a DOM keyCode value for
663 * aCodeNameIndex. This is keyCode value of the key when active keyboard
664 * layout is ANSI (US), JIS or ABNT keyboard layout (the latter 2 layouts
665 * are used only when ANSI doesn't have the key). The result is useful
666 * if the key doesn't produce ASCII character with active keyboard layout
667 * nor with alternative ASCII capable keyboard layout.
669 static uint32_t GetFallbackKeyCodeOfPunctuationKey(
670 CodeNameIndex aCodeNameIndex);
672 bool IsModifierKeyEvent() const {
673 return GetModifierForKeyName(mKeyNameIndex) != MODIFIER_NONE;
677 * Get the candidates for shortcut key.
679 * @param aCandidates [out] the candidate shortcut key combination list.
680 * the first item is most preferred.
682 void GetShortcutKeyCandidates(ShortcutKeyCandidateArray& aCandidates) const;
685 * Get the candidates for access key.
687 * @param aCandidates [out] the candidate access key list.
688 * the first item is most preferred.
690 void GetAccessKeyCandidates(nsTArray<uint32_t>& aCandidates) const;
693 * Check whether the modifiers match with chrome access key or
694 * content access key.
696 bool ModifiersMatchWithAccessKey(AccessKeyType aType) const;
699 * Return active modifiers which may match with access key.
700 * For example, even if Alt is access key modifier, then, when Control,
701 * CapseLock and NumLock are active, this returns only MODIFIER_CONTROL.
703 Modifiers ModifiersForAccessKeyMatching() const;
706 * Return access key modifiers.
708 static Modifiers AccessKeyModifiers(AccessKeyType aType);
710 static void Shutdown();
713 * ComputeLocationFromCodeValue() returns one of .mLocation value
714 * (eKeyLocation*) which is the most preferred value for the specified code
715 * value.
717 static uint32_t ComputeLocationFromCodeValue(CodeNameIndex aCodeNameIndex);
720 * ComputeKeyCodeFromKeyNameIndex() return a .mKeyCode value which can be
721 * mapped from the specified key value. Note that this returns 0 if the
722 * key name index is KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
723 * This means that this method is useful only for non-printable keys.
725 static uint32_t ComputeKeyCodeFromKeyNameIndex(KeyNameIndex aKeyNameIndex);
728 * ComputeCodeNameIndexFromKeyNameIndex() returns a code name index which
729 * is typically mapped to given key name index on the platform.
730 * Note that this returns CODE_NAME_INDEX_UNKNOWN if the key name index is
731 * KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
732 * This means that this method is useful only for non-printable keys.
734 * @param aKeyNameIndex A non-printable key name index.
735 * @param aLocation Should be one of location value. This is
736 * important when aKeyNameIndex may exist in
737 * both Numpad or Standard, or in both Left or
738 * Right. If this is nothing, this method
739 * returns Left or Standard position's code
740 * value.
742 static CodeNameIndex ComputeCodeNameIndexFromKeyNameIndex(
743 KeyNameIndex aKeyNameIndex, const Maybe<uint32_t>& aLocation);
746 * GetModifierForKeyName() returns a value of Modifier which is activated
747 * by the aKeyNameIndex.
749 static Modifier GetModifierForKeyName(KeyNameIndex aKeyNameIndex);
752 * IsLeftOrRightModiferKeyNameIndex() returns true if aKeyNameIndex is a
753 * modifier key which may be in Left and Right location.
755 static bool IsLeftOrRightModiferKeyNameIndex(KeyNameIndex aKeyNameIndex) {
756 switch (aKeyNameIndex) {
757 case KEY_NAME_INDEX_Alt:
758 case KEY_NAME_INDEX_Control:
759 case KEY_NAME_INDEX_Meta:
760 case KEY_NAME_INDEX_Shift:
761 return true;
762 default:
763 return false;
768 * IsLockableModifier() returns true if aKeyNameIndex is a lockable modifier
769 * key such as CapsLock and NumLock.
771 static bool IsLockableModifier(KeyNameIndex aKeyNameIndex);
773 static void GetDOMKeyName(KeyNameIndex aKeyNameIndex, nsAString& aKeyName);
774 static void GetDOMCodeName(CodeNameIndex aCodeNameIndex,
775 nsAString& aCodeName);
777 static KeyNameIndex GetKeyNameIndex(const nsAString& aKeyValue);
778 static CodeNameIndex GetCodeNameIndex(const nsAString& aCodeValue);
780 static const char* GetCommandStr(Command aCommand);
782 void AssignKeyEventData(const WidgetKeyboardEvent& aEvent,
783 bool aCopyTargets) {
784 AssignInputEventData(aEvent, aCopyTargets);
786 mKeyCode = aEvent.mKeyCode;
787 mCharCode = aEvent.mCharCode;
788 mPseudoCharCode = aEvent.mPseudoCharCode;
789 mLocation = aEvent.mLocation;
790 mAlternativeCharCodes = aEvent.mAlternativeCharCodes.Clone();
791 mIsRepeat = aEvent.mIsRepeat;
792 mIsComposing = aEvent.mIsComposing;
793 mKeyNameIndex = aEvent.mKeyNameIndex;
794 mCodeNameIndex = aEvent.mCodeNameIndex;
795 mKeyValue = aEvent.mKeyValue;
796 mCodeValue = aEvent.mCodeValue;
797 // Don't copy mNativeKeyEvent because it may be referred after its instance
798 // is destroyed.
799 mNativeKeyEvent = nullptr;
800 mUniqueId = aEvent.mUniqueId;
801 mIsSynthesizedByTIP = aEvent.mIsSynthesizedByTIP;
802 mMaybeSkippableInRemoteProcess = aEvent.mMaybeSkippableInRemoteProcess;
803 mUseLegacyKeyCodeAndCharCodeValues =
804 aEvent.mUseLegacyKeyCodeAndCharCodeValues;
806 // Don't copy mEditCommandsFor*Editor because it may require a lot of
807 // memory space. For example, if the event is dispatched but grabbed by
808 // a JS variable, they are not necessary anymore.
810 mEditCommandsForSingleLineEditorInitialized =
811 aEvent.mEditCommandsForSingleLineEditorInitialized;
812 mEditCommandsForMultiLineEditorInitialized =
813 aEvent.mEditCommandsForMultiLineEditorInitialized;
814 mEditCommandsForRichTextEditorInitialized =
815 aEvent.mEditCommandsForRichTextEditorInitialized;
818 void AssignCommands(const WidgetKeyboardEvent& aEvent) {
819 mEditCommandsForSingleLineEditorInitialized =
820 aEvent.mEditCommandsForSingleLineEditorInitialized;
821 if (mEditCommandsForSingleLineEditorInitialized) {
822 mEditCommandsForSingleLineEditor =
823 aEvent.mEditCommandsForSingleLineEditor.Clone();
824 } else {
825 mEditCommandsForSingleLineEditor.Clear();
827 mEditCommandsForMultiLineEditorInitialized =
828 aEvent.mEditCommandsForMultiLineEditorInitialized;
829 if (mEditCommandsForMultiLineEditorInitialized) {
830 mEditCommandsForMultiLineEditor =
831 aEvent.mEditCommandsForMultiLineEditor.Clone();
832 } else {
833 mEditCommandsForMultiLineEditor.Clear();
835 mEditCommandsForRichTextEditorInitialized =
836 aEvent.mEditCommandsForRichTextEditorInitialized;
837 if (mEditCommandsForRichTextEditorInitialized) {
838 mEditCommandsForRichTextEditor =
839 aEvent.mEditCommandsForRichTextEditor.Clone();
840 } else {
841 mEditCommandsForRichTextEditor.Clear();
845 private:
846 static const char16_t* const kKeyNames[];
847 static const char16_t* const kCodeNames[];
848 typedef nsTHashMap<nsStringHashKey, KeyNameIndex> KeyNameIndexHashtable;
849 typedef nsTHashMap<nsStringHashKey, CodeNameIndex> CodeNameIndexHashtable;
850 static KeyNameIndexHashtable* sKeyNameIndexHashtable;
851 static CodeNameIndexHashtable* sCodeNameIndexHashtable;
853 // mEditCommandsFor*Editor store edit commands. This should be initialized
854 // with InitEditCommandsFor().
855 // XXX Ideally, this should be array of Command rather than CommandInt.
856 // However, ParamTraits isn't aware of enum array.
857 CopyableTArray<CommandInt> mEditCommandsForSingleLineEditor;
858 CopyableTArray<CommandInt> mEditCommandsForMultiLineEditor;
859 CopyableTArray<CommandInt> mEditCommandsForRichTextEditor;
861 nsTArray<CommandInt>& EditCommandsRef(NativeKeyBindingsType aType) {
862 switch (aType) {
863 case NativeKeyBindingsType::SingleLineEditor:
864 return mEditCommandsForSingleLineEditor;
865 case NativeKeyBindingsType::MultiLineEditor:
866 return mEditCommandsForMultiLineEditor;
867 case NativeKeyBindingsType::RichTextEditor:
868 return mEditCommandsForRichTextEditor;
869 default:
870 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
871 "Invalid native key binding type");
875 // mEditCommandsFor*EditorInitialized are set to true when
876 // InitEditCommandsFor() initializes edit commands for the type.
877 bool mEditCommandsForSingleLineEditorInitialized;
878 bool mEditCommandsForMultiLineEditorInitialized;
879 bool mEditCommandsForRichTextEditorInitialized;
881 bool& IsEditCommandsInitializedRef(NativeKeyBindingsType aType) {
882 switch (aType) {
883 case NativeKeyBindingsType::SingleLineEditor:
884 return mEditCommandsForSingleLineEditorInitialized;
885 case NativeKeyBindingsType::MultiLineEditor:
886 return mEditCommandsForMultiLineEditorInitialized;
887 case NativeKeyBindingsType::RichTextEditor:
888 return mEditCommandsForRichTextEditorInitialized;
889 default:
890 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
891 "Invalid native key binding type");
896 /******************************************************************************
897 * mozilla::WidgetCompositionEvent
898 ******************************************************************************/
900 class WidgetCompositionEvent : public WidgetGUIEvent {
901 private:
902 friend class mozilla::dom::PBrowserParent;
903 friend class mozilla::dom::PBrowserChild;
904 ALLOW_DEPRECATED_READPARAM
906 WidgetCompositionEvent() : mOriginalMessage(eVoidEvent) {}
908 public:
909 virtual WidgetCompositionEvent* AsCompositionEvent() override { return this; }
911 WidgetCompositionEvent(bool aIsTrusted, EventMessage aMessage,
912 nsIWidget* aWidget,
913 const WidgetEventTime* aTime = nullptr)
914 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eCompositionEventClass,
915 aTime),
916 mNativeIMEContext(aWidget),
917 mOriginalMessage(eVoidEvent) {}
919 virtual WidgetEvent* Duplicate() const override {
920 MOZ_ASSERT(mClass == eCompositionEventClass,
921 "Duplicate() must be overridden by sub class");
922 // Not copying widget, it is a weak reference.
923 WidgetCompositionEvent* result =
924 new WidgetCompositionEvent(false, mMessage, nullptr, this);
925 result->AssignCompositionEventData(*this, true);
926 result->mFlags = mFlags;
927 return result;
930 // The composition string or the commit string. If the instance is a
931 // compositionstart event, this is initialized with selected text by
932 // TextComposition automatically.
933 nsString mData;
935 RefPtr<TextRangeArray> mRanges;
937 // mNativeIMEContext stores the native IME context which causes the
938 // composition event.
939 widget::NativeIMEContext mNativeIMEContext;
941 // If the instance is a clone of another event, mOriginalMessage stores
942 // the another event's mMessage.
943 EventMessage mOriginalMessage;
945 // Composition ID considered by TextComposition. If the event has not been
946 // handled by TextComposition yet, this is 0. And also if the event is for
947 // a composition synthesized in a content process, this is always 0.
948 uint32_t mCompositionId = 0;
950 void AssignCompositionEventData(const WidgetCompositionEvent& aEvent,
951 bool aCopyTargets) {
952 AssignGUIEventData(aEvent, aCopyTargets);
954 mData = aEvent.mData;
955 mOriginalMessage = aEvent.mOriginalMessage;
956 mRanges = aEvent.mRanges;
958 // Currently, we don't need to copy the other members because they are
959 // for internal use only (not available from JS).
962 bool IsComposing() const { return mRanges && mRanges->IsComposing(); }
964 uint32_t TargetClauseOffset() const {
965 return mRanges ? mRanges->TargetClauseOffset() : 0;
968 uint32_t TargetClauseLength() const {
969 uint32_t length = UINT32_MAX;
970 if (mRanges) {
971 length = mRanges->TargetClauseLength();
973 return length == UINT32_MAX ? mData.Length() : length;
976 uint32_t RangeCount() const { return mRanges ? mRanges->Length() : 0; }
978 bool CausesDOMTextEvent() const {
979 return mMessage == eCompositionChange || mMessage == eCompositionCommit ||
980 mMessage == eCompositionCommitAsIs;
983 bool CausesDOMCompositionEndEvent() const {
984 return mMessage == eCompositionEnd || mMessage == eCompositionCommit ||
985 mMessage == eCompositionCommitAsIs;
988 bool IsFollowedByCompositionEnd() const {
989 return IsFollowedByCompositionEnd(mOriginalMessage);
992 static bool IsFollowedByCompositionEnd(EventMessage aEventMessage) {
993 return aEventMessage == eCompositionCommit ||
994 aEventMessage == eCompositionCommitAsIs;
998 /******************************************************************************
999 * mozilla::WidgetQueryContentEvent
1000 ******************************************************************************/
1002 class WidgetQueryContentEvent : public WidgetGUIEvent {
1003 private:
1004 friend class dom::PBrowserParent;
1005 friend class dom::PBrowserChild;
1006 ALLOW_DEPRECATED_READPARAM
1008 WidgetQueryContentEvent()
1009 : mUseNativeLineBreak(true),
1010 mWithFontRanges(false),
1011 mNeedsToFlushLayout(true) {
1012 MOZ_CRASH("WidgetQueryContentEvent is created without proper arguments");
1015 public:
1016 virtual WidgetQueryContentEvent* AsQueryContentEvent() override {
1017 return this;
1020 WidgetQueryContentEvent(bool aIsTrusted, EventMessage aMessage,
1021 nsIWidget* aWidget)
1022 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eQueryContentEventClass),
1023 mUseNativeLineBreak(true),
1024 mWithFontRanges(false),
1025 mNeedsToFlushLayout(true) {}
1027 WidgetQueryContentEvent(EventMessage aMessage,
1028 const WidgetQueryContentEvent& aOtherEvent)
1029 : WidgetGUIEvent(aOtherEvent.IsTrusted(), aMessage,
1030 const_cast<nsIWidget*>(aOtherEvent.mWidget.get()),
1031 eQueryContentEventClass),
1032 mUseNativeLineBreak(aOtherEvent.mUseNativeLineBreak),
1033 mWithFontRanges(false),
1034 mNeedsToFlushLayout(aOtherEvent.mNeedsToFlushLayout) {}
1036 WidgetEvent* Duplicate() const override {
1037 // This event isn't an internal event of any DOM event.
1038 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1039 "WidgetQueryContentEvent needs to support Duplicate()");
1040 MOZ_CRASH("WidgetQueryContentEvent doesn't support Duplicate()");
1043 struct Options final {
1044 bool mUseNativeLineBreak;
1045 bool mRelativeToInsertionPoint;
1047 explicit Options()
1048 : mUseNativeLineBreak(true), mRelativeToInsertionPoint(false) {}
1050 explicit Options(const WidgetQueryContentEvent& aEvent)
1051 : mUseNativeLineBreak(aEvent.mUseNativeLineBreak),
1052 mRelativeToInsertionPoint(aEvent.mInput.mRelativeToInsertionPoint) {}
1055 void Init(const Options& aOptions) {
1056 mUseNativeLineBreak = aOptions.mUseNativeLineBreak;
1057 mInput.mRelativeToInsertionPoint = aOptions.mRelativeToInsertionPoint;
1058 MOZ_ASSERT(mInput.IsValidEventMessage(mMessage));
1061 void InitForQueryTextContent(int64_t aOffset, uint32_t aLength,
1062 const Options& aOptions = Options()) {
1063 NS_ASSERTION(mMessage == eQueryTextContent, "wrong initializer is called");
1064 mInput.mOffset = aOffset;
1065 mInput.mLength = aLength;
1066 Init(aOptions);
1067 MOZ_ASSERT(mInput.IsValidOffset());
1070 void InitForQueryCaretRect(int64_t aOffset,
1071 const Options& aOptions = Options()) {
1072 NS_ASSERTION(mMessage == eQueryCaretRect, "wrong initializer is called");
1073 mInput.mOffset = aOffset;
1074 Init(aOptions);
1075 MOZ_ASSERT(mInput.IsValidOffset());
1078 void InitForQueryTextRect(int64_t aOffset, uint32_t aLength,
1079 const Options& aOptions = Options()) {
1080 NS_ASSERTION(mMessage == eQueryTextRect, "wrong initializer is called");
1081 mInput.mOffset = aOffset;
1082 mInput.mLength = aLength;
1083 Init(aOptions);
1084 MOZ_ASSERT(mInput.IsValidOffset());
1087 void InitForQuerySelectedText(SelectionType aSelectionType,
1088 const Options& aOptions = Options()) {
1089 MOZ_ASSERT(mMessage == eQuerySelectedText);
1090 MOZ_ASSERT(aSelectionType != SelectionType::eNone);
1091 mInput.mSelectionType = aSelectionType;
1092 Init(aOptions);
1095 void InitForQueryDOMWidgetHittest(
1096 const mozilla::LayoutDeviceIntPoint& aPoint) {
1097 NS_ASSERTION(mMessage == eQueryDOMWidgetHittest,
1098 "wrong initializer is called");
1099 mRefPoint = aPoint;
1102 void InitForQueryTextRectArray(uint32_t aOffset, uint32_t aLength,
1103 const Options& aOptions = Options()) {
1104 NS_ASSERTION(mMessage == eQueryTextRectArray,
1105 "wrong initializer is called");
1106 mInput.mOffset = aOffset;
1107 mInput.mLength = aLength;
1108 Init(aOptions);
1111 void RequestFontRanges() {
1112 MOZ_ASSERT(mMessage == eQueryTextContent);
1113 mWithFontRanges = true;
1116 bool Succeeded() const {
1117 if (mReply.isNothing()) {
1118 return false;
1120 switch (mMessage) {
1121 case eQueryTextContent:
1122 case eQueryTextRect:
1123 case eQueryCaretRect:
1124 return mReply->mOffsetAndData.isSome();
1125 default:
1126 return true;
1130 bool Failed() const { return !Succeeded(); }
1132 bool FoundSelection() const {
1133 MOZ_ASSERT(mMessage == eQuerySelectedText);
1134 return Succeeded() && mReply->mOffsetAndData.isSome();
1137 bool FoundChar() const {
1138 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1139 return Succeeded() && mReply->mOffsetAndData.isSome();
1142 bool FoundTentativeCaretOffset() const {
1143 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1144 return Succeeded() && mReply->mTentativeCaretOffset.isSome();
1147 bool DidNotFindSelection() const {
1148 MOZ_ASSERT(mMessage == eQuerySelectedText);
1149 return Failed() || mReply->mOffsetAndData.isNothing();
1152 bool DidNotFindChar() const {
1153 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1154 return Failed() || mReply->mOffsetAndData.isNothing();
1157 bool DidNotFindTentativeCaretOffset() const {
1158 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1159 return Failed() || mReply->mTentativeCaretOffset.isNothing();
1162 bool mUseNativeLineBreak;
1163 bool mWithFontRanges;
1164 bool mNeedsToFlushLayout;
1165 struct Input final {
1166 uint32_t EndOffset() const {
1167 CheckedInt<uint32_t> endOffset = CheckedInt<uint32_t>(mOffset) + mLength;
1168 return NS_WARN_IF(!endOffset.isValid()) ? UINT32_MAX : endOffset.value();
1171 int64_t mOffset;
1172 uint32_t mLength;
1173 SelectionType mSelectionType;
1174 // If mOffset is true, mOffset is relative to the start offset of
1175 // composition if there is, otherwise, the start of the first selection
1176 // range.
1177 bool mRelativeToInsertionPoint;
1179 Input()
1180 : mOffset(0),
1181 mLength(0),
1182 mSelectionType(SelectionType::eNormal),
1183 mRelativeToInsertionPoint(false) {}
1185 bool IsValidOffset() const {
1186 return mRelativeToInsertionPoint || mOffset >= 0;
1188 bool IsValidEventMessage(EventMessage aEventMessage) const {
1189 if (!mRelativeToInsertionPoint) {
1190 return true;
1192 switch (aEventMessage) {
1193 case eQueryTextContent:
1194 case eQueryCaretRect:
1195 case eQueryTextRect:
1196 return true;
1197 default:
1198 return false;
1201 bool MakeOffsetAbsolute(uint32_t aInsertionPointOffset) {
1202 if (NS_WARN_IF(!mRelativeToInsertionPoint)) {
1203 return true;
1205 mRelativeToInsertionPoint = false;
1206 // If mOffset + aInsertionPointOffset becomes negative value,
1207 // we should assume the absolute offset is 0.
1208 if (mOffset < 0 && -mOffset > aInsertionPointOffset) {
1209 mOffset = 0;
1210 return true;
1212 // Otherwise, we don't allow too large offset.
1213 CheckedInt<uint32_t> absOffset(mOffset + aInsertionPointOffset);
1214 if (NS_WARN_IF(!absOffset.isValid())) {
1215 mOffset = UINT32_MAX;
1216 return false;
1218 mOffset = absOffset.value();
1219 return true;
1221 } mInput;
1223 struct Reply final {
1224 EventMessage const mEventMessage;
1225 void* mContentsRoot = nullptr;
1226 Maybe<OffsetAndData<uint32_t>> mOffsetAndData;
1227 // mTentativeCaretOffset is used by only eQueryCharacterAtPoint.
1228 // This is the offset where caret would be if user clicked at the mRefPoint.
1229 Maybe<uint32_t> mTentativeCaretOffset;
1230 // mRect is used by eQueryTextRect, eQueryCaretRect, eQueryCharacterAtPoint
1231 // and eQueryEditorRect. The coordinates is system coordinates relative to
1232 // the top level widget of mFocusedWidget. E.g., if a <xul:panel> which
1233 // is owned by a window has focused editor, the offset of mRect is relative
1234 // to the owner window, not the <xul:panel>.
1235 mozilla::LayoutDeviceIntRect mRect;
1236 // The return widget has the caret. This is set at all query events.
1237 nsIWidget* mFocusedWidget = nullptr;
1238 // mozilla::WritingMode value at the end (focus) of the selection
1239 mozilla::WritingMode mWritingMode;
1240 // Used by eQuerySelectionAsTransferable
1241 nsCOMPtr<nsITransferable> mTransferable;
1242 // Used by eQueryTextContent with font ranges requested
1243 CopyableAutoTArray<mozilla::FontRange, 1> mFontRanges;
1244 // Used by eQueryTextRectArray
1245 CopyableTArray<mozilla::LayoutDeviceIntRect> mRectArray;
1246 // true if selection is reversed (end < start)
1247 bool mReversed = false;
1248 // true if DOM element under mouse belongs to widget
1249 bool mWidgetIsHit = false;
1250 // true if mContentRoot is focused editable content
1251 bool mIsEditableContent = false;
1252 // Set to the element that a drop at the given coordinates would target
1253 mozilla::dom::Element* mDropElement;
1254 // Set to the frame that a drop at the given coordinates would target
1255 nsIFrame* mDropFrame;
1257 Reply() = delete;
1258 explicit Reply(EventMessage aEventMessage) : mEventMessage(aEventMessage) {}
1260 // Don't allow to copy/move because of `mEventMessage`.
1261 Reply(const Reply& aOther) = delete;
1262 Reply(Reply&& aOther) = delete;
1263 Reply& operator=(const Reply& aOther) = delete;
1264 Reply& operator=(Reply&& aOther) = delete;
1266 MOZ_NEVER_INLINE_DEBUG uint32_t StartOffset() const {
1267 MOZ_ASSERT(mOffsetAndData.isSome());
1268 return mOffsetAndData->StartOffset();
1270 MOZ_NEVER_INLINE_DEBUG uint32_t EndOffset() const {
1271 MOZ_ASSERT(mOffsetAndData.isSome());
1272 return mOffsetAndData->EndOffset();
1274 MOZ_NEVER_INLINE_DEBUG uint32_t DataLength() const {
1275 MOZ_ASSERT(mOffsetAndData.isSome() ||
1276 mEventMessage == eQuerySelectedText);
1277 return mOffsetAndData.isSome() ? mOffsetAndData->Length() : 0;
1279 MOZ_NEVER_INLINE_DEBUG uint32_t AnchorOffset() const {
1280 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1281 MOZ_ASSERT(mOffsetAndData.isSome());
1282 return StartOffset() + (mReversed ? DataLength() : 0);
1285 MOZ_NEVER_INLINE_DEBUG uint32_t FocusOffset() const {
1286 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1287 MOZ_ASSERT(mOffsetAndData.isSome());
1288 return StartOffset() + (mReversed ? 0 : DataLength());
1291 const WritingMode& WritingModeRef() const {
1292 MOZ_ASSERT(mEventMessage == eQuerySelectedText ||
1293 mEventMessage == eQueryCaretRect ||
1294 mEventMessage == eQueryTextRect);
1295 MOZ_ASSERT(mOffsetAndData.isSome() ||
1296 mEventMessage == eQuerySelectedText);
1297 return mWritingMode;
1300 MOZ_NEVER_INLINE_DEBUG const nsString& DataRef() const {
1301 MOZ_ASSERT(mOffsetAndData.isSome() ||
1302 mEventMessage == eQuerySelectedText);
1303 return mOffsetAndData.isSome() ? mOffsetAndData->DataRef()
1304 : EmptyString();
1306 MOZ_NEVER_INLINE_DEBUG bool IsDataEmpty() const {
1307 MOZ_ASSERT(mOffsetAndData.isSome() ||
1308 mEventMessage == eQuerySelectedText);
1309 return mOffsetAndData.isSome() ? mOffsetAndData->IsDataEmpty() : true;
1311 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRange(uint32_t aOffset) const {
1312 MOZ_ASSERT(mOffsetAndData.isSome() ||
1313 mEventMessage == eQuerySelectedText);
1314 return mOffsetAndData.isSome() ? mOffsetAndData->IsOffsetInRange(aOffset)
1315 : false;
1317 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRangeOrEndOffset(
1318 uint32_t aOffset) const {
1319 MOZ_ASSERT(mOffsetAndData.isSome() ||
1320 mEventMessage == eQuerySelectedText);
1321 return mOffsetAndData.isSome()
1322 ? mOffsetAndData->IsOffsetInRangeOrEndOffset(aOffset)
1323 : false;
1325 MOZ_NEVER_INLINE_DEBUG void TruncateData(uint32_t aLength = 0) {
1326 MOZ_ASSERT(mOffsetAndData.isSome());
1327 mOffsetAndData->TruncateData(aLength);
1330 friend std::ostream& operator<<(std::ostream& aStream,
1331 const Reply& aReply) {
1332 aStream << "{ ";
1333 if (aReply.mEventMessage == eQuerySelectedText ||
1334 aReply.mEventMessage == eQueryTextContent ||
1335 aReply.mEventMessage == eQueryTextRect ||
1336 aReply.mEventMessage == eQueryCaretRect ||
1337 aReply.mEventMessage == eQueryCharacterAtPoint) {
1338 aStream << "mOffsetAndData=" << ToString(aReply.mOffsetAndData).c_str()
1339 << ", ";
1340 if (aReply.mEventMessage == eQueryCharacterAtPoint) {
1341 aStream << "mTentativeCaretOffset="
1342 << ToString(aReply.mTentativeCaretOffset).c_str() << ", ";
1345 if (aReply.mOffsetAndData.isSome() && aReply.mOffsetAndData->Length()) {
1346 if (aReply.mEventMessage == eQuerySelectedText) {
1347 aStream << ", mReversed=" << (aReply.mReversed ? "true" : "false");
1349 if (aReply.mEventMessage == eQuerySelectionAsTransferable) {
1350 aStream << ", mTransferable=0x" << aReply.mTransferable;
1353 if (aReply.mEventMessage == eQuerySelectedText ||
1354 aReply.mEventMessage == eQueryTextRect ||
1355 aReply.mEventMessage == eQueryCaretRect) {
1356 aStream << ", mWritingMode=" << ToString(aReply.mWritingMode).c_str();
1358 aStream << ", mContentsRoot=0x" << aReply.mContentsRoot
1359 << ", mIsEditableContent="
1360 << (aReply.mIsEditableContent ? "true" : "false")
1361 << ", mFocusedWidget=0x" << aReply.mFocusedWidget;
1362 if (aReply.mEventMessage == eQueryTextContent) {
1363 aStream << ", mFontRanges={ Length()=" << aReply.mFontRanges.Length()
1364 << " }";
1365 } else if (aReply.mEventMessage == eQueryTextRect ||
1366 aReply.mEventMessage == eQueryCaretRect ||
1367 aReply.mEventMessage == eQueryCharacterAtPoint) {
1368 aStream << ", mRect=" << ToString(aReply.mRect).c_str();
1369 } else if (aReply.mEventMessage == eQueryTextRectArray) {
1370 aStream << ", mRectArray={ Length()=" << aReply.mRectArray.Length()
1371 << " }";
1372 } else if (aReply.mEventMessage == eQueryDOMWidgetHittest) {
1373 aStream << ", mWidgetIsHit="
1374 << (aReply.mWidgetIsHit ? "true" : "false");
1376 return aStream << " }";
1380 void EmplaceReply() { mReply.emplace(mMessage); }
1381 Maybe<Reply> mReply;
1383 // values of mComputedScrollAction
1384 enum { SCROLL_ACTION_NONE, SCROLL_ACTION_LINE, SCROLL_ACTION_PAGE };
1387 /******************************************************************************
1388 * mozilla::WidgetSelectionEvent
1389 ******************************************************************************/
1391 class WidgetSelectionEvent : public WidgetGUIEvent {
1392 private:
1393 friend class mozilla::dom::PBrowserParent;
1394 friend class mozilla::dom::PBrowserChild;
1395 ALLOW_DEPRECATED_READPARAM
1397 WidgetSelectionEvent()
1398 : mOffset(0),
1399 mLength(0),
1400 mReversed(false),
1401 mExpandToClusterBoundary(true),
1402 mSucceeded(false),
1403 mUseNativeLineBreak(true),
1404 mReason(nsISelectionListener::NO_REASON) {}
1406 public:
1407 virtual WidgetSelectionEvent* AsSelectionEvent() override { return this; }
1409 WidgetSelectionEvent(bool aIsTrusted, EventMessage aMessage,
1410 nsIWidget* aWidget)
1411 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eSelectionEventClass),
1412 mOffset(0),
1413 mLength(0),
1414 mReversed(false),
1415 mExpandToClusterBoundary(true),
1416 mSucceeded(false),
1417 mUseNativeLineBreak(true),
1418 mReason(nsISelectionListener::NO_REASON) {}
1420 virtual WidgetEvent* Duplicate() const override {
1421 // This event isn't an internal event of any DOM event.
1422 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1423 "WidgetSelectionEvent needs to support Duplicate()");
1424 MOZ_CRASH("WidgetSelectionEvent doesn't support Duplicate()");
1425 return nullptr;
1428 // Start offset of selection
1429 uint32_t mOffset;
1430 // Length of selection
1431 uint32_t mLength;
1432 // Selection "anchor" should be in front
1433 bool mReversed;
1434 // Cluster-based or character-based
1435 bool mExpandToClusterBoundary;
1436 // true if setting selection succeeded.
1437 bool mSucceeded;
1438 // true if native line breaks are used for mOffset and mLength
1439 bool mUseNativeLineBreak;
1440 // Fennec provides eSetSelection reason codes for downstream
1441 // use in AccessibleCaret visibility logic.
1442 int16_t mReason;
1445 /******************************************************************************
1446 * mozilla::InternalEditorInputEvent
1447 ******************************************************************************/
1449 class InternalEditorInputEvent : public InternalUIEvent {
1450 public:
1451 InternalEditorInputEvent() = delete;
1452 virtual InternalEditorInputEvent* AsEditorInputEvent() override {
1453 return this;
1456 InternalEditorInputEvent(bool aIsTrusted, EventMessage aMessage,
1457 nsIWidget* aWidget = nullptr,
1458 const WidgetEventTime* aTime = nullptr)
1459 : InternalUIEvent(aIsTrusted, aMessage, aWidget, eEditorInputEventClass,
1460 aTime) {}
1462 virtual WidgetEvent* Duplicate() const override {
1463 MOZ_ASSERT(mClass == eEditorInputEventClass,
1464 "Duplicate() must be overridden by sub class");
1465 // Not copying widget, it is a weak reference.
1466 InternalEditorInputEvent* result =
1467 new InternalEditorInputEvent(false, mMessage, nullptr, this);
1468 result->AssignEditorInputEventData(*this, true);
1469 result->mFlags = mFlags;
1470 return result;
1473 nsString mData = VoidString();
1474 RefPtr<dom::DataTransfer> mDataTransfer;
1475 OwningNonNullStaticRangeArray mTargetRanges;
1477 EditorInputType mInputType = EditorInputType::eUnknown;
1479 bool mIsComposing = false;
1481 void AssignEditorInputEventData(const InternalEditorInputEvent& aEvent,
1482 bool aCopyTargets) {
1483 AssignUIEventData(aEvent, aCopyTargets);
1485 mData = aEvent.mData;
1486 mDataTransfer = aEvent.mDataTransfer;
1487 mTargetRanges = aEvent.mTargetRanges.Clone();
1488 mInputType = aEvent.mInputType;
1489 mIsComposing = aEvent.mIsComposing;
1492 void GetDOMInputTypeName(nsAString& aInputTypeName) {
1493 GetDOMInputTypeName(mInputType, aInputTypeName);
1495 static void GetDOMInputTypeName(EditorInputType aInputType,
1496 nsAString& aInputTypeName);
1497 static EditorInputType GetEditorInputType(const nsAString& aInputType);
1499 static void Shutdown();
1501 private:
1502 static const char16_t* const kInputTypeNames[];
1503 using InputTypeHashtable = nsTHashMap<nsStringHashKey, EditorInputType>;
1504 static InputTypeHashtable* sInputTypeHashtable;
1507 /******************************************************************************
1508 * mozilla::InternalLegacyTextEvent
1509 ******************************************************************************/
1511 class InternalLegacyTextEvent : public InternalUIEvent {
1512 public:
1513 InternalLegacyTextEvent() = delete;
1515 virtual InternalLegacyTextEvent* AsLegacyTextEvent() override { return this; }
1517 InternalLegacyTextEvent(bool aIsTrusted, EventMessage aMessage,
1518 nsIWidget* aWidget = nullptr,
1519 const WidgetEventTime* aTime = nullptr)
1520 : InternalUIEvent(aIsTrusted, aMessage, aWidget, eLegacyTextEventClass,
1521 aTime) {}
1523 virtual WidgetEvent* Duplicate() const override {
1524 MOZ_ASSERT(mClass == eLegacyTextEventClass,
1525 "Duplicate() must be overridden by sub class");
1526 // Not copying widget, it is a weak reference.
1527 InternalLegacyTextEvent* result =
1528 new InternalLegacyTextEvent(false, mMessage, nullptr, this);
1529 result->AssignLegacyTextEventData(*this, true);
1530 result->mFlags = mFlags;
1531 return result;
1534 nsString mData;
1535 RefPtr<dom::DataTransfer> mDataTransfer;
1536 EditorInputType mInputType = EditorInputType::eUnknown;
1538 void AssignLegacyTextEventData(const InternalLegacyTextEvent& aEvent,
1539 bool aCopyTargets) {
1540 AssignUIEventData(aEvent, aCopyTargets);
1542 mData = aEvent.mData;
1543 mDataTransfer = aEvent.mDataTransfer;
1544 mInputType = aEvent.mInputType;
1548 } // namespace mozilla
1550 #endif // mozilla_TextEvents_h__