Bug 1793629 - Implement attention indicator for the unified extensions button, r...
[gecko.git] / widget / TextEventDispatcher.cpp
blobb9ec2f553f244ad44af7798cffad68912be331c2
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 #include "TextEventDispatcher.h"
8 #include "IMEData.h"
9 #include "PuppetWidget.h"
10 #include "TextEvents.h"
12 #include "mozilla/Preferences.h"
13 #include "mozilla/StaticPrefs_dom.h"
14 #include "nsIFrame.h"
15 #include "nsIWidget.h"
16 #include "nsPIDOMWindow.h"
17 #include "nsView.h"
19 namespace mozilla {
20 namespace widget {
22 /******************************************************************************
23 * TextEventDispatcher
24 *****************************************************************************/
25 TextEventDispatcher::TextEventDispatcher(nsIWidget* aWidget)
26 : mWidget(aWidget),
27 mDispatchingEvent(0),
28 mInputTransactionType(eNoInputTransaction),
29 mIsComposing(false),
30 mIsHandlingComposition(false),
31 mHasFocus(false) {
32 MOZ_RELEASE_ASSERT(mWidget, "aWidget must not be nullptr");
34 ClearNotificationRequests();
37 nsresult TextEventDispatcher::BeginInputTransaction(
38 TextEventDispatcherListener* aListener) {
39 return BeginInputTransactionInternal(aListener,
40 eSameProcessSyncInputTransaction);
43 nsresult TextEventDispatcher::BeginTestInputTransaction(
44 TextEventDispatcherListener* aListener, bool aIsAPZAware) {
45 return BeginInputTransactionInternal(
46 aListener, aIsAPZAware ? eAsyncTestInputTransaction
47 : eSameProcessSyncTestInputTransaction);
50 nsresult TextEventDispatcher::BeginNativeInputTransaction() {
51 if (NS_WARN_IF(!mWidget)) {
52 return NS_ERROR_FAILURE;
54 RefPtr<TextEventDispatcherListener> listener =
55 mWidget->GetNativeTextEventDispatcherListener();
56 if (NS_WARN_IF(!listener)) {
57 return NS_ERROR_FAILURE;
59 return BeginInputTransactionInternal(listener, eNativeInputTransaction);
62 nsresult TextEventDispatcher::BeginInputTransactionInternal(
63 TextEventDispatcherListener* aListener, InputTransactionType aType) {
64 if (NS_WARN_IF(!aListener)) {
65 return NS_ERROR_INVALID_ARG;
67 nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
68 if (listener) {
69 if (listener == aListener && mInputTransactionType == aType) {
70 UpdateNotificationRequests();
71 return NS_OK;
73 // If this has composition or is dispatching an event, any other listener
74 // can steal ownership. Especially, if the latter case is allowed,
75 // nobody cannot begin input transaction with this if a modal dialog is
76 // opened during dispatching an event.
77 if (IsComposing() || IsDispatchingEvent()) {
78 return NS_ERROR_ALREADY_INITIALIZED;
81 mListener = do_GetWeakReference(aListener);
82 mInputTransactionType = aType;
83 if (listener && listener != aListener) {
84 listener->OnRemovedFrom(this);
86 UpdateNotificationRequests();
87 return NS_OK;
90 nsresult TextEventDispatcher::BeginInputTransactionFor(
91 const WidgetGUIEvent* aEvent, PuppetWidget* aPuppetWidget) {
92 MOZ_ASSERT(XRE_IsContentProcess());
93 MOZ_ASSERT(!IsDispatchingEvent());
95 switch (aEvent->mMessage) {
96 case eKeyDown:
97 case eKeyPress:
98 case eKeyUp:
99 MOZ_ASSERT(aEvent->mClass == eKeyboardEventClass);
100 break;
101 case eCompositionStart:
102 case eCompositionChange:
103 case eCompositionCommit:
104 case eCompositionCommitAsIs:
105 MOZ_ASSERT(aEvent->mClass == eCompositionEventClass);
106 break;
107 default:
108 return NS_ERROR_INVALID_ARG;
111 if (aEvent->mFlags.mIsSynthesizedForTests) {
112 // If the event is for an automated test and this instance dispatched
113 // an event to the parent process, we can assume that this is already
114 // initialized properly.
115 if (mInputTransactionType == eAsyncTestInputTransaction) {
116 return NS_OK;
118 // Even if the event coming from the parent process is synthesized for
119 // tests, this process should treat it as "sync" test here because
120 // it won't be go back to the parent process.
121 nsresult rv = BeginInputTransactionInternal(
122 static_cast<TextEventDispatcherListener*>(aPuppetWidget),
123 eSameProcessSyncTestInputTransaction);
124 if (NS_WARN_IF(NS_FAILED(rv))) {
125 return rv;
127 } else {
128 nsresult rv = BeginNativeInputTransaction();
129 if (NS_WARN_IF(NS_FAILED(rv))) {
130 return rv;
134 // Emulate modifying members which indicate the state of composition.
135 // If we need to manage more states and/or more complexly, we should create
136 // internal methods which are called by both here and each event dispatcher
137 // method of this class.
138 switch (aEvent->mMessage) {
139 case eKeyDown:
140 case eKeyPress:
141 case eKeyUp:
142 return NS_OK;
143 case eCompositionStart:
144 MOZ_ASSERT(!mIsComposing);
145 mIsComposing = mIsHandlingComposition = true;
146 return NS_OK;
147 case eCompositionChange:
148 MOZ_ASSERT(mIsComposing);
149 MOZ_ASSERT(mIsHandlingComposition);
150 mIsComposing = mIsHandlingComposition = true;
151 return NS_OK;
152 case eCompositionCommit:
153 case eCompositionCommitAsIs:
154 MOZ_ASSERT(mIsComposing);
155 MOZ_ASSERT(mIsHandlingComposition);
156 mIsComposing = false;
157 mIsHandlingComposition = true;
158 return NS_OK;
159 default:
160 MOZ_ASSERT_UNREACHABLE("You forgot to handle the event");
161 return NS_ERROR_UNEXPECTED;
164 void TextEventDispatcher::EndInputTransaction(
165 TextEventDispatcherListener* aListener) {
166 if (NS_WARN_IF(IsComposing()) || NS_WARN_IF(IsDispatchingEvent())) {
167 return;
170 mInputTransactionType = eNoInputTransaction;
172 nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
173 if (NS_WARN_IF(!listener)) {
174 return;
177 if (NS_WARN_IF(listener != aListener)) {
178 return;
181 mListener = nullptr;
182 listener->OnRemovedFrom(this);
183 UpdateNotificationRequests();
186 void TextEventDispatcher::OnDestroyWidget() {
187 mWidget = nullptr;
188 mHasFocus = false;
189 ClearNotificationRequests();
190 mPendingComposition.Clear();
191 nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
192 mListener = nullptr;
193 mWritingMode.reset();
194 mInputTransactionType = eNoInputTransaction;
195 if (listener) {
196 listener->OnRemovedFrom(this);
200 nsresult TextEventDispatcher::GetState() const {
201 nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
202 if (!listener) {
203 return NS_ERROR_NOT_INITIALIZED;
205 if (!mWidget || mWidget->Destroyed()) {
206 return NS_ERROR_NOT_AVAILABLE;
208 return NS_OK;
211 void TextEventDispatcher::InitEvent(WidgetGUIEvent& aEvent) const {
212 aEvent.mTime = PR_IntervalNow();
213 aEvent.mRefPoint = LayoutDeviceIntPoint(0, 0);
214 aEvent.mFlags.mIsSynthesizedForTests = IsForTests();
215 if (aEvent.mClass != eCompositionEventClass) {
216 return;
218 void* pseudoIMEContext = GetPseudoIMEContext();
219 if (pseudoIMEContext) {
220 aEvent.AsCompositionEvent()->mNativeIMEContext.InitWithRawNativeIMEContext(
221 pseudoIMEContext);
223 #ifdef DEBUG
224 else {
225 MOZ_ASSERT(!XRE_IsContentProcess(),
226 "Why did the content process start native event transaction?");
227 MOZ_ASSERT(aEvent.AsCompositionEvent()->mNativeIMEContext.IsValid(),
228 "Native IME context shouldn't be invalid");
230 #endif // #ifdef DEBUG
233 Maybe<WritingMode> TextEventDispatcher::MaybeQueryWritingModeAtSelection()
234 const {
235 if (mHasFocus || mWritingMode.isSome()) {
236 return mWritingMode;
239 if (NS_WARN_IF(!mWidget)) {
240 return Nothing();
243 // If a remote content has focus and IME does not have focus, it's going to
244 // fail eQuerySelectedText in ContentCacheParent. For avoiding to waste
245 // unnecessary runtime cost and to prevent unnecessary warnings, we should
246 // not dispatch the event in the case.
247 const InputContext inputContext = mWidget->GetInputContext();
248 if (XRE_IsE10sParentProcess() && inputContext.IsOriginContentProcess() &&
249 !inputContext.mIMEState.IsEditable()) {
250 return Nothing();
253 WidgetQueryContentEvent querySelectedTextEvent(true, eQuerySelectedText,
254 mWidget);
255 nsEventStatus status = nsEventStatus_eIgnore;
256 const_cast<TextEventDispatcher*>(this)->DispatchEvent(
257 mWidget, querySelectedTextEvent, status);
258 if (!querySelectedTextEvent.FoundSelection()) {
259 return Nothing();
262 return Some(querySelectedTextEvent.mReply->mWritingMode);
265 nsresult TextEventDispatcher::DispatchEvent(nsIWidget* aWidget,
266 WidgetGUIEvent& aEvent,
267 nsEventStatus& aStatus) {
268 MOZ_ASSERT(!aEvent.AsInputEvent(), "Use DispatchInputEvent()");
270 RefPtr<TextEventDispatcher> kungFuDeathGrip(this);
271 nsCOMPtr<nsIWidget> widget(aWidget);
272 mDispatchingEvent++;
273 nsresult rv = widget->DispatchEvent(&aEvent, aStatus);
274 mDispatchingEvent--;
275 return rv;
278 nsresult TextEventDispatcher::DispatchInputEvent(nsIWidget* aWidget,
279 WidgetInputEvent& aEvent,
280 nsEventStatus& aStatus) {
281 RefPtr<TextEventDispatcher> kungFuDeathGrip(this);
282 nsCOMPtr<nsIWidget> widget(aWidget);
283 mDispatchingEvent++;
285 // If the event is dispatched via nsIWidget::DispatchInputEvent(), it
286 // sends the event to the parent process first since APZ needs to handle it
287 // first. However, some callers (e.g., keyboard apps on B2G and tests
288 // expecting synchronous dispatch) don't want this to do that.
289 nsresult rv = NS_OK;
290 if (ShouldSendInputEventToAPZ()) {
291 aStatus = widget->DispatchInputEvent(&aEvent).mContentStatus;
292 } else {
293 rv = widget->DispatchEvent(&aEvent, aStatus);
296 mDispatchingEvent--;
297 return rv;
300 nsresult TextEventDispatcher::StartComposition(
301 nsEventStatus& aStatus, const WidgetEventTime* aEventTime) {
302 aStatus = nsEventStatus_eIgnore;
304 nsresult rv = GetState();
305 if (NS_WARN_IF(NS_FAILED(rv))) {
306 return rv;
309 if (NS_WARN_IF(mIsComposing)) {
310 return NS_ERROR_FAILURE;
313 // When you change some members from here, you may need same change in
314 // BeginInputTransactionFor().
315 mIsComposing = mIsHandlingComposition = true;
316 WidgetCompositionEvent compositionStartEvent(true, eCompositionStart,
317 mWidget);
318 InitEvent(compositionStartEvent);
319 if (aEventTime) {
320 compositionStartEvent.AssignEventTime(*aEventTime);
322 rv = DispatchEvent(mWidget, compositionStartEvent, aStatus);
323 if (NS_WARN_IF(NS_FAILED(rv))) {
324 return rv;
327 return NS_OK;
330 nsresult TextEventDispatcher::StartCompositionAutomaticallyIfNecessary(
331 nsEventStatus& aStatus, const WidgetEventTime* aEventTime) {
332 if (IsComposing()) {
333 return NS_OK;
336 nsresult rv = StartComposition(aStatus, aEventTime);
337 if (NS_WARN_IF(NS_FAILED(rv))) {
338 return rv;
341 // If started composition has already been committed, we shouldn't dispatch
342 // the compositionchange event.
343 if (!IsComposing()) {
344 aStatus = nsEventStatus_eConsumeNoDefault;
345 return NS_OK;
348 // Note that the widget might be destroyed during a call of
349 // StartComposition(). In such case, we shouldn't keep dispatching next
350 // event.
351 rv = GetState();
352 if (NS_FAILED(rv)) {
353 MOZ_ASSERT(rv != NS_ERROR_NOT_INITIALIZED,
354 "aDispatcher must still be initialized in this case");
355 aStatus = nsEventStatus_eConsumeNoDefault;
356 return NS_OK; // Don't throw exception in this case
359 aStatus = nsEventStatus_eIgnore;
360 return NS_OK;
363 nsresult TextEventDispatcher::CommitComposition(
364 nsEventStatus& aStatus, const nsAString* aCommitString,
365 const WidgetEventTime* aEventTime) {
366 aStatus = nsEventStatus_eIgnore;
368 nsresult rv = GetState();
369 if (NS_WARN_IF(NS_FAILED(rv))) {
370 return rv;
373 // When there is no composition, caller shouldn't try to commit composition
374 // with non-existing composition string nor commit composition with empty
375 // string.
376 if (NS_WARN_IF(!IsComposing() &&
377 (!aCommitString || aCommitString->IsEmpty()))) {
378 return NS_ERROR_FAILURE;
381 nsCOMPtr<nsIWidget> widget(mWidget);
382 rv = StartCompositionAutomaticallyIfNecessary(aStatus, aEventTime);
383 if (NS_WARN_IF(NS_FAILED(rv))) {
384 return rv;
386 if (aStatus == nsEventStatus_eConsumeNoDefault) {
387 return NS_OK;
390 // When you change some members from here, you may need same change in
391 // BeginInputTransactionFor().
393 // End current composition and make this free for other IMEs.
394 mIsComposing = false;
396 EventMessage message =
397 aCommitString ? eCompositionCommit : eCompositionCommitAsIs;
398 WidgetCompositionEvent compositionCommitEvent(true, message, widget);
399 InitEvent(compositionCommitEvent);
400 if (aEventTime) {
401 compositionCommitEvent.AssignEventTime(*aEventTime);
403 if (message == eCompositionCommit) {
404 compositionCommitEvent.mData = *aCommitString;
405 // If aCommitString comes from TextInputProcessor, it may be void, but
406 // editor requires non-void string even when it's empty.
407 compositionCommitEvent.mData.SetIsVoid(false);
408 // Don't send CRLF nor CR, replace it with LF here.
409 compositionCommitEvent.mData.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns);
410 compositionCommitEvent.mData.ReplaceSubstring(u"\r"_ns, u"\n"_ns);
412 rv = DispatchEvent(widget, compositionCommitEvent, aStatus);
413 if (NS_WARN_IF(NS_FAILED(rv))) {
414 return rv;
417 return NS_OK;
420 nsresult TextEventDispatcher::NotifyIME(
421 const IMENotification& aIMENotification) {
422 nsresult rv = NS_ERROR_NOT_IMPLEMENTED;
424 switch (aIMENotification.mMessage) {
425 case NOTIFY_IME_OF_FOCUS: {
426 mWritingMode = MaybeQueryWritingModeAtSelection();
427 break;
429 case NOTIFY_IME_OF_BLUR:
430 mHasFocus = false;
431 mWritingMode.reset();
432 ClearNotificationRequests();
433 break;
434 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
435 // If content handles composition events when native IME doesn't have
436 // composition, that means that we completely finished handling
437 // composition(s). Note that when focused content is in a remote
438 // process, this is sent when all dispatched composition events
439 // have been handled in the remote process.
440 if (!IsComposing()) {
441 mIsHandlingComposition = false;
443 break;
444 case NOTIFY_IME_OF_SELECTION_CHANGE:
445 if (mHasFocus && aIMENotification.mSelectionChangeData.HasRange()) {
446 mWritingMode =
447 Some(aIMENotification.mSelectionChangeData.GetWritingMode());
449 break;
450 default:
451 break;
454 // First, send the notification to current input transaction's listener.
455 nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
456 if (listener) {
457 rv = listener->NotifyIME(this, aIMENotification);
460 if (!mWidget) {
461 return rv;
464 // If current input transaction isn't for native event handler, we should
465 // send the notification to the native text event dispatcher listener
466 // since native event handler may need to do something from
467 // TextEventDispatcherListener::NotifyIME() even before there is no
468 // input transaction yet. For example, native IME handler may need to
469 // create new context at receiving NOTIFY_IME_OF_FOCUS. In this case,
470 // mListener may not be initialized since input transaction should be
471 // initialized immediately before dispatching every WidgetKeyboardEvent
472 // and WidgetCompositionEvent (dispatching events always occurs after
473 // focus move).
474 nsCOMPtr<TextEventDispatcherListener> nativeListener =
475 mWidget->GetNativeTextEventDispatcherListener();
476 if (listener != nativeListener && nativeListener) {
477 switch (aIMENotification.mMessage) {
478 case REQUEST_TO_COMMIT_COMPOSITION:
479 case REQUEST_TO_CANCEL_COMPOSITION:
480 // It's not necessary to notify native IME of requests.
481 break;
482 default: {
483 // Even if current input transaction's listener returns NS_OK or
484 // something, we need to notify native IME of notifications because
485 // when user typing after TIP does something, the changed information
486 // is necessary for them.
487 nsresult rv2 = nativeListener->NotifyIME(this, aIMENotification);
488 // But return the result from current listener except when the
489 // notification isn't handled.
490 if (rv == NS_ERROR_NOT_IMPLEMENTED) {
491 rv = rv2;
493 break;
498 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
499 mHasFocus = true;
500 UpdateNotificationRequests();
503 return rv;
506 void TextEventDispatcher::ClearNotificationRequests() {
507 mIMENotificationRequests = IMENotificationRequests();
510 void TextEventDispatcher::UpdateNotificationRequests() {
511 ClearNotificationRequests();
513 // If it doesn't has focus, no notifications are available.
514 if (!mHasFocus || !mWidget) {
515 return;
518 // If there is a listener, its requests are necessary.
519 nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
520 if (listener) {
521 mIMENotificationRequests = listener->GetIMENotificationRequests();
524 // Even if this is in non-native input transaction, native IME needs
525 // requests. So, add native IME requests too.
526 if (!IsInNativeInputTransaction()) {
527 nsCOMPtr<TextEventDispatcherListener> nativeListener =
528 mWidget->GetNativeTextEventDispatcherListener();
529 if (nativeListener) {
530 mIMENotificationRequests |= nativeListener->GetIMENotificationRequests();
535 bool TextEventDispatcher::DispatchKeyboardEvent(
536 EventMessage aMessage, const WidgetKeyboardEvent& aKeyboardEvent,
537 nsEventStatus& aStatus, void* aData) {
538 return DispatchKeyboardEventInternal(aMessage, aKeyboardEvent, aStatus,
539 aData);
542 bool TextEventDispatcher::DispatchKeyboardEventInternal(
543 EventMessage aMessage, const WidgetKeyboardEvent& aKeyboardEvent,
544 nsEventStatus& aStatus, void* aData, uint32_t aIndexOfKeypress,
545 bool aNeedsCallback) {
546 // Note that this method is also used for dispatching key events on a plugin
547 // because key events on a plugin should be dispatched same as normal key
548 // events. Then, only some handlers which need to intercept key events
549 // before the focused plugin (e.g., reserved shortcut key handlers) can
550 // consume the events.
551 MOZ_ASSERT(
552 aMessage == eKeyDown || aMessage == eKeyUp || aMessage == eKeyPress,
553 "Invalid aMessage value");
554 nsresult rv = GetState();
555 if (NS_WARN_IF(NS_FAILED(rv))) {
556 return false;
559 // If the key shouldn't cause keypress events, don't this patch them.
560 if (aMessage == eKeyPress && !aKeyboardEvent.ShouldCauseKeypressEvents()) {
561 return false;
564 // Basically, key events shouldn't be dispatched during composition.
565 // Note that plugin process has different IME context. Therefore, we don't
566 // need to check our composition state when the key event is fired on a
567 // plugin.
568 if (IsComposing()) {
569 // However, if we need to behave like other browsers, we need the keydown
570 // and keyup events. Note that this behavior is also allowed by D3E spec.
571 // FYI: keypress events must not be fired during composition.
572 if (!StaticPrefs::dom_keyboardevent_dispatch_during_composition() ||
573 aMessage == eKeyPress) {
574 return false;
576 // XXX If there was mOnlyContentDispatch for this case, it might be useful
577 // because our chrome doesn't assume that key events are fired during
578 // composition.
581 WidgetKeyboardEvent keyEvent(true, aMessage, mWidget);
582 InitEvent(keyEvent);
583 keyEvent.AssignKeyEventData(aKeyboardEvent, false);
584 // Command arrays are not duplicated by AssignKeyEventData() due to
585 // both performance and footprint reasons. So, when TextInputProcessor
586 // emulates real text input or synthesizing keyboard events for tests,
587 // the arrays may be initialized all commands already. If so, we need to
588 // duplicate the arrays here, but we should do this only when we're
589 // dispatching eKeyPress events because BrowserParent::SendRealKeyEvent()
590 // does this only for eKeyPress event. Note that this is not required if
591 // we're in the main process because in the parent process, the edit commands
592 // will be initialized by `ExecuteEditCommands()` (when the event is handled
593 // by editor event listener) or `InitAllEditCommands()` (when the event is
594 // set to a content process). We should test whether these pathes work or
595 // not too.
596 if (XRE_IsContentProcess() && keyEvent.mIsSynthesizedByTIP) {
597 if (aMessage == eKeyPress) {
598 keyEvent.AssignCommands(aKeyboardEvent);
599 } else {
600 // Prevent retriving native edit commands if we're in a content process
601 // because only `eKeyPress` events coming from the main process have
602 // edit commands (See `BrowserParent::SendRealKeyEvent`). And also
603 // retriving edit commands from a content process requires synchonous
604 // IPC and that makes running tests slower. Therefore, we should mark
605 // the `eKeyPress` event does not need to retrieve edit commands anymore.
606 keyEvent.PreventNativeKeyBindings();
610 if (aStatus == nsEventStatus_eConsumeNoDefault) {
611 // If the key event should be dispatched as consumed event, marking it here.
612 // This is useful to prevent double action. This is intended to the system
613 // has already consumed the event but we need to dispatch the event for
614 // compatibility with older version and other browsers. So, we should not
615 // stop cross process forwarding of them.
616 keyEvent.PreventDefaultBeforeDispatch(CrossProcessForwarding::eAllow);
619 // Corrects each member for the specific key event type.
620 if (keyEvent.mKeyNameIndex != KEY_NAME_INDEX_USE_STRING) {
621 MOZ_ASSERT(!aIndexOfKeypress,
622 "aIndexOfKeypress must be 0 for non-printable key");
623 // If the keyboard event isn't caused by printable key, its charCode should
624 // be 0.
625 keyEvent.SetCharCode(0);
626 } else {
627 MOZ_DIAGNOSTIC_ASSERT_IF(aMessage == eKeyDown || aMessage == eKeyUp,
628 !aIndexOfKeypress);
629 MOZ_DIAGNOSTIC_ASSERT_IF(
630 aMessage == eKeyPress,
631 aIndexOfKeypress < std::max<size_t>(keyEvent.mKeyValue.Length(), 1));
632 char16_t ch =
633 keyEvent.mKeyValue.IsEmpty() ? 0 : keyEvent.mKeyValue[aIndexOfKeypress];
634 keyEvent.SetCharCode(static_cast<uint32_t>(ch));
635 if (aMessage == eKeyPress) {
636 // keyCode of eKeyPress events of printable keys should be always 0.
637 keyEvent.mKeyCode = 0;
638 // eKeyPress events are dispatched for every character.
639 // So, each key value of eKeyPress events should be a character.
640 if (ch) {
641 keyEvent.mKeyValue.Assign(ch);
642 } else {
643 keyEvent.mKeyValue.Truncate();
647 if (aMessage == eKeyUp) {
648 // mIsRepeat of keyup event must be false.
649 keyEvent.mIsRepeat = false;
651 // mIsComposing should be initialized later.
652 keyEvent.mIsComposing = false;
653 if (mInputTransactionType == eNativeInputTransaction) {
654 // Copy mNativeKeyEvent here because for safety for other users of
655 // AssignKeyEventData(), it doesn't copy this.
656 keyEvent.mNativeKeyEvent = aKeyboardEvent.mNativeKeyEvent;
657 } else {
658 // If it's not a keyboard event for native key event, we should ensure that
659 // mNativeKeyEvent is null.
660 keyEvent.mNativeKeyEvent = nullptr;
662 // TODO: Manage mUniqueId here.
664 // Request the alternative char codes for the key event.
665 // eKeyDown also needs alternative char codes because nsXBLWindowKeyHandler
666 // needs to check if a following keypress event is reserved by chrome for
667 // stopping propagation of its preceding keydown event.
668 keyEvent.mAlternativeCharCodes.Clear();
669 if ((aMessage == eKeyDown || aMessage == eKeyPress) &&
670 (aNeedsCallback || keyEvent.IsControl() || keyEvent.IsAlt() ||
671 keyEvent.IsMeta() || keyEvent.IsOS())) {
672 nsCOMPtr<TextEventDispatcherListener> listener =
673 do_QueryReferent(mListener);
674 if (listener) {
675 DebugOnly<WidgetKeyboardEvent> original(keyEvent);
676 listener->WillDispatchKeyboardEvent(this, keyEvent, aIndexOfKeypress,
677 aData);
678 MOZ_ASSERT(keyEvent.mMessage ==
679 static_cast<WidgetKeyboardEvent&>(original).mMessage);
680 MOZ_ASSERT(keyEvent.mKeyCode ==
681 static_cast<WidgetKeyboardEvent&>(original).mKeyCode);
682 MOZ_ASSERT(keyEvent.mLocation ==
683 static_cast<WidgetKeyboardEvent&>(original).mLocation);
684 MOZ_ASSERT(keyEvent.mIsRepeat ==
685 static_cast<WidgetKeyboardEvent&>(original).mIsRepeat);
686 MOZ_ASSERT(keyEvent.mIsComposing ==
687 static_cast<WidgetKeyboardEvent&>(original).mIsComposing);
688 MOZ_ASSERT(keyEvent.mKeyNameIndex ==
689 static_cast<WidgetKeyboardEvent&>(original).mKeyNameIndex);
690 MOZ_ASSERT(keyEvent.mCodeNameIndex ==
691 static_cast<WidgetKeyboardEvent&>(original).mCodeNameIndex);
692 MOZ_ASSERT(keyEvent.mKeyValue ==
693 static_cast<WidgetKeyboardEvent&>(original).mKeyValue);
694 MOZ_ASSERT(keyEvent.mCodeValue ==
695 static_cast<WidgetKeyboardEvent&>(original).mCodeValue);
699 if (StaticPrefs::
700 dom_keyboardevent_keypress_dispatch_non_printable_keys_only_system_group_in_content() &&
701 keyEvent.mMessage == eKeyPress &&
702 !keyEvent.ShouldKeyPressEventBeFiredOnContent()) {
703 // Note that even if we set it to true, this may be overwritten by
704 // PresShell::DispatchEventToDOM().
705 keyEvent.mFlags.mOnlySystemGroupDispatchInContent = true;
708 // If an editable element has focus and we're in the parent process, we should
709 // retrieve native key bindings right now because even if it matches with a
710 // reserved shortcut key, it should be handled by the editor.
711 if (XRE_IsParentProcess() && mHasFocus &&
712 (aMessage == eKeyDown || aMessage == eKeyPress)) {
713 keyEvent.InitAllEditCommands(mWritingMode);
716 DispatchInputEvent(mWidget, keyEvent, aStatus);
717 return true;
720 bool TextEventDispatcher::MaybeDispatchKeypressEvents(
721 const WidgetKeyboardEvent& aKeyboardEvent, nsEventStatus& aStatus,
722 void* aData, bool aNeedsCallback) {
723 // If the key event was consumed, keypress event shouldn't be fired.
724 if (aStatus == nsEventStatus_eConsumeNoDefault) {
725 return false;
728 // If the key shouldn't cause keypress events, don't fire them.
729 if (!aKeyboardEvent.ShouldCauseKeypressEvents()) {
730 return false;
733 // If the key isn't a printable key or just inputting one character or
734 // no character, we should dispatch only one keypress. Otherwise, i.e.,
735 // if the key is a printable key and inputs multiple characters, keypress
736 // event should be dispatched the count of inputting characters times.
737 size_t keypressCount =
738 aKeyboardEvent.mKeyNameIndex != KEY_NAME_INDEX_USE_STRING
740 : std::max(static_cast<nsAString::size_type>(1),
741 aKeyboardEvent.mKeyValue.Length());
742 bool isDispatched = false;
743 bool consumed = false;
744 for (size_t i = 0; i < keypressCount; i++) {
745 aStatus = nsEventStatus_eIgnore;
746 if (!DispatchKeyboardEventInternal(eKeyPress, aKeyboardEvent, aStatus,
747 aData, i, aNeedsCallback)) {
748 // The widget must have been gone.
749 break;
751 isDispatched = true;
752 if (!consumed) {
753 consumed = (aStatus == nsEventStatus_eConsumeNoDefault);
757 // If one of the keypress event was consumed, return ConsumeNoDefault.
758 if (consumed) {
759 aStatus = nsEventStatus_eConsumeNoDefault;
762 return isDispatched;
765 /******************************************************************************
766 * TextEventDispatcher::PendingComposition
767 *****************************************************************************/
769 TextEventDispatcher::PendingComposition::PendingComposition() { Clear(); }
771 void TextEventDispatcher::PendingComposition::Clear() {
772 mString.Truncate();
773 mClauses = nullptr;
774 mCaret.mRangeType = TextRangeType::eUninitialized;
775 mReplacedNativeLineBreakers = false;
778 void TextEventDispatcher::PendingComposition::EnsureClauseArray() {
779 if (mClauses) {
780 return;
782 mClauses = new TextRangeArray();
785 nsresult TextEventDispatcher::PendingComposition::SetString(
786 const nsAString& aString) {
787 MOZ_ASSERT(!mReplacedNativeLineBreakers);
788 mString = aString;
789 return NS_OK;
792 nsresult TextEventDispatcher::PendingComposition::AppendClause(
793 uint32_t aLength, TextRangeType aTextRangeType) {
794 MOZ_ASSERT(!mReplacedNativeLineBreakers);
796 if (NS_WARN_IF(!aLength)) {
797 return NS_ERROR_INVALID_ARG;
800 switch (aTextRangeType) {
801 case TextRangeType::eRawClause:
802 case TextRangeType::eSelectedRawClause:
803 case TextRangeType::eConvertedClause:
804 case TextRangeType::eSelectedClause: {
805 EnsureClauseArray();
806 TextRange textRange;
807 textRange.mStartOffset =
808 mClauses->IsEmpty() ? 0 : mClauses->LastElement().mEndOffset;
809 textRange.mEndOffset = textRange.mStartOffset + aLength;
810 textRange.mRangeType = aTextRangeType;
811 mClauses->AppendElement(textRange);
812 return NS_OK;
814 default:
815 return NS_ERROR_INVALID_ARG;
819 nsresult TextEventDispatcher::PendingComposition::SetCaret(uint32_t aOffset,
820 uint32_t aLength) {
821 MOZ_ASSERT(!mReplacedNativeLineBreakers);
823 mCaret.mStartOffset = aOffset;
824 mCaret.mEndOffset = mCaret.mStartOffset + aLength;
825 mCaret.mRangeType = TextRangeType::eCaret;
826 return NS_OK;
829 nsresult TextEventDispatcher::PendingComposition::Set(
830 const nsAString& aString, const TextRangeArray* aRanges) {
831 Clear();
833 nsresult rv = SetString(aString);
834 if (NS_WARN_IF(NS_FAILED(rv))) {
835 return rv;
838 if (!aRanges || aRanges->IsEmpty()) {
839 // Create dummy range if mString isn't empty.
840 if (!mString.IsEmpty()) {
841 rv = AppendClause(mString.Length(), TextRangeType::eRawClause);
842 if (NS_WARN_IF(NS_FAILED(rv))) {
843 return rv;
845 ReplaceNativeLineBreakers();
847 return NS_OK;
850 // Adjust offsets in the ranges for XP linefeed character (only \n).
851 for (uint32_t i = 0; i < aRanges->Length(); ++i) {
852 TextRange range = aRanges->ElementAt(i);
853 if (range.mRangeType == TextRangeType::eCaret) {
854 mCaret = range;
855 } else {
856 EnsureClauseArray();
857 mClauses->AppendElement(range);
860 ReplaceNativeLineBreakers();
861 return NS_OK;
864 void TextEventDispatcher::PendingComposition::ReplaceNativeLineBreakers() {
865 mReplacedNativeLineBreakers = true;
867 // If the composition string is empty, we don't need to do anything.
868 if (mString.IsEmpty()) {
869 return;
872 nsAutoString nativeString(mString);
873 // Don't expose CRLF nor CR to web contents, instead, use LF.
874 mString.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns);
875 mString.ReplaceSubstring(u"\r"_ns, u"\n"_ns);
877 // If the length isn't changed, we don't need to adjust any offset and length
878 // of mClauses nor mCaret.
879 if (nativeString.Length() == mString.Length()) {
880 return;
883 if (mClauses) {
884 for (TextRange& clause : *mClauses) {
885 AdjustRange(clause, nativeString);
888 if (mCaret.mRangeType == TextRangeType::eCaret) {
889 AdjustRange(mCaret, nativeString);
893 // static
894 void TextEventDispatcher::PendingComposition::AdjustRange(
895 TextRange& aRange, const nsAString& aNativeString) {
896 TextRange nativeRange = aRange;
897 // XXX Following code wastes runtime cost because this causes computing
898 // mStartOffset for each clause from the start of composition string.
899 // If we'd make TextRange have only its length, we don't need to do
900 // this. However, this must not be so serious problem because
901 // composition string is usually short and separated as a few clauses.
902 if (nativeRange.mStartOffset > 0) {
903 nsAutoString preText(Substring(aNativeString, 0, nativeRange.mStartOffset));
904 preText.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns);
905 aRange.mStartOffset = preText.Length();
907 if (nativeRange.Length() == 0) {
908 aRange.mEndOffset = aRange.mStartOffset;
909 } else {
910 nsAutoString clause(Substring(aNativeString, nativeRange.mStartOffset,
911 nativeRange.Length()));
912 clause.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns);
913 aRange.mEndOffset = aRange.mStartOffset + clause.Length();
917 nsresult TextEventDispatcher::PendingComposition::Flush(
918 TextEventDispatcher* aDispatcher, nsEventStatus& aStatus,
919 const WidgetEventTime* aEventTime) {
920 aStatus = nsEventStatus_eIgnore;
922 nsresult rv = aDispatcher->GetState();
923 if (NS_WARN_IF(NS_FAILED(rv))) {
924 return rv;
927 if (mClauses && !mClauses->IsEmpty() &&
928 mClauses->LastElement().mEndOffset != mString.Length()) {
929 NS_WARNING(
930 "Sum of length of the all clauses must be same as the string "
931 "length");
932 Clear();
933 return NS_ERROR_ILLEGAL_VALUE;
935 if (mCaret.mRangeType == TextRangeType::eCaret) {
936 if (mCaret.mEndOffset > mString.Length()) {
937 NS_WARNING("Caret position is out of the composition string");
938 Clear();
939 return NS_ERROR_ILLEGAL_VALUE;
941 EnsureClauseArray();
942 mClauses->AppendElement(mCaret);
945 // If the composition string is set without Set(), we need to replace native
946 // line breakers in the composition string with XP line breaker.
947 if (!mReplacedNativeLineBreakers) {
948 ReplaceNativeLineBreakers();
951 RefPtr<TextEventDispatcher> kungFuDeathGrip(aDispatcher);
952 nsCOMPtr<nsIWidget> widget(aDispatcher->mWidget);
953 WidgetCompositionEvent compChangeEvent(true, eCompositionChange, widget);
954 aDispatcher->InitEvent(compChangeEvent);
955 if (aEventTime) {
956 compChangeEvent.AssignEventTime(*aEventTime);
958 compChangeEvent.mData = mString;
959 // If mString comes from TextInputProcessor, it may be void, but editor
960 // requires non-void string even when it's empty.
961 compChangeEvent.mData.SetIsVoid(false);
962 if (mClauses) {
963 MOZ_ASSERT(!mClauses->IsEmpty(),
964 "mClauses must be non-empty array when it's not nullptr");
965 compChangeEvent.mRanges = mClauses;
968 // While this method dispatches a composition event, some other event handler
969 // cause more clauses to be added. So, we should clear pending composition
970 // before dispatching the event.
971 Clear();
973 rv = aDispatcher->StartCompositionAutomaticallyIfNecessary(aStatus,
974 aEventTime);
975 if (NS_WARN_IF(NS_FAILED(rv))) {
976 return rv;
978 if (aStatus == nsEventStatus_eConsumeNoDefault) {
979 return NS_OK;
981 rv = aDispatcher->DispatchEvent(widget, compChangeEvent, aStatus);
982 if (NS_WARN_IF(NS_FAILED(rv))) {
983 return rv;
986 return NS_OK;
989 } // namespace widget
990 } // namespace mozilla