1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=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/. */
12 #include "ErrorList.h"
14 #include "mozilla/AlreadyAddRefed.h"
15 #include "mozilla/Assertions.h"
16 #include "mozilla/Attributes.h"
17 #include "mozilla/EventForwards.h"
18 #include "mozilla/Maybe.h"
19 #include "mozilla/RefPtr.h"
20 #include "mozilla/TimeStamp.h"
21 #include "mozilla/UniquePtr.h"
22 #include "mozilla/gfx/Matrix.h"
23 #include "mozilla/gfx/Rect.h"
24 #include "mozilla/layers/LayersTypes.h"
25 #include "mozilla/layers/ScrollableLayerGuid.h"
26 #include "mozilla/layers/ZoomConstraints.h"
27 #include "mozilla/image/Resolution.h"
28 #include "mozilla/widget/IMEData.h"
33 #include "nsIObserver.h"
34 #include "nsISupports.h"
37 #include "nsIWidgetListener.h"
40 #include "nsStringFwd.h"
42 #include "nsTHashMap.h"
43 #include "mozilla/widget/InitData.h"
44 #include "nsXULAppAPI.h"
46 // forward declarations
47 class nsIBidiKeyboard
;
48 class nsIRollupListener
;
55 enum class NativeKeyBindingsType
: uint8_t;
56 class VsyncDispatcher
;
58 class WidgetInputEvent
;
59 class WidgetKeyboardEvent
;
62 enum class StyleWindowShadow
: uint8_t;
63 enum class ColorScheme
: uint8_t;
64 enum class WindowButtonType
: uint8_t;
66 #if defined(MOZ_WIDGET_ANDROID)
70 #endif // defined(MOZ_WIDGET_ANDROID)
73 enum class CallerType
: uint32_t;
77 class AsyncDragMetrics
;
79 class CompositorBridgeChild
;
82 class WebRenderBridgeChild
;
85 class TextEventDispatcher
;
86 class TextEventDispatcherListener
;
87 class CompositorWidget
;
88 class CompositorWidgetInitData
;
92 class DisplayListBuilder
;
93 class IpcResourceUpdateQueue
;
94 enum class RenderRoot
: uint8_t;
96 } // namespace mozilla
99 * Callback function that processes events.
101 * The argument is actually a subtype (subclass) of WidgetEvent which carries
102 * platform specific information about the event. Platform specific code
103 * knows how to deal with it.
105 * The return value determines whether or not the default action should take
108 typedef nsEventStatus (*EVENT_CALLBACK
)(mozilla::WidgetGUIEvent
* aEvent
);
110 // Hide the native window system's real window type so as to avoid
111 // including native window system types and APIs. This is necessary
112 // to ensure cross-platform code.
113 typedef void* nsNativeWidget
;
116 * Flags for the GetNativeData and SetNativeData functions
118 #define NS_NATIVE_WINDOW 0
119 #define NS_NATIVE_GRAPHIC 1
120 #define NS_NATIVE_TMP_WINDOW 2
121 #define NS_NATIVE_WIDGET 3
122 #define NS_NATIVE_DISPLAY 4
123 #define NS_NATIVE_REGION 5
124 #define NS_NATIVE_OFFSETX 6
125 #define NS_NATIVE_OFFSETY 7
126 #define NS_NATIVE_SCREEN 9
127 // The toplevel GtkWidget containing this nsIWidget:
128 #define NS_NATIVE_SHELLWIDGET 10
129 #define NS_NATIVE_OPENGL_CONTEXT 12
130 // This is available only with GetNativeData() in parent process. Anybody
131 // shouldn't access this pointer as a valid pointer since the result may be
132 // special value like NS_ONLY_ONE_NATIVE_IME_CONTEXT. So, the result is just
133 // an identifier of distinguishing a text composition is caused by which native
134 // IME context. Note that the result is only valid in the process. So,
135 // XP code should use nsIWidget::GetNativeIMEContext() instead of using this.
136 #define NS_RAW_NATIVE_IME_CONTEXT 14
137 #define NS_NATIVE_WINDOW_WEBRTC_DEVICE_ID 15
139 # define NS_NATIVE_TSF_THREAD_MGR 100
140 # define NS_NATIVE_TSF_CATEGORY_MGR 101
141 # define NS_NATIVE_TSF_DISPLAY_ATTR_MGR 102
142 # define NS_NATIVE_ICOREWINDOW 103 // winrt specific
144 #if defined(MOZ_WIDGET_GTK)
145 # define NS_NATIVE_EGL_WINDOW 106
147 #ifdef MOZ_WIDGET_ANDROID
148 # define NS_JAVA_SURFACE 100
151 #define MOZ_WIDGET_MAX_SIZE 16384
152 #define MOZ_WIDGET_INVALID_SCALE 0.0
154 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
155 #define NS_IWIDGET_IID \
157 0x06396bf6, 0x2dd8, 0x45e5, { \
158 0xac, 0x45, 0x75, 0x26, 0x53, 0xb1, 0xc9, 0x80 \
166 enum nsCursor
{ ///(normal cursor, usually rendered as an arrow)
168 ///(system is busy, usually rendered as a hourglass or watch)
170 ///(Selecting something, usually rendered as an IBeam)
172 ///(can hyper-link, usually rendered as a human hand)
174 ///(north/south/west/east edge sizing)
187 eCursor_copy
, // CSS3
189 eCursor_context_menu
,
200 eCursor_vertical_text
,
207 // This one is used for array sizing, and so better be the last
208 // one in this list...
211 // ...except for this one.
212 eCursorInvalid
= eCursorCount
+ 1
215 enum nsTopLevelWidgetZPlacement
{ // for PlaceBehind()
216 eZPlacementBottom
= 0, // bottom of the window stack
217 eZPlacementBelow
, // just below another widget
218 eZPlacementTop
// top of the window stack
222 * Before the OS goes to sleep, this topic is notified.
224 #define NS_WIDGET_SLEEP_OBSERVER_TOPIC "sleep_notification"
227 * After the OS wakes up, this topic is notified.
229 #define NS_WIDGET_WAKE_OBSERVER_TOPIC "wake_notification"
232 * Before the OS suspends the current process, this topic is notified. Some
233 * OS will kill processes that are suspended instead of resuming them.
234 * For that reason this topic may be useful to safely close down resources.
236 #define NS_WIDGET_SUSPEND_PROCESS_OBSERVER_TOPIC "suspend_process_notification"
239 * After the current process resumes from being suspended, this topic is
242 #define NS_WIDGET_RESUME_PROCESS_OBSERVER_TOPIC "resume_process_notification"
245 * When an app(-shell) is activated by the OS, this topic is notified.
246 * Currently, this only happens on Mac OSX.
248 #define NS_WIDGET_MAC_APP_ACTIVATE_OBSERVER_TOPIC "mac_app_activate"
250 namespace mozilla::widget
{
253 * Size constraints for setting the minimum and maximum size of a widget.
254 * Values are in device pixels.
256 struct SizeConstraints
{
258 : mMaxSize(MOZ_WIDGET_MAX_SIZE
, MOZ_WIDGET_MAX_SIZE
),
259 mScale(MOZ_WIDGET_INVALID_SCALE
) {}
261 SizeConstraints(mozilla::LayoutDeviceIntSize aMinSize
,
262 mozilla::LayoutDeviceIntSize aMaxSize
,
263 mozilla::DesktopToLayoutDeviceScale aScale
)
264 : mMinSize(aMinSize
), mMaxSize(aMaxSize
), mScale(aScale
) {
265 if (mMaxSize
.width
> MOZ_WIDGET_MAX_SIZE
) {
266 mMaxSize
.width
= MOZ_WIDGET_MAX_SIZE
;
268 if (mMaxSize
.height
> MOZ_WIDGET_MAX_SIZE
) {
269 mMaxSize
.height
= MOZ_WIDGET_MAX_SIZE
;
273 mozilla::LayoutDeviceIntSize mMinSize
;
274 mozilla::LayoutDeviceIntSize mMaxSize
;
277 * The scale used to convert from desktop to device dimensions.
278 * MOZ_WIDGET_INVALID_SCALE if the value is not known.
280 * Bug 1701109 is filed to revisit adding of 'mScale' and deal
281 * with multi-monitor scaling issues in more complete way across
282 * all widget implementations.
284 mozilla::DesktopToLayoutDeviceScale mScale
;
287 struct AutoObserverNotifier
{
288 AutoObserverNotifier(nsIObserver
* aObserver
, const char* aTopic
)
289 : mObserver(aObserver
), mTopic(aTopic
) {}
291 void SkipNotification() { mObserver
= nullptr; }
293 uint64_t SaveObserver() {
297 uint64_t observerId
= ++sObserverId
;
298 sSavedObservers
.InsertOrUpdate(observerId
, mObserver
);
303 ~AutoObserverNotifier() {
305 mObserver
->Observe(nullptr, mTopic
, nullptr);
309 static void NotifySavedObserver(const uint64_t& aObserverId
,
310 const char* aTopic
) {
311 nsCOMPtr
<nsIObserver
> observer
= sSavedObservers
.Get(aObserverId
);
313 MOZ_ASSERT(aObserverId
== 0,
314 "We should always find a saved observer for nonzero IDs");
318 sSavedObservers
.Remove(aObserverId
);
319 observer
->Observe(nullptr, aTopic
, nullptr);
323 nsCOMPtr
<nsIObserver
> mObserver
;
327 static uint64_t sObserverId
;
328 static nsTHashMap
<uint64_t, nsCOMPtr
<nsIObserver
>> sSavedObservers
;
331 } // namespace mozilla::widget
334 * The base class for all the widgets. It provides the interface for
335 * all basic and necessary functionality.
337 class nsIWidget
: public nsISupports
{
339 typedef mozilla::dom::BrowserChild BrowserChild
;
342 typedef mozilla::layers::CompositorBridgeChild CompositorBridgeChild
;
343 typedef mozilla::layers::AsyncDragMetrics AsyncDragMetrics
;
344 typedef mozilla::layers::FrameMetrics FrameMetrics
;
345 typedef mozilla::layers::LayerManager LayerManager
;
346 typedef mozilla::WindowRenderer WindowRenderer
;
347 typedef mozilla::layers::LayersBackend LayersBackend
;
348 typedef mozilla::layers::LayersId LayersId
;
349 typedef mozilla::layers::ScrollableLayerGuid ScrollableLayerGuid
;
350 typedef mozilla::layers::ZoomConstraints ZoomConstraints
;
351 typedef mozilla::widget::IMEEnabled IMEEnabled
;
352 typedef mozilla::widget::IMEMessage IMEMessage
;
353 typedef mozilla::widget::IMENotification IMENotification
;
354 typedef mozilla::widget::IMENotificationRequests IMENotificationRequests
;
355 typedef mozilla::widget::IMEState IMEState
;
356 typedef mozilla::widget::InputContext InputContext
;
357 typedef mozilla::widget::InputContextAction InputContextAction
;
358 typedef mozilla::widget::NativeIMEContext NativeIMEContext
;
359 typedef mozilla::widget::SizeConstraints SizeConstraints
;
360 typedef mozilla::widget::TextEventDispatcher TextEventDispatcher
;
361 typedef mozilla::widget::TextEventDispatcherListener
362 TextEventDispatcherListener
;
363 typedef mozilla::LayoutDeviceIntMargin LayoutDeviceIntMargin
;
364 typedef mozilla::LayoutDeviceIntPoint LayoutDeviceIntPoint
;
365 typedef mozilla::LayoutDeviceIntRect LayoutDeviceIntRect
;
366 typedef mozilla::LayoutDeviceIntRegion LayoutDeviceIntRegion
;
367 typedef mozilla::LayoutDeviceIntSize LayoutDeviceIntSize
;
368 typedef mozilla::ScreenIntPoint ScreenIntPoint
;
369 typedef mozilla::ScreenIntMargin ScreenIntMargin
;
370 typedef mozilla::ScreenIntSize ScreenIntSize
;
371 typedef mozilla::ScreenPoint ScreenPoint
;
372 typedef mozilla::CSSToScreenScale CSSToScreenScale
;
373 typedef mozilla::DesktopIntRect DesktopIntRect
;
374 typedef mozilla::DesktopPoint DesktopPoint
;
375 typedef mozilla::DesktopRect DesktopRect
;
376 typedef mozilla::DesktopSize DesktopSize
;
377 typedef mozilla::CSSPoint CSSPoint
;
378 typedef mozilla::CSSRect CSSRect
;
380 using InitData
= mozilla::widget::InitData
;
381 using WindowType
= mozilla::widget::WindowType
;
382 using PopupType
= mozilla::widget::PopupType
;
383 using PopupLevel
= mozilla::widget::PopupLevel
;
384 using BorderStyle
= mozilla::widget::BorderStyle
;
385 using TransparencyMode
= mozilla::widget::TransparencyMode
;
386 using Screen
= mozilla::widget::Screen
;
388 // Used in UpdateThemeGeometries.
389 struct ThemeGeometry
{
390 // The ThemeGeometryType value for the themed widget, see
391 // nsITheme::ThemeGeometryTypeForWidget.
392 nsITheme::ThemeGeometryType mType
;
393 // The device-pixel rect within the window for the themed widget
394 LayoutDeviceIntRect mRect
;
396 ThemeGeometry(nsITheme::ThemeGeometryType aType
,
397 const LayoutDeviceIntRect
& aRect
)
398 : mType(aType
), mRect(aRect
) {}
401 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWIDGET_IID
)
404 : mLastChild(nullptr),
405 mPrevSibling(nullptr),
406 mOnDestroyCalled(false),
407 mWindowType(WindowType::Child
),
411 ClearNativeTouchSequence(nullptr);
415 * Create and initialize a widget.
417 * All the arguments can be null in which case a top level window
418 * with size 0 is created. The event callback function has to be
419 * provided only if the caller wants to deal with the events this
420 * widget receives. The event callback is basically a preprocess
421 * hook called synchronously. The return value determines whether
422 * the event goes to the default window procedure or it is hidden
423 * to the os. The assumption is that if the event handler returns
424 * false the widget does not see the event. The widget should not
425 * automatically clear the window to the background color. The
426 * calling code must handle paint messages and clear the background
429 * In practice at least one of aParent and aNativeParent will be null. If
430 * both are null the widget isn't parented (e.g. context menus or
431 * independent top level windows).
433 * The dimensions given in aRect are specified in the parent's
434 * device coordinate system.
435 * This must not be called for parentless widgets such as top-level
436 * windows, which use the desktop pixel coordinate system; a separate
437 * method is provided for these.
439 * @param aParent parent nsIWidget
440 * @param aNativeParent native parent widget
441 * @param aRect the widget dimension
442 * @param aInitData data that is used for widget initialization
445 [[nodiscard
]] virtual nsresult
Create(nsIWidget
* aParent
,
446 nsNativeWidget aNativeParent
,
447 const LayoutDeviceIntRect
& aRect
,
448 InitData
* = nullptr) = 0;
451 * As above, but with aRect specified in DesktopPixel units (for top-level
453 * Default implementation just converts aRect to device pixels and calls
454 * through to device-pixel Create, but platforms may override this if the
455 * mapping is not straightforward or the native platform needs to use the
456 * desktop pixel values directly.
458 [[nodiscard
]] virtual nsresult
Create(nsIWidget
* aParent
,
459 nsNativeWidget aNativeParent
,
460 const DesktopIntRect
& aRect
,
461 InitData
* aInitData
= nullptr) {
462 LayoutDeviceIntRect devPixRect
=
463 RoundedToInt(aRect
* GetDesktopToDeviceScale());
464 return Create(aParent
, aNativeParent
, devPixRect
, aInitData
);
468 * Allocate, initialize, and return a widget that is a child of
469 * |this|. The returned widget (if nonnull) has gone through the
470 * equivalent of CreateInstance(widgetCID) + Create(...).
472 * |CreateChild()| lets widget backends decide whether to parent
473 * the new child widget to this, nonnatively parent it, or both.
474 * This interface exists to support the PuppetWidget backend,
475 * which is entirely non-native. All other params are the same as
478 * |aForceUseIWidgetParent| forces |CreateChild()| to only use the
479 * |nsIWidget*| this, not its native widget (if it exists), when
480 * calling |Create()|. This is a timid hack around poorly
481 * understood code, and shouldn't be used in new code.
483 virtual already_AddRefed
<nsIWidget
> CreateChild(
484 const LayoutDeviceIntRect
& aRect
, InitData
* = nullptr,
485 bool aForceUseIWidgetParent
= false) = 0;
488 * Attach to a top level widget.
490 * In cases where a top level chrome widget is being used as a content
491 * container, attach a secondary listener and update the device
492 * context. The primary widget listener will continue to be called for
493 * notifications relating to the top-level window, whereas other
494 * notifications such as painting and events will instead be called via
495 * the attached listener. SetAttachedWidgetListener should be used to
496 * assign the attached listener.
498 * aUseAttachedEvents if true, events are sent to the attached listener
499 * instead of the normal listener.
501 virtual void AttachViewToTopLevel(bool aUseAttachedEvents
) = 0;
504 * Accessor functions to get and set the attached listener. Used by
505 * nsView in connection with AttachViewToTopLevel above.
507 virtual void SetAttachedWidgetListener(nsIWidgetListener
* aListener
) = 0;
508 virtual nsIWidgetListener
* GetAttachedWidgetListener() const = 0;
509 virtual void SetPreviouslyAttachedWidgetListener(
510 nsIWidgetListener
* aListener
) = 0;
511 virtual nsIWidgetListener
* GetPreviouslyAttachedWidgetListener() = 0;
514 * Notifies the root widget of a non-blank paint.
516 virtual void DidGetNonBlankPaint() {}
519 * Accessor functions to get and set the listener which handles various
520 * actions for the widget.
523 virtual nsIWidgetListener
* GetWidgetListener() const = 0;
524 virtual void SetWidgetListener(nsIWidgetListener
* alistener
) = 0;
528 * Close and destroy the internal native window.
529 * This method does not delete the widget.
532 virtual void Destroy() = 0;
535 * Destroyed() returns true if Destroy() has been called already.
538 bool Destroyed() const { return mOnDestroyCalled
; }
543 * Change the widget's parent. Null parents are allowed.
545 * @param aNewParent new parent
547 virtual void SetParent(nsIWidget
* aNewParent
) = 0;
550 * Return the parent Widget of this Widget or nullptr if this is a
553 * @return the parent widget or nullptr if it does not have a parent
556 virtual nsIWidget
* GetParent(void) = 0;
559 * Return the top level Widget of this Widget
561 * @return the top level widget
563 virtual nsIWidget
* GetTopLevelWidget() = 0;
566 * Return the top (non-sheet) parent of this Widget if it's a sheet,
567 * or nullptr if this isn't a sheet (or some other error occurred).
568 * Sheets are only supported on some platforms (currently only macOS).
570 * @return the top (non-sheet) parent widget or nullptr
573 virtual nsIWidget
* GetSheetWindowParent(void) = 0;
576 * Return the physical DPI of the screen containing the window ...
577 * the number of device pixels per inch.
579 virtual float GetDPI() = 0;
582 * Fallback DPI for when there's no widget available.
584 static float GetFallbackDPI();
587 * Return the scaling factor between device pixels and the platform-
588 * dependent "desktop pixels" used to manage window positions on a
589 * potentially multi-screen, mixed-resolution desktop.
591 virtual mozilla::DesktopToLayoutDeviceScale
GetDesktopToDeviceScale() = 0;
594 * Return the scaling factor between device pixels and the platform-
595 * dependent "desktop pixels" by looking up the screen by the position
598 virtual mozilla::DesktopToLayoutDeviceScale
599 GetDesktopToDeviceScaleByScreen() = 0;
602 * Return the default scale factor for the window. This is the
603 * default number of device pixels per CSS pixel to use. This should
604 * depend on OS/platform settings such as the Mac's "UI scale factor"
605 * or Windows' "font DPI". This will take into account Gecko preferences
606 * overriding the system setting.
608 mozilla::CSSToLayoutDeviceScale
GetDefaultScale();
611 * Fallback default scale for when there's no widget available.
613 static mozilla::CSSToLayoutDeviceScale
GetFallbackDefaultScale();
616 * Return the first child of this widget. Will return null if
617 * there are no children.
619 nsIWidget
* GetFirstChild() const { return mFirstChild
; }
622 * Return the last child of this widget. Will return null if
623 * there are no children.
625 nsIWidget
* GetLastChild() const { return mLastChild
; }
628 * Return the next sibling of this widget
630 nsIWidget
* GetNextSibling() const { return mNextSibling
; }
633 * Set the next sibling of this widget
635 void SetNextSibling(nsIWidget
* aSibling
) { mNextSibling
= aSibling
; }
638 * Return the previous sibling of this widget
640 nsIWidget
* GetPrevSibling() const { return mPrevSibling
; }
643 * Set the previous sibling of this widget
645 void SetPrevSibling(nsIWidget
* aSibling
) { mPrevSibling
= aSibling
; }
648 * Show or hide this widget
650 * @param aState true to show the Widget, false to hide it
653 virtual void Show(bool aState
) = 0;
656 * Whether or not a widget must be recreated after being hidden to show
659 virtual bool NeedsRecreateToReshow() { return false; }
662 * Make the window modal.
664 virtual void SetModal(bool aModal
) = 0;
667 * Make the non-modal window opened by modal window fake-modal, that will
668 * call SetFakeModal(false) on destroy on Cocoa.
670 virtual void SetFakeModal(bool aModal
) { SetModal(aModal
); }
673 * Are we app modal. Currently only implemented on Cocoa.
675 virtual bool IsRunningAppModal() { return false; }
678 * The maximum number of simultaneous touch contacts supported by the device.
679 * In the case of devices with multiple digitizers (e.g. multiple touch
680 * screens), the value will be the maximum of the set of maximum supported
681 * contacts by each individual digitizer.
683 virtual uint32_t GetMaxTouchPoints() const = 0;
686 * Returns whether the window is visible
689 virtual bool IsVisible() const = 0;
692 * Perform platform-dependent sanity check on a potential window position.
693 * This is guaranteed to work only for top-level windows.
695 * @param aAllowSlop: if true, allow the window to slop offscreen;
696 * the window should be partially visible. if false,
697 * force the entire window onscreen (or at least
698 * the upper-left corner, if it's too large).
699 * @param aX in: an x position expressed in screen coordinates.
700 * out: the x position constrained to fit on the screen(s).
701 * @param aY in: an y position expressed in screen coordinates.
702 * out: the y position constrained to fit on the screen(s).
705 virtual void ConstrainPosition(bool aAllowSlop
, int32_t* aX
, int32_t* aY
) = 0;
710 * For a top-level window widget, the "parent's coordinate system" is the
711 * "global" display pixel coordinate space, *not* device pixels (which
712 * may be inconsistent between multiple screens, at least in the Mac OS
713 * case with mixed hi-dpi and lo-dpi displays). This applies to all the
714 * following Move and Resize widget APIs.
716 * The display-/device-pixel distinction becomes important for (at least)
717 * macOS with Hi-DPI (retina) displays, and Windows when the UI scale factor
718 * is set to other than 100%.
720 * The Move and Resize methods take floating-point parameters, rather than
721 * integer ones. This is important when manipulating top-level widgets,
722 * where the coordinate system may not be an integral multiple of the
723 * device-pixel space.
729 * Coordinates refer to the top-left of the widget. For toplevel windows
730 * with decorations, this is the top-left of the titlebar and frame .
732 * @param aX the new x position expressed in the parent's coordinate system
733 * @param aY the new y position expressed in the parent's coordinate system
736 virtual void Move(double aX
, double aY
) = 0;
739 * Reposition this widget so that the client area has the given offset.
741 * @param aOffset the new offset of the client area expressed as an
742 * offset from the origin of the client area of the parent
743 * widget (for root widgets and popup widgets it is in
744 * screen coordinates)
746 virtual void MoveClient(const DesktopPoint
& aOffset
) = 0;
749 * Resize this widget. Any size constraints set for the window by a
750 * previous call to SetSizeConstraints will be applied.
752 * @param aWidth the new width expressed in the parent's coordinate system
753 * @param aHeight the new height expressed in the parent's coordinate
755 * @param aRepaint whether the widget should be repainted
757 virtual void Resize(double aWidth
, double aHeight
, bool aRepaint
) = 0;
760 * Lock the aspect ratio of a Window
762 * @param aShouldLock bool
765 virtual void LockAspectRatio(bool aShouldLock
){};
768 * Move or resize this widget. Any size constraints set for the window by
769 * a previous call to SetSizeConstraints will be applied.
771 * @param aX the new x position expressed in the parent's coordinate
773 * @param aY the new y position expressed in the parent's coordinate
775 * @param aWidth the new width expressed in the parent's coordinate system
776 * @param aHeight the new height expressed in the parent's coordinate
778 * @param aRepaint whether the widget should be repainted if the size
782 virtual void Resize(double aX
, double aY
, double aWidth
, double aHeight
,
785 virtual mozilla::Maybe
<bool> IsResizingNativeWidget() {
786 return mozilla::Nothing();
790 * Resize the widget so that the inner client area has the given size.
792 * @param aSize the new size of the client area.
793 * @param aRepaint whether the widget should be repainted
795 virtual void ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) = 0;
798 * Resize and reposition the widget so tht inner client area has the given
801 * @param aRect the new offset and size of the client area. The offset is
802 * expressed as an offset from the origin of the client area
803 * of the parent widget (for root widgets and popup widgets it
804 * is in screen coordinates).
805 * @param aRepaint whether the widget should be repainted
807 virtual void ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) = 0;
810 * Sets the widget's z-index.
812 virtual void SetZIndex(int32_t aZIndex
) = 0;
815 * Gets the widget's z-index.
817 int32_t GetZIndex() { return mZIndex
; }
820 * Position this widget just behind the given widget. (Used to
821 * control z-order for top-level widgets. Get/SetZIndex by contrast
822 * control z-order for child widgets of other widgets.)
823 * @param aPlacement top, bottom, or below a widget
824 * (if top or bottom, param aWidget is ignored)
825 * @param aWidget widget to place this widget behind
826 * (only if aPlacement is eZPlacementBelow).
827 * null is equivalent to aPlacement of eZPlacementTop
828 * @param aActivate true to activate the widget after placing it
830 virtual void PlaceBehind(nsTopLevelWidgetZPlacement aPlacement
,
831 nsIWidget
* aWidget
, bool aActivate
) = 0;
834 * Minimize, maximize or normalize the window size.
835 * Takes a value from nsSizeMode (see nsIWidgetListener.h)
837 virtual void SetSizeMode(nsSizeMode aMode
) = 0;
839 virtual void GetWorkspaceID(nsAString
& workspaceID
) = 0;
841 virtual void MoveToWorkspace(const nsAString
& workspaceID
) = 0;
844 * Suppress animations that are applied to a window by OS.
846 virtual void SuppressAnimation(bool aSuppress
) {}
849 * Return size mode (minimized, maximized, normalized).
850 * Returns a value from nsSizeMode (see nsIWidgetListener.h)
852 virtual nsSizeMode
SizeMode() = 0;
855 * Ask whether the window is tiled.
857 virtual bool IsTiled() const = 0;
860 * Ask wether the widget is fully occluded
862 virtual bool IsFullyOccluded() const = 0;
865 * Enable or disable this Widget
867 * @param aState true to enable the Widget, false to disable it.
869 virtual void Enable(bool aState
) = 0;
872 * Ask whether the widget is enabled
874 virtual bool IsEnabled() const = 0;
877 * Whether we should request activation of this widget's toplevel window.
885 * Request activation of this window or give focus to this widget.
887 virtual void SetFocus(Raise
, mozilla::dom::CallerType aCallerType
) = 0;
890 * Get this widget's outside dimensions relative to its parent widget. For
891 * popup widgets the returned rect is in screen coordinates and not
892 * relative to its parent widget.
894 * @return the x, y, width and height of this widget.
896 virtual LayoutDeviceIntRect
GetBounds() = 0;
899 * Get this widget's outside dimensions in device coordinates. This
900 * includes any title bar on the window.
902 * @return the x, y, width and height of this widget.
904 virtual LayoutDeviceIntRect
GetScreenBounds() = 0;
907 * Similar to GetScreenBounds except that this function will always
908 * get the size when the widget is in the nsSizeMode_Normal size mode
909 * even if the current size mode is not nsSizeMode_Normal.
910 * This method will fail if the size mode is not nsSizeMode_Normal and
911 * the platform doesn't have the ability.
912 * This method will always succeed if the current size mode is
915 * @param aRect On return it holds the x, y, width and height of
918 [[nodiscard
]] virtual nsresult
GetRestoredBounds(
919 LayoutDeviceIntRect
& aRect
) = 0;
922 * Get this widget's client area bounds, if the window has a 3D border
923 * appearance this returns the area inside the border. The position is the
924 * position of the client area relative to the client area of the parent
925 * widget (for root widgets and popup widgets it is in screen coordinates).
927 * @return the x, y, width and height of the client area of this widget.
929 virtual LayoutDeviceIntRect
GetClientBounds() = 0;
932 * Sets the non-client area dimensions of the window. Pass -1 to restore
933 * the system default frame size for that border. Pass zero to remove
934 * a border, or pass a specific value adjust a border. Units are in
935 * pixels. (DPI dependent)
938 * Windows: shrinking top non-client height will remove application
939 * icon and window title text. Glass desktops will refuse to set
940 * dimensions between zero and size < system default.
942 virtual nsresult
SetNonClientMargins(const LayoutDeviceIntMargin
&) = 0;
945 * Sets the region around the edges of the window that can be dragged to
946 * resize the window. All four sides of the window will get the same margin.
948 virtual void SetResizeMargin(mozilla::LayoutDeviceIntCoord aResizeMargin
) = 0;
950 * Get the client offset from the window origin.
952 * @return the x and y of the offset.
954 virtual LayoutDeviceIntPoint
GetClientOffset() = 0;
957 * Equivalent to GetClientBounds but only returns the size.
959 virtual LayoutDeviceIntSize
GetClientSize() {
960 // Depending on the backend, overloading this method may be useful if
961 // requesting the client offset is expensive.
962 return GetClientBounds().Size();
966 * Set the background color for this widget
968 * @param aColor the new background color
972 virtual void SetBackgroundColor(const nscolor
& aColor
) {}
975 * If a cursor type is currently cached locally for this widget, clear the
976 * cached cursor to force an update on the next SetCursor call.
979 virtual void ClearCachedCursor() = 0;
982 // The system cursor chosen by the page. This is used if there's no custom
983 // cursor, or if we fail to use the custom cursor in some way (if the image
984 // fails to load, for example).
985 nsCursor mDefaultCursor
= eCursor_standard
;
986 // May be null, to represent no custom cursor image.
987 nsCOMPtr
<imgIContainer
> mContainer
;
988 uint32_t mHotspotX
= 0;
989 uint32_t mHotspotY
= 0;
990 mozilla::ImageResolution mResolution
;
992 bool IsCustom() const { return !!mContainer
; }
994 bool operator==(const Cursor
& aOther
) const {
995 return mDefaultCursor
== aOther
.mDefaultCursor
&&
996 mContainer
.get() == aOther
.mContainer
.get() &&
997 mHotspotX
== aOther
.mHotspotX
&& mHotspotY
== aOther
.mHotspotY
&&
998 mResolution
== aOther
.mResolution
;
1001 bool operator!=(const Cursor
& aOther
) const { return !(*this == aOther
); }
1005 * Sets the cursor for this widget.
1007 virtual void SetCursor(const Cursor
&) = 0;
1009 static nsIntSize
CustomCursorSize(const Cursor
&);
1012 * Get the window type of this widget.
1014 WindowType
GetWindowType() const { return mWindowType
; }
1017 * Set the transparency mode of the top-level window containing this widget.
1018 * So, e.g., if you call this on the widget for an IFRAME, the top level
1019 * browser window containing the IFRAME actually gets set. Be careful.
1021 * This can fail if the platform doesn't support
1022 * transparency/glass. By default widgets are not
1023 * transparent. This will also fail if the toplevel window is not
1024 * a Mozilla window, e.g., if the widget is in an embedded
1027 * After transparency/glass has been enabled, the initial alpha channel
1028 * value for all pixels is 1, i.e., opaque.
1029 * If the window is resized then the alpha channel values for
1030 * all pixels are reset to 1.
1031 * Pixel RGB color values are already premultiplied with alpha channel values.
1033 virtual void SetTransparencyMode(TransparencyMode aMode
) = 0;
1036 * Get the transparency mode of the top-level window that contains this
1039 virtual TransparencyMode
GetTransparencyMode() = 0;
1042 * Set the shadow style of the window.
1044 * Ignored on child widgets and on non-Mac platforms.
1046 virtual void SetWindowShadowStyle(mozilla::StyleWindowShadow aStyle
) = 0;
1049 * Set the opacity of the window.
1050 * Values need to be between 0.0f (invisible) and 1.0f (fully opaque).
1052 * Ignored on child widgets and on non-Mac platforms.
1054 virtual void SetWindowOpacity(float aOpacity
) {}
1057 * Set the transform of the window. Values are in device pixels,
1058 * the origin is the top left corner of the window.
1060 * Ignored on child widgets and on non-Mac platforms.
1062 virtual void SetWindowTransform(const mozilla::gfx::Matrix
& aTransform
) {}
1065 * Set the preferred color-scheme for the widget.
1066 * Ignored on non-Mac platforms.
1068 virtual void SetColorScheme(const mozilla::Maybe
<mozilla::ColorScheme
>&) {}
1071 * Set whether the window should ignore mouse events or not, and if it should
1072 * not, what input margin should it use.
1074 * This is only used on popup windows. The margin is only implemented on
1077 struct InputRegion
{
1078 bool mFullyTransparent
= false;
1079 mozilla::LayoutDeviceIntCoord mMargin
= 0;
1081 virtual void SetInputRegion(const InputRegion
&) {}
1084 * On macOS, this method shows or hides the pill button in the titlebar
1085 * that's used to collapse the toolbar.
1087 * Ignored on child widgets and on non-Mac platforms.
1089 virtual void SetShowsToolbarButton(bool aShow
) = 0;
1092 * On macOS, this method determines whether we tell cocoa that the window
1093 * supports native full screen. If we do so, and another window is in
1094 * native full screen, this window will also appear in native full screen.
1096 * We generally only want to do this for primary application windows.
1098 * Ignored on child widgets and on non-Mac platforms.
1100 virtual void SetSupportsNativeFullscreen(bool aSupportsNativeFullscreen
) = 0;
1102 enum WindowAnimationType
{
1103 eGenericWindowAnimation
,
1104 eDocumentWindowAnimation
1108 * Sets the kind of top-level window animation this widget should have. On
1109 * macOS, this causes a particular kind of animation to be shown when the
1110 * window is first made visible.
1112 * Ignored on child widgets and on non-Mac platforms.
1114 virtual void SetWindowAnimationType(WindowAnimationType aType
) = 0;
1117 * Specifies whether the window title should be drawn even if the window
1118 * contents extend into the titlebar. Ignored on windows that don't draw
1119 * in the titlebar. Only implemented on macOS.
1121 virtual void SetDrawsTitle(bool aDrawTitle
) {}
1124 * Hide window chrome (borders, buttons) for this widget.
1127 virtual void HideWindowChrome(bool aShouldHide
) = 0;
1129 enum FullscreenTransitionStage
{
1130 eBeforeFullscreenToggle
,
1131 eAfterFullscreenToggle
1135 * Prepares for fullscreen transition and returns whether the widget
1136 * supports fullscreen transition. If this method returns false,
1137 * PerformFullscreenTransition() must never be called. Otherwise,
1138 * caller should call that method twice with "before" and "after"
1139 * stages respectively in order. In the latter case, this method may
1140 * return some data via aData pointer. Caller must pass that data to
1141 * PerformFullscreenTransition() if any, and caller is responsible
1142 * for releasing that data.
1144 virtual bool PrepareForFullscreenTransition(nsISupports
** aData
) = 0;
1147 * Performs fullscreen transition. This method returns immediately,
1148 * and will post aCallback to the main thread when the transition
1151 virtual void PerformFullscreenTransition(FullscreenTransitionStage aStage
,
1154 nsIRunnable
* aCallback
) = 0;
1157 * Perform any actions needed after the fullscreen transition has ended.
1159 virtual void CleanupFullscreenTransition() = 0;
1162 * Return the screen the widget is in, or null if we don't know.
1164 virtual already_AddRefed
<Screen
> GetWidgetScreen() = 0;
1167 * Put the toplevel window into or out of fullscreen mode.
1169 * @return NS_OK if the widget is setup properly for fullscreen and
1170 * FullscreenChanged callback has been or will be called. If other
1171 * value is returned, the caller should continue the change itself.
1173 virtual nsresult
MakeFullScreen(bool aFullScreen
) = 0;
1176 * Same as MakeFullScreen, except that, on systems which natively
1177 * support fullscreen transition, calling this method explicitly
1178 * requests that behavior.
1179 * It is currently only supported on macOS 10.7+.
1181 virtual nsresult
MakeFullScreenWithNativeTransition(bool aFullScreen
) {
1182 return MakeFullScreen(aFullScreen
);
1186 * Invalidate a specified rect for a widget so that it will be repainted
1189 virtual void Invalidate(const LayoutDeviceIntRect
& aRect
) = 0;
1191 enum LayerManagerPersistence
{
1192 LAYER_MANAGER_CURRENT
= 0,
1193 LAYER_MANAGER_PERSISTENT
1197 * Return the widget's LayerManager. The layer tree for that LayerManager is
1198 * what gets rendered to the widget.
1200 * Note that this tries to create a renderer if it doesn't exist.
1202 virtual WindowRenderer
* GetWindowRenderer() = 0;
1205 * Returns whether there's an existing window renderer.
1207 virtual bool HasWindowRenderer() const = 0;
1210 * Called before each layer manager transaction to allow any preparation
1211 * for DrawWindowUnderlay/Overlay that needs to be on the main thread.
1213 * Always called on the main thread.
1215 virtual void PrepareWindowEffects() = 0;
1218 * Called on the main thread at the end of WebRender display list building.
1220 virtual void AddWindowOverlayWebRenderCommands(
1221 mozilla::layers::WebRenderBridgeChild
* aWrBridge
,
1222 mozilla::wr::DisplayListBuilder
& aBuilder
,
1223 mozilla::wr::IpcResourceUpdateQueue
& aResources
) {}
1226 * Called when Gecko knows which themed widgets exist in this window.
1227 * The passed array contains an entry for every themed widget of the right
1228 * type (currently only StyleAppearance::Toolbar) within the window, except
1229 * for themed widgets which are transformed or have effects applied to them
1230 * (e.g. CSS opacity or filters).
1231 * This could sometimes be called during display list construction
1232 * outside of painting.
1233 * If called during painting, it will be called before we actually
1236 virtual void UpdateThemeGeometries(
1237 const nsTArray
<ThemeGeometry
>& aThemeGeometries
) = 0;
1240 * Informs the widget about the region of the window that is opaque.
1242 * @param aOpaqueRegion the region of the window that is opaque.
1244 virtual void UpdateOpaqueRegion(const LayoutDeviceIntRegion
& aOpaqueRegion
) {}
1247 * Informs the widget about the region of the window that is draggable.
1249 virtual void UpdateWindowDraggingRegion(
1250 const LayoutDeviceIntRegion
& aRegion
) {}
1253 * Tells the widget whether the given input block results in a swipe.
1254 * Should be called in response to a WidgetWheelEvent that has
1255 * mFlags.mCanTriggerSwipe set on it.
1257 virtual void ReportSwipeStarted(uint64_t aInputBlockId
, bool aStartSwipe
) {}
1264 virtual void AddChild(nsIWidget
* aChild
) = 0;
1265 virtual void RemoveChild(nsIWidget
* aChild
) = 0;
1266 virtual void* GetNativeData(uint32_t aDataType
) = 0;
1267 virtual void SetNativeData(uint32_t aDataType
, uintptr_t aVal
) = 0;
1268 virtual void FreeNativeData(void* data
, uint32_t aDataType
) = 0; //~~~
1273 * Set the widget's title.
1274 * Must be called after Create.
1276 * @param aTitle string displayed as the title of the widget
1278 virtual nsresult
SetTitle(const nsAString
& aTitle
) = 0;
1281 * Set the widget's icon.
1282 * Must be called after Create.
1284 * @param aIconSpec string specifying the icon to use; convention is to
1285 * pass a resource: URL from which a platform-dependent
1286 * resource file name will be constructed
1288 virtual void SetIcon(const nsAString
& aIconSpec
) = 0;
1291 * Return this widget's origin in screen coordinates.
1293 * @return screen coordinates stored in the x,y members
1295 virtual LayoutDeviceIntPoint
WidgetToScreenOffset() = 0;
1298 * The same as WidgetToScreenOffset(), except in the case of
1299 * PuppetWidget where this method omits the chrome offset.
1301 virtual LayoutDeviceIntPoint
TopLevelWidgetToScreenOffset() {
1302 return WidgetToScreenOffset();
1306 * For a PuppetWidget, returns the transform from the coordinate
1307 * space of the PuppetWidget to the coordinate space of the
1308 * top-level native widget.
1310 * Identity transform in other cases.
1312 virtual mozilla::LayoutDeviceToLayoutDeviceMatrix4x4
1313 WidgetToTopLevelWidgetTransform() {
1314 return mozilla::LayoutDeviceToLayoutDeviceMatrix4x4();
1317 mozilla::LayoutDeviceIntPoint
WidgetToTopLevelWidgetOffset() {
1318 return mozilla::LayoutDeviceIntPoint::Round(
1319 WidgetToTopLevelWidgetTransform().TransformPoint(
1320 mozilla::LayoutDevicePoint()));
1324 * Returns the margins that are applied to go from client sizes to window
1325 * sizes (which includes window borders and titlebar).
1326 * This method should work even when the window is not yet visible.
1328 virtual LayoutDeviceIntMargin
ClientToWindowMargin() { return {}; }
1330 LayoutDeviceIntSize
ClientToWindowSizeDifference();
1333 * Dispatches an event to the widget
1335 virtual nsresult
DispatchEvent(mozilla::WidgetGUIEvent
* event
,
1336 nsEventStatus
& aStatus
) = 0;
1339 * Dispatches an event to APZ only.
1340 * No-op in the child process.
1342 virtual void DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) = 0;
1345 * Dispatch a gecko event for this widget.
1346 * Returns true if it's consumed. Otherwise, false.
1348 virtual bool DispatchWindowEvent(mozilla::WidgetGUIEvent
& event
) = 0;
1350 // A structure that groups the statuses from APZ dispatch and content
1352 struct ContentAndAPZEventStatus
{
1353 // Either of these may not be set if the event was not dispatched
1354 // to APZ or to content.
1355 nsEventStatus mApzStatus
= nsEventStatus_eIgnore
;
1356 nsEventStatus mContentStatus
= nsEventStatus_eIgnore
;
1360 * Dispatches an event that must be handled by APZ first, when APZ is
1361 * enabled. If invoked in the child process, it is forwarded to the
1362 * parent process synchronously.
1364 virtual ContentAndAPZEventStatus
DispatchInputEvent(
1365 mozilla::WidgetInputEvent
* aEvent
) = 0;
1368 * Confirm an APZ-aware event target. This should be used when APZ will
1369 * not need a layers update to process the event.
1371 virtual void SetConfirmedTargetAPZC(
1372 uint64_t aInputBlockId
,
1373 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const = 0;
1376 * Returns true if APZ is in use, false otherwise.
1378 virtual bool AsyncPanZoomEnabled() const = 0;
1382 virtual void SwipeFinished() = 0;
1385 * Enables the dropping of files to a widget.
1387 virtual void EnableDragDrop(bool aEnable
) = 0;
1388 virtual nsresult
AsyncEnableDragDrop(bool aEnable
) = 0;
1391 * Classify the window for the window manager. Mostly for X11.
1393 * @param xulWinType The window type. Characters other than [A-Za-z0-9_-] are
1394 * converted to '_'. Anything before the first colon is
1395 * assigned to name, anything after it to role. If there's
1396 * no colon, assign the whole thing to both role and name.
1398 * @param xulWinClass The window class. If set, overrides the normal value.
1399 * Otherwise, the program class it used.
1401 * @param xulWinName The window name. If set, overrides the value specified in
1402 * window type. Otherwise, name from window type is used.
1405 virtual void SetWindowClass(const nsAString
& xulWinType
,
1406 const nsAString
& xulWinClass
,
1407 const nsAString
& xulWinName
) = 0;
1410 * Enables/Disables system capture of any and all events that would cause a
1411 * popup to be rolled up. aListener should be set to a non-null value for
1412 * any popups that are not managed by the popup manager.
1413 * @param aDoCapture true enables capture, false disables capture
1416 virtual void CaptureRollupEvents(bool aDoCapture
) = 0;
1419 * Bring this window to the user's attention. This is intended to be a more
1420 * gentle notification than popping the window to the top or putting up an
1421 * alert. See, for example, Win32 FlashWindow or the NotificationManager on
1422 * the Mac. The notification should be suppressed if the window is already
1423 * in the foreground and should be dismissed when the user brings this window
1424 * to the foreground.
1425 * @param aCycleCount Maximum number of times to animate the window per system
1426 * conventions. If set to -1, cycles indefinitely until
1427 * window is brought into the foreground.
1429 [[nodiscard
]] virtual nsresult
GetAttention(int32_t aCycleCount
) = 0;
1432 * Ask whether there user input events pending. All input events are
1433 * included, including those not targeted at this nsIwidget instance.
1435 virtual bool HasPendingInputEvent() = 0;
1438 * If set to true, the window will draw its contents into the titlebar
1439 * instead of below it.
1441 * Ignored on any platform that does not support it. Ignored by widgets that
1442 * do not represent windows.
1443 * May result in a resize event, so should only be called from places where
1444 * reflow and painting is allowed.
1446 * @param aState Whether drawing into the titlebar should be activated.
1448 virtual void SetDrawsInTitlebar(bool aState
) = 0;
1451 * Determine whether the widget shows a resize widget. If it does,
1452 * aResizerRect returns the resizer's rect.
1454 * Returns false on any platform that does not support it.
1456 * @param aResizerRect The resizer's rect in device pixels.
1457 * @return Whether a resize widget is shown.
1459 virtual bool ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) = 0;
1461 // TODO: Make this an enum class with MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS or
1463 enum Modifiers
: uint32_t {
1464 NO_MODIFIERS
= 0x00000000,
1465 CAPS_LOCK
= 0x00000001, // when CapsLock is active
1466 NUM_LOCK
= 0x00000002, // when NumLock is active
1467 SHIFT_L
= 0x00000100,
1468 SHIFT_R
= 0x00000200,
1469 CTRL_L
= 0x00000400,
1470 CTRL_R
= 0x00000800,
1471 ALT_L
= 0x00001000, // includes Option
1473 COMMAND_L
= 0x00004000,
1474 COMMAND_R
= 0x00008000,
1476 ALTGRAPH
= 0x00020000, // AltGr key on Windows. This emulates
1477 // AltRight key behavior of keyboard
1478 // layouts which maps AltGr to AltRight
1480 FUNCTION
= 0x00100000,
1481 NUMERIC_KEY_PAD
= 0x01000000 // when the key is coming from the keypad
1484 * Utility method intended for testing. Dispatches native key events
1485 * to this widget to simulate the press and release of a key.
1486 * @param aNativeKeyboardLayout a *platform-specific* constant.
1487 * On Mac, this is the resource ID for a 'uchr' or 'kchr' resource.
1488 * On Windows, it is converted to a hex string and passed to
1489 * LoadKeyboardLayout, see
1490 * http://msdn.microsoft.com/en-us/library/ms646305(VS.85).aspx
1491 * @param aNativeKeyCode a *platform-specific* keycode.
1492 * On Windows, this is the virtual key code.
1493 * @param aModifiers some combination of the above 'Modifiers' flags;
1494 * not all flags will apply to all platforms. Mac ignores the _R
1495 * modifiers. Windows ignores COMMAND, NUMERIC_KEY_PAD, HELP and
1497 * @param aCharacters characters that the OS would decide to generate
1498 * from the event. On Windows, this is the charCode passed by
1500 * @param aUnmodifiedCharacters characters that the OS would decide
1501 * to generate from the event if modifier keys (other than shift)
1502 * were assumed inactive. Needed on Mac, ignored on Windows.
1503 * @param aObserver the observer that will get notified once the events
1504 * have been dispatched.
1505 * @return NS_ERROR_NOT_AVAILABLE to indicate that the keyboard
1506 * layout is not supported and the event was not fired
1508 virtual nsresult
SynthesizeNativeKeyEvent(
1509 int32_t aNativeKeyboardLayout
, int32_t aNativeKeyCode
,
1510 uint32_t aModifierFlags
, const nsAString
& aCharacters
,
1511 const nsAString
& aUnmodifiedCharacters
, nsIObserver
* aObserver
) = 0;
1514 * Utility method intended for testing. Dispatches native mouse events
1515 * may even move the mouse cursor. On Mac the events are guaranteed to
1516 * be sent to the window containing this widget, but on Windows they'll go
1517 * to whatever's topmost on the screen at that position, so for
1518 * cross-platform testing ensure that your window is at the top of the
1520 * @param aPoint screen location of the mouse, in device
1521 * pixels, with origin at the top left
1522 * @param aNativeMessage abstract native message.
1523 * @param aButton Mouse button defined by DOM UI Events.
1524 * @param aModifierFlags Some values of nsIWidget::Modifiers.
1525 * FYI: On Windows, Android and Headless widget on all
1526 * platroms, this hasn't been handled yet.
1527 * @param aObserver the observer that will get notified once the events
1528 * have been dispatched.
1530 enum class NativeMouseMessage
: uint32_t {
1531 ButtonDown
, // button down
1532 ButtonUp
, // button up
1533 Move
, // mouse cursor move
1534 EnterWindow
, // mouse cursor comes into a window
1535 LeaveWindow
, // mouse cursor leaves from a window
1537 virtual nsresult
SynthesizeNativeMouseEvent(
1538 LayoutDeviceIntPoint aPoint
, NativeMouseMessage aNativeMessage
,
1539 mozilla::MouseButton aButton
, nsIWidget::Modifiers aModifierFlags
,
1540 nsIObserver
* aObserver
) = 0;
1543 * A shortcut to SynthesizeNativeMouseEvent, abstracting away the native
1544 * message. aPoint is location in device pixels to which the mouse pointer
1546 * @param aObserver the observer that will get notified once the events
1547 * have been dispatched.
1549 virtual nsresult
SynthesizeNativeMouseMove(LayoutDeviceIntPoint aPoint
,
1550 nsIObserver
* aObserver
) = 0;
1553 * Utility method intended for testing. Dispatching native mouse scroll
1554 * events may move the mouse cursor.
1556 * @param aPoint Mouse cursor position in screen coordinates.
1557 * In device pixels, the origin at the top left of
1558 * the primary display.
1559 * @param aNativeMessage Platform native message.
1560 * @param aDeltaX The delta value for X direction. If the native
1561 * message doesn't indicate X direction scrolling,
1562 * this may be ignored.
1563 * @param aDeltaY The delta value for Y direction. If the native
1564 * message doesn't indicate Y direction scrolling,
1565 * this may be ignored.
1566 * @param aDeltaZ The delta value for Z direction. If the native
1567 * message doesn't indicate Z direction scrolling,
1568 * this may be ignored.
1569 * @param aModifierFlags Must be values of Modifiers, or zero.
1570 * @param aAdditionalFlags See nsIDOMWidnowUtils' consts and their
1572 * @param aObserver The observer that will get notified once the
1573 * events have been dispatched.
1575 virtual nsresult
SynthesizeNativeMouseScrollEvent(
1576 LayoutDeviceIntPoint aPoint
, uint32_t aNativeMessage
, double aDeltaX
,
1577 double aDeltaY
, double aDeltaZ
, uint32_t aModifierFlags
,
1578 uint32_t aAdditionalFlags
, nsIObserver
* aObserver
) = 0;
1581 * TouchPointerState states for SynthesizeNativeTouchPoint. Match
1582 * touch states in nsIDOMWindowUtils.idl.
1584 enum TouchPointerState
{
1585 // The pointer is in a hover state above the digitizer
1586 TOUCH_HOVER
= (1 << 0),
1587 // The pointer is in contact with the digitizer
1588 TOUCH_CONTACT
= (1 << 1),
1589 // The pointer has been removed from the digitizer detection area
1590 TOUCH_REMOVE
= (1 << 2),
1591 // The pointer has been canceled. Will cancel any pending os level
1592 // gestures that would triggered as a result of completion of the
1593 // input sequence. This may not cancel moz platform related events
1594 // that might get tirggered by input already delivered.
1595 TOUCH_CANCEL
= (1 << 3),
1597 // ALL_BITS used for validity checking during IPC serialization
1598 ALL_BITS
= (1 << 4) - 1
1601 * TouchpadGesturePhase states for SynthesizeNativeTouchPadPinch and
1602 * SynthesizeNativeTouchpadPan. Match phase states in nsIDOMWindowUtils.idl.
1604 enum TouchpadGesturePhase
{
1610 * Create a new or update an existing touch pointer on the digitizer.
1611 * To trigger os level gestures, individual touch points should
1612 * transition through a complete set of touch states which should be
1613 * sent as individual messages.
1615 * @param aPointerId The touch point id to create or update.
1616 * @param aPointerState one or more of the touch states listed above
1617 * @param aPoint coords of this event
1618 * @param aPressure 0.0 -> 1.0 float val indicating pressure
1619 * @param aOrientation 0 -> 359 degree value indicating the
1620 * orientation of the pointer. Use 90 for normal taps.
1621 * @param aObserver The observer that will get notified once the events
1622 * have been dispatched.
1624 virtual nsresult
SynthesizeNativeTouchPoint(uint32_t aPointerId
,
1625 TouchPointerState aPointerState
,
1626 LayoutDeviceIntPoint aPoint
,
1627 double aPointerPressure
,
1628 uint32_t aPointerOrientation
,
1629 nsIObserver
* aObserver
) = 0;
1631 * See nsIDOMWindowUtils.sendNativeTouchpadPinch().
1633 virtual nsresult
SynthesizeNativeTouchPadPinch(
1634 TouchpadGesturePhase aEventPhase
, float aScale
,
1635 LayoutDeviceIntPoint aPoint
, int32_t aModifierFlags
) = 0;
1638 * Helper for simulating a simple tap event with one touch point. When
1639 * aLongTap is true, simulates a native long tap with a duration equal to
1640 * ui.click_hold_context_menus.delay. This pref is compatible with the
1641 * apzc long tap duration. Defaults to 1.5 seconds.
1642 * @param aObserver The observer that will get notified once the events
1643 * have been dispatched.
1645 virtual nsresult
SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
1647 nsIObserver
* aObserver
);
1649 virtual nsresult
SynthesizeNativePenInput(uint32_t aPointerId
,
1650 TouchPointerState aPointerState
,
1651 LayoutDeviceIntPoint aPoint
,
1653 uint32_t aRotation
, int32_t aTiltX
,
1654 int32_t aTiltY
, int32_t aButton
,
1655 nsIObserver
* aObserver
) = 0;
1658 * Cancels all active simulated touch input points and pending long taps.
1659 * Native widgets should track existing points such that they can clear the
1660 * digitizer state when this call is made.
1661 * @param aObserver The observer that will get notified once the touch
1662 * sequence has been cleared.
1664 virtual nsresult
ClearNativeTouchSequence(nsIObserver
* aObserver
);
1667 * Send a native event as if the user double tapped the touchpad with two
1670 virtual nsresult
SynthesizeNativeTouchpadDoubleTap(
1671 LayoutDeviceIntPoint aPoint
, uint32_t aModifierFlags
) = 0;
1674 * See nsIDOMWindowUtils.sendNativeTouchpadPan().
1676 virtual nsresult
SynthesizeNativeTouchpadPan(TouchpadGesturePhase aEventPhase
,
1677 LayoutDeviceIntPoint aPoint
,
1678 double aDeltaX
, double aDeltaY
,
1679 int32_t aModifierFlags
,
1680 nsIObserver
* aObserver
) = 0;
1682 virtual void StartAsyncScrollbarDrag(
1683 const AsyncDragMetrics
& aDragMetrics
) = 0;
1686 * Notify APZ to start autoscrolling.
1687 * @param aAnchorLocation the location of the autoscroll anchor
1688 * @param aGuid identifies the scroll frame to be autoscrolled
1689 * @return true if APZ has been successfully notified
1691 virtual bool StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
1692 const ScrollableLayerGuid
& aGuid
) = 0;
1695 * Notify APZ to stop autoscrolling.
1696 * @param aGuid identifies the scroll frame which is being autoscrolled.
1698 virtual void StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) = 0;
1700 virtual LayersId
GetRootLayerTreeId() = 0;
1702 // If this widget supports out-of-process compositing, it can override
1703 // this method to provide additional information to the compositor.
1704 virtual void GetCompositorWidgetInitData(
1705 mozilla::widget::CompositorWidgetInitData
* aInitData
) {}
1708 * Setter/Getter of the system font setting for testing.
1710 virtual nsresult
SetSystemFont(const nsCString
& aFontName
) {
1711 return NS_ERROR_NOT_IMPLEMENTED
;
1713 virtual nsresult
GetSystemFont(nsCString
& aFontName
) {
1714 return NS_ERROR_NOT_IMPLEMENTED
;
1718 * Wayland specific routines.
1720 virtual LayoutDeviceIntSize
GetMoveToRectPopupSize() const {
1721 NS_WARNING("GetLayoutPopupRect implemented only for wayland");
1722 return LayoutDeviceIntSize();
1726 * If this widget uses native pointer lock instead of warp-to-center
1727 * (currently only GTK on Wayland), these methods provide access to that
1730 virtual void SetNativePointerLockCenter(
1731 const LayoutDeviceIntPoint
& aLockCenter
) {}
1732 virtual void LockNativePointer() {}
1733 virtual void UnlockNativePointer() {}
1736 * Get safe area insets except to cutout.
1737 * See https://drafts.csswg.org/css-env-1/#safe-area-insets.
1739 virtual mozilla::ScreenIntMargin
GetSafeAreaInsets() const {
1740 return mozilla::ScreenIntMargin();
1746 LongTapInfo(int32_t aPointerId
, LayoutDeviceIntPoint
& aPoint
,
1747 mozilla::TimeDuration aDuration
, nsIObserver
* aObserver
)
1748 : mPointerId(aPointerId
),
1750 mDuration(aDuration
),
1751 mObserver(aObserver
),
1752 mStamp(mozilla::TimeStamp::Now()) {}
1755 LayoutDeviceIntPoint mPosition
;
1756 mozilla::TimeDuration mDuration
;
1757 nsCOMPtr
<nsIObserver
> mObserver
;
1758 mozilla::TimeStamp mStamp
;
1761 static void OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
);
1763 static already_AddRefed
<nsIBidiKeyboard
> CreateBidiKeyboardContentProcess();
1764 static already_AddRefed
<nsIBidiKeyboard
> CreateBidiKeyboardInner();
1766 mozilla::UniquePtr
<LongTapInfo
> mLongTapTouchPoint
;
1767 nsCOMPtr
<nsITimer
> mLongTapTimer
;
1768 static int32_t sPointerIdCounter
;
1772 * If key events have not been handled by content or XBL handlers, they can
1773 * be offered to the system (for custom application shortcuts set in system
1774 * preferences, for example).
1776 virtual void PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
);
1779 * Activates a native menu item at the position specified by the index
1780 * string. The index string is a string of positive integers separated
1781 * by the "|" (pipe) character. The last integer in the string represents
1782 * the item index in a submenu located using the integers preceding it.
1785 * In this string, the first integer represents the top-level submenu
1786 * in the native menu bar. Since the integer is 1, it is the second submeu
1787 * in the native menu bar. Within that, the first item (index 0) is a
1788 * submenu, and we want to activate the 5th item within that submenu.
1790 virtual nsresult
ActivateNativeMenuItemAt(const nsAString
& indexString
) = 0;
1793 * This is used for native menu system testing.
1795 * Updates a native menu at the position specified by the index string.
1796 * The index string is a string of positive integers separated by the "|"
1800 * In this string, the first integer represents the top-level submenu
1801 * in the native menu bar. Since the integer is 1, it is the second submeu
1802 * in the native menu bar. Within that, the first item (index 0) is a
1803 * submenu, and we want to update submenu at index 4 within that submenu.
1805 * If this is called with an empty string it forces a full reload of the
1808 virtual nsresult
ForceUpdateNativeMenuAt(const nsAString
& indexString
) = 0;
1811 * This is used for testing macOS service menu code.
1813 * @param aResult - the current text selection. Is empty if no selection.
1814 * @return nsresult - whether or not aResult was assigned the selected text.
1816 [[nodiscard
]] virtual nsresult
GetSelectionAsPlaintext(nsAString
& aResult
) {
1817 return NS_ERROR_NOT_IMPLEMENTED
;
1821 * Notify IME of the specified notification.
1823 * @return If the notification is mouse button event and it's consumed by
1824 * IME, this returns NS_SUCCESS_EVENT_CONSUMED.
1826 virtual nsresult
NotifyIME(const IMENotification
& aIMENotification
) = 0;
1829 * MaybeDispatchInitialFocusEvent will dispatch a focus event after creation
1830 * of the widget, in the event that we were not able to observe and respond to
1831 * the initial focus event. This is necessary for the early skeleton UI
1832 * window, which is displayed and receives its initial focus event before we
1833 * can actually respond to it.
1835 virtual void MaybeDispatchInitialFocusEvent() {}
1838 * Notifies the input context changes.
1840 virtual void SetInputContext(const InputContext
& aContext
,
1841 const InputContextAction
& aAction
) = 0;
1844 * Get current input context.
1846 virtual InputContext
GetInputContext() = 0;
1849 * Get native IME context. This is different from GetNativeData() with
1850 * NS_RAW_NATIVE_IME_CONTEXT, the result is unique even if in a remote
1853 virtual NativeIMEContext
GetNativeIMEContext() = 0;
1856 * Given a WidgetKeyboardEvent, this method synthesizes a corresponding
1857 * native (OS-level) event for it. This method allows tests to simulate
1858 * keystrokes that trigger native key bindings (which require a native
1861 [[nodiscard
]] virtual nsresult
AttachNativeKeyEvent(
1862 mozilla::WidgetKeyboardEvent
& aEvent
) = 0;
1865 * Retrieve edit commands when the key combination of aEvent is used
1866 * in platform native applications.
1868 MOZ_CAN_RUN_SCRIPT
virtual bool GetEditCommands(
1869 mozilla::NativeKeyBindingsType aType
,
1870 const mozilla::WidgetKeyboardEvent
& aEvent
,
1871 nsTArray
<mozilla::CommandInt
>& aCommands
);
1874 * Retrieves a reference to notification requests of IME. Note that the
1875 * reference is valid while the nsIWidget instance is alive. So, if you
1876 * need to store the reference for a long time, you need to grab the widget
1879 const IMENotificationRequests
& IMENotificationRequestsRef();
1882 * Call this method when a dialog is opened which has a default button.
1883 * The button's rectangle should be supplied in aButtonRect.
1885 [[nodiscard
]] virtual nsresult
OnDefaultButtonLoaded(
1886 const LayoutDeviceIntRect
& aButtonRect
) = 0;
1889 * Return true if this process shouldn't use platform widgets, and
1890 * so should use PuppetWidgets instead. If this returns true, the
1891 * result of creating and using a platform widget is undefined,
1892 * and likely to end in crashes or other buggy behavior.
1894 static bool UsePuppetWidgets() { return XRE_IsContentProcess(); }
1896 static already_AddRefed
<nsIWidget
> CreateTopLevelWindow();
1898 static already_AddRefed
<nsIWidget
> CreateChildWindow();
1901 * Allocate and return a "puppet widget" that doesn't directly
1902 * correlate to a platform widget; platform events and data must
1903 * be fed to it. Currently used in content processes. NULL is
1904 * returned if puppet widgets aren't supported in this build
1905 * config, on this platform, or for this process type.
1907 * This function is called "Create" to match CreateInstance().
1908 * The returned widget must still be nsIWidget::Create()d.
1910 static already_AddRefed
<nsIWidget
> CreatePuppetWidget(
1911 BrowserChild
* aBrowserChild
);
1913 static already_AddRefed
<nsIWidget
> CreateHeadlessWidget();
1916 * Reparent this widget's native widget.
1917 * @param aNewParent the native widget of aNewParent is the new native
1920 virtual void ReparentNativeWidget(nsIWidget
* aNewParent
) = 0;
1923 * Return true if widget has it's own GL context
1925 virtual bool HasGLContext() { return false; }
1928 * Returns true to indicate that this widget paints an opaque background
1929 * that we want to be visible under the page, so layout should not force
1930 * a default background.
1932 virtual bool WidgetPaintsBackground() { return false; }
1934 virtual bool NeedsPaint() { return IsVisible() && !GetBounds().IsEmpty(); }
1937 * Get the natural bounds of this widget. This method is only
1938 * meaningful for widgets for which Gecko implements screen
1939 * rotation natively. When this is the case, GetBounds() returns
1940 * the widget bounds taking rotation into account, and
1941 * GetNaturalBounds() returns the bounds *not* taking rotation
1944 * No code outside of the composition pipeline should know or care
1945 * about this. If you're not an agent of the compositor, you
1946 * probably shouldn't call this method.
1948 virtual LayoutDeviceIntRect
GetNaturalBounds() { return GetBounds(); }
1951 * Set size constraints on the window size such that it is never less than
1952 * the specified minimum size and never larger than the specified maximum
1953 * size. The size constraints are sizes of the outer rectangle including
1954 * the window frame and title bar. Use 0 for an unconstrained minimum size
1955 * and NS_MAXSIZE for an unconstrained maximum size. Note that this method
1956 * does not necessarily change the size of a window to conform to this size,
1957 * thus Resize should be called afterwards.
1959 * @param aConstraints: the size constraints in device pixels
1961 virtual void SetSizeConstraints(const SizeConstraints
& aConstraints
) = 0;
1964 * Return the size constraints currently observed by the widget.
1966 * @return the constraints in device pixels
1968 virtual const SizeConstraints
GetSizeConstraints() = 0;
1971 * Apply the current size constraints to the given size.
1973 * @param aWidth width to constrain
1974 * @param aHeight height to constrain
1976 virtual void ConstrainSize(int32_t* aWidth
, int32_t* aHeight
) = 0;
1979 * If this is owned by a BrowserChild, return that. Otherwise return
1982 virtual BrowserChild
* GetOwningBrowserChild() { return nullptr; }
1985 * If this isn't directly compositing to its window surface,
1986 * return the compositor which is doing that on our behalf.
1988 virtual CompositorBridgeChild
* GetRemoteRenderer() { return nullptr; }
1991 * If there is a remote renderer, pause or resume it.
1993 virtual void PauseOrResumeCompositor(bool aPause
);
1996 * Clear WebRender resources
1998 virtual void ClearCachedWebrenderResources() {}
2001 * Clear WebRender animation resources
2003 virtual void ClearWebrenderAnimationResources() {}
2006 * Request fast snapshot at RenderCompositor of WebRender.
2007 * Since readback of Windows DirectComposition is very slow.
2009 virtual bool SetNeedFastSnaphot() { return false; }
2012 * If this widget has its own vsync dispatcher, return it, otherwise return
2013 * nullptr. An example of such a local vsync dispatcher would be Wayland frame
2016 virtual RefPtr
<mozilla::VsyncDispatcher
> GetVsyncDispatcher();
2019 * Returns true if the widget requires synchronous repaints on resize,
2022 virtual bool SynchronouslyRepaintOnResize() { return true; }
2025 * Some platforms (only cocoa right now) round widget coordinates to the
2026 * nearest even pixels (see bug 892994), this function allows us to
2027 * determine how widget coordinates will be rounded.
2029 virtual int32_t RoundsWidgetCoordinatesTo() { return 1; }
2031 virtual void UpdateZoomConstraints(
2032 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
2033 const mozilla::Maybe
<ZoomConstraints
>& aConstraints
){};
2036 * GetTextEventDispatcher() returns TextEventDispatcher belonging to the
2037 * widget. Note that this never returns nullptr.
2039 virtual TextEventDispatcher
* GetTextEventDispatcher() = 0;
2042 * GetNativeTextEventDispatcherListener() returns a
2043 * TextEventDispatcherListener instance which is used when the widget
2044 * instance handles native IME and/or keyboard events.
2046 virtual TextEventDispatcherListener
*
2047 GetNativeTextEventDispatcherListener() = 0;
2049 virtual void ZoomToRect(const uint32_t& aPresShellId
,
2050 const ScrollableLayerGuid::ViewID
& aViewId
,
2051 const CSSRect
& aRect
, const uint32_t& aFlags
) = 0;
2054 * LookUpDictionary shows the dictionary for the word around current point.
2056 * @param aText the word to look up dictiorary.
2057 * @param aFontRangeArray text decoration of aText
2058 * @param aIsVertical true if the word is vertical layout
2059 * @param aPoint top-left point of aText
2061 virtual void LookUpDictionary(
2062 const nsAString
& aText
,
2063 const nsTArray
<mozilla::FontRange
>& aFontRangeArray
,
2064 const bool aIsVertical
, const LayoutDeviceIntPoint
& aPoint
) {}
2066 virtual void RequestFxrOutput() {
2067 MOZ_ASSERT(false, "This function should only execute in Windows");
2070 #if defined(MOZ_WIDGET_ANDROID)
2072 * RecvToolbarAnimatorMessageFromCompositor receive message from compositor
2075 * @param aMessage message being sent to Android UI thread.
2077 virtual void RecvToolbarAnimatorMessageFromCompositor(int32_t aMessage
) = 0;
2080 * UpdateRootFrameMetrics steady state frame metrics send from compositor
2083 * @param aScrollOffset page scroll offset value in screen pixels.
2084 * @param aZoom current page zoom.
2086 virtual void UpdateRootFrameMetrics(const ScreenPoint
& aScrollOffset
,
2087 const CSSToScreenScale
& aZoom
) = 0;
2090 * RecvScreenPixels Buffer containing the pixel from the frame buffer. Used
2091 * for android robocop tests.
2093 * @param aMem shared memory containing the frame buffer pixels.
2094 * @param aSize size of the buffer in screen pixels.
2096 virtual void RecvScreenPixels(mozilla::ipc::Shmem
&& aMem
,
2097 const ScreenIntSize
& aSize
,
2098 bool aNeedsYFlip
) = 0;
2100 virtual void UpdateDynamicToolbarMaxHeight(mozilla::ScreenIntCoord aHeight
) {}
2101 virtual mozilla::ScreenIntCoord
GetDynamicToolbarMaxHeight() const {
2106 static already_AddRefed
<nsIBidiKeyboard
> CreateBidiKeyboard();
2109 * Like GetDefaultScale, but taking into account only the system settings
2110 * and ignoring Gecko preferences.
2112 virtual double GetDefaultScaleInternal() { return 1.0; }
2114 using WindowButtonType
= mozilla::WindowButtonType
;
2117 * Layout uses this to alert the widget to the client rect representing
2118 * the window maximize button. An empty rect indicates there is no
2119 * maximize button (for example, in fullscreen). This is only implemented
2122 virtual void SetWindowButtonRect(WindowButtonType aButtonType
,
2123 const LayoutDeviceIntRect
& aClientRect
) {}
2126 virtual nsresult
SetHiDPIMode(bool aHiDPI
) {
2127 return NS_ERROR_NOT_IMPLEMENTED
;
2129 virtual nsresult
RestoreHiDPIMode() { return NS_ERROR_NOT_IMPLEMENTED
; }
2133 // keep the list of children. We also keep track of our siblings.
2134 // The ownership model is as follows: parent holds a strong ref to
2135 // the first element of the list, and each element holds a strong
2136 // ref to the next element in the list. The prevsibling and
2137 // lastchild pointers are weak, which is fine as long as they are
2138 // maintained properly.
2139 nsCOMPtr
<nsIWidget
> mFirstChild
;
2140 nsIWidget
* MOZ_NON_OWNING_REF mLastChild
;
2141 nsCOMPtr
<nsIWidget
> mNextSibling
;
2142 nsIWidget
* MOZ_NON_OWNING_REF mPrevSibling
;
2143 // When Destroy() is called, the sub class should set this true.
2144 bool mOnDestroyCalled
;
2145 WindowType mWindowType
;
2149 NS_DEFINE_STATIC_IID_ACCESSOR(nsIWidget
, NS_IWIDGET_IID
)
2151 #endif // nsIWidget_h__