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