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"
9 #include "PuppetWidget.h"
10 #include "TextEvents.h"
12 #include "mozilla/Preferences.h"
13 #include "mozilla/StaticPrefs_dom.h"
15 #include "nsIWidget.h"
16 #include "nsPIDOMWindow.h"
22 /******************************************************************************
24 *****************************************************************************/
25 TextEventDispatcher::TextEventDispatcher(nsIWidget
* aWidget
)
28 mInputTransactionType(eNoInputTransaction
),
30 mIsHandlingComposition(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
);
69 if (listener
== aListener
&& mInputTransactionType
== aType
) {
70 UpdateNotificationRequests();
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();
90 nsresult
TextEventDispatcher::BeginInputTransactionFor(
91 const WidgetGUIEvent
* aEvent
, PuppetWidget
* aPuppetWidget
) {
92 MOZ_ASSERT(XRE_IsContentProcess());
93 MOZ_ASSERT(!IsDispatchingEvent());
95 switch (aEvent
->mMessage
) {
99 MOZ_ASSERT(aEvent
->mClass
== eKeyboardEventClass
);
101 case eCompositionStart
:
102 case eCompositionChange
:
103 case eCompositionCommit
:
104 case eCompositionCommitAsIs
:
105 MOZ_ASSERT(aEvent
->mClass
== eCompositionEventClass
);
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
) {
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
))) {
128 nsresult rv
= BeginNativeInputTransaction();
129 if (NS_WARN_IF(NS_FAILED(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
) {
143 case eCompositionStart
:
144 MOZ_ASSERT(!mIsComposing
);
145 mIsComposing
= mIsHandlingComposition
= true;
147 case eCompositionChange
:
148 MOZ_ASSERT(mIsComposing
);
149 MOZ_ASSERT(mIsHandlingComposition
);
150 mIsComposing
= mIsHandlingComposition
= true;
152 case eCompositionCommit
:
153 case eCompositionCommitAsIs
:
154 MOZ_ASSERT(mIsComposing
);
155 MOZ_ASSERT(mIsHandlingComposition
);
156 mIsComposing
= false;
157 mIsHandlingComposition
= true;
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())) {
170 mInputTransactionType
= eNoInputTransaction
;
172 nsCOMPtr
<TextEventDispatcherListener
> listener
= do_QueryReferent(mListener
);
173 if (NS_WARN_IF(!listener
)) {
177 if (NS_WARN_IF(listener
!= aListener
)) {
182 listener
->OnRemovedFrom(this);
183 UpdateNotificationRequests();
186 void TextEventDispatcher::OnDestroyWidget() {
189 ClearNotificationRequests();
190 mPendingComposition
.Clear();
191 nsCOMPtr
<TextEventDispatcherListener
> listener
= do_QueryReferent(mListener
);
193 mWritingMode
.reset();
194 mInputTransactionType
= eNoInputTransaction
;
196 listener
->OnRemovedFrom(this);
200 nsresult
TextEventDispatcher::GetState() const {
201 nsCOMPtr
<TextEventDispatcherListener
> listener
= do_QueryReferent(mListener
);
203 return NS_ERROR_NOT_INITIALIZED
;
205 if (!mWidget
|| mWidget
->Destroyed()) {
206 return NS_ERROR_NOT_AVAILABLE
;
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
) {
218 void* pseudoIMEContext
= GetPseudoIMEContext();
219 if (pseudoIMEContext
) {
220 aEvent
.AsCompositionEvent()->mNativeIMEContext
.InitWithRawNativeIMEContext(
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()
235 if (mHasFocus
|| mWritingMode
.isSome()) {
239 if (NS_WARN_IF(!mWidget
)) {
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()) {
253 WidgetQueryContentEvent
querySelectedTextEvent(true, eQuerySelectedText
,
255 nsEventStatus status
= nsEventStatus_eIgnore
;
256 const_cast<TextEventDispatcher
*>(this)->DispatchEvent(
257 mWidget
, querySelectedTextEvent
, status
);
258 if (!querySelectedTextEvent
.FoundSelection()) {
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
);
273 nsresult rv
= widget
->DispatchEvent(&aEvent
, aStatus
);
278 nsresult
TextEventDispatcher::DispatchInputEvent(nsIWidget
* aWidget
,
279 WidgetInputEvent
& aEvent
,
280 nsEventStatus
& aStatus
) {
281 RefPtr
<TextEventDispatcher
> kungFuDeathGrip(this);
282 nsCOMPtr
<nsIWidget
> widget(aWidget
);
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.
290 if (ShouldSendInputEventToAPZ()) {
291 aStatus
= widget
->DispatchInputEvent(&aEvent
).mContentStatus
;
293 rv
= widget
->DispatchEvent(&aEvent
, aStatus
);
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
))) {
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
,
318 InitEvent(compositionStartEvent
);
320 compositionStartEvent
.AssignEventTime(*aEventTime
);
322 rv
= DispatchEvent(mWidget
, compositionStartEvent
, aStatus
);
323 if (NS_WARN_IF(NS_FAILED(rv
))) {
330 nsresult
TextEventDispatcher::StartCompositionAutomaticallyIfNecessary(
331 nsEventStatus
& aStatus
, const WidgetEventTime
* aEventTime
) {
336 nsresult rv
= StartComposition(aStatus
, aEventTime
);
337 if (NS_WARN_IF(NS_FAILED(rv
))) {
341 // If started composition has already been committed, we shouldn't dispatch
342 // the compositionchange event.
343 if (!IsComposing()) {
344 aStatus
= nsEventStatus_eConsumeNoDefault
;
348 // Note that the widget might be destroyed during a call of
349 // StartComposition(). In such case, we shouldn't keep dispatching next
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
;
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
))) {
373 // When there is no composition, caller shouldn't try to commit composition
374 // with non-existing composition string nor commit composition with empty
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
))) {
386 if (aStatus
== nsEventStatus_eConsumeNoDefault
) {
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
);
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
))) {
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();
429 case NOTIFY_IME_OF_BLUR
:
431 mWritingMode
.reset();
432 ClearNotificationRequests();
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;
444 case NOTIFY_IME_OF_SELECTION_CHANGE
:
445 if (mHasFocus
&& aIMENotification
.mSelectionChangeData
.HasRange()) {
447 Some(aIMENotification
.mSelectionChangeData
.GetWritingMode());
454 // First, send the notification to current input transaction's listener.
455 nsCOMPtr
<TextEventDispatcherListener
> listener
= do_QueryReferent(mListener
);
457 rv
= listener
->NotifyIME(this, aIMENotification
);
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
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.
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
) {
498 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
500 UpdateNotificationRequests();
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
) {
518 // If there is a listener, its requests are necessary.
519 nsCOMPtr
<TextEventDispatcherListener
> listener
= do_QueryReferent(mListener
);
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
,
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.
552 aMessage
== eKeyDown
|| aMessage
== eKeyUp
|| aMessage
== eKeyPress
,
553 "Invalid aMessage value");
554 nsresult rv
= GetState();
555 if (NS_WARN_IF(NS_FAILED(rv
))) {
559 // If the key shouldn't cause keypress events, don't this patch them.
560 if (aMessage
== eKeyPress
&& !aKeyboardEvent
.ShouldCauseKeypressEvents()) {
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
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
) {
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
581 WidgetKeyboardEvent
keyEvent(true, aMessage
, mWidget
);
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
596 if (XRE_IsContentProcess() && keyEvent
.mIsSynthesizedByTIP
) {
597 if (aMessage
== eKeyPress
) {
598 keyEvent
.AssignCommands(aKeyboardEvent
);
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
625 keyEvent
.SetCharCode(0);
627 MOZ_DIAGNOSTIC_ASSERT_IF(aMessage
== eKeyDown
|| aMessage
== eKeyUp
,
629 MOZ_DIAGNOSTIC_ASSERT_IF(
630 aMessage
== eKeyPress
,
631 aIndexOfKeypress
< std::max
<size_t>(keyEvent
.mKeyValue
.Length(), 1));
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.
641 keyEvent
.mKeyValue
.Assign(ch
);
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
;
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
);
675 DebugOnly
<WidgetKeyboardEvent
> original(keyEvent
);
676 listener
->WillDispatchKeyboardEvent(this, keyEvent
, aIndexOfKeypress
,
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
);
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
);
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
) {
728 // If the key shouldn't cause keypress events, don't fire them.
729 if (!aKeyboardEvent
.ShouldCauseKeypressEvents()) {
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.
753 consumed
= (aStatus
== nsEventStatus_eConsumeNoDefault
);
757 // If one of the keypress event was consumed, return ConsumeNoDefault.
759 aStatus
= nsEventStatus_eConsumeNoDefault
;
765 /******************************************************************************
766 * TextEventDispatcher::PendingComposition
767 *****************************************************************************/
769 TextEventDispatcher::PendingComposition::PendingComposition() { Clear(); }
771 void TextEventDispatcher::PendingComposition::Clear() {
774 mCaret
.mRangeType
= TextRangeType::eUninitialized
;
775 mReplacedNativeLineBreakers
= false;
778 void TextEventDispatcher::PendingComposition::EnsureClauseArray() {
782 mClauses
= new TextRangeArray();
785 nsresult
TextEventDispatcher::PendingComposition::SetString(
786 const nsAString
& aString
) {
787 MOZ_ASSERT(!mReplacedNativeLineBreakers
);
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
: {
807 textRange
.mStartOffset
=
808 mClauses
->IsEmpty() ? 0 : mClauses
->LastElement().mEndOffset
;
809 textRange
.mEndOffset
= textRange
.mStartOffset
+ aLength
;
810 textRange
.mRangeType
= aTextRangeType
;
811 mClauses
->AppendElement(textRange
);
815 return NS_ERROR_INVALID_ARG
;
819 nsresult
TextEventDispatcher::PendingComposition::SetCaret(uint32_t aOffset
,
821 MOZ_ASSERT(!mReplacedNativeLineBreakers
);
823 mCaret
.mStartOffset
= aOffset
;
824 mCaret
.mEndOffset
= mCaret
.mStartOffset
+ aLength
;
825 mCaret
.mRangeType
= TextRangeType::eCaret
;
829 nsresult
TextEventDispatcher::PendingComposition::Set(
830 const nsAString
& aString
, const TextRangeArray
* aRanges
) {
833 nsresult rv
= SetString(aString
);
834 if (NS_WARN_IF(NS_FAILED(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
))) {
845 ReplaceNativeLineBreakers();
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
) {
857 mClauses
->AppendElement(range
);
860 ReplaceNativeLineBreakers();
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()) {
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()) {
884 for (TextRange
& clause
: *mClauses
) {
885 AdjustRange(clause
, nativeString
);
888 if (mCaret
.mRangeType
== TextRangeType::eCaret
) {
889 AdjustRange(mCaret
, nativeString
);
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
;
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
))) {
927 if (mClauses
&& !mClauses
->IsEmpty() &&
928 mClauses
->LastElement().mEndOffset
!= mString
.Length()) {
930 "Sum of length of the all clauses must be same as the string "
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");
939 return NS_ERROR_ILLEGAL_VALUE
;
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
);
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);
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.
973 rv
= aDispatcher
->StartCompositionAutomaticallyIfNecessary(aStatus
,
975 if (NS_WARN_IF(NS_FAILED(rv
))) {
978 if (aStatus
== nsEventStatus_eConsumeNoDefault
) {
981 rv
= aDispatcher
->DispatchEvent(widget
, compChangeEvent
, aStatus
);
982 if (NS_WARN_IF(NS_FAILED(rv
))) {
989 } // namespace widget
990 } // namespace mozilla