Bug 1831086 - Patch winsock2.h usage in nICEr to include missing types r=RyanVM
[gecko.git] / widget / TextEvents.h
blob43e2dbc8c0a3d423b243df1e7edaaf70a85389e4
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() : mUnshiftedCharCode(0), mShiftedCharCode(0) {}
84 AlternativeCharCode(uint32_t aUnshiftedCharCode, uint32_t aShiftedCharCode)
85 : mUnshiftedCharCode(aUnshiftedCharCode),
86 mShiftedCharCode(aShiftedCharCode) {}
87 uint32_t mUnshiftedCharCode;
88 uint32_t mShiftedCharCode;
91 /******************************************************************************
92 * mozilla::ShortcutKeyCandidate
94 * This stores a candidate of shortcut key combination.
95 ******************************************************************************/
97 struct ShortcutKeyCandidate {
98 ShortcutKeyCandidate() : mCharCode(0), mIgnoreShift(0) {}
99 ShortcutKeyCandidate(uint32_t aCharCode, bool aIgnoreShift)
100 : mCharCode(aCharCode), mIgnoreShift(aIgnoreShift) {}
101 // The mCharCode value which must match keyboard shortcut definition.
102 uint32_t mCharCode;
103 // true if Shift state can be ignored. Otherwise, Shift key state must
104 // match keyboard shortcut definition.
105 bool mIgnoreShift;
108 /******************************************************************************
109 * mozilla::IgnoreModifierState
111 * This stores flags for modifiers that should be ignored when matching
112 * XBL handlers.
113 ******************************************************************************/
115 struct IgnoreModifierState {
116 // When mShift is true, Shift key state will be ignored.
117 bool mShift;
118 // When mOS is true, OS key state will be ignored.
119 bool mOS;
121 IgnoreModifierState() : mShift(false), mOS(false) {}
124 /******************************************************************************
125 * mozilla::WidgetKeyboardEvent
126 ******************************************************************************/
128 class WidgetKeyboardEvent final : public WidgetInputEvent {
129 private:
130 friend class dom::PBrowserParent;
131 friend class dom::PBrowserChild;
132 friend struct IPC::ParamTraits<WidgetKeyboardEvent>;
133 ALLOW_DEPRECATED_READPARAM
135 protected:
136 WidgetKeyboardEvent()
137 : mNativeKeyEvent(nullptr),
138 mKeyCode(0),
139 mCharCode(0),
140 mPseudoCharCode(0),
141 mLocation(eKeyLocationStandard),
142 mUniqueId(0),
143 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
144 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
145 mIsRepeat(false),
146 mIsComposing(false),
147 mIsSynthesizedByTIP(false),
148 mMaybeSkippableInRemoteProcess(true),
149 mUseLegacyKeyCodeAndCharCodeValues(false),
150 mEditCommandsForSingleLineEditorInitialized(false),
151 mEditCommandsForMultiLineEditorInitialized(false),
152 mEditCommandsForRichTextEditorInitialized(false) {}
154 public:
155 WidgetKeyboardEvent* AsKeyboardEvent() override { return this; }
157 WidgetKeyboardEvent(bool aIsTrusted, EventMessage aMessage,
158 nsIWidget* aWidget,
159 EventClassID aEventClassID = eKeyboardEventClass)
160 : WidgetInputEvent(aIsTrusted, aMessage, aWidget, aEventClassID),
161 mNativeKeyEvent(nullptr),
162 mKeyCode(0),
163 mCharCode(0),
164 mPseudoCharCode(0),
165 mLocation(eKeyLocationStandard),
166 mUniqueId(0),
167 mKeyNameIndex(KEY_NAME_INDEX_Unidentified),
168 mCodeNameIndex(CODE_NAME_INDEX_UNKNOWN),
169 mIsRepeat(false),
170 mIsComposing(false),
171 mIsSynthesizedByTIP(false),
172 mMaybeSkippableInRemoteProcess(true),
173 mUseLegacyKeyCodeAndCharCodeValues(false),
174 mEditCommandsForSingleLineEditorInitialized(false),
175 mEditCommandsForMultiLineEditorInitialized(false),
176 mEditCommandsForRichTextEditorInitialized(false) {}
178 // IsInputtingText() and IsInputtingLineBreak() are used to check if
179 // it should cause eKeyPress events even on web content.
180 // UI Events defines that "keypress" event should be fired "if and only if
181 // that key normally produces a character value".
182 // <https://www.w3.org/TR/uievents/#event-type-keypress>
183 // Additionally, for backward compatiblity with all existing browsers,
184 // there is a spec issue for Enter key press.
185 // <https://github.com/w3c/uievents/issues/183>
186 bool IsInputtingText() const {
187 // NOTE: On some keyboard layout, some characters are inputted with Control
188 // key or Alt key, but at that time, widget clears the modifier flag
189 // from eKeyPress event because our TextEditor won't handle eKeyPress
190 // events as inputting text (bug 1346832).
191 // NOTE: There are some complicated issues of our traditional behavior.
192 // -- On Windows, KeyboardLayout::WillDispatchKeyboardEvent() clears
193 // MODIFIER_ALT and MODIFIER_CONTROL of eKeyPress event if it
194 // should be treated as inputting a character because AltGr is
195 // represented with both Alt key and Ctrl key are pressed, and
196 // some keyboard layouts may produces a character with Ctrl key.
197 // -- On Linux, KeymapWrapper doesn't have this hack since perhaps,
198 // we don't have any bug reports that user cannot input proper
199 // character with Alt and/or Ctrl key.
200 // -- On macOS, IMEInputHandler::WillDispatchKeyboardEvent() clears
201 // MODIFIER_ALT and MDOFIEIR_CONTROL of eKeyPress event only when
202 // TextInputHandler::InsertText() has been called for the event.
203 // I.e., they are cleared only when an editor has focus (even if IME
204 // is disabled in password field or by |ime-mode: disabled;|) because
205 // TextInputHandler::InsertText() is called while
206 // TextInputHandler::HandleKeyDownEvent() calls interpretKeyEvents:
207 // to notify text input processor of Cocoa (including IME). In other
208 // words, when we need to disable IME completey when no editor has
209 // focus, we cannot call interpretKeyEvents:. So,
210 // TextInputHandler::InsertText() won't be called when no editor has
211 // focus so that neither MODIFIER_ALT nor MODIFIER_CONTROL is
212 // cleared. So, fortunately, altKey and ctrlKey values of "keypress"
213 // events are same as the other browsers only when no editor has
214 // focus.
215 // NOTE: As mentioned above, for compatibility with the other browsers on
216 // macOS, we should keep MODIFIER_ALT and MODIFIER_CONTROL flags of
217 // eKeyPress events when no editor has focus. However, Alt key,
218 // labeled "option" on keyboard for Mac, is AltGraph key on the other
219 // platforms. So, even if MODIFIER_ALT is set, we need to dispatch
220 // eKeyPress event even on web content unless mCharCode is 0.
221 // Therefore, we need to ignore MODIFIER_ALT flag here only on macOS.
222 return mMessage == eKeyPress && mCharCode &&
223 !(mModifiers & (
224 #ifndef XP_MACOSX
225 // So, ignore MODIFIER_ALT only on macOS since
226 // option key is used as AltGraph key on macOS.
227 MODIFIER_ALT |
228 #endif // #ifndef XP_MAXOSX
229 MODIFIER_CONTROL | MODIFIER_META | MODIFIER_OS));
232 bool IsInputtingLineBreak() const {
233 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
234 !(mModifiers &
235 (MODIFIER_ALT | MODIFIER_CONTROL | MODIFIER_META | MODIFIER_OS));
239 * ShouldKeyPressEventBeFiredOnContent() should be called only when the
240 * instance is eKeyPress event. This returns true when the eKeyPress
241 * event should be fired even on content in the default event group.
243 bool ShouldKeyPressEventBeFiredOnContent() const {
244 MOZ_DIAGNOSTIC_ASSERT(mMessage == eKeyPress);
245 if (IsInputtingText() || IsInputtingLineBreak()) {
246 return true;
248 // Ctrl + Enter won't cause actual input in our editor.
249 // However, the other browsers fire keypress event in any platforms.
250 // So, for compatibility with them, we should fire keypress event for
251 // Ctrl + Enter too.
252 return mMessage == eKeyPress && mKeyNameIndex == KEY_NAME_INDEX_Enter &&
253 !(mModifiers &
254 (MODIFIER_ALT | MODIFIER_META | MODIFIER_OS | MODIFIER_SHIFT));
257 WidgetEvent* Duplicate() const override {
258 MOZ_ASSERT(mClass == eKeyboardEventClass,
259 "Duplicate() must be overridden by sub class");
260 // Not copying widget, it is a weak reference.
261 WidgetKeyboardEvent* result =
262 new WidgetKeyboardEvent(false, mMessage, nullptr);
263 result->AssignKeyEventData(*this, true);
264 result->mEditCommandsForSingleLineEditor =
265 mEditCommandsForSingleLineEditor.Clone();
266 result->mEditCommandsForMultiLineEditor =
267 mEditCommandsForMultiLineEditor.Clone();
268 result->mEditCommandsForRichTextEditor =
269 mEditCommandsForRichTextEditor.Clone();
270 result->mFlags = mFlags;
271 return result;
274 bool CanUserGestureActivateTarget() const {
275 // Printable keys, 'carriage return' and 'space' are supported user gestures
276 // for activating the document. However, if supported key is being pressed
277 // combining with other operation keys, such like alt, control ..etc., we
278 // won't activate the target for them because at that time user might
279 // interact with browser or window manager which doesn't necessarily
280 // demonstrate user's intent to play media.
281 const bool isCombiningWithOperationKeys = (IsControl() && !IsAltGraph()) ||
282 (IsAlt() && !IsAltGraph()) ||
283 IsMeta() || IsOS();
284 const bool isEnterOrSpaceKey =
285 mKeyNameIndex == KEY_NAME_INDEX_Enter || mKeyCode == NS_VK_SPACE;
286 return (PseudoCharCode() || isEnterOrSpaceKey) &&
287 (!isCombiningWithOperationKeys ||
288 // ctrl-c/ctrl-x/ctrl-v is quite common shortcut for clipboard
289 // operation.
290 // XXXedgar, we have to find a better way to handle browser keyboard
291 // shortcut for user activation, instead of just ignoring all
292 // combinations, see bug 1641171.
293 ((mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_C ||
294 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_V ||
295 mKeyCode == dom::KeyboardEvent_Binding::DOM_VK_X) &&
296 IsAccel()));
299 [[nodiscard]] bool ShouldWorkAsSpaceKey() const {
300 if (mKeyCode == NS_VK_SPACE) {
301 return true;
303 // Additionally, if the code value is "Space" and the key is not mapped to
304 // a function key (i.e., not a printable key), we should treat it as space
305 // key because the active keyboard layout may input different character
306 // from the ASCII white space (U+0020). For example, NBSP (U+00A0).
307 return mKeyNameIndex == KEY_NAME_INDEX_USE_STRING &&
308 mCodeNameIndex == CODE_NAME_INDEX_Space;
312 * CanTreatAsUserInput() returns true if the key is pressed for perhaps
313 * doing something on the web app or our UI. This means that when this
314 * returns false, e.g., when user presses a modifier key, user is probably
315 * displeased by opening popup, entering fullscreen mode, etc. Therefore,
316 * only when this returns true, such reactions should be allowed.
318 bool CanTreatAsUserInput() const {
319 if (!IsTrusted()) {
320 return false;
322 switch (mKeyNameIndex) {
323 case KEY_NAME_INDEX_Escape:
324 // modifier keys:
325 case KEY_NAME_INDEX_Alt:
326 case KEY_NAME_INDEX_AltGraph:
327 case KEY_NAME_INDEX_CapsLock:
328 case KEY_NAME_INDEX_Control:
329 case KEY_NAME_INDEX_Fn:
330 case KEY_NAME_INDEX_FnLock:
331 case KEY_NAME_INDEX_Meta:
332 case KEY_NAME_INDEX_NumLock:
333 case KEY_NAME_INDEX_ScrollLock:
334 case KEY_NAME_INDEX_Shift:
335 case KEY_NAME_INDEX_Symbol:
336 case KEY_NAME_INDEX_SymbolLock:
337 // legacy modifier keys:
338 case KEY_NAME_INDEX_Hyper:
339 case KEY_NAME_INDEX_Super:
340 // obsolete modifier key:
341 case KEY_NAME_INDEX_OS:
342 return false;
343 default:
344 return true;
349 * ShouldInteractionTimeRecorded() returns true if the handling time of
350 * the event should be recorded with the telemetry.
352 bool ShouldInteractionTimeRecorded() const {
353 // Let's record only when we can treat the instance is a user input.
354 return CanTreatAsUserInput();
357 // OS translated Unicode chars which are used for accesskey and accelkey
358 // handling. The handlers will try from first character to last character.
359 CopyableTArray<AlternativeCharCode> mAlternativeCharCodes;
360 // DOM KeyboardEvent.key only when mKeyNameIndex is KEY_NAME_INDEX_USE_STRING.
361 nsString mKeyValue;
362 // DOM KeyboardEvent.code only when mCodeNameIndex is
363 // CODE_NAME_INDEX_USE_STRING.
364 nsString mCodeValue;
366 // OS-specific native event can optionally be preserved.
367 // This is used to retrieve editing shortcut keys in the environment.
368 void* mNativeKeyEvent;
369 // A DOM keyCode value or 0. If a keypress event whose mCharCode is 0, this
370 // should be 0.
371 uint32_t mKeyCode;
372 // If the instance is a keypress event of a printable key, this is a UTF-16
373 // value of the key. Otherwise, 0. This value must not be a control
374 // character when some modifiers are active. Then, this value should be an
375 // unmodified value except Shift and AltGr.
376 uint32_t mCharCode;
377 // mPseudoCharCode is valid only when mMessage is an eKeyDown event.
378 // This stores mCharCode value of keypress event which is fired with same
379 // key value and same modifier state.
380 uint32_t mPseudoCharCode;
381 // One of eKeyLocation*
382 uint32_t mLocation;
383 // Unique id associated with a keydown / keypress event. It's ok if this wraps
384 // over long periods.
385 uint32_t mUniqueId;
387 // DOM KeyboardEvent.key
388 KeyNameIndex mKeyNameIndex;
389 // DOM KeyboardEvent.code
390 CodeNameIndex mCodeNameIndex;
392 // Indicates whether the event is generated by auto repeat or not.
393 // if this is keyup event, always false.
394 bool mIsRepeat;
395 // Indicates whether the event is generated during IME (or deadkey)
396 // composition. This is initialized by EventStateManager. So, key event
397 // dispatchers don't need to initialize this.
398 bool mIsComposing;
399 // Indicates whether the event is synthesized from Text Input Processor
400 // or an actual event from nsAppShell.
401 bool mIsSynthesizedByTIP;
402 // Indicates whether the event is skippable in remote process.
403 // Don't refer this member directly when you need to check this.
404 // Use CanSkipInRemoteProcess() instead.
405 bool mMaybeSkippableInRemoteProcess;
406 // Indicates whether the event should return legacy keyCode value and
407 // charCode value to web apps (one of them is always 0) or not, when it's
408 // an eKeyPress event.
409 bool mUseLegacyKeyCodeAndCharCodeValues;
411 bool CanSkipInRemoteProcess() const {
412 // If this is a repeat event (i.e., generated by auto-repeat feature of
413 // the platform), remove process may skip to handle it because of
414 // performances reasons.. However, if it's caused by odd keyboard utils,
415 // we should not ignore any key events even marked as repeated since
416 // generated key sequence may be important to input proper text. E.g.,
417 // "SinhalaTamil IME" on Windows emulates dead key like input with
418 // generating WM_KEYDOWN for VK_PACKET (inputting any Unicode characters
419 // without keyboard layout information) and VK_BACK (Backspace) to remove
420 // previous character(s) and those messages may be marked as "repeat" by
421 // their bug.
422 return mIsRepeat && mMaybeSkippableInRemoteProcess;
426 * If the key is an arrow key, and the current selection is in a vertical
427 * content, the caret should be moved to physically. However, arrow keys
428 * are mapped to logical move commands in horizontal content. Therefore,
429 * we need to check writing mode if and only if the key is an arrow key, and
430 * need to remap the command to logical command in vertical content if the
431 * writing mode at selection is vertical. These methods help to convert
432 * arrow keys in horizontal content to correspnding direction arrow keys
433 * in vertical content.
435 bool NeedsToRemapNavigationKey() const {
436 // TODO: Use mKeyNameIndex instead.
437 return mKeyCode >= NS_VK_LEFT && mKeyCode <= NS_VK_DOWN;
440 uint32_t GetRemappedKeyCode(const WritingMode& aWritingMode) const {
441 if (!aWritingMode.IsVertical()) {
442 return mKeyCode;
444 switch (mKeyCode) {
445 case NS_VK_LEFT:
446 return aWritingMode.IsVerticalLR() ? NS_VK_UP : NS_VK_DOWN;
447 case NS_VK_RIGHT:
448 return aWritingMode.IsVerticalLR() ? NS_VK_DOWN : NS_VK_UP;
449 case NS_VK_UP:
450 return NS_VK_LEFT;
451 case NS_VK_DOWN:
452 return NS_VK_RIGHT;
453 default:
454 return mKeyCode;
458 KeyNameIndex GetRemappedKeyNameIndex(const WritingMode& aWritingMode) const {
459 if (!aWritingMode.IsVertical()) {
460 return mKeyNameIndex;
462 uint32_t remappedKeyCode = GetRemappedKeyCode(aWritingMode);
463 if (remappedKeyCode == mKeyCode) {
464 return mKeyNameIndex;
466 switch (remappedKeyCode) {
467 case NS_VK_LEFT:
468 return KEY_NAME_INDEX_ArrowLeft;
469 case NS_VK_RIGHT:
470 return KEY_NAME_INDEX_ArrowRight;
471 case NS_VK_UP:
472 return KEY_NAME_INDEX_ArrowUp;
473 case NS_VK_DOWN:
474 return KEY_NAME_INDEX_ArrowDown;
475 default:
476 MOZ_ASSERT_UNREACHABLE("Add a case for the new remapped key");
477 return mKeyNameIndex;
482 * Retrieves all edit commands from mWidget. This shouldn't be called when
483 * the instance is an untrusted event, doesn't have widget or in non-chrome
484 * process.
486 * @param aWritingMode
487 * When writing mode of focused element is vertical, this
488 * will resolve some key's physical direction to logical
489 * direction. For doing it, this must be set to the
490 * writing mode at current selection. However, when there
491 * is no focused element and no selection ranges, this
492 * should be set to Nothing(). Using the result of
493 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
494 * is recommended.
496 MOZ_CAN_RUN_SCRIPT void InitAllEditCommands(
497 const Maybe<WritingMode>& aWritingMode);
500 * Retrieves edit commands from mWidget only for aType. This shouldn't be
501 * called when the instance is an untrusted event or doesn't have widget.
503 * @param aWritingMode
504 * When writing mode of focused element is vertical, this
505 * will resolve some key's physical direction to logical
506 * direction. For doing it, this must be set to the
507 * writing mode at current selection. However, when there
508 * is no focused element and no selection ranges, this
509 * should be set to Nothing(). Using the result of
510 * `TextEventDispatcher::MaybeQueryWritingModeAtSelection()`
511 * is recommended.
512 * @return false if some resource is not available to get
513 * commands unexpectedly. Otherwise, true even if
514 * retrieved command is nothing.
516 MOZ_CAN_RUN_SCRIPT bool InitEditCommandsFor(
517 NativeKeyBindingsType aType, const Maybe<WritingMode>& aWritingMode);
520 * PreventNativeKeyBindings() makes the instance to not cause any edit
521 * actions even if it matches with a native key binding.
523 void PreventNativeKeyBindings() {
524 mEditCommandsForSingleLineEditor.Clear();
525 mEditCommandsForMultiLineEditor.Clear();
526 mEditCommandsForRichTextEditor.Clear();
527 mEditCommandsForSingleLineEditorInitialized = true;
528 mEditCommandsForMultiLineEditorInitialized = true;
529 mEditCommandsForRichTextEditorInitialized = true;
533 * EditCommandsConstRef() returns reference to edit commands for aType.
535 const nsTArray<CommandInt>& EditCommandsConstRef(
536 NativeKeyBindingsType aType) const {
537 return const_cast<WidgetKeyboardEvent*>(this)->EditCommandsRef(aType);
541 * IsEditCommandsInitialized() returns true if edit commands for aType
542 * was already initialized. Otherwise, false.
544 bool IsEditCommandsInitialized(NativeKeyBindingsType aType) const {
545 return const_cast<WidgetKeyboardEvent*>(this)->IsEditCommandsInitializedRef(
546 aType);
550 * AreAllEditCommandsInitialized() returns true if edit commands for all
551 * types were already initialized. Otherwise, false.
553 bool AreAllEditCommandsInitialized() const {
554 return mEditCommandsForSingleLineEditorInitialized &&
555 mEditCommandsForMultiLineEditorInitialized &&
556 mEditCommandsForRichTextEditorInitialized;
560 * Execute edit commands for aType.
562 * @return true if the caller should do nothing anymore.
563 * false, otherwise.
565 typedef void (*DoCommandCallback)(Command, void*);
566 MOZ_CAN_RUN_SCRIPT bool ExecuteEditCommands(NativeKeyBindingsType aType,
567 DoCommandCallback aCallback,
568 void* aCallbackData);
570 // If the key should cause keypress events, this returns true.
571 // Otherwise, false.
572 bool ShouldCauseKeypressEvents() const;
574 // mCharCode value of non-eKeyPress events is always 0. However, if
575 // non-eKeyPress event has one or more alternative char code values,
576 // its first item should be the mCharCode value of following eKeyPress event.
577 // PseudoCharCode() returns mCharCode value for eKeyPress event,
578 // the first alternative char code value of non-eKeyPress event or 0.
579 uint32_t PseudoCharCode() const {
580 return mMessage == eKeyPress ? mCharCode : mPseudoCharCode;
582 void SetCharCode(uint32_t aCharCode) {
583 if (mMessage == eKeyPress) {
584 mCharCode = aCharCode;
585 } else {
586 mPseudoCharCode = aCharCode;
590 void GetDOMKeyName(nsAString& aKeyName) {
591 if (mKeyNameIndex == KEY_NAME_INDEX_USE_STRING) {
592 aKeyName = mKeyValue;
593 return;
595 GetDOMKeyName(mKeyNameIndex, aKeyName);
597 void GetDOMCodeName(nsAString& aCodeName) {
598 if (mCodeNameIndex == CODE_NAME_INDEX_USE_STRING) {
599 aCodeName = mCodeValue;
600 return;
602 GetDOMCodeName(mCodeNameIndex, aCodeName);
606 * GetFallbackKeyCodeOfPunctuationKey() returns a DOM keyCode value for
607 * aCodeNameIndex. This is keyCode value of the key when active keyboard
608 * layout is ANSI (US), JIS or ABNT keyboard layout (the latter 2 layouts
609 * are used only when ANSI doesn't have the key). The result is useful
610 * if the key doesn't produce ASCII character with active keyboard layout
611 * nor with alternative ASCII capable keyboard layout.
613 static uint32_t GetFallbackKeyCodeOfPunctuationKey(
614 CodeNameIndex aCodeNameIndex);
616 bool IsModifierKeyEvent() const {
617 return GetModifierForKeyName(mKeyNameIndex) != MODIFIER_NONE;
621 * Get the candidates for shortcut key.
623 * @param aCandidates [out] the candidate shortcut key combination list.
624 * the first item is most preferred.
626 void GetShortcutKeyCandidates(ShortcutKeyCandidateArray& aCandidates) const;
629 * Get the candidates for access key.
631 * @param aCandidates [out] the candidate access key list.
632 * the first item is most preferred.
634 void GetAccessKeyCandidates(nsTArray<uint32_t>& aCandidates) const;
637 * Check whether the modifiers match with chrome access key or
638 * content access key.
640 bool ModifiersMatchWithAccessKey(AccessKeyType aType) const;
643 * Return active modifiers which may match with access key.
644 * For example, even if Alt is access key modifier, then, when Control,
645 * CapseLock and NumLock are active, this returns only MODIFIER_CONTROL.
647 Modifiers ModifiersForAccessKeyMatching() const;
650 * Return access key modifiers.
652 static Modifiers AccessKeyModifiers(AccessKeyType aType);
654 static void Shutdown();
657 * ComputeLocationFromCodeValue() returns one of .mLocation value
658 * (eKeyLocation*) which is the most preferred value for the specified code
659 * value.
661 static uint32_t ComputeLocationFromCodeValue(CodeNameIndex aCodeNameIndex);
664 * ComputeKeyCodeFromKeyNameIndex() return a .mKeyCode value which can be
665 * mapped from the specified key value. Note that this returns 0 if the
666 * key name index is KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
667 * This means that this method is useful only for non-printable keys.
669 static uint32_t ComputeKeyCodeFromKeyNameIndex(KeyNameIndex aKeyNameIndex);
672 * ComputeCodeNameIndexFromKeyNameIndex() returns a code name index which
673 * is typically mapped to given key name index on the platform.
674 * Note that this returns CODE_NAME_INDEX_UNKNOWN if the key name index is
675 * KEY_NAME_INDEX_Unidentified or KEY_NAME_INDEX_USE_STRING.
676 * This means that this method is useful only for non-printable keys.
678 * @param aKeyNameIndex A non-printable key name index.
679 * @param aLocation Should be one of location value. This is
680 * important when aKeyNameIndex may exist in
681 * both Numpad or Standard, or in both Left or
682 * Right. If this is nothing, this method
683 * returns Left or Standard position's code
684 * value.
686 static CodeNameIndex ComputeCodeNameIndexFromKeyNameIndex(
687 KeyNameIndex aKeyNameIndex, const Maybe<uint32_t>& aLocation);
690 * GetModifierForKeyName() returns a value of Modifier which is activated
691 * by the aKeyNameIndex.
693 static Modifier GetModifierForKeyName(KeyNameIndex aKeyNameIndex);
696 * IsLeftOrRightModiferKeyNameIndex() returns true if aKeyNameIndex is a
697 * modifier key which may be in Left and Right location.
699 static bool IsLeftOrRightModiferKeyNameIndex(KeyNameIndex aKeyNameIndex) {
700 switch (aKeyNameIndex) {
701 case KEY_NAME_INDEX_Alt:
702 case KEY_NAME_INDEX_Control:
703 case KEY_NAME_INDEX_Meta:
704 case KEY_NAME_INDEX_OS:
705 case KEY_NAME_INDEX_Shift:
706 return true;
707 default:
708 return false;
713 * IsLockableModifier() returns true if aKeyNameIndex is a lockable modifier
714 * key such as CapsLock and NumLock.
716 static bool IsLockableModifier(KeyNameIndex aKeyNameIndex);
718 static void GetDOMKeyName(KeyNameIndex aKeyNameIndex, nsAString& aKeyName);
719 static void GetDOMCodeName(CodeNameIndex aCodeNameIndex,
720 nsAString& aCodeName);
722 static KeyNameIndex GetKeyNameIndex(const nsAString& aKeyValue);
723 static CodeNameIndex GetCodeNameIndex(const nsAString& aCodeValue);
725 static const char* GetCommandStr(Command aCommand);
727 void AssignKeyEventData(const WidgetKeyboardEvent& aEvent,
728 bool aCopyTargets) {
729 AssignInputEventData(aEvent, aCopyTargets);
731 mKeyCode = aEvent.mKeyCode;
732 mCharCode = aEvent.mCharCode;
733 mPseudoCharCode = aEvent.mPseudoCharCode;
734 mLocation = aEvent.mLocation;
735 mAlternativeCharCodes = aEvent.mAlternativeCharCodes.Clone();
736 mIsRepeat = aEvent.mIsRepeat;
737 mIsComposing = aEvent.mIsComposing;
738 mKeyNameIndex = aEvent.mKeyNameIndex;
739 mCodeNameIndex = aEvent.mCodeNameIndex;
740 mKeyValue = aEvent.mKeyValue;
741 mCodeValue = aEvent.mCodeValue;
742 // Don't copy mNativeKeyEvent because it may be referred after its instance
743 // is destroyed.
744 mNativeKeyEvent = nullptr;
745 mUniqueId = aEvent.mUniqueId;
746 mIsSynthesizedByTIP = aEvent.mIsSynthesizedByTIP;
747 mMaybeSkippableInRemoteProcess = aEvent.mMaybeSkippableInRemoteProcess;
748 mUseLegacyKeyCodeAndCharCodeValues =
749 aEvent.mUseLegacyKeyCodeAndCharCodeValues;
751 // Don't copy mEditCommandsFor*Editor because it may require a lot of
752 // memory space. For example, if the event is dispatched but grabbed by
753 // a JS variable, they are not necessary anymore.
755 mEditCommandsForSingleLineEditorInitialized =
756 aEvent.mEditCommandsForSingleLineEditorInitialized;
757 mEditCommandsForMultiLineEditorInitialized =
758 aEvent.mEditCommandsForMultiLineEditorInitialized;
759 mEditCommandsForRichTextEditorInitialized =
760 aEvent.mEditCommandsForRichTextEditorInitialized;
763 void AssignCommands(const WidgetKeyboardEvent& aEvent) {
764 mEditCommandsForSingleLineEditorInitialized =
765 aEvent.mEditCommandsForSingleLineEditorInitialized;
766 if (mEditCommandsForSingleLineEditorInitialized) {
767 mEditCommandsForSingleLineEditor =
768 aEvent.mEditCommandsForSingleLineEditor.Clone();
769 } else {
770 mEditCommandsForSingleLineEditor.Clear();
772 mEditCommandsForMultiLineEditorInitialized =
773 aEvent.mEditCommandsForMultiLineEditorInitialized;
774 if (mEditCommandsForMultiLineEditorInitialized) {
775 mEditCommandsForMultiLineEditor =
776 aEvent.mEditCommandsForMultiLineEditor.Clone();
777 } else {
778 mEditCommandsForMultiLineEditor.Clear();
780 mEditCommandsForRichTextEditorInitialized =
781 aEvent.mEditCommandsForRichTextEditorInitialized;
782 if (mEditCommandsForRichTextEditorInitialized) {
783 mEditCommandsForRichTextEditor =
784 aEvent.mEditCommandsForRichTextEditor.Clone();
785 } else {
786 mEditCommandsForRichTextEditor.Clear();
790 private:
791 static const char16_t* const kKeyNames[];
792 static const char16_t* const kCodeNames[];
793 typedef nsTHashMap<nsStringHashKey, KeyNameIndex> KeyNameIndexHashtable;
794 typedef nsTHashMap<nsStringHashKey, CodeNameIndex> CodeNameIndexHashtable;
795 static KeyNameIndexHashtable* sKeyNameIndexHashtable;
796 static CodeNameIndexHashtable* sCodeNameIndexHashtable;
798 // mEditCommandsFor*Editor store edit commands. This should be initialized
799 // with InitEditCommandsFor().
800 // XXX Ideally, this should be array of Command rather than CommandInt.
801 // However, ParamTraits isn't aware of enum array.
802 CopyableTArray<CommandInt> mEditCommandsForSingleLineEditor;
803 CopyableTArray<CommandInt> mEditCommandsForMultiLineEditor;
804 CopyableTArray<CommandInt> mEditCommandsForRichTextEditor;
806 nsTArray<CommandInt>& EditCommandsRef(NativeKeyBindingsType aType) {
807 switch (aType) {
808 case NativeKeyBindingsType::SingleLineEditor:
809 return mEditCommandsForSingleLineEditor;
810 case NativeKeyBindingsType::MultiLineEditor:
811 return mEditCommandsForMultiLineEditor;
812 case NativeKeyBindingsType::RichTextEditor:
813 return mEditCommandsForRichTextEditor;
814 default:
815 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
816 "Invalid native key binding type");
820 // mEditCommandsFor*EditorInitialized are set to true when
821 // InitEditCommandsFor() initializes edit commands for the type.
822 bool mEditCommandsForSingleLineEditorInitialized;
823 bool mEditCommandsForMultiLineEditorInitialized;
824 bool mEditCommandsForRichTextEditorInitialized;
826 bool& IsEditCommandsInitializedRef(NativeKeyBindingsType aType) {
827 switch (aType) {
828 case NativeKeyBindingsType::SingleLineEditor:
829 return mEditCommandsForSingleLineEditorInitialized;
830 case NativeKeyBindingsType::MultiLineEditor:
831 return mEditCommandsForMultiLineEditorInitialized;
832 case NativeKeyBindingsType::RichTextEditor:
833 return mEditCommandsForRichTextEditorInitialized;
834 default:
835 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
836 "Invalid native key binding type");
841 /******************************************************************************
842 * mozilla::WidgetCompositionEvent
843 ******************************************************************************/
845 class WidgetCompositionEvent : public WidgetGUIEvent {
846 private:
847 friend class mozilla::dom::PBrowserParent;
848 friend class mozilla::dom::PBrowserChild;
849 ALLOW_DEPRECATED_READPARAM
851 WidgetCompositionEvent() : mOriginalMessage(eVoidEvent) {}
853 public:
854 virtual WidgetCompositionEvent* AsCompositionEvent() override { return this; }
856 WidgetCompositionEvent(bool aIsTrusted, EventMessage aMessage,
857 nsIWidget* aWidget)
858 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eCompositionEventClass),
859 mNativeIMEContext(aWidget),
860 mOriginalMessage(eVoidEvent) {}
862 virtual WidgetEvent* Duplicate() const override {
863 MOZ_ASSERT(mClass == eCompositionEventClass,
864 "Duplicate() must be overridden by sub class");
865 // Not copying widget, it is a weak reference.
866 WidgetCompositionEvent* result =
867 new WidgetCompositionEvent(false, mMessage, nullptr);
868 result->AssignCompositionEventData(*this, true);
869 result->mFlags = mFlags;
870 return result;
873 // The composition string or the commit string. If the instance is a
874 // compositionstart event, this is initialized with selected text by
875 // TextComposition automatically.
876 nsString mData;
878 RefPtr<TextRangeArray> mRanges;
880 // mNativeIMEContext stores the native IME context which causes the
881 // composition event.
882 widget::NativeIMEContext mNativeIMEContext;
884 // If the instance is a clone of another event, mOriginalMessage stores
885 // the another event's mMessage.
886 EventMessage mOriginalMessage;
888 void AssignCompositionEventData(const WidgetCompositionEvent& aEvent,
889 bool aCopyTargets) {
890 AssignGUIEventData(aEvent, aCopyTargets);
892 mData = aEvent.mData;
893 mOriginalMessage = aEvent.mOriginalMessage;
894 mRanges = aEvent.mRanges;
896 // Currently, we don't need to copy the other members because they are
897 // for internal use only (not available from JS).
900 bool IsComposing() const { return mRanges && mRanges->IsComposing(); }
902 uint32_t TargetClauseOffset() const {
903 return mRanges ? mRanges->TargetClauseOffset() : 0;
906 uint32_t TargetClauseLength() const {
907 uint32_t length = UINT32_MAX;
908 if (mRanges) {
909 length = mRanges->TargetClauseLength();
911 return length == UINT32_MAX ? mData.Length() : length;
914 uint32_t RangeCount() const { return mRanges ? mRanges->Length() : 0; }
916 bool CausesDOMTextEvent() const {
917 return mMessage == eCompositionChange || mMessage == eCompositionCommit ||
918 mMessage == eCompositionCommitAsIs;
921 bool CausesDOMCompositionEndEvent() const {
922 return mMessage == eCompositionEnd || mMessage == eCompositionCommit ||
923 mMessage == eCompositionCommitAsIs;
926 bool IsFollowedByCompositionEnd() const {
927 return IsFollowedByCompositionEnd(mOriginalMessage);
930 static bool IsFollowedByCompositionEnd(EventMessage aEventMessage) {
931 return aEventMessage == eCompositionCommit ||
932 aEventMessage == eCompositionCommitAsIs;
936 /******************************************************************************
937 * mozilla::WidgetQueryContentEvent
938 ******************************************************************************/
940 class WidgetQueryContentEvent : public WidgetGUIEvent {
941 private:
942 friend class dom::PBrowserParent;
943 friend class dom::PBrowserChild;
944 ALLOW_DEPRECATED_READPARAM
946 WidgetQueryContentEvent()
947 : mUseNativeLineBreak(true),
948 mWithFontRanges(false),
949 mNeedsToFlushLayout(true) {
950 MOZ_CRASH("WidgetQueryContentEvent is created without proper arguments");
953 public:
954 virtual WidgetQueryContentEvent* AsQueryContentEvent() override {
955 return this;
958 WidgetQueryContentEvent(bool aIsTrusted, EventMessage aMessage,
959 nsIWidget* aWidget)
960 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eQueryContentEventClass),
961 mUseNativeLineBreak(true),
962 mWithFontRanges(false),
963 mNeedsToFlushLayout(true) {}
965 WidgetQueryContentEvent(EventMessage aMessage,
966 const WidgetQueryContentEvent& aOtherEvent)
967 : WidgetGUIEvent(aOtherEvent.IsTrusted(), aMessage,
968 const_cast<nsIWidget*>(aOtherEvent.mWidget.get()),
969 eQueryContentEventClass),
970 mUseNativeLineBreak(aOtherEvent.mUseNativeLineBreak),
971 mWithFontRanges(false),
972 mNeedsToFlushLayout(aOtherEvent.mNeedsToFlushLayout) {}
974 virtual WidgetEvent* Duplicate() const override {
975 // This event isn't an internal event of any DOM event.
976 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
977 "WidgetQueryContentEvent needs to support Duplicate()");
978 MOZ_CRASH("WidgetQueryContentEvent doesn't support Duplicate()");
981 struct Options final {
982 bool mUseNativeLineBreak;
983 bool mRelativeToInsertionPoint;
985 explicit Options()
986 : mUseNativeLineBreak(true), mRelativeToInsertionPoint(false) {}
988 explicit Options(const WidgetQueryContentEvent& aEvent)
989 : mUseNativeLineBreak(aEvent.mUseNativeLineBreak),
990 mRelativeToInsertionPoint(aEvent.mInput.mRelativeToInsertionPoint) {}
993 void Init(const Options& aOptions) {
994 mUseNativeLineBreak = aOptions.mUseNativeLineBreak;
995 mInput.mRelativeToInsertionPoint = aOptions.mRelativeToInsertionPoint;
996 MOZ_ASSERT(mInput.IsValidEventMessage(mMessage));
999 void InitForQueryTextContent(int64_t aOffset, uint32_t aLength,
1000 const Options& aOptions = Options()) {
1001 NS_ASSERTION(mMessage == eQueryTextContent, "wrong initializer is called");
1002 mInput.mOffset = aOffset;
1003 mInput.mLength = aLength;
1004 Init(aOptions);
1005 MOZ_ASSERT(mInput.IsValidOffset());
1008 void InitForQueryCaretRect(int64_t aOffset,
1009 const Options& aOptions = Options()) {
1010 NS_ASSERTION(mMessage == eQueryCaretRect, "wrong initializer is called");
1011 mInput.mOffset = aOffset;
1012 Init(aOptions);
1013 MOZ_ASSERT(mInput.IsValidOffset());
1016 void InitForQueryTextRect(int64_t aOffset, uint32_t aLength,
1017 const Options& aOptions = Options()) {
1018 NS_ASSERTION(mMessage == eQueryTextRect, "wrong initializer is called");
1019 mInput.mOffset = aOffset;
1020 mInput.mLength = aLength;
1021 Init(aOptions);
1022 MOZ_ASSERT(mInput.IsValidOffset());
1025 void InitForQuerySelectedText(SelectionType aSelectionType,
1026 const Options& aOptions = Options()) {
1027 MOZ_ASSERT(mMessage == eQuerySelectedText);
1028 MOZ_ASSERT(aSelectionType != SelectionType::eNone);
1029 mInput.mSelectionType = aSelectionType;
1030 Init(aOptions);
1033 void InitForQueryDOMWidgetHittest(
1034 const mozilla::LayoutDeviceIntPoint& aPoint) {
1035 NS_ASSERTION(mMessage == eQueryDOMWidgetHittest,
1036 "wrong initializer is called");
1037 mRefPoint = aPoint;
1040 void InitForQueryTextRectArray(uint32_t aOffset, uint32_t aLength,
1041 const Options& aOptions = Options()) {
1042 NS_ASSERTION(mMessage == eQueryTextRectArray,
1043 "wrong initializer is called");
1044 mInput.mOffset = aOffset;
1045 mInput.mLength = aLength;
1046 Init(aOptions);
1049 bool NeedsToFlushLayout() const { return mNeedsToFlushLayout; }
1051 void RequestFontRanges() {
1052 MOZ_ASSERT(mMessage == eQueryTextContent);
1053 mWithFontRanges = true;
1056 bool Succeeded() const {
1057 if (mReply.isNothing()) {
1058 return false;
1060 switch (mMessage) {
1061 case eQueryTextContent:
1062 case eQueryTextRect:
1063 case eQueryCaretRect:
1064 return mReply->mOffsetAndData.isSome();
1065 default:
1066 return true;
1070 bool Failed() const { return !Succeeded(); }
1072 bool FoundSelection() const {
1073 MOZ_ASSERT(mMessage == eQuerySelectedText);
1074 return Succeeded() && mReply->mOffsetAndData.isSome();
1077 bool FoundChar() const {
1078 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1079 return Succeeded() && mReply->mOffsetAndData.isSome();
1082 bool FoundTentativeCaretOffset() const {
1083 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1084 return Succeeded() && mReply->mTentativeCaretOffset.isSome();
1087 bool DidNotFindSelection() const {
1088 MOZ_ASSERT(mMessage == eQuerySelectedText);
1089 return Failed() || mReply->mOffsetAndData.isNothing();
1092 bool DidNotFindChar() const {
1093 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1094 return Failed() || mReply->mOffsetAndData.isNothing();
1097 bool DidNotFindTentativeCaretOffset() const {
1098 MOZ_ASSERT(mMessage == eQueryCharacterAtPoint);
1099 return Failed() || mReply->mTentativeCaretOffset.isNothing();
1102 bool mUseNativeLineBreak;
1103 bool mWithFontRanges;
1104 bool mNeedsToFlushLayout;
1105 struct Input final {
1106 uint32_t EndOffset() const {
1107 CheckedInt<uint32_t> endOffset = CheckedInt<uint32_t>(mOffset) + mLength;
1108 return NS_WARN_IF(!endOffset.isValid()) ? UINT32_MAX : endOffset.value();
1111 int64_t mOffset;
1112 uint32_t mLength;
1113 SelectionType mSelectionType;
1114 // If mOffset is true, mOffset is relative to the start offset of
1115 // composition if there is, otherwise, the start of the first selection
1116 // range.
1117 bool mRelativeToInsertionPoint;
1119 Input()
1120 : mOffset(0),
1121 mLength(0),
1122 mSelectionType(SelectionType::eNormal),
1123 mRelativeToInsertionPoint(false) {}
1125 bool IsValidOffset() const {
1126 return mRelativeToInsertionPoint || mOffset >= 0;
1128 bool IsValidEventMessage(EventMessage aEventMessage) const {
1129 if (!mRelativeToInsertionPoint) {
1130 return true;
1132 switch (aEventMessage) {
1133 case eQueryTextContent:
1134 case eQueryCaretRect:
1135 case eQueryTextRect:
1136 return true;
1137 default:
1138 return false;
1141 bool MakeOffsetAbsolute(uint32_t aInsertionPointOffset) {
1142 if (NS_WARN_IF(!mRelativeToInsertionPoint)) {
1143 return true;
1145 mRelativeToInsertionPoint = false;
1146 // If mOffset + aInsertionPointOffset becomes negative value,
1147 // we should assume the absolute offset is 0.
1148 if (mOffset < 0 && -mOffset > aInsertionPointOffset) {
1149 mOffset = 0;
1150 return true;
1152 // Otherwise, we don't allow too large offset.
1153 CheckedInt<uint32_t> absOffset(mOffset + aInsertionPointOffset);
1154 if (NS_WARN_IF(!absOffset.isValid())) {
1155 mOffset = UINT32_MAX;
1156 return false;
1158 mOffset = absOffset.value();
1159 return true;
1161 } mInput;
1163 struct Reply final {
1164 EventMessage const mEventMessage;
1165 void* mContentsRoot = nullptr;
1166 Maybe<OffsetAndData<uint32_t>> mOffsetAndData;
1167 // mTentativeCaretOffset is used by only eQueryCharacterAtPoint.
1168 // This is the offset where caret would be if user clicked at the mRefPoint.
1169 Maybe<uint32_t> mTentativeCaretOffset;
1170 // mRect is used by eQueryTextRect, eQueryCaretRect, eQueryCharacterAtPoint
1171 // and eQueryEditorRect. The coordinates is system coordinates relative to
1172 // the top level widget of mFocusedWidget. E.g., if a <xul:panel> which
1173 // is owned by a window has focused editor, the offset of mRect is relative
1174 // to the owner window, not the <xul:panel>.
1175 mozilla::LayoutDeviceIntRect mRect;
1176 // The return widget has the caret. This is set at all query events.
1177 nsIWidget* mFocusedWidget = nullptr;
1178 // mozilla::WritingMode value at the end (focus) of the selection
1179 mozilla::WritingMode mWritingMode;
1180 // Used by eQuerySelectionAsTransferable
1181 nsCOMPtr<nsITransferable> mTransferable;
1182 // Used by eQueryTextContent with font ranges requested
1183 CopyableAutoTArray<mozilla::FontRange, 1> mFontRanges;
1184 // Used by eQueryTextRectArray
1185 CopyableTArray<mozilla::LayoutDeviceIntRect> mRectArray;
1186 // true if selection is reversed (end < start)
1187 bool mReversed = false;
1188 // true if DOM element under mouse belongs to widget
1189 bool mWidgetIsHit = false;
1190 // true if mContentRoot is focused editable content
1191 bool mIsEditableContent = false;
1193 Reply() = delete;
1194 explicit Reply(EventMessage aEventMessage) : mEventMessage(aEventMessage) {}
1196 // Don't allow to copy/move because of `mEventMessage`.
1197 Reply(const Reply& aOther) = delete;
1198 Reply(Reply&& aOther) = delete;
1199 Reply& operator=(const Reply& aOther) = delete;
1200 Reply& operator=(Reply&& aOther) = delete;
1202 MOZ_NEVER_INLINE_DEBUG uint32_t StartOffset() const {
1203 MOZ_ASSERT(mOffsetAndData.isSome());
1204 return mOffsetAndData->StartOffset();
1206 MOZ_NEVER_INLINE_DEBUG uint32_t EndOffset() const {
1207 MOZ_ASSERT(mOffsetAndData.isSome());
1208 return mOffsetAndData->EndOffset();
1210 MOZ_NEVER_INLINE_DEBUG uint32_t DataLength() const {
1211 MOZ_ASSERT(mOffsetAndData.isSome() ||
1212 mEventMessage == eQuerySelectedText);
1213 return mOffsetAndData.isSome() ? mOffsetAndData->Length() : 0;
1215 MOZ_NEVER_INLINE_DEBUG uint32_t AnchorOffset() const {
1216 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1217 MOZ_ASSERT(mOffsetAndData.isSome());
1218 return StartOffset() + (mReversed ? DataLength() : 0);
1221 MOZ_NEVER_INLINE_DEBUG uint32_t FocusOffset() const {
1222 MOZ_ASSERT(mEventMessage == eQuerySelectedText);
1223 MOZ_ASSERT(mOffsetAndData.isSome());
1224 return StartOffset() + (mReversed ? 0 : DataLength());
1227 const WritingMode& WritingModeRef() const {
1228 MOZ_ASSERT(mEventMessage == eQuerySelectedText ||
1229 mEventMessage == eQueryCaretRect ||
1230 mEventMessage == eQueryTextRect);
1231 MOZ_ASSERT(mOffsetAndData.isSome() ||
1232 mEventMessage == eQuerySelectedText);
1233 return mWritingMode;
1236 MOZ_NEVER_INLINE_DEBUG const nsString& DataRef() const {
1237 MOZ_ASSERT(mOffsetAndData.isSome() ||
1238 mEventMessage == eQuerySelectedText);
1239 return mOffsetAndData.isSome() ? mOffsetAndData->DataRef()
1240 : EmptyString();
1242 MOZ_NEVER_INLINE_DEBUG bool IsDataEmpty() const {
1243 MOZ_ASSERT(mOffsetAndData.isSome() ||
1244 mEventMessage == eQuerySelectedText);
1245 return mOffsetAndData.isSome() ? mOffsetAndData->IsDataEmpty() : true;
1247 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRange(uint32_t aOffset) const {
1248 MOZ_ASSERT(mOffsetAndData.isSome() ||
1249 mEventMessage == eQuerySelectedText);
1250 return mOffsetAndData.isSome() ? mOffsetAndData->IsOffsetInRange(aOffset)
1251 : false;
1253 MOZ_NEVER_INLINE_DEBUG bool IsOffsetInRangeOrEndOffset(
1254 uint32_t aOffset) const {
1255 MOZ_ASSERT(mOffsetAndData.isSome() ||
1256 mEventMessage == eQuerySelectedText);
1257 return mOffsetAndData.isSome()
1258 ? mOffsetAndData->IsOffsetInRangeOrEndOffset(aOffset)
1259 : false;
1261 MOZ_NEVER_INLINE_DEBUG void TruncateData(uint32_t aLength = 0) {
1262 MOZ_ASSERT(mOffsetAndData.isSome());
1263 mOffsetAndData->TruncateData(aLength);
1266 friend std::ostream& operator<<(std::ostream& aStream,
1267 const Reply& aReply) {
1268 aStream << "{ ";
1269 if (aReply.mEventMessage == eQuerySelectedText ||
1270 aReply.mEventMessage == eQueryTextContent ||
1271 aReply.mEventMessage == eQueryTextRect ||
1272 aReply.mEventMessage == eQueryCaretRect ||
1273 aReply.mEventMessage == eQueryCharacterAtPoint) {
1274 aStream << "mOffsetAndData=" << ToString(aReply.mOffsetAndData).c_str()
1275 << ", ";
1276 if (aReply.mEventMessage == eQueryCharacterAtPoint) {
1277 aStream << "mTentativeCaretOffset="
1278 << ToString(aReply.mTentativeCaretOffset).c_str() << ", ";
1281 if (aReply.mOffsetAndData.isSome() && aReply.mOffsetAndData->Length()) {
1282 if (aReply.mEventMessage == eQuerySelectedText) {
1283 aStream << ", mReversed=" << (aReply.mReversed ? "true" : "false");
1285 if (aReply.mEventMessage == eQuerySelectionAsTransferable) {
1286 aStream << ", mTransferable=0x" << aReply.mTransferable;
1289 if (aReply.mEventMessage == eQuerySelectedText ||
1290 aReply.mEventMessage == eQueryTextRect ||
1291 aReply.mEventMessage == eQueryCaretRect) {
1292 aStream << ", mWritingMode=" << ToString(aReply.mWritingMode).c_str();
1294 aStream << ", mContentsRoot=0x" << aReply.mContentsRoot
1295 << ", mIsEditableContent="
1296 << (aReply.mIsEditableContent ? "true" : "false")
1297 << ", mFocusedWidget=0x" << aReply.mFocusedWidget;
1298 if (aReply.mEventMessage == eQueryTextContent) {
1299 aStream << ", mFontRanges={ Length()=" << aReply.mFontRanges.Length()
1300 << " }";
1301 } else if (aReply.mEventMessage == eQueryTextRect ||
1302 aReply.mEventMessage == eQueryCaretRect ||
1303 aReply.mEventMessage == eQueryCharacterAtPoint) {
1304 aStream << ", mRect=" << ToString(aReply.mRect).c_str();
1305 } else if (aReply.mEventMessage == eQueryTextRectArray) {
1306 aStream << ", mRectArray={ Length()=" << aReply.mRectArray.Length()
1307 << " }";
1308 } else if (aReply.mEventMessage == eQueryDOMWidgetHittest) {
1309 aStream << ", mWidgetIsHit="
1310 << (aReply.mWidgetIsHit ? "true" : "false");
1312 return aStream << " }";
1316 void EmplaceReply() { mReply.emplace(mMessage); }
1317 Maybe<Reply> mReply;
1319 // values of mComputedScrollAction
1320 enum { SCROLL_ACTION_NONE, SCROLL_ACTION_LINE, SCROLL_ACTION_PAGE };
1323 /******************************************************************************
1324 * mozilla::WidgetSelectionEvent
1325 ******************************************************************************/
1327 class WidgetSelectionEvent : public WidgetGUIEvent {
1328 private:
1329 friend class mozilla::dom::PBrowserParent;
1330 friend class mozilla::dom::PBrowserChild;
1331 ALLOW_DEPRECATED_READPARAM
1333 WidgetSelectionEvent()
1334 : mOffset(0),
1335 mLength(0),
1336 mReversed(false),
1337 mExpandToClusterBoundary(true),
1338 mSucceeded(false),
1339 mUseNativeLineBreak(true),
1340 mReason(nsISelectionListener::NO_REASON) {}
1342 public:
1343 virtual WidgetSelectionEvent* AsSelectionEvent() override { return this; }
1345 WidgetSelectionEvent(bool aIsTrusted, EventMessage aMessage,
1346 nsIWidget* aWidget)
1347 : WidgetGUIEvent(aIsTrusted, aMessage, aWidget, eSelectionEventClass),
1348 mOffset(0),
1349 mLength(0),
1350 mReversed(false),
1351 mExpandToClusterBoundary(true),
1352 mSucceeded(false),
1353 mUseNativeLineBreak(true),
1354 mReason(nsISelectionListener::NO_REASON) {}
1356 virtual WidgetEvent* Duplicate() const override {
1357 // This event isn't an internal event of any DOM event.
1358 NS_ASSERTION(!IsAllowedToDispatchDOMEvent(),
1359 "WidgetSelectionEvent needs to support Duplicate()");
1360 MOZ_CRASH("WidgetSelectionEvent doesn't support Duplicate()");
1361 return nullptr;
1364 // Start offset of selection
1365 uint32_t mOffset;
1366 // Length of selection
1367 uint32_t mLength;
1368 // Selection "anchor" should be in front
1369 bool mReversed;
1370 // Cluster-based or character-based
1371 bool mExpandToClusterBoundary;
1372 // true if setting selection succeeded.
1373 bool mSucceeded;
1374 // true if native line breaks are used for mOffset and mLength
1375 bool mUseNativeLineBreak;
1376 // Fennec provides eSetSelection reason codes for downstream
1377 // use in AccessibleCaret visibility logic.
1378 int16_t mReason;
1381 /******************************************************************************
1382 * mozilla::InternalEditorInputEvent
1383 ******************************************************************************/
1385 class InternalEditorInputEvent : public InternalUIEvent {
1386 private:
1387 InternalEditorInputEvent()
1388 : mData(VoidString()),
1389 mInputType(EditorInputType::eUnknown),
1390 mIsComposing(false) {}
1392 public:
1393 virtual InternalEditorInputEvent* AsEditorInputEvent() override {
1394 return this;
1397 InternalEditorInputEvent(bool aIsTrusted, EventMessage aMessage,
1398 nsIWidget* aWidget = nullptr)
1399 : InternalUIEvent(aIsTrusted, aMessage, aWidget, eEditorInputEventClass),
1400 mData(VoidString()),
1401 mInputType(EditorInputType::eUnknown) {}
1403 virtual WidgetEvent* Duplicate() const override {
1404 MOZ_ASSERT(mClass == eEditorInputEventClass,
1405 "Duplicate() must be overridden by sub class");
1406 // Not copying widget, it is a weak reference.
1407 InternalEditorInputEvent* result =
1408 new InternalEditorInputEvent(false, mMessage, nullptr);
1409 result->AssignEditorInputEventData(*this, true);
1410 result->mFlags = mFlags;
1411 return result;
1414 nsString mData;
1415 RefPtr<dom::DataTransfer> mDataTransfer;
1416 OwningNonNullStaticRangeArray mTargetRanges;
1418 EditorInputType mInputType;
1420 bool mIsComposing;
1422 void AssignEditorInputEventData(const InternalEditorInputEvent& aEvent,
1423 bool aCopyTargets) {
1424 AssignUIEventData(aEvent, aCopyTargets);
1426 mData = aEvent.mData;
1427 mDataTransfer = aEvent.mDataTransfer;
1428 mTargetRanges = aEvent.mTargetRanges.Clone();
1429 mInputType = aEvent.mInputType;
1430 mIsComposing = aEvent.mIsComposing;
1433 void GetDOMInputTypeName(nsAString& aInputTypeName) {
1434 GetDOMInputTypeName(mInputType, aInputTypeName);
1436 static void GetDOMInputTypeName(EditorInputType aInputType,
1437 nsAString& aInputTypeName);
1438 static EditorInputType GetEditorInputType(const nsAString& aInputType);
1440 static void Shutdown();
1442 private:
1443 static const char16_t* const kInputTypeNames[];
1444 typedef nsTHashMap<nsStringHashKey, EditorInputType> InputTypeHashtable;
1445 static InputTypeHashtable* sInputTypeHashtable;
1448 } // namespace mozilla
1450 #endif // mozilla_TextEvents_h__