1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_IMEStateManager_h_
8 #define mozilla_IMEStateManager_h_
10 #include "mozilla/EventForwards.h"
11 #include "mozilla/Maybe.h"
12 #include "mozilla/StaticPtr.h"
13 #include "mozilla/dom/BrowserParent.h"
14 #include "nsIWidget.h"
23 class EventDispatchingCallback
;
24 class IMEContentObserver
;
25 class PseudoFocusChangeRunnable
;
26 class TextCompositionArray
;
27 class TextComposition
;
35 * IMEStateManager manages InputContext (e.g., active editor type, IME enabled
36 * state and IME open state) of nsIWidget instances, manages IMEContentObserver
37 * and provides useful API for IME.
40 class IMEStateManager
{
41 using BrowserParent
= dom::BrowserParent
;
42 using IMEMessage
= widget::IMEMessage
;
43 using IMENotification
= widget::IMENotification
;
44 using IMEState
= widget::IMEState
;
45 using InputContext
= widget::InputContext
;
46 using InputContextAction
= widget::InputContextAction
;
50 static void Shutdown();
53 * GetActiveBrowserParent() returns a pointer to a BrowserParent instance
54 * which is managed by the focused content (sFocusedElement). If the focused
55 * content isn't managing another process, this returns nullptr.
57 static BrowserParent
* GetActiveBrowserParent() {
58 // If menu has pseudo focus, we should ignore active child process.
59 if (sInstalledMenuKeyboardListener
) {
62 // If we know focused browser parent, use it for making any events related
63 // to composition go to same content process.
64 if (sFocusedIMEBrowserParent
) {
65 return sFocusedIMEBrowserParent
;
67 return BrowserParent::GetFocused();
71 * DoesBrowserParentHaveIMEFocus() returns true when aBrowserParent has IME
72 * focus, i.e., the BrowserParent sent "focus" notification but not yet sends
73 * "blur". Note that this doesn't check if the remote processes are same
74 * because if another BrowserParent has focus, committing composition causes
75 * firing composition events in different BrowserParent. (Anyway, such case
78 static bool DoesBrowserParentHaveIMEFocus(
79 const BrowserParent
* aBrowserParent
) {
80 MOZ_ASSERT(aBrowserParent
);
81 return sFocusedIMEBrowserParent
== aBrowserParent
;
85 * If CanSendNotificationToWidget() returns false (it should occur
86 * only in a content process), we shouldn't notify the widget of
87 * any focused editor changes since the content process was blurred.
88 * Also, even if content process, widget has native text event dispatcher such
89 * as Android, it still notify it.
91 static bool CanSendNotificationToWidget() {
92 #ifdef MOZ_WIDGET_ANDROID
95 return !sCleaningUpForStoppingIMEStateManagement
;
100 * Focus moved between browsers from aBlur to aFocus. (nullptr means the
103 static void OnFocusMovedBetweenBrowsers(BrowserParent
* aBlur
,
104 BrowserParent
* aFocus
);
107 * Called when aWidget is being deleted.
109 static void WidgetDestroyed(nsIWidget
* aWidget
);
112 * Called when a widget exists when the app is quitting
114 static void WidgetOnQuit(nsIWidget
* aWidget
);
117 * GetWidgetForActiveInputContext() returns a widget which IMEStateManager
118 * is managing input context with. If a widget instance needs to cache
119 * the last input context for nsIWidget::GetInputContext() or something,
120 * it should check if its cache is valid with this method before using it
121 * because if this method returns another instance, it means that
122 * IMEStateManager may have already changed shared input context via the
125 static nsIWidget
* GetWidgetForActiveInputContext() {
126 return sActiveInputContextWidget
;
130 * Return a widget which is for handling text input. This should be valid
131 * while an editable element has focus or an editable document has focus.
133 static nsIWidget
* GetWidgetForTextInputHandling() {
134 return sTextInputHandlingWidget
;
138 * SetIMEContextForChildProcess() is called when aBrowserParent receives
139 * SetInputContext() from the remote process.
141 static void SetInputContextForChildProcess(BrowserParent
* aBrowserParent
,
142 const InputContext
& aInputContext
,
143 const InputContextAction
& aAction
);
146 * StopIMEStateManagement() is called when the process should stop managing
149 static void StopIMEStateManagement();
152 * MaybeStartOffsetUpdatedInChild() is called when composition start offset
153 * is maybe updated in the child process. I.e., even if it's not updated,
154 * this is called and never called if the composition is in this process.
155 * @param aWidget The widget whose native IME context has the
157 * @param aStartOffset New composition start offset with native
160 static void MaybeStartOffsetUpdatedInChild(nsIWidget
* aWidget
,
161 uint32_t aStartOffset
);
163 MOZ_CAN_RUN_SCRIPT
static nsresult
OnDestroyPresContext(
164 nsPresContext
& aPresContext
);
165 MOZ_CAN_RUN_SCRIPT
static nsresult
OnRemoveContent(
166 nsPresContext
& aPresContext
, dom::Element
& aElement
);
168 * OnChangeFocus() should be called when focused content is changed or
169 * IME enabled state is changed. If nobody has focus, set both aPresContext
170 * and aContent nullptr. E.g., all windows are deactivated. Otherwise,
171 * set focused element (even if it won't receive `focus`event) and
172 * corresponding nsPresContext for it. Then, IMEStateManager can avoid
173 * handling delayed notifications from the others with verifying the
176 MOZ_CAN_RUN_SCRIPT
static nsresult
OnChangeFocus(
177 nsPresContext
* aPresContext
, dom::Element
* aElement
,
178 InputContextAction::Cause aCause
);
181 * OnInstalledMenuKeyboardListener() is called when menu keyboard listener
182 * is installed or uninstalled in the process. So, even if menu keyboard
183 * listener was installed in chrome process, this won't be called in content
186 * @param aInstalling true if menu keyboard listener is installed.
187 * Otherwise, i.e., menu keyboard listener is
188 * uninstalled, false.
190 MOZ_CAN_RUN_SCRIPT
static void OnInstalledMenuKeyboardListener(
193 // These two methods manage focus and selection/text observers.
194 // They are separate from OnChangeFocus above because this offers finer
195 // control compared to having the two methods incorporated into OnChangeFocus
197 // Get the focused editor's selection and root
198 static nsresult
GetFocusSelectionAndRootElement(dom::Selection
** aSel
,
199 dom::Element
** aRootElement
);
200 // This method updates the current IME state. However, if the enabled state
201 // isn't changed by the new state, this method does nothing.
202 // Note that this method changes the IME state of the active element in the
203 // widget. So, the caller must have focus.
204 // XXX Changing this to MOZ_CAN_RUN_SCRIPT requires too many callers to be
205 // marked too. Probably, we should initialize IMEContentObserver
207 enum class UpdateIMEStateOption
{
209 DontCommitComposition
,
211 using UpdateIMEStateOptions
= EnumSet
<UpdateIMEStateOption
, uint32_t>;
212 MOZ_CAN_RUN_SCRIPT
static void UpdateIMEState(
213 const IMEState
& aNewIMEState
, dom::Element
* aElement
,
214 EditorBase
& aEditorBase
, const UpdateIMEStateOptions
& aOptions
= {});
216 // This method is called when user operates mouse button in focused editor
217 // and before the editor handles it.
218 // Returns true if IME consumes the event. Otherwise, false.
219 MOZ_CAN_RUN_SCRIPT
static bool OnMouseButtonEventInEditor(
220 nsPresContext
& aPresContext
, dom::Element
* aElement
,
221 WidgetMouseEvent
& aMouseEvent
);
223 // This method is called when user clicked in an editor.
225 // If the editor is for <input> or <textarea>, the element.
226 // If the editor is for contenteditable, the active editinghost.
227 // If the editor is for designMode, nullptr.
228 MOZ_CAN_RUN_SCRIPT
static void OnClickInEditor(
229 nsPresContext
& aPresContext
, dom::Element
* aElement
,
230 const WidgetMouseEvent
& aMouseEvent
);
232 // This method is called when editor actually gets focus.
234 // If the editor is for <input> or <textarea>, the element.
235 // If the editor is for contenteditable, the active editinghost.
236 // If the editor is for designMode, nullptr.
237 static void OnFocusInEditor(nsPresContext
& aPresContext
,
238 dom::Element
* aElement
, EditorBase
& aEditorBase
);
240 // This method is called when the editor is initialized.
241 static void OnEditorInitialized(EditorBase
& aEditorBase
);
243 // This method is called when the editor is (might be temporarily) being
245 static void OnEditorDestroying(EditorBase
& aEditorBase
);
247 // This method is called when focus is set to same content again.
248 MOZ_CAN_RUN_SCRIPT
static void OnReFocus(nsPresContext
& aPresContext
,
249 dom::Element
& aElement
);
251 // This method is called when designMode is set to "off" or an editing host
252 // becomes not editable due to removing `contenteditable` attribute or setting
254 MOZ_CAN_RUN_SCRIPT
static void MaybeOnEditableStateDisabled(
255 nsPresContext
& aPresContext
, dom::Element
* aElement
);
258 * All composition events must be dispatched via DispatchCompositionEvent()
259 * for storing the composition target and ensuring a set of composition
260 * events must be fired the stored target. If the stored composition event
261 * target is destroying, this removes the stored composition automatically.
263 MOZ_CAN_RUN_SCRIPT
static void DispatchCompositionEvent(
264 nsINode
* aEventTargetNode
, nsPresContext
* aPresContext
,
265 BrowserParent
* aBrowserParent
, WidgetCompositionEvent
* aCompositionEvent
,
266 nsEventStatus
* aStatus
, EventDispatchingCallback
* aCallBack
,
267 bool aIsSynthesized
= false);
270 * All selection events must be handled via HandleSelectionEvent()
271 * because they must be handled by same target as composition events when
272 * there is a composition.
275 static void HandleSelectionEvent(nsPresContext
* aPresContext
,
276 nsIContent
* aEventTargetContent
,
277 WidgetSelectionEvent
* aSelectionEvent
);
280 * This is called when PresShell ignores a composition event due to not safe
281 * to dispatch events.
283 static void OnCompositionEventDiscarded(
284 WidgetCompositionEvent
* aCompositionEvent
);
287 * Get TextComposition from widget.
289 static TextComposition
* GetTextCompositionFor(nsIWidget
* aWidget
);
292 * Returns TextComposition instance for the event.
294 static TextComposition
* GetTextCompositionFor(
295 const WidgetCompositionEvent
* aCompositionEvent
);
298 * Returns TextComposition instance for the pres context.
299 * Be aware, even if another pres context which shares native IME context with
300 * specified pres context has composition, this returns nullptr.
302 static TextComposition
* GetTextCompositionFor(nsPresContext
* aPresContext
);
305 * Send a notification to IME. It depends on the IME or platform spec what
306 * will occur (or not occur).
308 static nsresult
NotifyIME(const IMENotification
& aNotification
,
310 BrowserParent
* aBrowserParent
= nullptr);
311 static nsresult
NotifyIME(IMEMessage aMessage
, nsIWidget
* aWidget
,
312 BrowserParent
* aBrowserParent
= nullptr);
313 static nsresult
NotifyIME(IMEMessage aMessage
, nsPresContext
* aPresContext
,
314 BrowserParent
* aBrowserParent
= nullptr);
316 static nsINode
* GetRootEditableNode(const nsPresContext
& aPresContext
,
317 const dom::Element
* aElement
);
320 * Returns active IMEContentObserver but may be nullptr if focused content
321 * isn't editable or focus in a remote process.
323 static IMEContentObserver
* GetActiveContentObserver();
326 * Return focused element which was notified by a OnChangeFocus() call.
328 static dom::Element
* GetFocusedElement();
331 MOZ_CAN_RUN_SCRIPT
static nsresult
OnChangeFocusInternal(
332 nsPresContext
* aPresContext
, dom::Element
* aElement
,
333 InputContextAction aAction
);
334 MOZ_CAN_RUN_SCRIPT
static void SetIMEState(const IMEState
& aState
,
335 const nsPresContext
* aPresContext
,
336 dom::Element
* aElement
,
338 InputContextAction aAction
,
339 InputContext::Origin aOrigin
);
340 static void SetInputContext(nsIWidget
& aWidget
,
341 const InputContext
& aInputContext
,
342 const InputContextAction
& aAction
);
343 static IMEState
GetNewIMEState(const nsPresContext
& aPresContext
,
344 dom::Element
* aElement
);
346 static void EnsureTextCompositionArray();
348 // XXX Changing this to MOZ_CAN_RUN_SCRIPT requires too many callers to be
349 // marked too. Probably, we should initialize IMEContentObserver
351 MOZ_CAN_RUN_SCRIPT_BOUNDARY
static void CreateIMEContentObserver(
352 EditorBase
& aEditorBase
, dom::Element
* aFocusedElement
);
355 * Check whether the content matches or does not match with focus information
356 * which is previously notified via OnChangeFocus();
358 [[nodiscard
]] static bool IsFocusedElement(
359 const nsPresContext
& aPresContext
, const dom::Element
* aFocusedElement
);
361 static void DestroyIMEContentObserver();
363 [[nodiscard
]] static bool IsEditable(nsINode
* node
);
365 [[nodiscard
]] static bool IsIMEObserverNeeded(const IMEState
& aState
);
367 [[nodiscard
]] static nsIContent
* GetRootContent(nsPresContext
* aPresContext
);
370 * CanHandleWith() returns false if it's destroyed.
372 [[nodiscard
]] static bool CanHandleWith(const nsPresContext
* aPresContext
);
375 * ResetActiveChildInputContext() resets sActiveChildInputContext.
376 * So, HasActiveChildSetInputContext() will return false until a remote
377 * process gets focus and set input context.
379 static void ResetActiveChildInputContext();
382 * HasActiveChildSetInputContext() returns true if a remote tab has focus
383 * and it has already set input context. Otherwise, returns false.
385 static bool HasActiveChildSetInputContext();
388 * This is the runner of OnInstalledMenuKeyboardListener(), called by
389 * PseudoFocusChangeRunnable maybe asynchronously.
391 * @param aCaller The caller instance, used only for debug.
392 * @param aSetPseudoFocus Whether the menu keyboard listener is installed
393 * or uninstalled when
394 * OnInstalledMenuKeyboardListener() is called and
395 * the PseudoFocusChangeRunnable instance is
397 * @param aFocusedPresContextAtRequested
398 * sFocusedPresContext when
399 * OnInstalledMenuKeyboardListener() is called and
400 * the PseudoFocusChangeRunnable instance is
403 MOZ_CAN_RUN_SCRIPT
static void SetMenubarPseudoFocus(
404 PseudoFocusChangeRunnable
* aCaller
, bool aSetPseudoFocus
,
405 nsPresContext
* aFocusedPresContextAtRequested
);
407 // sFocusedElement and sFocusedPresContext are the focused content and
408 // PresContext. If a document has focus but there is no focused element,
409 // sFocusedElement may be nullptr.
410 static StaticRefPtr
<dom::Element
> sFocusedElement
;
411 static StaticRefPtr
<nsPresContext
> sFocusedPresContext
;
412 // sTextInputHandlingWidget is cache for the result of
413 // sFocusedPresContext->GetTextInputHandlingWidget(). Even after
414 // sFocusedPresContext has gone, we need to clean up some IME state on the
415 // widget if the widget is available.
416 // Note that this is cleared when the widget is being destroyed.
417 static nsIWidget
* sTextInputHandlingWidget
;
418 // sFocusedIMEBrowserParent is the tab parent, which send "focus" notification
419 // to sFocusedIMEWidget (and didn't yet sent "blur" notification).
420 // Note that this is cleared when the widget is being destroyed.
421 static nsIWidget
* sFocusedIMEWidget
;
422 static StaticRefPtr
<BrowserParent
> sFocusedIMEBrowserParent
;
423 // sActiveInputContextWidget is the last widget whose SetInputContext() is
424 // called. This is important to reduce sync IPC cost with parent process.
425 // If IMEStateManager set input context to different widget, PuppetWidget can
426 // return cached input context safely.
427 // Note that this is cleared when the widget is being destroyed.
428 static nsIWidget
* sActiveInputContextWidget
;
429 // sActiveIMEContentObserver points to the currently active
430 // IMEContentObserver. This is null if there is no focused editor.
431 static StaticRefPtr
<IMEContentObserver
> sActiveIMEContentObserver
;
433 // All active compositions in the process are stored by this array.
434 // When you get an item of this array and use it, please be careful.
435 // The instances in this array can be destroyed automatically if you do
436 // something to cause committing or canceling the composition.
437 static TextCompositionArray
* sTextCompositions
;
439 // Origin type of current process.
440 static InputContext::Origin sOrigin
;
442 // sActiveChildInputContext is valid only when BrowserParent::GetFocused() is
443 // not nullptr. This stores last information of input context in the remote
444 // process of BrowserParent::GetFocused(). I.e., they are set when
445 // SetInputContextForChildProcess() is called. This is necessary for
446 // restoring IME state when menu keyboard listener is uninstalled.
447 static InputContext sActiveChildInputContext
;
449 // sInstalledMenuKeyboardListener is true if menu keyboard listener is
450 // installed in the process.
451 static bool sInstalledMenuKeyboardListener
;
453 static bool sIsGettingNewIMEState
;
454 static bool sCheckForIMEUnawareWebApps
;
456 // Set to true only if this is an instance in a content process and
457 // only while `IMEStateManager::StopIMEStateManagement()`.
458 static bool sCleaningUpForStoppingIMEStateManagement
;
461 // - In the main process, a window belonging to this app is active in the
463 // - In a content process, the process has focus.
465 // This is updated by `OnChangeFocusInternal()` is called in the main
466 // process. Therefore, this indicates the active state which
467 // `IMEStateManager` notified the focus change, there is timelag from
468 // the `nsFocusManager`'s status update. This allows that all methods
469 // to handle something specially when they are called while the process
470 // is being activated or inactivated. E.g., `OnFocusMovedBetweenBrowsers()`
471 // is called twice before `OnChangeFocusInternal()` when the main process
472 // becomes active. In this case, it wants to wait a following call of
473 // `OnChangeFocusInternal()` to keep active composition. See also below.
474 static bool sIsActive
;
476 // While the application is being activated, `OnFocusMovedBetweenBrowsers()`
477 // are called twice before `OnChangeFocusInternal()`. First time, aBlur is
478 // the last focused `BrowserParent` at deactivating and aFocus is always
479 // `nullptr`. Then, it'll be called again with actually focused
480 // `BrowserParent` when a content in a remote process has focus. If we need
481 // to keep active composition while all windows are deactivated, we shouldn't
482 // commit it at the first call since usually, the second call's aFocus
483 // and the first call's aBlur are same `BrowserParent`. For solving this
484 // issue, we need to merge the given `BrowserParent`s of multiple calls of
485 // `OnFocusMovedBetweenBrowsers()`. The following struct is the data for
486 // calling `OnFocusMovedBetweenBrowsers()` later from
487 // `OnChangeFocusInternal()`. Note that focus can be moved even while the
488 // main process is not active because JS can change focus. In such case,
489 // composition is committed at that time. Therefore, this is required only
490 // when the main process is activated and there is a composition in a remote
492 struct PendingFocusedBrowserSwitchingData final
{
493 RefPtr
<BrowserParent
> mBrowserParentBlurred
;
494 RefPtr
<BrowserParent
> mBrowserParentFocused
;
496 PendingFocusedBrowserSwitchingData() = delete;
497 explicit PendingFocusedBrowserSwitchingData(BrowserParent
* aBlur
,
498 BrowserParent
* aFocus
)
499 : mBrowserParentBlurred(aBlur
), mBrowserParentFocused(aFocus
) {}
501 static Maybe
<PendingFocusedBrowserSwitchingData
>
502 sPendingFocusedBrowserSwitchingData
;
504 class MOZ_STACK_CLASS GettingNewIMEStateBlocker final
{
506 GettingNewIMEStateBlocker()
507 : mOldValue(IMEStateManager::sIsGettingNewIMEState
) {
508 IMEStateManager::sIsGettingNewIMEState
= true;
510 ~GettingNewIMEStateBlocker() {
511 IMEStateManager::sIsGettingNewIMEState
= mOldValue
;
518 // OnInstalledMenuKeyboardListener may be called when it's not safe.
519 // Therefore, it tries to update with adding this as a script runner.
520 static StaticRefPtr
<PseudoFocusChangeRunnable
> sPseudoFocusChangeRunnable
;
521 friend class PseudoFocusChangeRunnable
;
524 } // namespace mozilla
526 #endif // mozilla_IMEStateManager_h_