Bug 1838154 - Don't poke store buffer overflow state in testing code if the nursery...
[gecko.git] / widget / TextEvents.h
blob1cc2f63b7b25164feba7c40a37504c68ee1f13b5
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 ShortcutKeyCandidate() : mCharCode(0), mIgnoreShift(0) {}
108 ShortcutKeyCandidate(uint32_t aCharCode, bool aIgnoreShift)
109 : mCharCode(aCharCode), mIgnoreShift(aIgnoreShift) {}
110 // The mCharCode value which must match keyboard shortcut definition.
111 uint32_t mCharCode;
112 // true if Shift state can be ignored. Otherwise, Shift key state must
113 // match keyboard shortcut definition.
114 bool mIgnoreShift;
117 /******************************************************************************
118 * mozilla::IgnoreModifierState
120 * This stores flags for modifiers that should be ignored when matching
121 * XBL handlers.
122 ******************************************************************************/
124 struct IgnoreModifierState {
125 // When mShift is true, Shift key state will be ignored.
126 bool mShift;
127 // When mOS is true, OS key state will be ignored.
128 bool mOS;
130 IgnoreModifierState() : mShift(false), mOS(false) {}
133 /******************************************************************************
134 * mozilla::WidgetKeyboardEvent
135 ******************************************************************************/
137 class WidgetKeyboardEvent final : public WidgetInputEvent {
138 private:
139 friend class dom::PBrowserParent;
140 friend class dom::PBrowserChild;
141 friend struct IPC::ParamTraits<WidgetKeyboardEvent>;
142 ALLOW_DEPRECATED_READPARAM
144 protected:
145 WidgetKeyboardEvent()
146 : mNativeKeyEvent(nullptr),
147 mKeyCode(0),
148 mCharCode(0),
149 mPseudoCharCode(0),
150 mLocation(eKeyLocationStandard),
151 mUniqueId(0),
152 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
153 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
154 mIsRepeat(false),
155 mIsComposing(false),
156 mIsSynthesizedByTIP(false),
157 mMaybeSkippableInRemoteProcess(true),
158 mUseLegacyKeyCodeAndCharCodeValues(false),
159 mEditCommandsForSingleLineEditorInitialized(false),
160 mEditCommandsForMultiLineEditorInitialized(false),
161 mEditCommandsForRichTextEditorInitialized(false) {}
163 public:
164 WidgetKeyboardEvent* AsKeyboardEvent() override { return this; }
166 WidgetKeyboardEvent(bool aIsTrusted, EventMessage aMessage,
167 nsIWidget* aWidget,
168 EventClassID aEventClassID = eKeyboardEventClass)
169 : WidgetInputEvent(aIsTrusted, aMessage, aWidget, aEventClassID),
170 mNativeKeyEvent(nullptr),
171 mKeyCode(0),
172 mCharCode(0),
173 mPseudoCharCode(0),
174 mLocation(eKeyLocationStandard),
175 mUniqueId(0),
176 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
177 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
178 mIsRepeat(false),
179 mIsComposing(false),
180 mIsSynthesizedByTIP(false),
181 mMaybeSkippableInRemoteProcess(true),
182 mUseLegacyKeyCodeAndCharCodeValues(false),
183 mEditCommandsForSingleLineEditorInitialized(false),
184 mEditCommandsForMultiLineEditorInitialized(false),
185 mEditCommandsForRichTextEditorInitialized(false) {}
187 // IsInputtingText() and IsInputtingLineBreak() are used to check if
188 // it should cause eKeyPress events even on web content.
189 // UI Events defines that "keypress" event should be fired "if and only if
190 // that key normally produces a character value".
191 // <https://www.w3.org/TR/uievents/#event-type-keypress>
192 // Additionally, for backward compatiblity with all existing browsers,
193 // there is a spec issue for Enter key press.
194 // <https://github.com/w3c/uievents/issues/183>
195 bool IsInputtingText() const {
196 // NOTE: On some keyboard layout, some characters are inputted with Control
197 // key or Alt key, but at that time, widget clears the modifier flag
198 // from eKeyPress event because our TextEditor won't handle eKeyPress
199 // events as inputting text (bug 1346832).
200 // NOTE: There are some complicated issues of our traditional behavior.
201 // -- On Windows, KeyboardLayout::WillDispatchKeyboardEvent() clears
202 // MODIFIER_ALT and MODIFIER_CONTROL of eKeyPress event if it
203 // should be treated as inputting a character because AltGr is
204 // represented with both Alt key and Ctrl key are pressed, and
205 // some keyboard layouts may produces a character with Ctrl key.
206 // -- On Linux, KeymapWrapper doesn't have this hack since perhaps,
207 // we don't have any bug reports that user cannot input proper
208 // character with Alt and/or Ctrl key.
209 // -- On macOS, IMEInputHandler::WillDispatchKeyboardEvent() clears
210 // MODIFIER_ALT and MDOFIEIR_CONTROL of eKeyPress event only when
211 // TextInputHandler::InsertText() has been called for the event.
212 // I.e., they are cleared only when an editor has focus (even if IME
213 // is disabled in password field or by |ime-mode: disabled;|) because
214 // TextInputHandler::InsertText() is called while
215 // TextInputHandler::HandleKeyDownEvent() calls interpretKeyEvents:
216 // to notify text input processor of Cocoa (including IME). In other
217 // words, when we need to disable IME completey when no editor has
218 // focus, we cannot call interpretKeyEvents:. So,
219 // TextInputHandler::InsertText() won't be called when no editor has
220 // focus so that neither MODIFIER_ALT nor MODIFIER_CONTROL is
221 // cleared. So, fortunately, altKey and ctrlKey values of "keypress"
222 // events are same as the other browsers only when no editor has
223 // focus.
224 // NOTE: As mentioned above, for compatibility with the other browsers on
225 // macOS, we should keep MODIFIER_ALT and MODIFIER_CONTROL flags of
226 // eKeyPress events when no editor has focus. However, Alt key,
227 // labeled "option" on keyboard for Mac, is AltGraph key on the other
228 // platforms. So, even if MODIFIER_ALT is set, we need to dispatch
229 // eKeyPress event even on web content unless mCharCode is 0.
230 // Therefore, we need to ignore MODIFIER_ALT flag here only on macOS.
231 return mMessage == eKeyPress && mCharCode &&
232 !(mModifiers & (
233 #ifndef XP_MACOSX
234 // So, ignore MODIFIER_ALT only on macOS since
235 // option key is used as AltGraph key on macOS.
236 MODIFIER_ALT |
237 #endif // #ifndef XP_MAXOSX
238 MODIFIER_CONTROL | MODIFIER_META | MODIFIER_OS));
241 bool IsInputtingLineBreak() const {
242 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
243 !(mModifiers &
244 (MODIFIER_ALT | MODIFIER_CONTROL | MODIFIER_META | MODIFIER_OS));
248 * ShouldKeyPressEventBeFiredOnContent() should be called only when the
249 * instance is eKeyPress event. This returns true when the eKeyPress
250 * event should be fired even on content in the default event group.
252 bool ShouldKeyPressEventBeFiredOnContent() const {
253 MOZ_DIAGNOSTIC_ASSERT(mMessage == eKeyPress);
254 if (IsInputtingText() || IsInputtingLineBreak()) {
255 return true;
257 // Ctrl + Enter won't cause actual input in our editor.
258 // However, the other browsers fire keypress event in any platforms.
259 // So, for compatibility with them, we should fire keypress event for
260 // Ctrl + Enter too.
261 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
262 !(mModifiers &
263 (MODIFIER_ALT | MODIFIER_META | MODIFIER_OS | MODIFIER_SHIFT));
266 WidgetEvent* Duplicate() const override {
267 MOZ_ASSERT(mClass == eKeyboardEventClass,
268 "Duplicate() must be overridden by sub class");
269 // Not copying widget, it is a weak reference.
270 WidgetKeyboardEvent* result =
271 new WidgetKeyboardEvent(false, mMessage, nullptr);
272 result->AssignKeyEventData(*this, true);
273 result->mEditCommandsForSingleLineEditor =
274 mEditCommandsForSingleLineEditor.Clone();
275 result->mEditCommandsForMultiLineEditor =
276 mEditCommandsForMultiLineEditor.Clone();
277 result->mEditCommandsForRichTextEditor =
278 mEditCommandsForRichTextEditor.Clone();
279 result->mFlags = mFlags;
280 return result;
283 bool CanUserGestureActivateTarget() const {
284 // Printable keys, 'carriage return' and 'space' are supported user gestures
285 // for activating the document. However, if supported key is being pressed
286 // combining with other operation keys, such like alt, control ..etc., we
287 // won't activate the target for them because at that time user might
288 // interact with browser or window manager which doesn't necessarily
289 // demonstrate user's intent to play media.
290 const bool isCombiningWithOperationKeys = (IsControl() && !IsAltGraph()) ||
291 (IsAlt() && !IsAltGraph()) ||
292 IsMeta() || IsOS();
293 const bool isEnterOrSpaceKey =
294 mKeyNameIndex == KEY_NAME_INDEX_Enter || mKeyCode == NS_VK_SPACE;
295 return (PseudoCharCode() || isEnterOrSpaceKey) &&
296 (!isCombiningWithOperationKeys ||
297 // ctrl-c/ctrl-x/ctrl-v is quite common shortcut for clipboard
298 // operation.
299 // XXXedgar, we have to find a better way to handle browser keyboard
300 // shortcut for user activation, instead of just ignoring all
301 // combinations, see bug 1641171.
302 ((mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_C ||
303 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_V ||
304 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_X) &&
305 IsAccel()));
308 [[nodiscard]] bool ShouldWorkAsSpaceKey() const {
309 if (mKeyCode == NS_VK_SPACE) {
310 return true;
312 // Additionally, if the code value is "Space" and the key is not mapped to
313 // a function key (i.e., not a printable key), we should treat it as space
314 // key because the active keyboard layout may input different character
315 // from the ASCII white space (U+0020). For example, NBSP (U+00A0).
316 return mKeyNameIndex == KEY_NAME_INDEX_USE_STRING &&
317 mCodeNameIndex == CODE_NAME_INDEX_Space;
321 * CanTreatAsUserInput() returns true if the key is pressed for perhaps
322 * doing something on the web app or our UI. This means that when this
323 * returns false, e.g., when user presses a modifier key, user is probably
324 * displeased by opening popup, entering fullscreen mode, etc. Therefore,
325 * only when this returns true, such reactions should be allowed.
327 bool CanTreatAsUserInput() const {
328 if (!IsTrusted()) {
329 return false;
331 switch (mKeyNameIndex) {
332 case KEY_NAME_INDEX_Escape:
333 // modifier keys:
334 case KEY_NAME_INDEX_Alt:
335 case KEY_NAME_INDEX_AltGraph:
336 case KEY_NAME_INDEX_CapsLock:
337 case KEY_NAME_INDEX_Control:
338 case KEY_NAME_INDEX_Fn:
339 case KEY_NAME_INDEX_FnLock:
340 case KEY_NAME_INDEX_Meta:
341 case KEY_NAME_INDEX_NumLock:
342 case KEY_NAME_INDEX_ScrollLock:
343 case KEY_NAME_INDEX_Shift:
344 case KEY_NAME_INDEX_Symbol:
345 case KEY_NAME_INDEX_SymbolLock:
346 // legacy modifier keys:
347 case KEY_NAME_INDEX_Hyper:
348 case KEY_NAME_INDEX_Super:
349 // obsolete modifier key:
350 case KEY_NAME_INDEX_OS:
351 return false;
352 default:
353 return true;
358 * ShouldInteractionTimeRecorded() returns true if the handling time of
359 * the event should be recorded with the telemetry.
361 bool ShouldInteractionTimeRecorded() const {
362 // Let's record only when we can treat the instance is a user input.
363 return CanTreatAsUserInput();
366 // OS translated Unicode chars which are used for accesskey and accelkey
367 // handling. The handlers will try from first character to last character.
368 CopyableTArray<AlternativeCharCode> mAlternativeCharCodes;
369 // DOM KeyboardEvent.key only when mKeyNameIndex is KEY_NAME_INDEX_USE_STRING.
370 nsString mKeyValue;
371 // DOM KeyboardEvent.code only when mCodeNameIndex is
372 // CODE_NAME_INDEX_USE_STRING.
373 nsString mCodeValue;
375 // OS-specific native event can optionally be preserved.
376 // This is used to retrieve editing shortcut keys in the environment.
377 void* mNativeKeyEvent;
378 // A DOM keyCode value or 0. If a keypress event whose mCharCode is 0, this
379 // should be 0.
380 uint32_t mKeyCode;
381 // If the instance is a keypress event of a printable key, this is a UTF-16
382 // value of the key. Otherwise, 0. This value must not be a control
383 // character when some modifiers are active. Then, this value should be an
384 // unmodified value except Shift and AltGr.
385 uint32_t mCharCode;
386 // mPseudoCharCode is valid only when mMessage is an eKeyDown event.
387 // This stores mCharCode value of keypress event which is fired with same
388 // key value and same modifier state.
389 uint32_t mPseudoCharCode;
390 // One of eKeyLocation*
391 uint32_t mLocation;
392 // Unique id associated with a keydown / keypress event. It's ok if this wraps
393 // over long periods.
394 uint32_t mUniqueId;
396 // DOM KeyboardEvent.key
397 KeyNameIndex mKeyNameIndex;
398 // DOM KeyboardEvent.code
399 CodeNameIndex mCodeNameIndex;
401 // Indicates whether the event is generated by auto repeat or not.
402 // if this is keyup event, always false.
403 bool mIsRepeat;
404 // Indicates whether the event is generated during IME (or deadkey)
405 // composition. This is initialized by EventStateManager. So, key event
406 // dispatchers don't need to initialize this.
407 bool mIsComposing;
408 // Indicates whether the event is synthesized from Text Input Processor
409 // or an actual event from nsAppShell.
410 bool mIsSynthesizedByTIP;
411 // Indicates whether the event is skippable in remote process.
412 // Don't refer this member directly when you need to check this.
413 // Use CanSkipInRemoteProcess() instead.
414 bool mMaybeSkippableInRemoteProcess;
415 // Indicates whether the event should return legacy keyCode value and
416 // charCode value to web apps (one of them is always 0) or not, when it's
417 // an eKeyPress event.
418 bool mUseLegacyKeyCodeAndCharCodeValues;
420 bool CanSkipInRemoteProcess() const {
421 // If this is a repeat event (i.e., generated by auto-repeat feature of
422 // the platform), remove process may skip to handle it because of
423 // performances reasons.. However, if it's caused by odd keyboard utils,
424 // we should not ignore any key events even marked as repeated since
425 // generated key sequence may be important to input proper text. E.g.,
426 // "SinhalaTamil IME" on Windows emulates dead key like input with
427 // generating WM_KEYDOWN for VK_PACKET (inputting any Unicode characters
428 // without keyboard layout information) and VK_BACK (Backspace) to remove
429 // previous character(s) and those messages may be marked as "repeat" by
430 // their bug.
431 return mIsRepeat && mMaybeSkippableInRemoteProcess;
435 * If the key is an arrow key, and the current selection is in a vertical
436 * content, the caret should be moved to physically. However, arrow keys
437 * are mapped to logical move commands in horizontal content. Therefore,
438 * we need to check writing mode if and only if the key is an arrow key, and
439 * need to remap the command to logical command in vertical content if the
440 * writing mode at selection is vertical. These methods help to convert
441 * arrow keys in horizontal content to correspnding direction arrow keys
442 * in vertical content.
444 bool NeedsToRemapNavigationKey() const {
445 // TODO: Use mKeyNameIndex instead.
446 return mKeyCode >= NS_VK_LEFT && mKeyCode <= NS_VK_DOWN;
449 uint32_t GetRemappedKeyCode(const WritingMode& aWritingMode) const {
450 if (!aWritingMode.IsVertical()) {
451 return mKeyCode;
453 switch (mKeyCode) {
454 case NS_VK_LEFT:
455 return aWritingMode.IsVerticalLR() ? NS_VK_UP : NS_VK_DOWN;
456 case NS_VK_RIGHT:
457 return aWritingMode.IsVerticalLR() ? NS_VK_DOWN : NS_VK_UP;
458 case NS_VK_UP:
459 return NS_VK_LEFT;
460 case NS_VK_DOWN:
461 return NS_VK_RIGHT;
462 default:
463 return mKeyCode;
467 KeyNameIndex GetRemappedKeyNameIndex(const WritingMode& aWritingMode) const {
468 if (!aWritingMode.IsVertical()) {
469 return mKeyNameIndex;
471 uint32_t remappedKeyCode = GetRemappedKeyCode(aWritingMode);
472 if (remappedKeyCode == mKeyCode) {
473 return mKeyNameIndex;
475 switch (remappedKeyCode) {
476 case NS_VK_LEFT:
477 return KEY_NAME_INDEX_ArrowLeft;
478 case NS_VK_RIGHT:
479 return KEY_NAME_INDEX_ArrowRight;
480 case NS_VK_UP:
481 return KEY_NAME_INDEX_ArrowUp;
482 case NS_VK_DOWN:
483 return KEY_NAME_INDEX_ArrowDown;
484 default:
485 MOZ_ASSERT_UNREACHABLE("Add a case for the new remapped key");
486 return mKeyNameIndex;
491 * Retrieves all edit commands from mWidget. This shouldn't be called when
492 * the instance is an untrusted event, doesn't have widget or in non-chrome
493 * process.
495 * @param aWritingMode
496 * When writing mode of focused element is vertical, this
497 * will resolve some key's physical direction to logical
498 * direction. For doing it, this must be set to the
499 * writing mode at current selection. However, when there
500 * is no focused element and no selection ranges, this
501 * should be set to Nothing(). Using the result of
502 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
503 * is recommended.
505 MOZ_CAN_RUN_SCRIPT void InitAllEditCommands(
506 const Maybe<WritingMode>& aWritingMode);
509 * Retrieves edit commands from mWidget only for aType. This shouldn't be
510 * called when the instance is an untrusted event or doesn't have widget.
512 * @param aWritingMode
513 * When writing mode of focused element is vertical, this
514 * will resolve some key's physical direction to logical
515 * direction. For doing it, this must be set to the
516 * writing mode at current selection. However, when there
517 * is no focused element and no selection ranges, this
518 * should be set to Nothing(). Using the result of
519 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
520 * is recommended.
521 * @return false if some resource is not available to get
522 * commands unexpectedly. Otherwise, true even if
523 * retrieved command is nothing.
525 MOZ_CAN_RUN_SCRIPT bool InitEditCommandsFor(
526 NativeKeyBindingsType aType, const Maybe<WritingMode>& aWritingMode);
529 * PreventNativeKeyBindings() makes the instance to not cause any edit
530 * actions even if it matches with a native key binding.
532 void PreventNativeKeyBindings() {
533 mEditCommandsForSingleLineEditor.Clear();
534 mEditCommandsForMultiLineEditor.Clear();
535 mEditCommandsForRichTextEditor.Clear();
536 mEditCommandsForSingleLineEditorInitialized = true;
537 mEditCommandsForMultiLineEditorInitialized = true;
538 mEditCommandsForRichTextEditorInitialized = true;
542 * EditCommandsConstRef() returns reference to edit commands for aType.
544 const nsTArray<CommandInt>& EditCommandsConstRef(
545 NativeKeyBindingsType aType) const {
546 return const_cast<WidgetKeyboardEvent*>(this)->EditCommandsRef(aType);
550 * IsEditCommandsInitialized() returns true if edit commands for aType
551 * was already initialized. Otherwise, false.
553 bool IsEditCommandsInitialized(NativeKeyBindingsType aType) const {
554 return const_cast<WidgetKeyboardEvent*>(this)->IsEditCommandsInitializedRef(
555 aType);
559 * AreAllEditCommandsInitialized() returns true if edit commands for all
560 * types were already initialized. Otherwise, false.
562 bool AreAllEditCommandsInitialized() const {
563 return mEditCommandsForSingleLineEditorInitialized &&
564 mEditCommandsForMultiLineEditorInitialized &&
565 mEditCommandsForRichTextEditorInitialized;
569 * Execute edit commands for aType.
571 * @return true if the caller should do nothing anymore.
572 * false, otherwise.
574 typedef void (*DoCommandCallback)(Command, void*);
575 MOZ_CAN_RUN_SCRIPT bool ExecuteEditCommands(NativeKeyBindingsType aType,
576 DoCommandCallback aCallback,
577 void* aCallbackData);
579 // If the key should cause keypress events, this returns true.
580 // Otherwise, false.
581 bool ShouldCauseKeypressEvents() const;
583 // mCharCode value of non-eKeyPress events is always 0. However, if
584 // non-eKeyPress event has one or more alternative char code values,
585 // its first item should be the mCharCode value of following eKeyPress event.
586 // PseudoCharCode() returns mCharCode value for eKeyPress event,
587 // the first alternative char code value of non-eKeyPress event or 0.
588 uint32_t PseudoCharCode() const {
589 return mMessage == eKeyPress ? mCharCode : mPseudoCharCode;
591 void SetCharCode(uint32_t aCharCode) {
592 if (mMessage == eKeyPress) {
593 mCharCode = aCharCode;
594 } else {
595 mPseudoCharCode = aCharCode;
599 void GetDOMKeyName(nsAString& aKeyName) {
600 if (mKeyNameIndex == KEY_NAME_INDEX_USE_STRING) {
601 aKeyName = mKeyValue;
602 return;
604 GetDOMKeyName(mKeyNameIndex, aKeyName);
606 void GetDOMCodeName(nsAString& aCodeName) {
607 if (mCodeNameIndex == CODE_NAME_INDEX_USE_STRING) {
608 aCodeName = mCodeValue;
609 return;
611 GetDOMCodeName(mCodeNameIndex, aCodeName);
615 * GetFallbackKeyCodeOfPunctuationKey() returns a DOM keyCode value for
616 * aCodeNameIndex. This is keyCode value of the key when active keyboard
617 * layout is ANSI (US), JIS or ABNT keyboard layout (the latter 2 layouts
618 * are used only when ANSI doesn't have the key). The result is useful
619 * if the key doesn't produce ASCII character with active keyboard layout
620 * nor with alternative ASCII capable keyboard layout.
622 static uint32_t GetFallbackKeyCodeOfPunctuationKey(
623 CodeNameIndex aCodeNameIndex);
625 bool IsModifierKeyEvent() const {
626 return GetModifierForKeyName(mKeyNameIndex) != MODIFIER_NONE;
630 * Get the candidates for shortcut key.
632 * @param aCandidates [out] the candidate shortcut key combination list.
633 * the first item is most preferred.
635 void GetShortcutKeyCandidates(ShortcutKeyCandidateArray& aCandidates) const;
638 * Get the candidates for access key.
640 * @param aCandidates [out] the candidate access key list.
641 * the first item is most preferred.
643 void GetAccessKeyCandidates(nsTArray<uint32_t>& aCandidates) const;
646 * Check whether the modifiers match with chrome access key or
647 * content access key.
649 bool ModifiersMatchWithAccessKey(AccessKeyType aType) const;
652 * Return active modifiers which may match with access key.
653 * For example, even if Alt is access key modifier, then, when Control,
654 * CapseLock and NumLock are active, this returns only MODIFIER_CONTROL.
656 Modifiers ModifiersForAccessKeyMatching() const;
659 * Return access key modifiers.
661 static Modifiers AccessKeyModifiers(AccessKeyType aType);
663 static void Shutdown();
666 * ComputeLocationFromCodeValue() returns one of .mLocation value
667 * (eKeyLocation*) which is the most preferred value for the specified code
668 * value.
670 static uint32_t ComputeLocationFromCodeValue(CodeNameIndex aCodeNameIndex);
673 * ComputeKeyCodeFromKeyNameIndex() return a .mKeyCode value which can be
674 * mapped from the specified key value. Note that this returns 0 if the
675 * key name index is KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
676 * This means that this method is useful only for non-printable keys.
678 static uint32_t ComputeKeyCodeFromKeyNameIndex(KeyNameIndex aKeyNameIndex);
681 * ComputeCodeNameIndexFromKeyNameIndex() returns a code name index which
682 * is typically mapped to given key name index on the platform.
683 * Note that this returns CODE_NAME_INDEX_UNKNOWN if the key name index is
684 * KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
685 * This means that this method is useful only for non-printable keys.
687 * @param aKeyNameIndex A non-printable key name index.
688 * @param aLocation Should be one of location value. This is
689 * important when aKeyNameIndex may exist in
690 * both Numpad or Standard, or in both Left or
691 * Right. If this is nothing, this method
692 * returns Left or Standard position's code
693 * value.
695 static CodeNameIndex ComputeCodeNameIndexFromKeyNameIndex(
696 KeyNameIndex aKeyNameIndex, const Maybe<uint32_t>& aLocation);
699 * GetModifierForKeyName() returns a value of Modifier which is activated
700 * by the aKeyNameIndex.
702 static Modifier GetModifierForKeyName(KeyNameIndex aKeyNameIndex);
705 * IsLeftOrRightModiferKeyNameIndex() returns true if aKeyNameIndex is a
706 * modifier key which may be in Left and Right location.
708 static bool IsLeftOrRightModiferKeyNameIndex(KeyNameIndex aKeyNameIndex) {
709 switch (aKeyNameIndex) {
710 case KEY_NAME_INDEX_Alt:
711 case KEY_NAME_INDEX_Control:
712 case KEY_NAME_INDEX_Meta:
713 case KEY_NAME_INDEX_OS:
714 case KEY_NAME_INDEX_Shift:
715 return true;
716 default:
717 return false;
722 * IsLockableModifier() returns true if aKeyNameIndex is a lockable modifier
723 * key such as CapsLock and NumLock.
725 static bool IsLockableModifier(KeyNameIndex aKeyNameIndex);
727 static void GetDOMKeyName(KeyNameIndex aKeyNameIndex, nsAString& aKeyName);
728 static void GetDOMCodeName(CodeNameIndex aCodeNameIndex,
729 nsAString& aCodeName);
731 static KeyNameIndex GetKeyNameIndex(const nsAString& aKeyValue);
732 static CodeNameIndex GetCodeNameIndex(const nsAString& aCodeValue);
734 static const char* GetCommandStr(Command aCommand);
736 void AssignKeyEventData(const WidgetKeyboardEvent& aEvent,
737 bool aCopyTargets) {
738 AssignInputEventData(aEvent, aCopyTargets);
740 mKeyCode = aEvent.mKeyCode;
741 mCharCode = aEvent.mCharCode;
742 mPseudoCharCode = aEvent.mPseudoCharCode;
743 mLocation = aEvent.mLocation;
744 mAlternativeCharCodes = aEvent.mAlternativeCharCodes.Clone();
745 mIsRepeat = aEvent.mIsRepeat;
746 mIsComposing = aEvent.mIsComposing;
747 mKeyNameIndex = aEvent.mKeyNameIndex;
748 mCodeNameIndex = aEvent.mCodeNameIndex;
749 mKeyValue = aEvent.mKeyValue;
750 mCodeValue = aEvent.mCodeValue;
751 // Don't copy mNativeKeyEvent because it may be referred after its instance
752 // is destroyed.
753 mNativeKeyEvent = nullptr;
754 mUniqueId = aEvent.mUniqueId;
755 mIsSynthesizedByTIP = aEvent.mIsSynthesizedByTIP;
756 mMaybeSkippableInRemoteProcess = aEvent.mMaybeSkippableInRemoteProcess;
757 mUseLegacyKeyCodeAndCharCodeValues =
758 aEvent.mUseLegacyKeyCodeAndCharCodeValues;
760 // Don't copy mEditCommandsFor*Editor because it may require a lot of
761 // memory space. For example, if the event is dispatched but grabbed by
762 // a JS variable, they are not necessary anymore.
764 mEditCommandsForSingleLineEditorInitialized =
765 aEvent.mEditCommandsForSingleLineEditorInitialized;
766 mEditCommandsForMultiLineEditorInitialized =
767 aEvent.mEditCommandsForMultiLineEditorInitialized;
768 mEditCommandsForRichTextEditorInitialized =
769 aEvent.mEditCommandsForRichTextEditorInitialized;
772 void AssignCommands(const WidgetKeyboardEvent& aEvent) {
773 mEditCommandsForSingleLineEditorInitialized =
774 aEvent.mEditCommandsForSingleLineEditorInitialized;
775 if (mEditCommandsForSingleLineEditorInitialized) {
776 mEditCommandsForSingleLineEditor =
777 aEvent.mEditCommandsForSingleLineEditor.Clone();
778 } else {
779 mEditCommandsForSingleLineEditor.Clear();
781 mEditCommandsForMultiLineEditorInitialized =
782 aEvent.mEditCommandsForMultiLineEditorInitialized;
783 if (mEditCommandsForMultiLineEditorInitialized) {
784 mEditCommandsForMultiLineEditor =
785 aEvent.mEditCommandsForMultiLineEditor.Clone();
786 } else {
787 mEditCommandsForMultiLineEditor.Clear();
789 mEditCommandsForRichTextEditorInitialized =
790 aEvent.mEditCommandsForRichTextEditorInitialized;
791 if (mEditCommandsForRichTextEditorInitialized) {
792 mEditCommandsForRichTextEditor =
793 aEvent.mEditCommandsForRichTextEditor.Clone();
794 } else {
795 mEditCommandsForRichTextEditor.Clear();
799 private:
800 static const char16_t* const kKeyNames[];
801 static const char16_t* const kCodeNames[];
802 typedef nsTHashMap<nsStringHashKey, KeyNameIndex> KeyNameIndexHashtable;
803 typedef nsTHashMap<nsStringHashKey, CodeNameIndex> CodeNameIndexHashtable;
804 static KeyNameIndexHashtable* sKeyNameIndexHashtable;
805 static CodeNameIndexHashtable* sCodeNameIndexHashtable;
807 // mEditCommandsFor*Editor store edit commands. This should be initialized
808 // with InitEditCommandsFor().
809 // XXX Ideally, this should be array of Command rather than CommandInt.
810 // However, ParamTraits isn't aware of enum array.
811 CopyableTArray<CommandInt> mEditCommandsForSingleLineEditor;
812 CopyableTArray<CommandInt> mEditCommandsForMultiLineEditor;
813 CopyableTArray<CommandInt> mEditCommandsForRichTextEditor;
815 nsTArray<CommandInt>& EditCommandsRef(NativeKeyBindingsType aType) {
816 switch (aType) {
817 case NativeKeyBindingsType::SingleLineEditor:
818 return mEditCommandsForSingleLineEditor;
819 case NativeKeyBindingsType::MultiLineEditor:
820 return mEditCommandsForMultiLineEditor;
821 case NativeKeyBindingsType::RichTextEditor:
822 return mEditCommandsForRichTextEditor;
823 default:
824 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
825 "Invalid native key binding type");
829 // mEditCommandsFor*EditorInitialized are set to true when
830 // InitEditCommandsFor() initializes edit commands for the type.
831 bool mEditCommandsForSingleLineEditorInitialized;
832 bool mEditCommandsForMultiLineEditorInitialized;
833 bool mEditCommandsForRichTextEditorInitialized;
835 bool& IsEditCommandsInitializedRef(NativeKeyBindingsType aType) {
836 switch (aType) {
837 case NativeKeyBindingsType::SingleLineEditor:
838 return mEditCommandsForSingleLineEditorInitialized;
839 case NativeKeyBindingsType::MultiLineEditor:
840 return mEditCommandsForMultiLineEditorInitialized;
841 case NativeKeyBindingsType::RichTextEditor:
842 return mEditCommandsForRichTextEditorInitialized;
843 default:
844 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
845 "Invalid native key binding type");
850 /******************************************************************************
851 * mozilla::WidgetCompositionEvent
852 ******************************************************************************/
854 class WidgetCompositionEvent : public WidgetGUIEvent {
855 private:
856 friend class mozilla::dom::PBrowserParent;
857 friend class mozilla::dom::PBrowserChild;
858 ALLOW_DEPRECATED_READPARAM
860 WidgetCompositionEvent() : mOriginalMessage(eVoidEvent) {}
862 public:
863 virtual WidgetCompositionEvent* AsCompositionEvent() override { return this; }
865 WidgetCompositionEvent(bool aIsTrusted, EventMessage aMessage,
866 nsIWidget* aWidget)
867 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eCompositionEventClass),
868 mNativeIMEContext(aWidget),
869 mOriginalMessage(eVoidEvent) {}
871 virtual WidgetEvent* Duplicate() const override {
872 MOZ_ASSERT(mClass == eCompositionEventClass,
873 "Duplicate() must be overridden by sub class");
874 // Not copying widget, it is a weak reference.
875 WidgetCompositionEvent* result =
876 new WidgetCompositionEvent(false, mMessage, nullptr);
877 result->AssignCompositionEventData(*this, true);
878 result->mFlags = mFlags;
879 return result;
882 // The composition string or the commit string. If the instance is a
883 // compositionstart event, this is initialized with selected text by
884 // TextComposition automatically.
885 nsString mData;
887 RefPtr<TextRangeArray> mRanges;
889 // mNativeIMEContext stores the native IME context which causes the
890 // composition event.
891 widget::NativeIMEContext mNativeIMEContext;
893 // If the instance is a clone of another event, mOriginalMessage stores
894 // the another event's mMessage.
895 EventMessage mOriginalMessage;
897 // Composition ID considered by TextComposition. If the event has not been
898 // handled by TextComposition yet, this is 0. And also if the event is for
899 // a composition synthesized in a content process, this is always 0.
900 uint32_t mCompositionId = 0;
902 void AssignCompositionEventData(const WidgetCompositionEvent& aEvent,
903 bool aCopyTargets) {
904 AssignGUIEventData(aEvent, aCopyTargets);
906 mData = aEvent.mData;
907 mOriginalMessage = aEvent.mOriginalMessage;
908 mRanges = aEvent.mRanges;
910 // Currently, we don't need to copy the other members because they are
911 // for internal use only (not available from JS).
914 bool IsComposing() const { return mRanges && mRanges->IsComposing(); }
916 uint32_t TargetClauseOffset() const {
917 return mRanges ? mRanges->TargetClauseOffset() : 0;
920 uint32_t TargetClauseLength() const {
921 uint32_t length = UINT32_MAX;
922 if (mRanges) {
923 length = mRanges->TargetClauseLength();
925 return length == UINT32_MAX ? mData.Length() : length;
928 uint32_t RangeCount() const { return mRanges ? mRanges->Length() : 0; }
930 bool CausesDOMTextEvent() const {
931 return mMessage == eCompositionChange || mMessage == eCompositionCommit ||
932 mMessage == eCompositionCommitAsIs;
935 bool CausesDOMCompositionEndEvent() const {
936 return mMessage == eCompositionEnd || mMessage == eCompositionCommit ||
937 mMessage == eCompositionCommitAsIs;
940 bool IsFollowedByCompositionEnd() const {
941 return IsFollowedByCompositionEnd(mOriginalMessage);
944 static bool IsFollowedByCompositionEnd(EventMessage aEventMessage) {
945 return aEventMessage == eCompositionCommit ||
946 aEventMessage == eCompositionCommitAsIs;
950 /******************************************************************************
951 * mozilla::WidgetQueryContentEvent
952 ******************************************************************************/
954 class WidgetQueryContentEvent : public WidgetGUIEvent {
955 private:
956 friend class dom::PBrowserParent;
957 friend class dom::PBrowserChild;
958 ALLOW_DEPRECATED_READPARAM
960 WidgetQueryContentEvent()
961 : mUseNativeLineBreak(true),
962 mWithFontRanges(false),
963 mNeedsToFlushLayout(true) {
964 MOZ_CRASH("WidgetQueryContentEvent is created without proper arguments");
967 public:
968 virtual WidgetQueryContentEvent* AsQueryContentEvent() override {
969 return this;
972 WidgetQueryContentEvent(bool aIsTrusted, EventMessage aMessage,
973 nsIWidget* aWidget)
974 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eQueryContentEventClass),
975 mUseNativeLineBreak(true),
976 mWithFontRanges(false),
977 mNeedsToFlushLayout(true) {}
979 WidgetQueryContentEvent(EventMessage aMessage,
980 const WidgetQueryContentEvent& aOtherEvent)
981 : WidgetGUIEvent(aOtherEvent.IsTrusted(), aMessage,
982 const_cast<nsIWidget*>(aOtherEvent.mWidget.get()),
983 eQueryContentEventClass),
984 mUseNativeLineBreak(aOtherEvent.mUseNativeLineBreak),
985 mWithFontRanges(false),
986 mNeedsToFlushLayout(aOtherEvent.mNeedsToFlushLayout) {}
988 virtual WidgetEvent* Duplicate() const override {
989 // This event isn't an internal event of any DOM event.
990 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
991 "WidgetQueryContentEvent needs to support Duplicate()");
992 MOZ_CRASH("WidgetQueryContentEvent doesn't support Duplicate()");
995 struct Options final {
996 bool mUseNativeLineBreak;
997 bool mRelativeToInsertionPoint;
999 explicit Options()
1000 : mUseNativeLineBreak(true), mRelativeToInsertionPoint(false) {}
1002 explicit Options(const WidgetQueryContentEvent& aEvent)
1003 : mUseNativeLineBreak(aEvent.mUseNativeLineBreak),
1004 mRelativeToInsertionPoint(aEvent.mInput.mRelativeToInsertionPoint) {}
1007 void Init(const Options& aOptions) {
1008 mUseNativeLineBreak = aOptions.mUseNativeLineBreak;
1009 mInput.mRelativeToInsertionPoint = aOptions.mRelativeToInsertionPoint;
1010 MOZ_ASSERT(mInput.IsValidEventMessage(mMessage));
1013 void InitForQueryTextContent(int64_t aOffset, uint32_t aLength,
1014 const Options& aOptions = Options()) {
1015 NS_ASSERTION(mMessage == eQueryTextContent, "wrong initializer is called");
1016 mInput.mOffset = aOffset;
1017 mInput.mLength = aLength;
1018 Init(aOptions);
1019 MOZ_ASSERT(mInput.IsValidOffset());
1022 void InitForQueryCaretRect(int64_t aOffset,
1023 const Options& aOptions = Options()) {
1024 NS_ASSERTION(mMessage == eQueryCaretRect, "wrong initializer is called");
1025 mInput.mOffset = aOffset;
1026 Init(aOptions);
1027 MOZ_ASSERT(mInput.IsValidOffset());
1030 void InitForQueryTextRect(int64_t aOffset, uint32_t aLength,
1031 const Options& aOptions = Options()) {
1032 NS_ASSERTION(mMessage == eQueryTextRect, "wrong initializer is called");
1033 mInput.mOffset = aOffset;
1034 mInput.mLength = aLength;
1035 Init(aOptions);
1036 MOZ_ASSERT(mInput.IsValidOffset());
1039 void InitForQuerySelectedText(SelectionType aSelectionType,
1040 const Options& aOptions = Options()) {
1041 MOZ_ASSERT(mMessage == eQuerySelectedText);
1042 MOZ_ASSERT(aSelectionType != SelectionType::eNone);
1043 mInput.mSelectionType = aSelectionType;
1044 Init(aOptions);
1047 void InitForQueryDOMWidgetHittest(
1048 const mozilla::LayoutDeviceIntPoint& aPoint) {
1049 NS_ASSERTION(mMessage == eQueryDOMWidgetHittest,
1050 "wrong initializer is called");
1051 mRefPoint = aPoint;
1054 void InitForQueryTextRectArray(uint32_t aOffset, uint32_t aLength,
1055 const Options& aOptions = Options()) {
1056 NS_ASSERTION(mMessage == eQueryTextRectArray,
1057 "wrong initializer is called");
1058 mInput.mOffset = aOffset;
1059 mInput.mLength = aLength;
1060 Init(aOptions);
1063 bool NeedsToFlushLayout() const { return mNeedsToFlushLayout; }
1065 void RequestFontRanges() {
1066 MOZ_ASSERT(mMessage == eQueryTextContent);
1067 mWithFontRanges = true;
1070 bool Succeeded() const {
1071 if (mReply.isNothing()) {
1072 return false;
1074 switch (mMessage) {
1075 case eQueryTextContent:
1076 case eQueryTextRect:
1077 case eQueryCaretRect:
1078 return mReply->mOffsetAndData.isSome();
1079 default:
1080 return true;
1084 bool Failed() const { return !Succeeded(); }
1086 bool FoundSelection() const {
1087 MOZ_ASSERT(mMessage == eQuerySelectedText);
1088 return Succeeded() && mReply->mOffsetAndData.isSome();
1091 bool FoundChar() const {
1092 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1093 return Succeeded() && mReply->mOffsetAndData.isSome();
1096 bool FoundTentativeCaretOffset() const {
1097 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1098 return Succeeded() && mReply->mTentativeCaretOffset.isSome();
1101 bool DidNotFindSelection() const {
1102 MOZ_ASSERT(mMessage == eQuerySelectedText);
1103 return Failed() || mReply->mOffsetAndData.isNothing();
1106 bool DidNotFindChar() const {
1107 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1108 return Failed() || mReply->mOffsetAndData.isNothing();
1111 bool DidNotFindTentativeCaretOffset() const {
1112 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1113 return Failed() || mReply->mTentativeCaretOffset.isNothing();
1116 bool mUseNativeLineBreak;
1117 bool mWithFontRanges;
1118 bool mNeedsToFlushLayout;
1119 struct Input final {
1120 uint32_t EndOffset() const {
1121 CheckedInt<uint32_t> endOffset = CheckedInt<uint32_t>(mOffset) + mLength;
1122 return NS_WARN_IF(!endOffset.isValid()) ? UINT32_MAX : endOffset.value();
1125 int64_t mOffset;
1126 uint32_t mLength;
1127 SelectionType mSelectionType;
1128 // If mOffset is true, mOffset is relative to the start offset of
1129 // composition if there is, otherwise, the start of the first selection
1130 // range.
1131 bool mRelativeToInsertionPoint;
1133 Input()
1134 : mOffset(0),
1135 mLength(0),
1136 mSelectionType(SelectionType::eNormal),
1137 mRelativeToInsertionPoint(false) {}
1139 bool IsValidOffset() const {
1140 return mRelativeToInsertionPoint || mOffset >= 0;
1142 bool IsValidEventMessage(EventMessage aEventMessage) const {
1143 if (!mRelativeToInsertionPoint) {
1144 return true;
1146 switch (aEventMessage) {
1147 case eQueryTextContent:
1148 case eQueryCaretRect:
1149 case eQueryTextRect:
1150 return true;
1151 default:
1152 return false;
1155 bool MakeOffsetAbsolute(uint32_t aInsertionPointOffset) {
1156 if (NS_WARN_IF(!mRelativeToInsertionPoint)) {
1157 return true;
1159 mRelativeToInsertionPoint = false;
1160 // If mOffset + aInsertionPointOffset becomes negative value,
1161 // we should assume the absolute offset is 0.
1162 if (mOffset < 0 && -mOffset > aInsertionPointOffset) {
1163 mOffset = 0;
1164 return true;
1166 // Otherwise, we don't allow too large offset.
1167 CheckedInt<uint32_t> absOffset(mOffset + aInsertionPointOffset);
1168 if (NS_WARN_IF(!absOffset.isValid())) {
1169 mOffset = UINT32_MAX;
1170 return false;
1172 mOffset = absOffset.value();
1173 return true;
1175 } mInput;
1177 struct Reply final {
1178 EventMessage const mEventMessage;
1179 void* mContentsRoot = nullptr;
1180 Maybe<OffsetAndData<uint32_t>> mOffsetAndData;
1181 // mTentativeCaretOffset is used by only eQueryCharacterAtPoint.
1182 // This is the offset where caret would be if user clicked at the mRefPoint.
1183 Maybe<uint32_t> mTentativeCaretOffset;
1184 // mRect is used by eQueryTextRect, eQueryCaretRect, eQueryCharacterAtPoint
1185 // and eQueryEditorRect. The coordinates is system coordinates relative to
1186 // the top level widget of mFocusedWidget. E.g., if a <xul:panel> which
1187 // is owned by a window has focused editor, the offset of mRect is relative
1188 // to the owner window, not the <xul:panel>.
1189 mozilla::LayoutDeviceIntRect mRect;
1190 // The return widget has the caret. This is set at all query events.
1191 nsIWidget* mFocusedWidget = nullptr;
1192 // mozilla::WritingMode value at the end (focus) of the selection
1193 mozilla::WritingMode mWritingMode;
1194 // Used by eQuerySelectionAsTransferable
1195 nsCOMPtr<nsITransferable> mTransferable;
1196 // Used by eQueryTextContent with font ranges requested
1197 CopyableAutoTArray<mozilla::FontRange, 1> mFontRanges;
1198 // Used by eQueryTextRectArray
1199 CopyableTArray<mozilla::LayoutDeviceIntRect> mRectArray;
1200 // true if selection is reversed (end < start)
1201 bool mReversed = false;
1202 // true if DOM element under mouse belongs to widget
1203 bool mWidgetIsHit = false;
1204 // true if mContentRoot is focused editable content
1205 bool mIsEditableContent = false;
1207 Reply() = delete;
1208 explicit Reply(EventMessage aEventMessage) : mEventMessage(aEventMessage) {}
1210 // Don't allow to copy/move because of `mEventMessage`.
1211 Reply(const Reply& aOther) = delete;
1212 Reply(Reply&& aOther) = delete;
1213 Reply& operator=(const Reply& aOther) = delete;
1214 Reply& operator=(Reply&& aOther) = delete;
1216 MOZ_NEVER_INLINE_DEBUG uint32_t StartOffset() const {
1217 MOZ_ASSERT(mOffsetAndData.isSome());
1218 return mOffsetAndData->StartOffset();
1220 MOZ_NEVER_INLINE_DEBUG uint32_t EndOffset() const {
1221 MOZ_ASSERT(mOffsetAndData.isSome());
1222 return mOffsetAndData->EndOffset();
1224 MOZ_NEVER_INLINE_DEBUG uint32_t DataLength() const {
1225 MOZ_ASSERT(mOffsetAndData.isSome() ||
1226 mEventMessage == eQuerySelectedText);
1227 return mOffsetAndData.isSome() ? mOffsetAndData->Length() : 0;
1229 MOZ_NEVER_INLINE_DEBUG uint32_t AnchorOffset() const {
1230 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1231 MOZ_ASSERT(mOffsetAndData.isSome());
1232 return StartOffset() + (mReversed ? DataLength() : 0);
1235 MOZ_NEVER_INLINE_DEBUG uint32_t FocusOffset() const {
1236 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1237 MOZ_ASSERT(mOffsetAndData.isSome());
1238 return StartOffset() + (mReversed ? 0 : DataLength());
1241 const WritingMode& WritingModeRef() const {
1242 MOZ_ASSERT(mEventMessage == eQuerySelectedText ||
1243 mEventMessage == eQueryCaretRect ||
1244 mEventMessage == eQueryTextRect);
1245 MOZ_ASSERT(mOffsetAndData.isSome() ||
1246 mEventMessage == eQuerySelectedText);
1247 return mWritingMode;
1250 MOZ_NEVER_INLINE_DEBUG const nsString& DataRef() const {
1251 MOZ_ASSERT(mOffsetAndData.isSome() ||
1252 mEventMessage == eQuerySelectedText);
1253 return mOffsetAndData.isSome() ? mOffsetAndData->DataRef()
1254 : EmptyString();
1256 MOZ_NEVER_INLINE_DEBUG bool IsDataEmpty() const {
1257 MOZ_ASSERT(mOffsetAndData.isSome() ||
1258 mEventMessage == eQuerySelectedText);
1259 return mOffsetAndData.isSome() ? mOffsetAndData->IsDataEmpty() : true;
1261 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRange(uint32_t aOffset) const {
1262 MOZ_ASSERT(mOffsetAndData.isSome() ||
1263 mEventMessage == eQuerySelectedText);
1264 return mOffsetAndData.isSome() ? mOffsetAndData->IsOffsetInRange(aOffset)
1265 : false;
1267 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRangeOrEndOffset(
1268 uint32_t aOffset) const {
1269 MOZ_ASSERT(mOffsetAndData.isSome() ||
1270 mEventMessage == eQuerySelectedText);
1271 return mOffsetAndData.isSome()
1272 ? mOffsetAndData->IsOffsetInRangeOrEndOffset(aOffset)
1273 : false;
1275 MOZ_NEVER_INLINE_DEBUG void TruncateData(uint32_t aLength = 0) {
1276 MOZ_ASSERT(mOffsetAndData.isSome());
1277 mOffsetAndData->TruncateData(aLength);
1280 friend std::ostream& operator<<(std::ostream& aStream,
1281 const Reply& aReply) {
1282 aStream << "{ ";
1283 if (aReply.mEventMessage == eQuerySelectedText ||
1284 aReply.mEventMessage == eQueryTextContent ||
1285 aReply.mEventMessage == eQueryTextRect ||
1286 aReply.mEventMessage == eQueryCaretRect ||
1287 aReply.mEventMessage == eQueryCharacterAtPoint) {
1288 aStream << "mOffsetAndData=" << ToString(aReply.mOffsetAndData).c_str()
1289 << ", ";
1290 if (aReply.mEventMessage == eQueryCharacterAtPoint) {
1291 aStream << "mTentativeCaretOffset="
1292 << ToString(aReply.mTentativeCaretOffset).c_str() << ", ";
1295 if (aReply.mOffsetAndData.isSome() && aReply.mOffsetAndData->Length()) {
1296 if (aReply.mEventMessage == eQuerySelectedText) {
1297 aStream << ", mReversed=" << (aReply.mReversed ? "true" : "false");
1299 if (aReply.mEventMessage == eQuerySelectionAsTransferable) {
1300 aStream << ", mTransferable=0x" << aReply.mTransferable;
1303 if (aReply.mEventMessage == eQuerySelectedText ||
1304 aReply.mEventMessage == eQueryTextRect ||
1305 aReply.mEventMessage == eQueryCaretRect) {
1306 aStream << ", mWritingMode=" << ToString(aReply.mWritingMode).c_str();
1308 aStream << ", mContentsRoot=0x" << aReply.mContentsRoot
1309 << ", mIsEditableContent="
1310 << (aReply.mIsEditableContent ? "true" : "false")
1311 << ", mFocusedWidget=0x" << aReply.mFocusedWidget;
1312 if (aReply.mEventMessage == eQueryTextContent) {
1313 aStream << ", mFontRanges={ Length()=" << aReply.mFontRanges.Length()
1314 << " }";
1315 } else if (aReply.mEventMessage == eQueryTextRect ||
1316 aReply.mEventMessage == eQueryCaretRect ||
1317 aReply.mEventMessage == eQueryCharacterAtPoint) {
1318 aStream << ", mRect=" << ToString(aReply.mRect).c_str();
1319 } else if (aReply.mEventMessage == eQueryTextRectArray) {
1320 aStream << ", mRectArray={ Length()=" << aReply.mRectArray.Length()
1321 << " }";
1322 } else if (aReply.mEventMessage == eQueryDOMWidgetHittest) {
1323 aStream << ", mWidgetIsHit="
1324 << (aReply.mWidgetIsHit ? "true" : "false");
1326 return aStream << " }";
1330 void EmplaceReply() { mReply.emplace(mMessage); }
1331 Maybe<Reply> mReply;
1333 // values of mComputedScrollAction
1334 enum { SCROLL_ACTION_NONE, SCROLL_ACTION_LINE, SCROLL_ACTION_PAGE };
1337 /******************************************************************************
1338 * mozilla::WidgetSelectionEvent
1339 ******************************************************************************/
1341 class WidgetSelectionEvent : public WidgetGUIEvent {
1342 private:
1343 friend class mozilla::dom::PBrowserParent;
1344 friend class mozilla::dom::PBrowserChild;
1345 ALLOW_DEPRECATED_READPARAM
1347 WidgetSelectionEvent()
1348 : mOffset(0),
1349 mLength(0),
1350 mReversed(false),
1351 mExpandToClusterBoundary(true),
1352 mSucceeded(false),
1353 mUseNativeLineBreak(true),
1354 mReason(nsISelectionListener::NO_REASON) {}
1356 public:
1357 virtual WidgetSelectionEvent* AsSelectionEvent() override { return this; }
1359 WidgetSelectionEvent(bool aIsTrusted, EventMessage aMessage,
1360 nsIWidget* aWidget)
1361 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eSelectionEventClass),
1362 mOffset(0),
1363 mLength(0),
1364 mReversed(false),
1365 mExpandToClusterBoundary(true),
1366 mSucceeded(false),
1367 mUseNativeLineBreak(true),
1368 mReason(nsISelectionListener::NO_REASON) {}
1370 virtual WidgetEvent* Duplicate() const override {
1371 // This event isn't an internal event of any DOM event.
1372 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1373 "WidgetSelectionEvent needs to support Duplicate()");
1374 MOZ_CRASH("WidgetSelectionEvent doesn't support Duplicate()");
1375 return nullptr;
1378 // Start offset of selection
1379 uint32_t mOffset;
1380 // Length of selection
1381 uint32_t mLength;
1382 // Selection "anchor" should be in front
1383 bool mReversed;
1384 // Cluster-based or character-based
1385 bool mExpandToClusterBoundary;
1386 // true if setting selection succeeded.
1387 bool mSucceeded;
1388 // true if native line breaks are used for mOffset and mLength
1389 bool mUseNativeLineBreak;
1390 // Fennec provides eSetSelection reason codes for downstream
1391 // use in AccessibleCaret visibility logic.
1392 int16_t mReason;
1395 /******************************************************************************
1396 * mozilla::InternalEditorInputEvent
1397 ******************************************************************************/
1399 class InternalEditorInputEvent : public InternalUIEvent {
1400 private:
1401 InternalEditorInputEvent()
1402 : mData(VoidString()),
1403 mInputType(EditorInputType::eUnknown),
1404 mIsComposing(false) {}
1406 public:
1407 virtual InternalEditorInputEvent* AsEditorInputEvent() override {
1408 return this;
1411 InternalEditorInputEvent(bool aIsTrusted, EventMessage aMessage,
1412 nsIWidget* aWidget = nullptr)
1413 : InternalUIEvent(aIsTrusted, aMessage, aWidget, eEditorInputEventClass),
1414 mData(VoidString()),
1415 mInputType(EditorInputType::eUnknown) {}
1417 virtual WidgetEvent* Duplicate() const override {
1418 MOZ_ASSERT(mClass == eEditorInputEventClass,
1419 "Duplicate() must be overridden by sub class");
1420 // Not copying widget, it is a weak reference.
1421 InternalEditorInputEvent* result =
1422 new InternalEditorInputEvent(false, mMessage, nullptr);
1423 result->AssignEditorInputEventData(*this, true);
1424 result->mFlags = mFlags;
1425 return result;
1428 nsString mData;
1429 RefPtr<dom::DataTransfer> mDataTransfer;
1430 OwningNonNullStaticRangeArray mTargetRanges;
1432 EditorInputType mInputType;
1434 bool mIsComposing;
1436 void AssignEditorInputEventData(const InternalEditorInputEvent& aEvent,
1437 bool aCopyTargets) {
1438 AssignUIEventData(aEvent, aCopyTargets);
1440 mData = aEvent.mData;
1441 mDataTransfer = aEvent.mDataTransfer;
1442 mTargetRanges = aEvent.mTargetRanges.Clone();
1443 mInputType = aEvent.mInputType;
1444 mIsComposing = aEvent.mIsComposing;
1447 void GetDOMInputTypeName(nsAString& aInputTypeName) {
1448 GetDOMInputTypeName(mInputType, aInputTypeName);
1450 static void GetDOMInputTypeName(EditorInputType aInputType,
1451 nsAString& aInputTypeName);
1452 static EditorInputType GetEditorInputType(const nsAString& aInputType);
1454 static void Shutdown();
1456 private:
1457 static const char16_t* const kInputTypeNames[];
1458 typedef nsTHashMap<nsStringHashKey, EditorInputType> InputTypeHashtable;
1459 static InputTypeHashtable* sInputTypeHashtable;
1462 } // namespace mozilla
1464 #endif // mozilla_TextEvents_h__