1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef UI_VIEWS_WIDGET_WIDGET_H_
6 #define UI_VIEWS_WIDGET_WIDGET_H_
7 
8 #include <memory>
9 #include <set>
10 #include <string>
11 #include <vector>
12 
13 #include "base/macros.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/observer_list.h"
16 #include "base/optional.h"
17 #include "base/scoped_observer.h"
18 #include "build/build_config.h"
19 #include "ui/base/default_theme_provider.h"
20 #include "ui/base/ui_base_types.h"
21 #include "ui/events/event_source.h"
22 #include "ui/gfx/geometry/rect.h"
23 #include "ui/gfx/native_widget_types.h"
24 #include "ui/native_theme/native_theme.h"
25 #include "ui/native_theme/native_theme_observer.h"
26 #include "ui/views/focus/focus_manager.h"
27 #include "ui/views/widget/native_widget_delegate.h"
28 #include "ui/views/window/client_view.h"
29 #include "ui/views/window/non_client_view.h"
30 
31 namespace base {
32 class TimeDelta;
33 }
34 
35 namespace gfx {
36 class Point;
37 class Rect;
38 }  // namespace gfx
39 
40 namespace ui {
41 class Accelerator;
42 class Compositor;
43 class GestureRecognizer;
44 class InputMethod;
45 class Layer;
46 class OSExchangeData;
47 class ThemeProvider;
48 }  // namespace ui
49 
50 namespace views {
51 
52 class DesktopWindowTreeHost;
53 class NativeWidget;
54 class NonClientFrameView;
55 class TooltipManager;
56 class View;
57 class WidgetDelegate;
58 class WidgetObserver;
59 class WidgetRemovalsObserver;
60 
61 namespace internal {
62 class NativeWidgetPrivate;
63 class RootView;
64 }  // namespace internal
65 
66 ////////////////////////////////////////////////////////////////////////////////
67 // Widget class
68 //
69 //  Encapsulates the platform-specific rendering, event receiving and widget
70 //  management aspects of the UI framework.
71 //
72 //  Owns a RootView and thus a View hierarchy. Can contain child Widgets.
73 //  Widget is a platform-independent type that communicates with a platform or
74 //  context specific NativeWidget implementation.
75 //
76 //  A special note on ownership:
77 //
78 //    Depending on the value of the InitParams' ownership field, the Widget
79 //    either owns or is owned by its NativeWidget:
80 //
81 //    ownership = NATIVE_WIDGET_OWNS_WIDGET (default)
82 //      The Widget instance is owned by its NativeWidget. When the NativeWidget
83 //      is destroyed (in response to a native destruction message), it deletes
84 //      the Widget from its destructor.
85 //    ownership = WIDGET_OWNS_NATIVE_WIDGET (non-default)
86 //      The Widget instance owns its NativeWidget. This state implies someone
87 //      else wants to control the lifetime of this object. When they destroy
88 //      the Widget it is responsible for destroying the NativeWidget (from its
89 //      destructor). This is often used to place a Widget in a std::unique_ptr<>
90 //      or on the stack in a test.
91 class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate,
92                             public ui::EventSource,
93                             public FocusTraversable,
94                             public ui::NativeThemeObserver {
95  public:
96   using Widgets = std::set<Widget*>;
97   using ShapeRects = std::vector<gfx::Rect>;
98 
99   enum class FrameType {
100     kDefault,      // Use whatever the default would be.
101     kForceCustom,  // Force the custom frame.
102     kForceNative   // Force the native frame.
103   };
104 
105   // Result from RunMoveLoop().
106   enum MoveLoopResult {
107     // The move loop completed successfully.
108     MOVE_LOOP_SUCCESSFUL,
109 
110     // The user canceled the move loop.
111     MOVE_LOOP_CANCELED
112   };
113 
114   // Source that initiated the move loop.
115   enum class MoveLoopSource {
116     kMouse,
117     kTouch,
118   };
119 
120   // Behavior when escape is pressed during a move loop.
121   enum MoveLoopEscapeBehavior {
122     // Indicates the window should be hidden.
123     MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE,
124 
125     // Indicates the window should not be hidden.
126     MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE,
127   };
128 
129   // Type of visibility change transition that should animate.
130   enum VisibilityTransition {
131     ANIMATE_SHOW = 0x1,
132     ANIMATE_HIDE = 0x2,
133     ANIMATE_BOTH = ANIMATE_SHOW | ANIMATE_HIDE,
134     ANIMATE_NONE = 0x4,
135   };
136 
137   // Represents the reason a Widget was closed, if it is known.
138   //
139   // For backwards compatibility, we default to kUnspecified when
140   // Widget::Close() is called. Note that we do not currently handle close
141   // reason for menu or for the main Chrome browser, as we have no reason to
142   // specifically differentiate those yet.
143   //
144   // Add additional values as needed.
145   enum class ClosedReason {
146     kUnspecified = 0,      // No reason was given for the widget closing.
147     kEscKeyPressed,        // The ESC key was pressed to cancel the widget.
148     kCloseButtonClicked,   // The [X] button was explicitly clicked.
149     kLostFocus,            // The widget destroyed itself when it lost focus.
150     kCancelButtonClicked,  // The widget's cancel button was clicked.
151     kAcceptButtonClicked   // The widget's done/accept button was clicked.
152   };
153 
154   struct VIEWS_EXPORT InitParams {
155     enum Type {
156       TYPE_WINDOW,  // A decorated Window, like a frame window.
157                     // Widgets of TYPE_WINDOW will have a NonClientView.
158       TYPE_WINDOW_FRAMELESS,  // An undecorated Window.
159       TYPE_CONTROL,           // A control, like a button.
160       TYPE_POPUP,  // An undecorated Window, with transient properties.
161       TYPE_MENU,   // An undecorated Window, with transient properties
162                    // specialized to menus.
163       TYPE_TOOLTIP,
164       TYPE_BUBBLE,
165       TYPE_DRAG,  // An undecorated Window, used during a drag-and-drop to
166                   // show the drag image.
167     };
168 
169     enum class WindowOpacity {
170       // Infer fully opaque or not. For WinAura, top-level windows that are not
171       // of TYPE_WINDOW are translucent so that they can be made to fade in.
172       // For LinuxAura, only windows that are TYPE_DRAG are translucent.  In all
173       // other cases, windows are fully opaque.
174       kInferred,
175       // Fully opaque.
176       kOpaque,
177       // Possibly translucent/transparent.  Widgets that fade in or out using
178       // SetOpacity() but do not make use of an alpha channel should use
179       // kInferred.
180       kTranslucent,
181     };
182 
183     enum Activatable {
184       // Infer whether the window should be activatable from the window type.
185       ACTIVATABLE_DEFAULT,
186 
187       ACTIVATABLE_YES,
188       ACTIVATABLE_NO
189     };
190 
191     enum Ownership {
192       // Default. Creator is not responsible for managing the lifetime of the
193       // Widget, it is destroyed when the corresponding NativeWidget is
194       // destroyed.
195       NATIVE_WIDGET_OWNS_WIDGET,
196       // Used when the Widget is owned by someone other than the NativeWidget,
197       // e.g. a scoped_ptr in tests.
198       WIDGET_OWNS_NATIVE_WIDGET
199     };
200 
201     enum class ShadowType {
202       kDefault,  // Use default shadow setting. It will be one of
203                  // the settings below depending on InitParams::type
204                  // and the native widget's type.
205       kNone,     // Don't draw any shadow.
206       kDrop,     // Draw a drop shadow that emphasizes Z-order
207                  // relationship to other windows.
208     };
209 
210     // Default initialization with |type| set to TYPE_WINDOW.
211     InitParams();
212 
213     // Initialization for other |type| types.
214     explicit InitParams(Type type);
215 
216     InitParams(InitParams&& other);
217     ~InitParams();
218 
219     InitParams& operator=(InitParams&& rhs) = default;
220 
221     // Returns the activatablity based on |activatable|, but also handles the
222     // case where |activatable| is |ACTIVATABLE_DEFAULT|.
223     bool CanActivate() const;
224 
225     // Returns the z-order level, based on the overriding |z_order| but also
226     // taking into account special levels due to |type|.
227     ui::ZOrderLevel EffectiveZOrderLevel() const;
228 
229     Type type = TYPE_WINDOW;
230 
231     // If null, a default implementation will be constructed. The default
232     // implementation deletes itself when the Widget closes.
233     WidgetDelegate* delegate = nullptr;
234 
235     // Internal name. Propagated to the NativeWidget. Useful for debugging.
236     std::string name;
237 
238     // False if this widget behaves like a top-level widget, true otherwise. A
239     // top-level widget has its own focus and IME state, independent of any
240     // other widget. A widget for which child is true should have a parent; if
241     // it doesn't, it will not handle keyboard events or IME input at all.
242     // TODO(https://crbug.com/1057758): DCHECK(parent || !child)
243     bool child = false;
244 
245     // If kTranslucent, the widget may be fully or partially transparent.
246     // If kOpaque, we can perform optimizations based on the widget being fully
247     // opaque. Default is based on ViewsDelegate::GetOpacityForInitParams().
248     // Defaults to kOpaque for non-window widgets. Translucent windows may not
249     // always be supported. Use IsTranslucentWindowOpacitySupported() to
250     // determine whether they are.
251     WindowOpacity opacity = WindowOpacity::kInferred;
252 
253     bool accept_events = true;
254 
255     Activatable activatable = ACTIVATABLE_DEFAULT;
256 
257     // The class of window and its overall z-order.
258     base::Optional<ui::ZOrderLevel> z_order;
259 
260     bool visible_on_all_workspaces = false;
261 
262     // See Widget class comment above.
263     Ownership ownership = NATIVE_WIDGET_OWNS_WIDGET;
264 
265     bool mirror_origin_in_rtl = false;
266 
267     ShadowType shadow_type = ShadowType::kDefault;
268 
269     // A hint about the size of the shadow if the type is ShadowType::kDrop. May
270     // be ignored on some platforms. No value indicates no preference.
271     base::Optional<int> shadow_elevation;
272 
273     // The window corner radius. May be ignored on some platforms.
274     base::Optional<int> corner_radius;
275 
276     // Specifies that the system default caption and icon should not be
277     // rendered, and that the client area should be equivalent to the window
278     // area. Only used on some platforms (Windows and Linux).
279     bool remove_standard_frame = false;
280 
281     // Only used by ShellWindow on Windows. Specifies that the default icon of
282     // packaged app should be the system default icon.
283     bool use_system_default_icon = false;
284 
285     // Whether the widget should be maximized or minimized.
286     ui::WindowShowState show_state = ui::SHOW_STATE_DEFAULT;
287 
288     // The native *view* (not native *window*) to which this widget should be
289     // parented. If this widget has a parent, then:
290     // * If that parent closes, this widget is closed too
291     // * If that parent is hidden, this widget is hidden too
292     // * This widget is stacked above the parent widget (always on Mac, usually
293     //   elsewhere)
294     // * This widget's initial bounds are constrained to the parent widget's
295     //   bounds, which prevents window restoration from placing windows
296     //   offscreen
297     // Note: on some platforms (Mac) this directly implies a parent-child
298     // relationship in the backing native windows, but on Aura platforms it does
299     // not necessarily.
300     //
301     // Windows with no parent window are permitted, although in Aura these
302     // windows instead need a "context". On Aura systems, if a widget has no
303     // parent set, its backing aura::Window is parented to the Aura root window.
304     //
305     // TODO(https://crbug.com/1057758): It makes no sense that this is a
306     // NativeView instead of a NativeWindow. On Aura, NativeView and
307     // NativeWindow are synonyms, and NativeWidgetAura immediately treats the
308     // provided NativeView as an aura::Window; on Mac, the NativeView is
309     // immediately converted to an NSWindow (ie a gfx::NativeWindow) and used
310     // that way throughout. This should simply be a NativeWindow - windows are
311     // parented to other windows, not to views, and it being a view confuses
312     // the concept with bubble anchoring a la BubbleDialogDelegateView.
313     gfx::NativeView parent = nullptr;
314 
315     // Specifies the initial bounds of the Widget. Default is empty, which means
316     // the NativeWidget may specify a default size. If the parent is specified,
317     // |bounds| is in the parent's coordinate system. If the parent is not
318     // specified, it's in screen's global coordinate system.
319     gfx::Rect bounds;
320 
321     // The initial workspace of the Widget. Default is "", which means the
322     // current workspace.
323     std::string workspace;
324 
325     // If set, this value is used as the Widget's NativeWidget implementation.
326     // The Widget will not construct a default one.
327     NativeWidget* native_widget = nullptr;
328 
329     // Aura-only. Provides a DesktopWindowTreeHost implementation to use instead
330     // of the default one.
331     // TODO(beng): Figure out if there's a better way to expose this, e.g. get
332     // rid of NW subclasses and do this all via message handling.
333     DesktopWindowTreeHost* desktop_window_tree_host = nullptr;
334 
335     // Only used by NativeWidgetAura. Specifies the type of layer for the
336     // aura::Window.
337     ui::LayerType layer_type = ui::LAYER_TEXTURED;
338 
339     // Only used by Aura. Provides a context window whose RootWindow is
340     // consulted during widget creation to determine where in the Window
341     // hierarchy this widget should be placed. (This is separate from |parent|;
342     // if you pass a RootWindow to |parent|, your window will be parented to
343     // |parent|. If you pass a RootWindow to |context|, we ask that RootWindow
344     // where it wants your window placed.) Nullptr is not allowed on Windows and
345     // Linux. Nullptr is allowed on Chrome OS, which will place the window on
346     // the default desktop for new windows.
347     gfx::NativeWindow context = nullptr;
348 
349     // If true, forces the window to be shown in the taskbar, even for window
350     // types that do not appear in the taskbar by default (popup and bubble).
351     bool force_show_in_taskbar = false;
352 
353     // Only used by X11, for root level windows. Specifies the res_name and
354     // res_class fields, respectively, of the WM_CLASS window property. Controls
355     // window grouping and desktop file matching in Linux window managers.
356     std::string wm_role_name;
357     std::string wm_class_name;
358     std::string wm_class_class;
359 
360     // If true then the widget uses software compositing.
361     bool force_software_compositing = false;
362 
363     // If set, mouse events will be sent to the widget even if inactive.
364     bool wants_mouse_events_when_inactive = false;
365 
366     // Contains any properties with which the native widget should be
367     // initialized prior to adding it to the window hierarchy. All the
368     // properties in |init_properties_container| will be moved to the native
369     // widget.
370     ui::PropertyHandler init_properties_container;
371   };
372 
373   // Represents a lock held on the widget's ShouldPaintAsActive() state. As
374   // long as at least one lock is held, the widget will paint as active.
375   // Multiple locks can exist for the same widget, and a lock can outlive its
376   // associated widget. See Widget::LockPaintAsActive().
377   class PaintAsActiveLock {
378    public:
379     virtual ~PaintAsActiveLock();
380 
381    protected:
382     PaintAsActiveLock();
383 
384     DISALLOW_COPY_AND_ASSIGN(PaintAsActiveLock);
385   };
386 
387   Widget();
388   explicit Widget(InitParams params);
389   ~Widget() override;
390 
391   // Creates a decorated window Widget with the specified properties. The
392   // returned Widget is owned by its NativeWidget; see Widget class comment for
393   // details.
394   static Widget* CreateWindowWithParent(WidgetDelegate* delegate,
395                                         gfx::NativeView parent,
396                                         const gfx::Rect& bounds = gfx::Rect());
397 
398   // Creates a decorated window Widget in the same desktop context as |context|.
399   // The returned Widget is owned by its NativeWidget; see Widget class comment
400   // for details.
401   static Widget* CreateWindowWithContext(WidgetDelegate* delegate,
402                                          gfx::NativeWindow context,
403                                          const gfx::Rect& bounds = gfx::Rect());
404 
405   // Closes all Widgets that aren't identified as "secondary widgets". Called
406   // during application shutdown when the last non-secondary widget is closed.
407   static void CloseAllSecondaryWidgets();
408 
409   // Retrieves the Widget implementation associated with the given
410   // NativeView or Window, or NULL if the supplied handle has no associated
411   // Widget.
412   static Widget* GetWidgetForNativeView(gfx::NativeView native_view);
413   static Widget* GetWidgetForNativeWindow(gfx::NativeWindow native_window);
414 
415   // Retrieves the top level widget in a native view hierarchy
416   // starting at |native_view|. Top level widget is a widget with TYPE_WINDOW,
417   // TYPE_PANEL, TYPE_WINDOW_FRAMELESS, POPUP or MENU and has its own
418   // focus manager. This may be itself if the |native_view| is top level,
419   // or NULL if there is no toplevel in a native view hierarchy.
420   static Widget* GetTopLevelWidgetForNativeView(gfx::NativeView native_view);
421 
422   // Returns all Widgets in |native_view|'s hierarchy, including itself if
423   // it is one.
424   static void GetAllChildWidgets(gfx::NativeView native_view,
425                                  Widgets* children);
426 
427   // Returns all Widgets owned by |native_view| (including child widgets, but
428   // not including itself).
429   static void GetAllOwnedWidgets(gfx::NativeView native_view, Widgets* owned);
430 
431   // Re-parent a NativeView and notify all Widgets in |native_view|'s hierarchy
432   // of the change.
433   static void ReparentNativeView(gfx::NativeView native_view,
434                                  gfx::NativeView new_parent);
435 
436   // Returns the preferred size of the contents view of this window based on
437   // its localized size data. The width in cols is held in a localized string
438   // resource identified by |col_resource_id|, the height in the same fashion.
439   // TODO(beng): This should eventually live somewhere else, probably closer to
440   //             ClientView.
441   static int GetLocalizedContentsWidth(int col_resource_id);
442   static int GetLocalizedContentsHeight(int row_resource_id);
443   static gfx::Size GetLocalizedContentsSize(int col_resource_id,
444                                             int row_resource_id);
445 
446   // Returns true if the specified type requires a NonClientView.
447   static bool RequiresNonClientView(InitParams::Type type);
448 
449   // Initializes the widget, and in turn, the native widget. |params| should be
450   // moved to Init() by the caller.
451   void Init(InitParams params);
452 
453   // Returns the gfx::NativeView associated with this Widget.
454   gfx::NativeView GetNativeView() const;
455 
456   // Returns the gfx::NativeWindow associated with this Widget. This may return
457   // NULL on some platforms if the widget was created with a type other than
458   // TYPE_WINDOW or TYPE_PANEL.
459   gfx::NativeWindow GetNativeWindow() const;
460 
461   // Add/remove observer.
462   void AddObserver(WidgetObserver* observer);
463   void RemoveObserver(WidgetObserver* observer);
464   bool HasObserver(const WidgetObserver* observer) const;
465 
466   // Add/remove removals observer.
467   void AddRemovalsObserver(WidgetRemovalsObserver* observer);
468   void RemoveRemovalsObserver(WidgetRemovalsObserver* observer);
469   bool HasRemovalsObserver(const WidgetRemovalsObserver* observer) const;
470 
471   // Returns the accelerator given a command id. Returns false if there is
472   // no accelerator associated with a given id, which is a common condition.
473   virtual bool GetAccelerator(int cmd_id, ui::Accelerator* accelerator) const;
474 
475   // Forwarded from the RootView so that the widget can do any cleanup.
476   void ViewHierarchyChanged(const ViewHierarchyChangedDetails& details);
477 
478   // Called right before changing the widget's parent NativeView to do any
479   // cleanup.
480   void NotifyNativeViewHierarchyWillChange();
481 
482   // Called after changing the widget's parent NativeView. Notifies the RootView
483   // about the change.
484   void NotifyNativeViewHierarchyChanged();
485 
486   // Called immediately before removing |view| from this widget.
487   void NotifyWillRemoveView(View* view);
488 
489   // Returns the top level widget in a hierarchy (see is_top_level() for
490   // the definition of top level widget.) Will return NULL if called
491   // before the widget is attached to the top level widget's hierarchy.
492   Widget* GetTopLevelWidget();
493   const Widget* GetTopLevelWidget() const;
494 
495   // Gets/Sets the WidgetDelegate.
widget_delegate()496   WidgetDelegate* widget_delegate() const { return widget_delegate_; }
497 
498   // Sets the specified view as the contents of this Widget. There can only
499   // be one contents view child of this Widget's RootView. This view is sized to
500   // fit the entire size of the RootView. The RootView takes ownership of this
501   // View, unless it is set as not being parent-owned.
502   void SetContentsView(View* view);
503 
504   // NOTE: This may not be the same view as WidgetDelegate::GetContentsView().
505   // See RootView::GetContentsView().
506   View* GetContentsView();
507 
508   // Returns the bounds of the Widget in screen coordinates.
509   gfx::Rect GetWindowBoundsInScreen() const;
510 
511   // Returns the bounds of the Widget's client area in screen coordinates.
512   gfx::Rect GetClientAreaBoundsInScreen() const;
513 
514   // Retrieves the restored bounds for the window.
515   gfx::Rect GetRestoredBounds() const;
516 
517   // Retrieves the current workspace for the window. (On macOS: an opaque
518   // binary blob that encodes the workspace and other window state.)
519   std::string GetWorkspace() const;
520 
521   // Sizes and/or places the widget to the specified bounds, size or position.
522   void SetBounds(const gfx::Rect& bounds);
523   void SetSize(const gfx::Size& size);
524 
525   // Sizes the window to the specified size and centers it.
526   void CenterWindow(const gfx::Size& size);
527 
528   // Like SetBounds(), but ensures the Widget is fully visible on screen or
529   // parent widget, resizing and/or repositioning as necessary.
530   void SetBoundsConstrained(const gfx::Rect& bounds);
531 
532   // Sets whether animations that occur when visibility is changed are enabled.
533   // Default is true.
534   void SetVisibilityChangedAnimationsEnabled(bool value);
535 
536   // Sets the duration of visibility change animations.
537   void SetVisibilityAnimationDuration(const base::TimeDelta& duration);
538 
539   // Sets the visibility transitions that should animate.
540   // Default behavior is to animate both show and hide.
541   void SetVisibilityAnimationTransition(VisibilityTransition transition);
542 
543   // Starts a nested run loop that moves the window. This can be used to
544   // start a window move operation from a mouse or touch event. This returns
545   // when the move completes. |drag_offset| is the offset from the top left
546   // corner of the window to the point where the cursor is dragging, and is used
547   // to offset the bounds of the window from the cursor.
548   MoveLoopResult RunMoveLoop(const gfx::Vector2d& drag_offset,
549                              MoveLoopSource source,
550                              MoveLoopEscapeBehavior escape_behavior);
551 
552   // Stops a previously started move loop. This is not immediate.
553   void EndMoveLoop();
554 
555   // Places the widget in front of the specified widget in z-order.
556   void StackAboveWidget(Widget* widget);
557   void StackAbove(gfx::NativeView native_view);
558   void StackAtTop();
559 
560   // Sets a shape on the widget. Passing a NULL |shape| reverts the widget to
561   // be rectangular.
562   void SetShape(std::unique_ptr<ShapeRects> shape);
563 
564   // Equivalent to CloseWithReason(ClosedReason::kUnspecified).
565   // DEPRECATED: Please use CloseWithReason() instead.
566   void Close();
567 
568   // Hides the widget, then closes it after a return to the message loop,
569   // specifying the reason for it having been closed.
570   // Note that while you can pass ClosedReason::kUnspecified, it is highly
571   // discouraged and only supported for backwards-compatibility with Close().
572   void CloseWithReason(ClosedReason closed_reason);
573 
574   // A UI test which tries to asynchronously examine a widget (e.g. the pixel
575   // tests) will fail if the widget is closed before that.  This can happen
576   // easily with widgets that close on focus loss coupled with tests being run
577   // in parallel, since one test's widget can be closed by the appearance of
578   // another test's.  This method can be used to temporarily disable
579   // Widget::Close() for such asynchronous cases.
SetBlockCloseForTesting(bool block_close)580   void SetBlockCloseForTesting(bool block_close) { block_close_ = block_close; }
581 
582   // TODO(beng): Move off public API.
583   // Closes the widget immediately. Compare to |Close|. This will destroy the
584   // window handle associated with this Widget, so should not be called from
585   // any code that expects it to be valid beyond this call.
586   void CloseNow();
587 
588   // Whether the widget has been asked to close itself. In particular this is
589   // set to true after Close() has been invoked on the NativeWidget.
590   bool IsClosed() const;
591 
592   // Returns the reason the widget was closed, if it was specified.
closed_reason()593   ClosedReason closed_reason() const { return closed_reason_; }
594 
595   // Shows the widget. The widget is activated if during initialization the
596   // can_activate flag in the InitParams structure is set to true.
597   void Show();
598 
599   // Hides the widget.
600   void Hide();
601 
602   // Like Show(), but does not activate the window.
603   void ShowInactive();
604 
605   // Activates the widget, assuming it already exists and is visible.
606   void Activate();
607 
608   // Deactivates the widget, making the next window in the Z order the active
609   // window.
610   void Deactivate();
611 
612   // Returns whether the Widget is the currently active window.
613   virtual bool IsActive() const;
614 
615   // Sets the z-order of the widget. This only applies to top-level widgets.
616   void SetZOrderLevel(ui::ZOrderLevel order);
617 
618   // Gets the z-order of the widget. This only applies to top-level widgets.
619   ui::ZOrderLevel GetZOrderLevel() const;
620 
621   // Sets the widget to be visible on all work spaces.
622   void SetVisibleOnAllWorkspaces(bool always_visible);
623 
624   // Is this widget currently visible on all workspaces?
625   // A call to SetVisibleOnAllWorkspaces(true) won't necessarily mean
626   // IsVisbleOnAllWorkspaces() == true (for example, when the platform doesn't
627   // support workspaces).
628   bool IsVisibleOnAllWorkspaces() const;
629 
630   // Maximizes/minimizes/restores the window.
631   void Maximize();
632   void Minimize();
633   void Restore();
634 
635   // Whether or not the window is maximized or minimized.
636   virtual bool IsMaximized() const;
637   bool IsMinimized() const;
638 
639   // Accessors for fullscreen state.
640   void SetFullscreen(bool fullscreen);
641   bool IsFullscreen() const;
642 
643   // macOS: Sets whether the window can share fullscreen windows' spaces.
644   void SetCanAppearInExistingFullscreenSpaces(
645       bool can_appear_in_existing_fullscreen_spaces);
646 
647   // Sets the opacity of the widget. This may allow widgets behind the widget
648   // in the Z-order to become visible, depending on the capabilities of the
649   // underlying windowing system.
650   void SetOpacity(float opacity);
651 
652   // Sets the aspect ratio of the widget's content, which will be maintained
653   // during interactive resizing. This size disregards title bar and borders.
654   // Once set, some platforms ensure the content will only size to integer
655   // multiples of |aspect_ratio|.
656   void SetAspectRatio(const gfx::SizeF& aspect_ratio);
657 
658   // Flashes the frame of the window to draw attention to it. Currently only
659   // implemented on Windows for non-Aura.
660   void FlashFrame(bool flash);
661 
662   // Returns the View at the root of the View hierarchy contained by this
663   // Widget.
664   View* GetRootView();
665   const View* GetRootView() const;
666 
667   // A secondary widget is one that is automatically closed (via Close()) when
668   // all non-secondary widgets are closed.
669   // Default is true.
670   // TODO(beng): This is an ugly API, should be handled implicitly via
671   //             transience.
set_is_secondary_widget(bool is_secondary_widget)672   void set_is_secondary_widget(bool is_secondary_widget) {
673     is_secondary_widget_ = is_secondary_widget;
674   }
is_secondary_widget()675   bool is_secondary_widget() const { return is_secondary_widget_; }
676 
677   // Returns whether the Widget is visible to the user.
678   virtual bool IsVisible() const;
679 
680   // Returns the ThemeProvider that provides theme resources for this Widget.
681   virtual const ui::ThemeProvider* GetThemeProvider() const;
682 
GetNativeTheme()683   ui::NativeTheme* GetNativeTheme() {
684     return const_cast<ui::NativeTheme*>(
685         const_cast<const Widget*>(this)->GetNativeTheme());
686   }
687   virtual const ui::NativeTheme* GetNativeTheme() const;
688 
689   // Returns the FocusManager for this widget.
690   // Note that all widgets in a widget hierarchy share the same focus manager.
691   FocusManager* GetFocusManager();
692   const FocusManager* GetFocusManager() const;
693 
694   // Returns the ui::InputMethod for this widget.
695   ui::InputMethod* GetInputMethod();
696 
697   // Starts a drag operation for the specified view. This blocks until the drag
698   // operation completes. |view| can be NULL.
699   // If the view is non-NULL it can be accessed during the drag by calling
700   // dragged_view(). If the view has not been deleted during the drag,
701   // OnDragDone() is called on it. |location| is in the widget's coordinate
702   // system.
703   void RunShellDrag(View* view,
704                     std::unique_ptr<ui::OSExchangeData> data,
705                     const gfx::Point& location,
706                     int operation,
707                     ui::DragDropTypes::DragEventSource source);
708 
709   // Returns the view that requested the current drag operation via
710   // RunShellDrag(), or NULL if there is no such view or drag operation.
dragged_view()711   View* dragged_view() {
712     return const_cast<View*>(const_cast<const Widget*>(this)->dragged_view());
713   }
dragged_view()714   const View* dragged_view() const { return dragged_view_; }
715 
716   // Adds the specified |rect| in client area coordinates to the rectangle to be
717   // redrawn.
718   virtual void SchedulePaintInRect(const gfx::Rect& rect);
719 
720   // Schedule a layout to occur. This is called by RootView, client code should
721   // not need to call this.
722   void ScheduleLayout();
723 
724   // Sets the currently visible cursor. If |cursor| is NULL, the cursor used
725   // before the current is restored.
726   void SetCursor(gfx::NativeCursor cursor);
727 
728   // Returns true if and only if mouse events are enabled.
729   bool IsMouseEventsEnabled() const;
730 
731   // Sets/Gets a native window property on the underlying native window object.
732   // Returns NULL if the property does not exist. Setting the property value to
733   // NULL removes the property.
734   void SetNativeWindowProperty(const char* name, void* value);
735   void* GetNativeWindowProperty(const char* name) const;
736 
737   // Tell the window to update its title from the delegate.
738   void UpdateWindowTitle();
739 
740   // Tell the window to update its icon from the delegate.
741   void UpdateWindowIcon();
742 
743   // Shows the platform specific emoji picker for this widget.
744   void ShowEmojiPanel();
745 
746   // Retrieves the focus traversable for this widget.
747   FocusTraversable* GetFocusTraversable();
748 
749   // Notifies the view hierarchy contained in this widget that theme resources
750   // changed.
751   void ThemeChanged();
752 
753   // Notifies the view hierarchy contained in this widget that the device scale
754   // factor changed.
755   void DeviceScaleFactorChanged(float old_device_scale_factor,
756                                 float new_device_scale_factor);
757 
758   void SetFocusTraversableParent(FocusTraversable* parent);
759   void SetFocusTraversableParentView(View* parent_view);
760 
761   // Clear native focus set to the Widget's NativeWidget.
762   void ClearNativeFocus();
763 
set_frame_type(FrameType frame_type)764   void set_frame_type(FrameType frame_type) { frame_type_ = frame_type; }
frame_type()765   FrameType frame_type() const { return frame_type_; }
766 
767   // Creates an appropriate NonClientFrameView for this widget. The
768   // WidgetDelegate is given the first opportunity to create one, followed by
769   // the NativeWidget implementation. If both return NULL, a default one is
770   // created.
771   virtual NonClientFrameView* CreateNonClientFrameView();
772 
773   // Whether we should be using a native frame.
774   bool ShouldUseNativeFrame() const;
775 
776   // Determines whether the window contents should be rendered transparently
777   // (for example, so that they can overhang onto the window title bar).
778   bool ShouldWindowContentsBeTransparent() const;
779 
780   // Forces the frame into the alternate frame type (custom or native) depending
781   // on its current state.
782   void DebugToggleFrameType();
783 
784   // Tell the window that something caused the frame type to change.
785   void FrameTypeChanged();
786 
non_client_view()787   NonClientView* non_client_view() {
788     return const_cast<NonClientView*>(
789         const_cast<const Widget*>(this)->non_client_view());
790   }
non_client_view()791   const NonClientView* non_client_view() const { return non_client_view_; }
792 
client_view()793   ClientView* client_view() {
794     return const_cast<ClientView*>(
795         const_cast<const Widget*>(this)->client_view());
796   }
client_view()797   const ClientView* client_view() const {
798     // non_client_view_ may be NULL, especially during creation.
799     return non_client_view_ ? non_client_view_->client_view() : nullptr;
800   }
801 
802   // Returns the compositor for this Widget, note that this may change during
803   // the Widget's lifetime (e.g. when switching monitors on Chrome OS).
GetCompositor()804   ui::Compositor* GetCompositor() {
805     return const_cast<ui::Compositor*>(
806         const_cast<const Widget*>(this)->GetCompositor());
807   }
808   const ui::Compositor* GetCompositor() const;
809 
810   // Returns the widget's layer, if any.
GetLayer()811   ui::Layer* GetLayer() {
812     return const_cast<ui::Layer*>(const_cast<const Widget*>(this)->GetLayer());
813   }
814   const ui::Layer* GetLayer() const;
815 
816   // Reorders the widget's child NativeViews which are associated to the view
817   // tree (eg via a NativeViewHost) to match the z-order of the views in the
818   // view tree. The z-order of views with layers relative to views with
819   // associated NativeViews is used to reorder the NativeView layers. This
820   // method assumes that the widget's child layers which are owned by a view are
821   // already in the correct z-order relative to each other and does no
822   // reordering if there are no views with an associated NativeView.
823   void ReorderNativeViews();
824 
825   // Called by a View when the status of it's layer or one of the views
826   // descendants layer status changes.
827   void LayerTreeChanged();
828 
829   const NativeWidget* native_widget() const;
830   NativeWidget* native_widget();
831 
native_widget_private()832   internal::NativeWidgetPrivate* native_widget_private() {
833     return native_widget_;
834   }
native_widget_private()835   const internal::NativeWidgetPrivate* native_widget_private() const {
836     return native_widget_;
837   }
838 
839   // Sets capture to the specified view. This makes it so that all mouse, touch
840   // and gesture events go to |view|. If |view| is NULL, the widget still
841   // obtains event capture, but the events will go to the view they'd normally
842   // go to.
843   void SetCapture(View* view);
844 
845   // Releases capture.
846   void ReleaseCapture();
847 
848   // Returns true if the widget has capture.
849   bool HasCapture();
850 
set_auto_release_capture(bool auto_release_capture)851   void set_auto_release_capture(bool auto_release_capture) {
852     auto_release_capture_ = auto_release_capture;
853   }
854 
855   // Returns the font used for tooltips.
856   TooltipManager* GetTooltipManager();
857   const TooltipManager* GetTooltipManager() const;
858 
set_focus_on_creation(bool focus_on_creation)859   void set_focus_on_creation(bool focus_on_creation) {
860     focus_on_creation_ = focus_on_creation;
861   }
862 
863   // True if the widget is considered top level widget. Top level widget
864   // is a widget of TYPE_WINDOW, TYPE_PANEL, TYPE_WINDOW_FRAMELESS, BUBBLE,
865   // POPUP or MENU, and has a focus manager and input method object associated
866   // with it. TYPE_CONTROL and TYPE_TOOLTIP is not considered top level.
is_top_level()867   bool is_top_level() const { return is_top_level_; }
868 
869   // True when window movement via mouse interaction with the frame is disabled.
movement_disabled()870   bool movement_disabled() const { return movement_disabled_; }
set_movement_disabled(bool disabled)871   void set_movement_disabled(bool disabled) { movement_disabled_ = disabled; }
872 
873   // Returns the work area bounds of the screen the Widget belongs to.
874   gfx::Rect GetWorkAreaBoundsInScreen() const;
875 
876   // Creates and dispatches synthesized mouse move event using the current
877   // mouse location to refresh hovering status in the widget.
878   void SynthesizeMouseMoveEvent();
879 
880   // Whether the widget supports translucency.
881   bool IsTranslucentWindowOpacitySupported() const;
882 
883   // Returns the gesture recognizer which can handle touch/gesture events on
884   // this.
885   ui::GestureRecognizer* GetGestureRecognizer();
886 
887   // Called when the delegate's CanResize or CanMaximize changes.
888   void OnSizeConstraintsChanged();
889 
890   // Notification that our owner is closing.
891   // NOTE: this is not invoked for aura as it's currently not needed there.
892   // Under aura menus close by way of activation getting reset when the owner
893   // closes.
894   virtual void OnOwnerClosing();
895 
896   // Returns the internal name for this Widget and NativeWidget.
897   std::string GetName() const;
898 
899   // Prevents the widget from being rendered as inactive during the lifetime of
900   // the returned lock. Multiple locks can exist with disjoint lifetimes. The
901   // returned lock can safely outlive the associated widget.
902   std::unique_ptr<PaintAsActiveLock> LockPaintAsActive();
903 
904   base::WeakPtr<Widget> GetWeakPtr();
905 
906   // Overridden from NativeWidgetDelegate:
907   bool IsModal() const override;
908   bool IsDialogBox() const override;
909   bool CanActivate() const override;
910   bool ShouldPaintAsActive() const override;
911   bool IsNativeWidgetInitialized() const override;
912   bool OnNativeWidgetActivationChanged(bool active) override;
913   void OnNativeFocus() override;
914   void OnNativeBlur() override;
915   void OnNativeWidgetVisibilityChanging(bool visible) override;
916   void OnNativeWidgetVisibilityChanged(bool visible) override;
917   void OnNativeWidgetCreated() override;
918   void OnNativeWidgetDestroying() override;
919   void OnNativeWidgetDestroyed() override;
920   gfx::Size GetMinimumSize() const override;
921   gfx::Size GetMaximumSize() const override;
922   void OnNativeWidgetMove() override;
923   void OnNativeWidgetSizeChanged(const gfx::Size& new_size) override;
924   void OnNativeWidgetWorkspaceChanged() override;
925   void OnNativeWidgetWindowShowStateChanged() override;
926   void OnNativeWidgetBeginUserBoundsChange() override;
927   void OnNativeWidgetEndUserBoundsChange() override;
928   bool HasFocusManager() const override;
929   void OnNativeWidgetPaint(const ui::PaintContext& context) override;
930   int GetNonClientComponent(const gfx::Point& point) override;
931   void OnKeyEvent(ui::KeyEvent* event) override;
932   void OnMouseEvent(ui::MouseEvent* event) override;
933   void OnMouseCaptureLost() override;
934   void OnScrollEvent(ui::ScrollEvent* event) override;
935   void OnGestureEvent(ui::GestureEvent* event) override;
936   bool ExecuteCommand(int command_id) override;
937   bool HasHitTestMask() const override;
938   void GetHitTestMask(SkPath* mask) const override;
939   Widget* AsWidget() override;
940   const Widget* AsWidget() const override;
941   bool SetInitialFocus(ui::WindowShowState show_state) override;
942   bool ShouldDescendIntoChildForEventHandling(
943       ui::Layer* root_layer,
944       gfx::NativeView child,
945       ui::Layer* child_layer,
946       const gfx::Point& location) override;
947   void LayoutRootViewIfNecessary() override;
948 
949   // Overridden from ui::EventSource:
950   ui::EventSink* GetEventSink() override;
951 
952   // Overridden from FocusTraversable:
953   FocusSearch* GetFocusSearch() override;
954   FocusTraversable* GetFocusTraversableParent() override;
955   View* GetFocusTraversableParentView() override;
956 
957   // Overridden from ui::NativeThemeObserver:
958   void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
959 
960  protected:
961   // Call this to propagate native theme changes to the root view. Subclasses
962   // may override this to customize how native theme updates are propagated.
963   virtual void PropagateNativeThemeChanged();
964 
965   // Creates the RootView to be used within this Widget. Subclasses may override
966   // to create custom RootViews that do specialized event processing.
967   // TODO(beng): Investigate whether or not this is needed.
968   virtual internal::RootView* CreateRootView();
969 
970   // Provided to allow the NativeWidget implementations to destroy the RootView
971   // _before_ the focus manager/tooltip manager.
972   // TODO(beng): remove once we fold those objects onto this one.
973   void DestroyRootView();
974 
975   // Notification that a drag will start. Default implementation does nothing.
976   virtual void OnDragWillStart();
977 
978   // Notification that the drag performed by RunShellDrag() has completed.
979   virtual void OnDragComplete();
980 
981  private:
982   class PaintAsActiveLockImpl;
983 
984   friend class ButtonTest;
985   friend class ComboboxTest;
986   friend class PaintAsActiveLockImpl;
987   friend class TextfieldTest;
988   friend class ViewAuraTest;
989   friend void DisableActivationChangeHandlingForTests();
990 
991   // Persists the window's restored position and "show" state using the
992   // window delegate.
993   void SaveWindowPlacement();
994 
995   // Invokes SaveWindowPlacement() if the native widget has been initialized.
996   // This is called at times when the native widget may not have been
997   // initialized.
998   void SaveWindowPlacementIfInitialized();
999 
1000   // Sizes and positions the window just after it is created.
1001   void SetInitialBounds(const gfx::Rect& bounds);
1002 
1003   // Sizes and positions the frameless window just after it is created.
1004   void SetInitialBoundsForFramelessWindow(const gfx::Rect& bounds);
1005 
1006   // Returns the bounds and "show" state from the delegate. Returns true if
1007   // the delegate wants to use a specified bounds.
1008   bool GetSavedWindowPlacement(gfx::Rect* bounds,
1009                                ui::WindowShowState* show_state);
1010 
1011   // Returns the Views whose layers are parented directly to the Widget's
1012   // layer.
1013   const View::Views& GetViewsWithLayers();
1014 
1015   // Undoes LockPaintAsActive(). Called by PaintAsActiveLock destructor.
1016   void UnlockPaintAsActive();
1017 
1018   // Notifies the window frame that the active rendering state has changed.
1019   void UpdatePaintAsActiveState(bool paint_as_active);
1020 
1021   // If a descendent of |root_view_| is focused, then clear the focus.
1022   void ClearFocusFromWidget();
1023 
1024   static bool g_disable_activation_change_handling_;
1025 
1026   internal::NativeWidgetPrivate* native_widget_ = nullptr;
1027 
1028   base::ObserverList<WidgetObserver> observers_;
1029 
1030   base::ObserverList<WidgetRemovalsObserver>::Unchecked removals_observers_;
1031 
1032   // Non-owned pointer to the Widget's delegate. If a NULL delegate is supplied
1033   // to Init() a default WidgetDelegate is created.
1034   WidgetDelegate* widget_delegate_ = nullptr;
1035 
1036   // The root of the View hierarchy attached to this window.
1037   // WARNING: see warning in tooltip_manager_ for ordering dependencies with
1038   // this and tooltip_manager_.
1039   std::unique_ptr<internal::RootView> root_view_;
1040 
1041   // The View that provides the non-client area of the window (title bar,
1042   // window controls, sizing borders etc). To use an implementation other than
1043   // the default, this class must be sub-classed and this value set to the
1044   // desired implementation before calling |InitWindow()|.
1045   NonClientView* non_client_view_ = nullptr;
1046 
1047   // The focus manager keeping track of focus for this Widget and any of its
1048   // children.  NULL for non top-level widgets.
1049   // WARNING: RootView's destructor calls into the FocusManager. As such, this
1050   // must be destroyed AFTER root_view_. This is enforced in DestroyRootView().
1051   std::unique_ptr<FocusManager> focus_manager_;
1052 
1053   // A theme provider to use when no other theme provider is specified.
1054   const ui::DefaultThemeProvider default_theme_provider_;
1055 
1056   // Valid for the lifetime of RunShellDrag(), indicates the view the drag
1057   // started from.
1058   View* dragged_view_ = nullptr;
1059 
1060   // See class documentation for Widget above for a note about ownership.
1061   InitParams::Ownership ownership_ = InitParams::NATIVE_WIDGET_OWNS_WIDGET;
1062 
1063   // See set_is_secondary_widget().
1064   bool is_secondary_widget_ = true;
1065 
1066   // The current frame type in use by this window. Defaults to
1067   // FrameType::kDefault.
1068   FrameType frame_type_ = FrameType::kDefault;
1069 
1070   // Tracks whether the native widget is active.
1071   bool native_widget_active_ = false;
1072 
1073   // Tracks locks on the paint-as-active behavior. See LockPaintAsActive().
1074   size_t paint_as_active_refcount_ = 0;
1075 
1076   // Set to true if the widget is in the process of closing.
1077   bool widget_closed_ = false;
1078 
1079   // The reason the widget was closed.
1080   // Note that this may be ClosedReason::kUnspecified if the deprecated Close()
1081   // method was called rather than CloseWithReason().
1082   ClosedReason closed_reason_ = ClosedReason::kUnspecified;
1083 
1084   // The saved "show" state for this window. See note in SetInitialBounds
1085   // that explains why we save this.
1086   ui::WindowShowState saved_show_state_ = ui::SHOW_STATE_DEFAULT;
1087 
1088   // The restored bounds used for the initial show. This is only used if
1089   // |saved_show_state_| is maximized.
1090   gfx::Rect initial_restored_bounds_;
1091 
1092   // Focus is automatically set to the view provided by the delegate
1093   // when the widget is shown. Set this value to false to override
1094   // initial focus for the widget.
1095   bool focus_on_creation_ = true;
1096 
1097   // See |is_top_level()| accessor.
1098   bool is_top_level_ = false;
1099 
1100   // Tracks whether native widget has been initialized.
1101   bool native_widget_initialized_ = false;
1102 
1103   // Whether native widget has been destroyed.
1104   bool native_widget_destroyed_ = false;
1105 
1106   // TODO(beng): Remove NativeWidgetGtk's dependence on these:
1107   // If true, the mouse is currently down.
1108   bool is_mouse_button_pressed_ = false;
1109 
1110   // True if capture losses should be ignored.
1111   bool ignore_capture_loss_ = false;
1112 
1113   // TODO(beng): Remove NativeWidgetGtk's dependence on these:
1114   // The following are used to detect duplicate mouse move events and not
1115   // deliver them. Displaying a window may result in the system generating
1116   // duplicate move events even though the mouse hasn't moved.
1117   bool last_mouse_event_was_move_ = false;
1118   gfx::Point last_mouse_event_position_;
1119 
1120   // True if event capture should be released on a mouse up event. Default is
1121   // true.
1122   bool auto_release_capture_ = true;
1123 
1124   // See description in GetViewsWithLayers().
1125   View::Views views_with_layers_;
1126 
1127   // Does |views_with_layers_| need updating?
1128   bool views_with_layers_dirty_ = false;
1129 
1130   // True when window movement via mouse interaction with the frame should be
1131   // disabled.
1132   bool movement_disabled_ = false;
1133 
1134   // Block the widget from closing.
1135   bool block_close_ = false;
1136 
1137   ScopedObserver<ui::NativeTheme, ui::NativeThemeObserver> observer_manager_{
1138       this};
1139 
1140   base::WeakPtrFactory<Widget> weak_ptr_factory_{this};
1141 
1142   DISALLOW_COPY_AND_ASSIGN(Widget);
1143 };
1144 
1145 }  // namespace views
1146 
1147 #endif  // UI_VIEWS_WIDGET_WIDGET_H_
1148