Bug 1833854 - Part 7: Add the FOR_EACH_GC_TUNABLE macro to describe tunable GC parame...
[gecko.git] / widget / IMEData.h
blob8664ce0ed9c9f2191fbcf3e013b35fee58089ee9
1 /* -*- Mode: C++; tab-width: 40; 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_widget_IMEData_h_
7 #define mozilla_widget_IMEData_h_
9 #include "mozilla/CheckedInt.h"
10 #include "mozilla/EventForwards.h"
11 #include "mozilla/NativeKeyBindingsType.h"
12 #include "mozilla/ToString.h"
14 #include "nsCOMPtr.h"
15 #include "nsIURI.h"
16 #include "nsPoint.h"
17 #include "nsRect.h"
18 #include "nsString.h"
19 #include "nsXULAppAPI.h"
20 #include "Units.h"
22 class nsIWidget;
24 namespace mozilla {
26 class ContentSelection;
27 class WritingMode;
29 template <class T>
30 class Maybe;
32 // Helper class to logging string which may contain various Unicode characters
33 // and/or may be too long string for logging.
34 class MOZ_STACK_CLASS PrintStringDetail : public nsAutoCString {
35 public:
36 static constexpr uint32_t kMaxLengthForCompositionString = 8;
37 static constexpr uint32_t kMaxLengthForSelectedString = 12;
38 static constexpr uint32_t kMaxLengthForEditor = 20;
40 PrintStringDetail() = delete;
41 explicit PrintStringDetail(const nsAString& aString,
42 uint32_t aMaxLength = UINT32_MAX);
43 template <typename StringType>
44 explicit PrintStringDetail(const Maybe<StringType>& aMaybeString,
45 uint32_t aMaxLength = UINT32_MAX);
47 private:
48 static nsCString PrintCharData(char32_t aChar);
51 // StartAndEndOffsets represents a range in flat-text.
52 template <typename IntType>
53 class StartAndEndOffsets {
54 protected:
55 static IntType MaxOffset() { return std::numeric_limits<IntType>::max(); }
57 public:
58 StartAndEndOffsets() = delete;
59 explicit StartAndEndOffsets(IntType aStartOffset, IntType aEndOffset)
60 : mStartOffset(aStartOffset),
61 mEndOffset(aStartOffset <= aEndOffset ? aEndOffset : aStartOffset) {
62 MOZ_ASSERT(aStartOffset <= mEndOffset);
65 IntType StartOffset() const { return mStartOffset; }
66 IntType Length() const { return mEndOffset - mStartOffset; }
67 IntType EndOffset() const { return mEndOffset; }
69 bool IsOffsetInRange(IntType aOffset) const {
70 return aOffset >= mStartOffset && aOffset < mEndOffset;
72 bool IsOffsetInRangeOrEndOffset(IntType aOffset) const {
73 return aOffset >= mStartOffset && aOffset <= mEndOffset;
76 void MoveTo(IntType aNewStartOffset) {
77 auto delta = static_cast<int64_t>(mStartOffset) - aNewStartOffset;
78 mStartOffset += delta;
79 mEndOffset += delta;
81 void SetOffsetAndLength(IntType aNewOffset, IntType aNewLength) {
82 mStartOffset = aNewOffset;
83 CheckedInt<IntType> endOffset(aNewOffset + aNewLength);
84 mEndOffset = endOffset.isValid() ? endOffset.value() : MaxOffset();
86 void SetEndOffset(IntType aEndOffset) {
87 MOZ_ASSERT(mStartOffset <= aEndOffset);
88 mEndOffset = std::max(aEndOffset, mStartOffset);
90 void SetStartAndEndOffsets(IntType aStartOffset, IntType aEndOffset) {
91 MOZ_ASSERT(aStartOffset <= aEndOffset);
92 mStartOffset = aStartOffset;
93 mEndOffset = aStartOffset <= aEndOffset ? aEndOffset : aStartOffset;
95 void SetLength(IntType aNewLength) {
96 CheckedInt<IntType> endOffset(mStartOffset + aNewLength);
97 mEndOffset = endOffset.isValid() ? endOffset.value() : MaxOffset();
100 friend std::ostream& operator<<(
101 std::ostream& aStream,
102 const StartAndEndOffsets<IntType>& aStartAndEndOffsets) {
103 aStream << "{ mStartOffset=" << aStartAndEndOffsets.mStartOffset
104 << ", mEndOffset=" << aStartAndEndOffsets.mEndOffset
105 << ", Length()=" << aStartAndEndOffsets.Length() << " }";
106 return aStream;
109 private:
110 IntType mStartOffset;
111 IntType mEndOffset;
114 // OffsetAndData class is designed for storing composition string and its
115 // start offset. Length() and EndOffset() return only valid length or
116 // offset. I.e., if the string is too long for inserting at the offset,
117 // the length is shrunken. However, the string itself is not shrunken.
118 // Therefore, moving it to where all of the string can be contained,
119 // they will return longer/bigger value.
120 enum class OffsetAndDataFor {
121 CompositionString,
122 SelectedString,
123 EditorString,
125 template <typename IntType>
126 class OffsetAndData {
127 protected:
128 static IntType MaxOffset() { return std::numeric_limits<IntType>::max(); }
130 public:
131 OffsetAndData() = delete;
132 explicit OffsetAndData(
133 IntType aStartOffset, const nsAString& aData,
134 OffsetAndDataFor aFor = OffsetAndDataFor::CompositionString)
135 : mData(aData), mOffset(aStartOffset), mFor(aFor) {}
137 bool IsValid() const {
138 CheckedInt<IntType> offset(mOffset);
139 offset += mData.Length();
140 return offset.isValid();
142 IntType StartOffset() const { return mOffset; }
143 IntType Length() const {
144 CheckedInt<IntType> endOffset(CheckedInt<IntType>(mOffset) +
145 mData.Length());
146 return endOffset.isValid() ? mData.Length() : MaxOffset() - mOffset;
148 IntType EndOffset() const { return mOffset + Length(); }
149 StartAndEndOffsets<IntType> CreateStartAndEndOffsets() const {
150 return StartAndEndOffsets<IntType>(StartOffset(), EndOffset());
152 const nsString& DataRef() const {
153 // In strictly speaking, we should return substring which may be shrunken
154 // for rounding to the max offset. However, it's unrealistic edge case,
155 // and creating new string is not so cheap job in a hot path. Therefore,
156 // this just returns the data as-is.
157 return mData;
159 bool IsDataEmpty() const { return mData.IsEmpty(); }
161 bool IsOffsetInRange(IntType aOffset) const {
162 return aOffset >= mOffset && aOffset < EndOffset();
164 bool IsOffsetInRangeOrEndOffset(IntType aOffset) const {
165 return aOffset >= mOffset && aOffset <= EndOffset();
168 void Collapse(IntType aOffset) {
169 mOffset = aOffset;
170 mData.Truncate();
172 void MoveTo(IntType aNewOffset) { mOffset = aNewOffset; }
173 void SetOffsetAndData(IntType aStartOffset, const nsAString& aData) {
174 mOffset = aStartOffset;
175 mData = aData;
177 void SetData(const nsAString& aData) { mData = aData; }
178 void TruncateData(uint32_t aLength = 0) { mData.Truncate(aLength); }
179 void ReplaceData(nsAString::size_type aCutStart,
180 nsAString::size_type aCutLength,
181 const nsAString& aNewString) {
182 mData.Replace(aCutStart, aCutLength, aNewString);
185 friend std::ostream& operator<<(
186 std::ostream& aStream, const OffsetAndData<IntType>& aOffsetAndData) {
187 const auto maxDataLength =
188 aOffsetAndData.mFor == OffsetAndDataFor::CompositionString
189 ? PrintStringDetail::kMaxLengthForCompositionString
190 : (aOffsetAndData.mFor == OffsetAndDataFor::SelectedString
191 ? PrintStringDetail::kMaxLengthForSelectedString
192 : PrintStringDetail::kMaxLengthForEditor);
193 aStream << "{ mOffset=" << aOffsetAndData.mOffset << ", mData="
194 << PrintStringDetail(aOffsetAndData.mData, maxDataLength).get()
195 << ", Length()=" << aOffsetAndData.Length()
196 << ", EndOffset()=" << aOffsetAndData.EndOffset() << " }";
197 return aStream;
200 private:
201 nsString mData;
202 IntType mOffset;
203 OffsetAndDataFor mFor;
206 namespace widget {
209 * Preference for receiving IME updates
211 * If mWantUpdates is not NOTIFY_NOTHING, nsTextStateManager will observe text
212 * change and/or selection change and call nsIWidget::NotifyIME() with
213 * NOTIFY_IME_OF_SELECTION_CHANGE and/or NOTIFY_IME_OF_TEXT_CHANGE.
214 * Please note that the text change observing cost is very expensive especially
215 * on an HTML editor has focus.
216 * If the IME implementation on a particular platform doesn't care about
217 * NOTIFY_IME_OF_SELECTION_CHANGE and/or NOTIFY_IME_OF_TEXT_CHANGE,
218 * they should set mWantUpdates to NOTIFY_NOTHING to avoid the cost.
219 * If the IME implementation needs notifications even while our process is
220 * deactive, it should also set NOTIFY_DURING_DEACTIVE.
222 struct IMENotificationRequests final {
223 typedef uint8_t Notifications;
225 enum : Notifications {
226 NOTIFY_NOTHING = 0,
227 NOTIFY_TEXT_CHANGE = 1 << 1,
228 NOTIFY_POSITION_CHANGE = 1 << 2,
229 // NOTIFY_MOUSE_BUTTON_EVENT_ON_CHAR is used when mouse button is pressed
230 // or released on a character in the focused editor. The notification is
231 // notified to IME as a mouse event. If it's consumed by IME, NotifyIME()
232 // returns NS_SUCCESS_EVENT_CONSUMED. Otherwise, it returns NS_OK if it's
233 // handled without any error.
234 NOTIFY_MOUSE_BUTTON_EVENT_ON_CHAR = 1 << 3,
235 // NOTE: NOTIFY_DURING_DEACTIVE isn't supported in environments where two
236 // or more compositions are possible. E.g., Mac and Linux (GTK).
237 NOTIFY_DURING_DEACTIVE = 1 << 7,
239 NOTIFY_ALL = NOTIFY_TEXT_CHANGE | NOTIFY_POSITION_CHANGE |
240 NOTIFY_MOUSE_BUTTON_EVENT_ON_CHAR,
243 IMENotificationRequests() : mWantUpdates(NOTIFY_NOTHING) {}
245 explicit IMENotificationRequests(Notifications aWantUpdates)
246 : mWantUpdates(aWantUpdates) {}
248 IMENotificationRequests operator|(
249 const IMENotificationRequests& aOther) const {
250 return IMENotificationRequests(aOther.mWantUpdates | mWantUpdates);
252 IMENotificationRequests& operator|=(const IMENotificationRequests& aOther) {
253 mWantUpdates |= aOther.mWantUpdates;
254 return *this;
256 bool operator==(const IMENotificationRequests& aOther) const {
257 return mWantUpdates == aOther.mWantUpdates;
260 bool WantTextChange() const { return !!(mWantUpdates & NOTIFY_TEXT_CHANGE); }
262 bool WantPositionChanged() const {
263 return !!(mWantUpdates & NOTIFY_POSITION_CHANGE);
266 bool WantChanges() const { return WantTextChange(); }
268 bool WantMouseButtonEventOnChar() const {
269 return !!(mWantUpdates & NOTIFY_MOUSE_BUTTON_EVENT_ON_CHAR);
272 bool WantDuringDeactive() const {
273 return !!(mWantUpdates & NOTIFY_DURING_DEACTIVE);
276 Notifications mWantUpdates;
280 * IME enabled states.
282 * WARNING: If you change these values, you also need to edit:
283 * nsIDOMWindowUtils.idl
285 enum class IMEEnabled {
287 * 'Disabled' means the user cannot use IME. So, the IME open state should
288 * be 'closed' during 'disabled'.
290 Disabled,
292 * 'Enabled' means the user can use IME.
294 Enabled,
296 * 'Password' state is a special case for the password editors.
297 * E.g., on mac, the password editors should disable the non-Roman
298 * keyboard layouts at getting focus. Thus, the password editor may have
299 * special rules on some platforms.
301 Password,
303 * 'Unknown' is useful when you cache this enum. So, this shouldn't be
304 * used with nsIWidget::SetInputContext().
306 Unknown,
310 * Contains IMEStatus plus information about the current
311 * input context that the IME can use as hints if desired.
314 struct IMEState final {
315 IMEEnabled mEnabled;
318 * IME open states the mOpen value of SetInputContext() should be one value of
319 * OPEN, CLOSE or DONT_CHANGE_OPEN_STATE. GetInputContext() should return
320 * OPEN, CLOSE or OPEN_STATE_NOT_SUPPORTED.
322 enum Open {
324 * 'Unsupported' means the platform cannot return actual IME open state.
325 * This value is used only by GetInputContext().
327 OPEN_STATE_NOT_SUPPORTED,
329 * 'Don't change' means the widget shouldn't change IME open state when
330 * SetInputContext() is called.
332 DONT_CHANGE_OPEN_STATE = OPEN_STATE_NOT_SUPPORTED,
334 * 'Open' means that IME should compose in its primary language (or latest
335 * input mode except direct ASCII character input mode). Even if IME is
336 * opened by this value, users should be able to close IME by theirselves.
337 * Web contents can specify this value by |ime-mode: active;|.
339 OPEN,
341 * 'Closed' means that IME shouldn't handle key events (or should handle
342 * as ASCII character inputs on mobile device). Even if IME is closed by
343 * this value, users should be able to open IME by theirselves.
344 * Web contents can specify this value by |ime-mode: inactive;|.
346 CLOSED
348 Open mOpen;
350 IMEState() : mEnabled(IMEEnabled::Enabled), mOpen(DONT_CHANGE_OPEN_STATE) {}
352 explicit IMEState(IMEEnabled aEnabled, Open aOpen = DONT_CHANGE_OPEN_STATE)
353 : mEnabled(aEnabled), mOpen(aOpen) {}
355 // Returns true if the user can input characters.
356 // This means that a plain text editor, an HTML editor, a password editor or
357 // a plain text editor whose ime-mode is "disabled".
358 bool IsEditable() const {
359 return mEnabled == IMEEnabled::Enabled || mEnabled == IMEEnabled::Password;
363 // NS_ONLY_ONE_NATIVE_IME_CONTEXT is a special value of native IME context.
364 // If there can be only one IME composition in a process, this can be used.
365 #define NS_ONLY_ONE_NATIVE_IME_CONTEXT \
366 (reinterpret_cast<void*>(static_cast<intptr_t>(-1)))
368 struct NativeIMEContext final {
369 // Pointer to native IME context. Typically this is the result of
370 // nsIWidget::GetNativeData(NS_RAW_NATIVE_IME_CONTEXT) in the parent process.
371 // See also NS_ONLY_ONE_NATIVE_IME_CONTEXT.
372 uintptr_t mRawNativeIMEContext;
373 // Process ID of the origin of mNativeIMEContext.
374 uint64_t mOriginProcessID;
376 NativeIMEContext() : mRawNativeIMEContext(0), mOriginProcessID(0) {
377 Init(nullptr);
380 explicit NativeIMEContext(nsIWidget* aWidget)
381 : mRawNativeIMEContext(0), mOriginProcessID(0) {
382 Init(aWidget);
385 bool IsValid() const {
386 return mRawNativeIMEContext &&
387 mOriginProcessID != static_cast<uintptr_t>(-1);
390 void Init(nsIWidget* aWidget);
391 void InitWithRawNativeIMEContext(const void* aRawNativeIMEContext) {
392 InitWithRawNativeIMEContext(const_cast<void*>(aRawNativeIMEContext));
394 void InitWithRawNativeIMEContext(void* aRawNativeIMEContext);
396 bool operator==(const NativeIMEContext& aOther) const {
397 return mRawNativeIMEContext == aOther.mRawNativeIMEContext &&
398 mOriginProcessID == aOther.mOriginProcessID;
400 bool operator!=(const NativeIMEContext& aOther) const {
401 return !(*this == aOther);
405 struct InputContext final {
406 InputContext()
407 : mOrigin(XRE_IsParentProcess() ? ORIGIN_MAIN : ORIGIN_CONTENT),
408 mHasHandledUserInput(false),
409 mInPrivateBrowsing(false) {}
411 // If InputContext instance is a static variable, any heap allocated stuff
412 // of its members need to be deleted at XPCOM shutdown. Otherwise, it's
413 // detected as memory leak.
414 void ShutDown() {
415 mURI = nullptr;
416 mHTMLInputType.Truncate();
417 mHTMLInputMode.Truncate();
418 mActionHint.Truncate();
419 mAutocapitalize.Truncate();
422 bool IsPasswordEditor() const {
423 return mHTMLInputType.LowerCaseEqualsLiteral("password");
426 NativeKeyBindingsType GetNativeKeyBindingsType() const {
427 MOZ_DIAGNOSTIC_ASSERT(mIMEState.IsEditable());
428 // See GetInputType in IMEStateManager.cpp
429 if (mHTMLInputType.IsEmpty()) {
430 return NativeKeyBindingsType::RichTextEditor;
432 return mHTMLInputType.EqualsLiteral("textarea")
433 ? NativeKeyBindingsType::MultiLineEditor
434 : NativeKeyBindingsType::SingleLineEditor;
437 // https://html.spec.whatwg.org/dev/interaction.html#autocapitalization
438 bool IsAutocapitalizeSupported() const {
439 return !mHTMLInputType.EqualsLiteral("password") &&
440 !mHTMLInputType.EqualsLiteral("url") &&
441 !mHTMLInputType.EqualsLiteral("email");
444 bool IsInputAttributeChanged(const InputContext& aOldContext) const {
445 return mIMEState.mEnabled != aOldContext.mIMEState.mEnabled ||
446 #if defined(ANDROID) || defined(MOZ_WIDGET_GTK) || defined(XP_WIN)
447 // input type and inputmode are supported by Windows IME API, GTK
448 // IME API and Android IME API
449 mHTMLInputType != aOldContext.mHTMLInputType ||
450 mHTMLInputMode != aOldContext.mHTMLInputMode ||
451 #endif
452 #if defined(ANDROID) || defined(MOZ_WIDGET_GTK)
453 // autocapitalize is supported by Android IME API and GTK IME API
454 mAutocapitalize != aOldContext.mAutocapitalize ||
455 #endif
456 #if defined(ANDROID)
457 // enterkeyhint is only supported by Android IME API.
458 mActionHint != aOldContext.mActionHint ||
459 #endif
460 false;
463 IMEState mIMEState;
465 // The URI of the document which has the editable element.
466 nsCOMPtr<nsIURI> mURI;
468 /* The type of the input if the input is a html input field */
469 nsString mHTMLInputType;
471 // The value of the inputmode
472 nsString mHTMLInputMode;
474 /* A hint for the action that is performed when the input is submitted */
475 nsString mActionHint;
477 /* A hint for autocapitalize */
478 nsString mAutocapitalize;
481 * mOrigin indicates whether this focus event refers to main or remote
482 * content.
484 enum Origin {
485 // Adjusting focus of content on the main process
486 ORIGIN_MAIN,
487 // Adjusting focus of content in a remote process
488 ORIGIN_CONTENT
490 Origin mOrigin;
493 * True if the document has ever received user input
495 bool mHasHandledUserInput;
497 /* Whether the owning document of the input element has been loaded
498 * in private browsing mode. */
499 bool mInPrivateBrowsing;
501 bool IsOriginMainProcess() const { return mOrigin == ORIGIN_MAIN; }
503 bool IsOriginContentProcess() const { return mOrigin == ORIGIN_CONTENT; }
505 bool IsOriginCurrentProcess() const {
506 if (XRE_IsParentProcess()) {
507 return IsOriginMainProcess();
509 return IsOriginContentProcess();
513 // FYI: Implemented in nsBaseWidget.cpp
514 const char* ToChar(InputContext::Origin aOrigin);
516 struct InputContextAction final {
518 * mCause indicates what action causes calling nsIWidget::SetInputContext().
519 * It must be one of following values.
521 enum Cause {
522 // The cause is unknown but originated from content. Focus might have been
523 // changed by content script.
524 CAUSE_UNKNOWN,
525 // The cause is unknown but originated from chrome. Focus might have been
526 // changed by chrome script.
527 CAUSE_UNKNOWN_CHROME,
528 // The cause is user's keyboard operation.
529 CAUSE_KEY,
530 // The cause is user's mouse operation.
531 CAUSE_MOUSE,
532 // The cause is user's touch operation (implies mouse)
533 CAUSE_TOUCH,
534 // The cause is users' long press operation.
535 CAUSE_LONGPRESS,
536 // The cause is unknown but it occurs during user input except keyboard
537 // input. E.g., an event handler of a user input event moves focus.
538 CAUSE_UNKNOWN_DURING_NON_KEYBOARD_INPUT,
539 // The cause is unknown but it occurs during keyboard input.
540 CAUSE_UNKNOWN_DURING_KEYBOARD_INPUT,
542 Cause mCause;
545 * mFocusChange indicates what happened for focus.
547 enum FocusChange {
548 FOCUS_NOT_CHANGED,
549 // A content got focus.
550 GOT_FOCUS,
551 // Focused content lost focus.
552 LOST_FOCUS,
553 // Menu got pseudo focus that means focused content isn't changed but
554 // keyboard events will be handled by menu.
555 MENU_GOT_PSEUDO_FOCUS,
556 // Menu lost pseudo focus that means focused content will handle keyboard
557 // events.
558 MENU_LOST_PSEUDO_FOCUS,
559 // The widget is created. When a widget is crated, it may need to notify
560 // IME module to initialize its native IME context. In such case, this is
561 // used. I.e., this isn't used by IMEStateManager.
562 WIDGET_CREATED
564 FocusChange mFocusChange;
566 bool ContentGotFocusByTrustedCause() const {
567 return (mFocusChange == GOT_FOCUS && mCause != CAUSE_UNKNOWN);
570 bool UserMightRequestOpenVKB() const {
571 // If focus is changed, user must not request to open VKB.
572 if (mFocusChange != FOCUS_NOT_CHANGED) {
573 return false;
575 switch (mCause) {
576 // If user clicks or touches focused editor, user must request to open
577 // VKB.
578 case CAUSE_MOUSE:
579 case CAUSE_TOUCH:
580 // If script does something during a user input and that causes changing
581 // input context, user might request to open VKB. E.g., user clicks
582 // dummy editor and JS moves focus to an actual editable node. However,
583 // this should return false if the user input is a keyboard event since
584 // physical keyboard operation shouldn't cause opening VKB.
585 case CAUSE_UNKNOWN_DURING_NON_KEYBOARD_INPUT:
586 return true;
587 default:
588 return false;
593 * IsHandlingUserInput() returns true if it's caused by a user action directly
594 * or it's caused by script or something but it occurred while we're handling
595 * a user action. E.g., when it's caused by Element.focus() in an event
596 * handler of a user input, this returns true.
598 static bool IsHandlingUserInput(Cause aCause) {
599 switch (aCause) {
600 case CAUSE_KEY:
601 case CAUSE_MOUSE:
602 case CAUSE_TOUCH:
603 case CAUSE_LONGPRESS:
604 case CAUSE_UNKNOWN_DURING_NON_KEYBOARD_INPUT:
605 case CAUSE_UNKNOWN_DURING_KEYBOARD_INPUT:
606 return true;
607 default:
608 return false;
612 bool IsHandlingUserInput() const { return IsHandlingUserInput(mCause); }
614 InputContextAction()
615 : mCause(CAUSE_UNKNOWN), mFocusChange(FOCUS_NOT_CHANGED) {}
617 explicit InputContextAction(Cause aCause,
618 FocusChange aFocusChange = FOCUS_NOT_CHANGED)
619 : mCause(aCause), mFocusChange(aFocusChange) {}
622 // IMEMessage is shared by IMEStateManager and TextComposition.
623 // Update values in GeckoEditable.java if you make changes here.
624 // XXX Negative values are used in Android...
625 typedef int8_t IMEMessageType;
626 enum IMEMessage : IMEMessageType {
627 // This is used by IMENotification internally. This means that the instance
628 // hasn't been initialized yet.
629 NOTIFY_IME_OF_NOTHING,
630 // An editable content is getting focus
631 NOTIFY_IME_OF_FOCUS,
632 // An editable content is losing focus
633 NOTIFY_IME_OF_BLUR,
634 // Selection in the focused editable content is changed
635 NOTIFY_IME_OF_SELECTION_CHANGE,
636 // Text in the focused editable content is changed
637 NOTIFY_IME_OF_TEXT_CHANGE,
638 // Notified when a dispatched composition event is handled by the
639 // contents. This must be notified after the other notifications.
640 // Note that if a remote process has focus, this is notified only once when
641 // all dispatched events are handled completely. So, the receiver shouldn't
642 // count number of received this notification for comparing with the number
643 // of dispatched events.
644 // NOTE: If a composition event causes moving focus from the focused editor,
645 // this notification may not be notified as usual. Even in such case,
646 // NOTIFY_IME_OF_BLUR is always sent. So, notification listeners
647 // should tread the blur notification as including this if there is
648 // pending composition events.
649 NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED,
650 // Position or size of focused element may be changed.
651 NOTIFY_IME_OF_POSITION_CHANGE,
652 // Mouse button event is fired on a character in focused editor
653 NOTIFY_IME_OF_MOUSE_BUTTON_EVENT,
654 // Request to commit current composition to IME
655 // (some platforms may not support)
656 REQUEST_TO_COMMIT_COMPOSITION,
657 // Request to cancel current composition to IME
658 // (some platforms may not support)
659 REQUEST_TO_CANCEL_COMPOSITION
662 // FYI: Implemented in nsBaseWidget.cpp
663 const char* ToChar(IMEMessage aIMEMessage);
665 struct IMENotification final {
666 IMENotification() : mMessage(NOTIFY_IME_OF_NOTHING), mSelectionChangeData() {}
668 IMENotification(const IMENotification& aOther)
669 : mMessage(NOTIFY_IME_OF_NOTHING) {
670 Assign(aOther);
673 ~IMENotification() { Clear(); }
675 MOZ_IMPLICIT IMENotification(IMEMessage aMessage)
676 : mMessage(aMessage), mSelectionChangeData() {
677 switch (aMessage) {
678 case NOTIFY_IME_OF_SELECTION_CHANGE:
679 mSelectionChangeData.mString = new nsString();
680 mSelectionChangeData.Clear();
681 break;
682 case NOTIFY_IME_OF_TEXT_CHANGE:
683 mTextChangeData.Clear();
684 break;
685 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
686 mMouseButtonEventData.mEventMessage = eVoidEvent;
687 mMouseButtonEventData.mOffset = UINT32_MAX;
688 mMouseButtonEventData.mCursorPos.MoveTo(0, 0);
689 mMouseButtonEventData.mCharRect.SetRect(0, 0, 0, 0);
690 mMouseButtonEventData.mButton = -1;
691 mMouseButtonEventData.mButtons = 0;
692 mMouseButtonEventData.mModifiers = 0;
693 break;
694 default:
695 break;
699 void Assign(const IMENotification& aOther) {
700 bool changingMessage = mMessage != aOther.mMessage;
701 if (changingMessage) {
702 Clear();
703 mMessage = aOther.mMessage;
705 switch (mMessage) {
706 case NOTIFY_IME_OF_SELECTION_CHANGE:
707 if (changingMessage) {
708 mSelectionChangeData.mString = new nsString();
710 mSelectionChangeData.Assign(aOther.mSelectionChangeData);
711 break;
712 case NOTIFY_IME_OF_TEXT_CHANGE:
713 mTextChangeData = aOther.mTextChangeData;
714 break;
715 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
716 mMouseButtonEventData = aOther.mMouseButtonEventData;
717 break;
718 default:
719 break;
723 IMENotification& operator=(const IMENotification& aOther) {
724 Assign(aOther);
725 return *this;
728 void Clear() {
729 if (mMessage == NOTIFY_IME_OF_SELECTION_CHANGE) {
730 MOZ_ASSERT(mSelectionChangeData.mString);
731 delete mSelectionChangeData.mString;
732 mSelectionChangeData.mString = nullptr;
734 mMessage = NOTIFY_IME_OF_NOTHING;
737 bool HasNotification() const { return mMessage != NOTIFY_IME_OF_NOTHING; }
739 void MergeWith(const IMENotification& aNotification) {
740 switch (mMessage) {
741 case NOTIFY_IME_OF_NOTHING:
742 MOZ_ASSERT(aNotification.mMessage != NOTIFY_IME_OF_NOTHING);
743 Assign(aNotification);
744 break;
745 case NOTIFY_IME_OF_SELECTION_CHANGE:
746 MOZ_ASSERT(aNotification.mMessage == NOTIFY_IME_OF_SELECTION_CHANGE);
747 mSelectionChangeData.Assign(aNotification.mSelectionChangeData);
748 break;
749 case NOTIFY_IME_OF_TEXT_CHANGE:
750 MOZ_ASSERT(aNotification.mMessage == NOTIFY_IME_OF_TEXT_CHANGE);
751 mTextChangeData += aNotification.mTextChangeData;
752 break;
753 case NOTIFY_IME_OF_POSITION_CHANGE:
754 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
755 MOZ_ASSERT(aNotification.mMessage == mMessage);
756 break;
757 default:
758 MOZ_CRASH("Merging notification isn't supported");
759 break;
763 IMEMessage mMessage;
765 // NOTIFY_IME_OF_SELECTION_CHANGE specific data
766 struct SelectionChangeDataBase {
767 // Selection range.
768 uint32_t mOffset;
770 // Selected string
771 nsString* mString;
773 // Writing mode at the selection.
774 uint8_t mWritingModeBits;
776 bool mIsInitialized;
777 bool mHasRange;
778 bool mReversed;
779 bool mCausedByComposition;
780 bool mCausedBySelectionEvent;
781 bool mOccurredDuringComposition;
783 void SetWritingMode(const WritingMode& aWritingMode);
784 WritingMode GetWritingMode() const;
786 uint32_t StartOffset() const {
787 MOZ_ASSERT(mHasRange);
788 return mOffset;
790 uint32_t EndOffset() const {
791 MOZ_ASSERT(mHasRange);
792 return mOffset + Length();
794 uint32_t AnchorOffset() const {
795 MOZ_ASSERT(mHasRange);
796 return mOffset + (mReversed ? Length() : 0);
798 uint32_t FocusOffset() const {
799 MOZ_ASSERT(mHasRange);
800 return mOffset + (mReversed ? 0 : Length());
802 const nsString& String() const {
803 MOZ_ASSERT(mHasRange);
804 return *mString;
806 uint32_t Length() const {
807 MOZ_ASSERT(mHasRange);
808 return mString->Length();
810 bool IsInInt32Range() const {
811 return mHasRange && mOffset <= INT32_MAX && Length() <= INT32_MAX &&
812 mOffset + Length() <= INT32_MAX;
814 bool HasRange() const { return mIsInitialized && mHasRange; }
815 bool IsCollapsed() const { return !mHasRange || mString->IsEmpty(); }
816 void ClearSelectionData() {
817 mIsInitialized = false;
818 mHasRange = false;
819 mOffset = UINT32_MAX;
820 mString->Truncate();
821 mWritingModeBits = 0;
822 mReversed = false;
824 void Clear() {
825 ClearSelectionData();
826 mCausedByComposition = false;
827 mCausedBySelectionEvent = false;
828 mOccurredDuringComposition = false;
830 bool IsInitialized() const { return mIsInitialized; }
831 void Assign(const SelectionChangeDataBase& aOther) {
832 mIsInitialized = aOther.mIsInitialized;
833 mHasRange = aOther.mHasRange;
834 if (mIsInitialized && mHasRange) {
835 mOffset = aOther.mOffset;
836 *mString = aOther.String();
837 mReversed = aOther.mReversed;
838 mWritingModeBits = aOther.mWritingModeBits;
839 } else {
840 mOffset = UINT32_MAX;
841 mString->Truncate();
842 mReversed = false;
843 // Let's keep the writing mode for avoiding temporarily changing the
844 // writing mode at no selection range.
846 AssignReason(aOther.mCausedByComposition, aOther.mCausedBySelectionEvent,
847 aOther.mOccurredDuringComposition);
849 void Assign(const WidgetQueryContentEvent& aQuerySelectedTextEvent);
850 void AssignReason(bool aCausedByComposition, bool aCausedBySelectionEvent,
851 bool aOccurredDuringComposition) {
852 mCausedByComposition = aCausedByComposition;
853 mCausedBySelectionEvent = aCausedBySelectionEvent;
854 mOccurredDuringComposition = aOccurredDuringComposition;
857 bool EqualsRange(const SelectionChangeDataBase& aOther) const {
858 if (HasRange() != aOther.HasRange()) {
859 return false;
861 if (!HasRange()) {
862 return true;
864 return mOffset == aOther.mOffset && mString->Equals(*aOther.mString);
866 bool EqualsRangeAndDirection(const SelectionChangeDataBase& aOther) const {
867 return EqualsRange(aOther) &&
868 (!HasRange() || mReversed == aOther.mReversed);
870 bool EqualsRangeAndDirectionAndWritingMode(
871 const SelectionChangeDataBase& aOther) const {
872 return EqualsRangeAndDirection(aOther) &&
873 mWritingModeBits == aOther.mWritingModeBits;
876 bool EqualsRange(const ContentSelection& aContentSelection) const;
877 bool EqualsRangeAndWritingMode(
878 const ContentSelection& aContentSelection) const;
880 OffsetAndData<uint32_t> ToUint32OffsetAndData() const {
881 return OffsetAndData<uint32_t>(mOffset, *mString,
882 OffsetAndDataFor::SelectedString);
886 // SelectionChangeDataBase cannot have constructors because it's used in
887 // the union. Therefore, SelectionChangeData should only implement
888 // constructors. In other words, add other members to
889 // SelectionChangeDataBase.
890 struct SelectionChangeData final : public SelectionChangeDataBase {
891 SelectionChangeData() {
892 mString = &mStringInstance;
893 Clear();
895 explicit SelectionChangeData(const SelectionChangeDataBase& aOther) {
896 mString = &mStringInstance;
897 Assign(aOther);
899 SelectionChangeData(const SelectionChangeData& aOther) {
900 mString = &mStringInstance;
901 Assign(aOther);
903 SelectionChangeData& operator=(const SelectionChangeDataBase& aOther) {
904 mString = &mStringInstance;
905 Assign(aOther);
906 return *this;
908 SelectionChangeData& operator=(const SelectionChangeData& aOther) {
909 mString = &mStringInstance;
910 Assign(aOther);
911 return *this;
914 private:
915 // When SelectionChangeData is used outside of union, it shouldn't create
916 // nsString instance in the heap as far as possible.
917 nsString mStringInstance;
920 struct TextChangeDataBase {
921 // mStartOffset is the start offset of modified or removed text in
922 // original content and inserted text in new content.
923 uint32_t mStartOffset;
924 // mRemovalEndOffset is the end offset of modified or removed text in
925 // original content. If the value is same as mStartOffset, no text hasn't
926 // been removed yet.
927 uint32_t mRemovedEndOffset;
928 // mAddedEndOffset is the end offset of inserted text or same as
929 // mStartOffset if just removed. The vlaue is offset in the new content.
930 uint32_t mAddedEndOffset;
932 // Note that TextChangeDataBase may be the result of merging two or more
933 // changes especially in e10s mode.
935 // mCausedOnlyByComposition is true only when *all* merged changes are
936 // caused by composition.
937 bool mCausedOnlyByComposition;
938 // mIncludingChangesDuringComposition is true if at least one change which
939 // is not caused by composition occurred during the last composition.
940 // Note that if after the last composition is finished and there are some
941 // changes not caused by composition, this is set to false.
942 bool mIncludingChangesDuringComposition;
943 // mIncludingChangesWithoutComposition is true if there is at least one
944 // change which did occur when there wasn't a composition ongoing.
945 bool mIncludingChangesWithoutComposition;
947 uint32_t OldLength() const {
948 MOZ_ASSERT(IsValid());
949 return mRemovedEndOffset - mStartOffset;
951 uint32_t NewLength() const {
952 MOZ_ASSERT(IsValid());
953 return mAddedEndOffset - mStartOffset;
956 // Positive if text is added. Negative if text is removed.
957 int64_t Difference() const { return mAddedEndOffset - mRemovedEndOffset; }
959 bool IsInInt32Range() const {
960 MOZ_ASSERT(IsValid());
961 return mStartOffset <= INT32_MAX && mRemovedEndOffset <= INT32_MAX &&
962 mAddedEndOffset <= INT32_MAX;
965 bool IsValid() const {
966 return !(mStartOffset == UINT32_MAX && !mRemovedEndOffset &&
967 !mAddedEndOffset);
970 void Clear() {
971 mStartOffset = UINT32_MAX;
972 mRemovedEndOffset = mAddedEndOffset = 0;
975 void MergeWith(const TextChangeDataBase& aOther);
976 TextChangeDataBase& operator+=(const TextChangeDataBase& aOther) {
977 MergeWith(aOther);
978 return *this;
981 #ifdef DEBUG
982 void Test();
983 #endif // #ifdef DEBUG
986 // TextChangeDataBase cannot have constructors because they are used in union.
987 // Therefore, TextChangeData should only implement constructor. In other
988 // words, add other members to TextChangeDataBase.
989 struct TextChangeData : public TextChangeDataBase {
990 TextChangeData() { Clear(); }
992 TextChangeData(uint32_t aStartOffset, uint32_t aRemovedEndOffset,
993 uint32_t aAddedEndOffset, bool aCausedByComposition,
994 bool aOccurredDuringComposition) {
995 MOZ_ASSERT(aRemovedEndOffset >= aStartOffset,
996 "removed end offset must not be smaller than start offset");
997 MOZ_ASSERT(aAddedEndOffset >= aStartOffset,
998 "added end offset must not be smaller than start offset");
999 mStartOffset = aStartOffset;
1000 mRemovedEndOffset = aRemovedEndOffset;
1001 mAddedEndOffset = aAddedEndOffset;
1002 mCausedOnlyByComposition = aCausedByComposition;
1003 mIncludingChangesDuringComposition =
1004 !aCausedByComposition && aOccurredDuringComposition;
1005 mIncludingChangesWithoutComposition =
1006 !aCausedByComposition && !aOccurredDuringComposition;
1010 struct MouseButtonEventData {
1011 // The value of WidgetEvent::mMessage
1012 EventMessage mEventMessage;
1013 // Character offset from the start of the focused editor under the cursor
1014 uint32_t mOffset;
1015 // Cursor position in pixels relative to the widget
1016 LayoutDeviceIntPoint mCursorPos;
1017 // Character rect in pixels under the cursor relative to the widget
1018 LayoutDeviceIntRect mCharRect;
1019 // The value of WidgetMouseEventBase::button and buttons
1020 int16_t mButton;
1021 int16_t mButtons;
1022 // The value of WidgetInputEvent::modifiers
1023 Modifiers mModifiers;
1026 union {
1027 // NOTIFY_IME_OF_SELECTION_CHANGE specific data
1028 SelectionChangeDataBase mSelectionChangeData;
1030 // NOTIFY_IME_OF_TEXT_CHANGE specific data
1031 TextChangeDataBase mTextChangeData;
1033 // NOTIFY_IME_OF_MOUSE_BUTTON_EVENT specific data
1034 MouseButtonEventData mMouseButtonEventData;
1037 void SetData(const SelectionChangeDataBase& aSelectionChangeData) {
1038 MOZ_RELEASE_ASSERT(mMessage == NOTIFY_IME_OF_SELECTION_CHANGE);
1039 mSelectionChangeData.Assign(aSelectionChangeData);
1042 void SetData(const TextChangeDataBase& aTextChangeData) {
1043 MOZ_RELEASE_ASSERT(mMessage == NOTIFY_IME_OF_TEXT_CHANGE);
1044 mTextChangeData = aTextChangeData;
1048 struct CandidateWindowPosition {
1049 // Upper left corner of the candidate window if mExcludeRect is false.
1050 // Otherwise, the position currently interested. E.g., caret position.
1051 LayoutDeviceIntPoint mPoint;
1052 // Rect which shouldn't be overlapped with the candidate window.
1053 // This is valid only when mExcludeRect is true.
1054 LayoutDeviceIntRect mRect;
1055 // See explanation of mPoint and mRect.
1056 bool mExcludeRect;
1059 std::ostream& operator<<(std::ostream& aStream, const IMEEnabled& aEnabled);
1060 std::ostream& operator<<(std::ostream& aStream, const IMEState::Open& aOpen);
1061 std::ostream& operator<<(std::ostream& aStream, const IMEState& aState);
1062 std::ostream& operator<<(std::ostream& aStream,
1063 const InputContext::Origin& aOrigin);
1064 std::ostream& operator<<(std::ostream& aStream, const InputContext& aContext);
1065 std::ostream& operator<<(std::ostream& aStream,
1066 const InputContextAction::Cause& aCause);
1067 std::ostream& operator<<(std::ostream& aStream,
1068 const InputContextAction::FocusChange& aFocusChange);
1069 std::ostream& operator<<(std::ostream& aStream,
1070 const IMENotification::SelectionChangeDataBase& aData);
1071 std::ostream& operator<<(std::ostream& aStream,
1072 const IMENotification::TextChangeDataBase& aData);
1074 } // namespace widget
1075 } // namespace mozilla
1077 #endif // #ifndef mozilla_widget_IMEData_h_