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 <set>
9#include <stack>
10#include <vector>
11
12#include "base/gtest_prod_util.h"
13#include "base/memory/scoped_ptr.h"
14#include "base/observer_list.h"
15#include "base/scoped_observer.h"
16#include "ui/aura/window_layer_type.h"
17#include "ui/base/ui_base_types.h"
18#include "ui/events/event_source.h"
19#include "ui/gfx/native_widget_types.h"
20#include "ui/gfx/rect.h"
21#include "ui/native_theme/native_theme_observer.h"
22#include "ui/views/focus/focus_manager.h"
23#include "ui/views/widget/native_widget_delegate.h"
24#include "ui/views/window/client_view.h"
25#include "ui/views/window/non_client_view.h"
26
27#if defined(OS_WIN)
28// Windows headers define macros for these function names which screw with us.
29#if defined(IsMaximized)
30#undef IsMaximized
31#endif
32#if defined(IsMinimized)
33#undef IsMinimized
34#endif
35#if defined(CreateWindow)
36#undef CreateWindow
37#endif
38#endif
39
40namespace gfx {
41class Canvas;
42class Point;
43class Rect;
44}
45
46namespace ui {
47class Accelerator;
48class Compositor;
49class DefaultThemeProvider;
50class InputMethod;
51class Layer;
52class NativeTheme;
53class OSExchangeData;
54class ThemeProvider;
55}
56
57namespace views {
58
59class DesktopWindowTreeHost;
60class InputMethod;
61class NativeWidget;
62class NonClientFrameView;
63class TooltipManager;
64class View;
65class WidgetDelegate;
66class WidgetObserver;
67class WidgetRemovalsObserver;
68
69namespace internal {
70class NativeWidgetPrivate;
71class RootView;
72}
73
74////////////////////////////////////////////////////////////////////////////////
75// Widget class
76//
77//  Encapsulates the platform-specific rendering, event receiving and widget
78//  management aspects of the UI framework.
79//
80//  Owns a RootView and thus a View hierarchy. Can contain child Widgets.
81//  Widget is a platform-independent type that communicates with a platform or
82//  context specific NativeWidget implementation.
83//
84//  A special note on ownership:
85//
86//    Depending on the value of the InitParams' ownership field, the Widget
87//    either owns or is owned by its NativeWidget:
88//
89//    ownership = NATIVE_WIDGET_OWNS_WIDGET (default)
90//      The Widget instance is owned by its NativeWidget. When the NativeWidget
91//      is destroyed (in response to a native destruction message), it deletes
92//      the Widget from its destructor.
93//    ownership = WIDGET_OWNS_NATIVE_WIDGET (non-default)
94//      The Widget instance owns its NativeWidget. This state implies someone
95//      else wants to control the lifetime of this object. When they destroy
96//      the Widget it is responsible for destroying the NativeWidget (from its
97//      destructor).
98//
99class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate,
100                            public ui::EventSource,
101                            public FocusTraversable,
102                            public ui::NativeThemeObserver {
103 public:
104  typedef std::set<Widget*> Widgets;
105
106  enum FrameType {
107    FRAME_TYPE_DEFAULT,         // Use whatever the default would be.
108    FRAME_TYPE_FORCE_CUSTOM,    // Force the custom frame.
109    FRAME_TYPE_FORCE_NATIVE     // Force the native frame.
110  };
111
112  // Result from RunMoveLoop().
113  enum MoveLoopResult {
114    // The move loop completed successfully.
115    MOVE_LOOP_SUCCESSFUL,
116
117    // The user canceled the move loop.
118    MOVE_LOOP_CANCELED
119  };
120
121  // Source that initiated the move loop.
122  enum MoveLoopSource {
123    MOVE_LOOP_SOURCE_MOUSE,
124    MOVE_LOOP_SOURCE_TOUCH,
125  };
126
127  // Behavior when escape is pressed during a move loop.
128  enum MoveLoopEscapeBehavior {
129    // Indicates the window should be hidden.
130    MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE,
131
132    // Indicates the window should not be hidden.
133    MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE,
134  };
135
136  struct VIEWS_EXPORT InitParams {
137    enum Type {
138      TYPE_WINDOW,      // A decorated Window, like a frame window.
139                        // Widgets of TYPE_WINDOW will have a NonClientView.
140      TYPE_PANEL,       // Always on top window managed by PanelManager.
141                        // Widgets of TYPE_PANEL will have a NonClientView.
142      TYPE_WINDOW_FRAMELESS,
143                        // An undecorated Window.
144      TYPE_CONTROL,     // A control, like a button.
145      TYPE_POPUP,       // An undecorated Window, with transient properties.
146      TYPE_MENU,        // An undecorated Window, with transient properties
147                        // specialized to menus.
148      TYPE_TOOLTIP,
149      TYPE_BUBBLE,
150      TYPE_DRAG,        // An undecorated Window, used during a drag-and-drop to
151                        // show the drag image.
152    };
153
154    enum WindowOpacity {
155      // Infer fully opaque or not. For WinAura, top-level windows that are not
156      // of TYPE_WINDOW are translucent so that they can be made to fade in. In
157      // all other cases, windows are fully opaque.
158      INFER_OPACITY,
159      // Fully opaque.
160      OPAQUE_WINDOW,
161      // Possibly translucent/transparent.
162      TRANSLUCENT_WINDOW,
163    };
164
165    enum Activatable {
166      // Infer whether the window should be activatable from the window type.
167      ACTIVATABLE_DEFAULT,
168
169      ACTIVATABLE_YES,
170      ACTIVATABLE_NO
171    };
172
173    enum Ownership {
174      // Default. Creator is not responsible for managing the lifetime of the
175      // Widget, it is destroyed when the corresponding NativeWidget is
176      // destroyed.
177      NATIVE_WIDGET_OWNS_WIDGET,
178      // Used when the Widget is owned by someone other than the NativeWidget,
179      // e.g. a scoped_ptr in tests.
180      WIDGET_OWNS_NATIVE_WIDGET
181    };
182
183    enum ShadowType {
184      SHADOW_TYPE_DEFAULT,  // Use default shadow setting. It will be one of
185                            // the settings below depending on InitParams::type
186                            // and the native widget's type.
187      SHADOW_TYPE_NONE,     // Don't draw any shadow.
188      SHADOW_TYPE_DROP,     // Draw a drop shadow that emphasizes Z-order
189                            // relationship to other windows.
190    };
191
192    InitParams();
193    explicit InitParams(Type type);
194    ~InitParams();
195
196    Type type;
197    // If NULL, a default implementation will be constructed.
198    WidgetDelegate* delegate;
199    bool child;
200    // If TRANSLUCENT_WINDOW, the widget may be fully or partially transparent.
201    // Translucent windows may not always be supported. Use
202    // IsTranslucentWindowOpacitySupported to determine if translucent windows
203    // are supported.
204    // If OPAQUE_WINDOW, we can perform optimizations based on the widget being
205    // fully opaque.  Defaults to TRANSLUCENT_WINDOW if
206    // ViewsDelegate::UseTransparentWindows().  Defaults to OPAQUE_WINDOW for
207    // non-window widgets.
208    WindowOpacity opacity;
209    bool accept_events;
210    Activatable activatable;
211    bool keep_on_top;
212    bool visible_on_all_workspaces;
213    Ownership ownership;
214    bool mirror_origin_in_rtl;
215    ShadowType shadow_type;
216    // Specifies that the system default caption and icon should not be
217    // rendered, and that the client area should be equivalent to the window
218    // area. Only used on some platforms (Windows and Linux).
219    bool remove_standard_frame;
220    // Only used by ShellWindow on Windows. Specifies that the default icon of
221    // packaged app should be the system default icon.
222    bool use_system_default_icon;
223    // Whether the widget should be maximized or minimized.
224    ui::WindowShowState show_state;
225    // Should the widget be double buffered? Default is false.
226    bool double_buffer;
227    gfx::NativeView parent;
228    // Specifies the initial bounds of the Widget. Default is empty, which means
229    // the NativeWidget may specify a default size. If the parent is specified,
230    // |bounds| is in the parent's coordinate system. If the parent is not
231    // specified, it's in screen's global coordinate system.
232    gfx::Rect bounds;
233    // When set, this value is used as the Widget's NativeWidget implementation.
234    // The Widget will not construct a default one. Default is NULL.
235    NativeWidget* native_widget;
236    // Aura-only. Provides a DesktopWindowTreeHost implementation to use instead
237    // of the default one.
238    // TODO(beng): Figure out if there's a better way to expose this, e.g. get
239    // rid of NW subclasses and do this all via message handling.
240    DesktopWindowTreeHost* desktop_window_tree_host;
241    // Only used by NativeWidgetAura. Specifies the type of layer for the
242    // aura::Window. Default is WINDOW_LAYER_TEXTURED.
243    aura::WindowLayerType layer_type;
244    // Only used by Aura. Provides a context window whose RootWindow is
245    // consulted during widget creation to determine where in the Window
246    // hierarchy this widget should be placed. (This is separate from |parent|;
247    // if you pass a RootWindow to |parent|, your window will be parented to
248    // |parent|. If you pass a RootWindow to |context|, we ask that RootWindow
249    // where it wants your window placed.) NULL is not allowed if you are using
250    // aura.
251    gfx::NativeWindow context;
252    // If true, forces the window to be shown in the taskbar, even for window
253    // types that do not appear in the taskbar by default (popup and bubble).
254    bool force_show_in_taskbar;
255    // Only used by X11, for root level windows. Specifies the res_name and
256    // res_class fields, respectively, of the WM_CLASS window property. Controls
257    // window grouping and desktop file matching in Linux window managers.
258    std::string wm_role_name;
259    std::string wm_class_name;
260    std::string wm_class_class;
261  };
262
263  Widget();
264  virtual ~Widget();
265
266  // Creates a toplevel window with no context. These methods should only be
267  // used in cases where there is no contextual information because we're
268  // creating a toplevel window connected to no other event.
269  //
270  // If you have any parenting or context information, or can pass that
271  // information, prefer the WithParent or WithContext versions of these
272  // methods.
273  static Widget* CreateWindow(WidgetDelegate* delegate);
274  static Widget* CreateWindowWithBounds(WidgetDelegate* delegate,
275                                        const gfx::Rect& bounds);
276
277  // Creates a decorated window Widget with the specified properties.
278  static Widget* CreateWindowWithParent(WidgetDelegate* delegate,
279                                        gfx::NativeView parent);
280  static Widget* CreateWindowWithParentAndBounds(WidgetDelegate* delegate,
281                                                 gfx::NativeView parent,
282                                                 const gfx::Rect& bounds);
283
284  // Creates a decorated window Widget in the same desktop context as |context|.
285  static Widget* CreateWindowWithContext(WidgetDelegate* delegate,
286                                         gfx::NativeWindow context);
287  static Widget* CreateWindowWithContextAndBounds(WidgetDelegate* delegate,
288                                                  gfx::NativeWindow context,
289                                                  const gfx::Rect& bounds);
290
291  // Closes all Widgets that aren't identified as "secondary widgets". Called
292  // during application shutdown when the last non-secondary widget is closed.
293  static void CloseAllSecondaryWidgets();
294
295  // Converts a rectangle from one Widget's coordinate system to another's.
296  // Returns false if the conversion couldn't be made, because either these two
297  // Widgets do not have a common ancestor or they are not on the screen yet.
298  // The value of |*rect| won't be changed when false is returned.
299  static bool ConvertRect(const Widget* source,
300                          const Widget* target,
301                          gfx::Rect* rect);
302
303  // Retrieves the Widget implementation associated with the given
304  // NativeView or Window, or NULL if the supplied handle has no associated
305  // Widget.
306  static Widget* GetWidgetForNativeView(gfx::NativeView native_view);
307  static Widget* GetWidgetForNativeWindow(gfx::NativeWindow native_window);
308
309  // Retrieves the top level widget in a native view hierarchy
310  // starting at |native_view|. Top level widget is a widget with TYPE_WINDOW,
311  // TYPE_PANEL, TYPE_WINDOW_FRAMELESS, POPUP or MENU and has its own
312  // focus manager. This may be itself if the |native_view| is top level,
313  // or NULL if there is no toplevel in a native view hierarchy.
314  static Widget* GetTopLevelWidgetForNativeView(gfx::NativeView native_view);
315
316  // Returns all Widgets in |native_view|'s hierarchy, including itself if
317  // it is one.
318  static void GetAllChildWidgets(gfx::NativeView native_view,
319                                 Widgets* children);
320
321  // Returns all non-child Widgets owned by |native_view|.
322  static void GetAllOwnedWidgets(gfx::NativeView native_view,
323                                 Widgets* owned);
324
325  // Re-parent a NativeView and notify all Widgets in |native_view|'s hierarchy
326  // of the change.
327  static void ReparentNativeView(gfx::NativeView native_view,
328                                 gfx::NativeView new_parent);
329
330  // Returns the preferred size of the contents view of this window based on
331  // its localized size data. The width in cols is held in a localized string
332  // resource identified by |col_resource_id|, the height in the same fashion.
333  // TODO(beng): This should eventually live somewhere else, probably closer to
334  //             ClientView.
335  static int GetLocalizedContentsWidth(int col_resource_id);
336  static int GetLocalizedContentsHeight(int row_resource_id);
337  static gfx::Size GetLocalizedContentsSize(int col_resource_id,
338                                            int row_resource_id);
339
340  // Returns true if the specified type requires a NonClientView.
341  static bool RequiresNonClientView(InitParams::Type type);
342
343  void Init(const InitParams& params);
344
345  // Returns the gfx::NativeView associated with this Widget.
346  gfx::NativeView GetNativeView() const;
347
348  // Returns the gfx::NativeWindow associated with this Widget. This may return
349  // NULL on some platforms if the widget was created with a type other than
350  // TYPE_WINDOW or TYPE_PANEL.
351  gfx::NativeWindow GetNativeWindow() const;
352
353  // Add/remove observer.
354  void AddObserver(WidgetObserver* observer);
355  void RemoveObserver(WidgetObserver* observer);
356  bool HasObserver(WidgetObserver* observer);
357
358  // Add/remove removals observer.
359  void AddRemovalsObserver(WidgetRemovalsObserver* observer);
360  void RemoveRemovalsObserver(WidgetRemovalsObserver* observer);
361  bool HasRemovalsObserver(WidgetRemovalsObserver* observer);
362
363  // Returns the accelerator given a command id. Returns false if there is
364  // no accelerator associated with a given id, which is a common condition.
365  virtual bool GetAccelerator(int cmd_id, ui::Accelerator* accelerator) const;
366
367  // Forwarded from the RootView so that the widget can do any cleanup.
368  void ViewHierarchyChanged(const View::ViewHierarchyChangedDetails& details);
369
370  // Called right before changing the widget's parent NativeView to do any
371  // cleanup.
372  void NotifyNativeViewHierarchyWillChange();
373
374  // Called after changing the widget's parent NativeView. Notifies the RootView
375  // about the change.
376  void NotifyNativeViewHierarchyChanged();
377
378  // Called immediately before removing |view| from this widget.
379  void NotifyWillRemoveView(View* view);
380
381  // Returns the top level widget in a hierarchy (see is_top_level() for
382  // the definition of top level widget.) Will return NULL if called
383  // before the widget is attached to the top level widget's hierarchy.
384  Widget* GetTopLevelWidget();
385  const Widget* GetTopLevelWidget() const;
386
387  // Gets/Sets the WidgetDelegate.
388  WidgetDelegate* widget_delegate() const { return widget_delegate_; }
389
390  // Sets the specified view as the contents of this Widget. There can only
391  // be one contents view child of this Widget's RootView. This view is sized to
392  // fit the entire size of the RootView. The RootView takes ownership of this
393  // View, unless it is set as not being parent-owned.
394  void SetContentsView(View* view);
395  View* GetContentsView();
396
397  // Returns the bounds of the Widget in screen coordinates.
398  gfx::Rect GetWindowBoundsInScreen() const;
399
400  // Returns the bounds of the Widget's client area in screen coordinates.
401  gfx::Rect GetClientAreaBoundsInScreen() const;
402
403  // Retrieves the restored bounds for the window.
404  gfx::Rect GetRestoredBounds() const;
405
406  // Sizes and/or places the widget to the specified bounds, size or position.
407  void SetBounds(const gfx::Rect& bounds);
408  void SetSize(const gfx::Size& size);
409
410  // Sizes the window to the specified size and centerizes it.
411  void CenterWindow(const gfx::Size& size);
412
413  // Like SetBounds(), but ensures the Widget is fully visible on screen,
414  // resizing and/or repositioning as necessary. This is only useful for
415  // non-child widgets.
416  void SetBoundsConstrained(const gfx::Rect& bounds);
417
418  // Sets whether animations that occur when visibility is changed are enabled.
419  // Default is true.
420  void SetVisibilityChangedAnimationsEnabled(bool value);
421
422  // Starts a nested message loop that moves the window. This can be used to
423  // start a window move operation from a mouse or touch event. This returns
424  // when the move completes. |drag_offset| is the offset from the top left
425  // corner of the window to the point where the cursor is dragging, and is used
426  // to offset the bounds of the window from the cursor.
427  MoveLoopResult RunMoveLoop(const gfx::Vector2d& drag_offset,
428                             MoveLoopSource source,
429                             MoveLoopEscapeBehavior escape_behavior);
430
431  // Stops a previously started move loop. This is not immediate.
432  void EndMoveLoop();
433
434  // Places the widget in front of the specified widget in z-order.
435  void StackAboveWidget(Widget* widget);
436  void StackAbove(gfx::NativeView native_view);
437  void StackAtTop();
438
439  // Places the widget below the specified NativeView.
440  void StackBelow(gfx::NativeView native_view);
441
442  // Sets a shape on the widget. Passing a NULL |shape| reverts the widget to
443  // be rectangular. Takes ownership of |shape|.
444  void SetShape(gfx::NativeRegion shape);
445
446  // Hides the widget then closes it after a return to the message loop.
447  virtual void Close();
448
449  // TODO(beng): Move off public API.
450  // Closes the widget immediately. Compare to |Close|. This will destroy the
451  // window handle associated with this Widget, so should not be called from
452  // any code that expects it to be valid beyond this call.
453  void CloseNow();
454
455  // Whether the widget has been asked to close itself. In particular this is
456  // set to true after Close() has been invoked on the NativeWidget.
457  bool IsClosed() const;
458
459  // Shows the widget. The widget is activated if during initialization the
460  // can_activate flag in the InitParams structure is set to true.
461  virtual void Show();
462  // Hides the widget.
463  void Hide();
464
465  // Like Show(), but does not activate the window.
466  void ShowInactive();
467
468  // Activates the widget, assuming it already exists and is visible.
469  void Activate();
470
471  // Deactivates the widget, making the next window in the Z order the active
472  // window.
473  void Deactivate();
474
475  // Returns whether the Widget is the currently active window.
476  virtual bool IsActive() const;
477
478  // Prevents the window from being rendered as deactivated. This state is
479  // reset automatically as soon as the window becomes activated again. There is
480  // no ability to control the state through this API as this leads to sync
481  // problems.
482  void DisableInactiveRendering();
483
484  // Sets the widget to be on top of all other widgets in the windowing system.
485  void SetAlwaysOnTop(bool on_top);
486
487  // Returns whether the widget has been set to be on top of most other widgets
488  // in the windowing system.
489  bool IsAlwaysOnTop() const;
490
491  // Sets the widget to be visible on all work spaces.
492  void SetVisibleOnAllWorkspaces(bool always_visible);
493
494  // Maximizes/minimizes/restores the window.
495  void Maximize();
496  void Minimize();
497  void Restore();
498
499  // Whether or not the window is maximized or minimized.
500  virtual bool IsMaximized() const;
501  bool IsMinimized() const;
502
503  // Accessors for fullscreen state.
504  void SetFullscreen(bool fullscreen);
505  bool IsFullscreen() const;
506
507  // Sets the opacity of the widget. This may allow widgets behind the widget
508  // in the Z-order to become visible, depending on the capabilities of the
509  // underlying windowing system.
510  void SetOpacity(unsigned char opacity);
511
512  // Sets whether or not the window should show its frame as a "transient drag
513  // frame" - slightly transparent and without the standard window controls.
514  void SetUseDragFrame(bool use_drag_frame);
515
516  // Flashes the frame of the window to draw attention to it. Currently only
517  // implemented on Windows for non-Aura.
518  void FlashFrame(bool flash);
519
520  // Returns the View at the root of the View hierarchy contained by this
521  // Widget.
522  View* GetRootView();
523  const View* GetRootView() const;
524
525  // A secondary widget is one that is automatically closed (via Close()) when
526  // all non-secondary widgets are closed.
527  // Default is true.
528  // TODO(beng): This is an ugly API, should be handled implicitly via
529  //             transience.
530  void set_is_secondary_widget(bool is_secondary_widget) {
531    is_secondary_widget_ = is_secondary_widget;
532  }
533  bool is_secondary_widget() const { return is_secondary_widget_; }
534
535  // Returns whether the Widget is visible to the user.
536  virtual bool IsVisible() const;
537
538  // Returns the ThemeProvider that provides theme resources for this Widget.
539  virtual ui::ThemeProvider* GetThemeProvider() const;
540
541  ui::NativeTheme* GetNativeTheme() {
542    return const_cast<ui::NativeTheme*>(
543        const_cast<const Widget*>(this)->GetNativeTheme());
544  }
545  const ui::NativeTheme* GetNativeTheme() const;
546
547  // Returns the FocusManager for this widget.
548  // Note that all widgets in a widget hierarchy share the same focus manager.
549  FocusManager* GetFocusManager();
550  const FocusManager* GetFocusManager() const;
551
552  // Returns the InputMethod for this widget.
553  // Note that all widgets in a widget hierarchy share the same input method.
554  InputMethod* GetInputMethod();
555  const InputMethod* GetInputMethod() const;
556
557  // Returns the ui::InputMethod for this widget.
558  // TODO(yukishiino): Rename this method to GetInputMethod once we remove
559  // views::InputMethod.
560  ui::InputMethod* GetHostInputMethod();
561
562  // Starts a drag operation for the specified view. This blocks until the drag
563  // operation completes. |view| can be NULL.
564  // If the view is non-NULL it can be accessed during the drag by calling
565  // dragged_view(). If the view has not been deleted during the drag,
566  // OnDragDone() is called on it. |location| is in the widget's coordinate
567  // system.
568  void RunShellDrag(View* view,
569                    const ui::OSExchangeData& data,
570                    const gfx::Point& location,
571                    int operation,
572                    ui::DragDropTypes::DragEventSource source);
573
574  // Returns the view that requested the current drag operation via
575  // RunShellDrag(), or NULL if there is no such view or drag operation.
576  View* dragged_view() { return dragged_view_; }
577
578  // Adds the specified |rect| in client area coordinates to the rectangle to be
579  // redrawn.
580  virtual void SchedulePaintInRect(const gfx::Rect& rect);
581
582  // Sets the currently visible cursor. If |cursor| is NULL, the cursor used
583  // before the current is restored.
584  void SetCursor(gfx::NativeCursor cursor);
585
586  // Returns true if and only if mouse events are enabled.
587  bool IsMouseEventsEnabled() const;
588
589  // Sets/Gets a native window property on the underlying native window object.
590  // Returns NULL if the property does not exist. Setting the property value to
591  // NULL removes the property.
592  void SetNativeWindowProperty(const char* name, void* value);
593  void* GetNativeWindowProperty(const char* name) const;
594
595  // Tell the window to update its title from the delegate.
596  void UpdateWindowTitle();
597
598  // Tell the window to update its icon from the delegate.
599  void UpdateWindowIcon();
600
601  // Retrieves the focus traversable for this widget.
602  FocusTraversable* GetFocusTraversable();
603
604  // Notifies the view hierarchy contained in this widget that theme resources
605  // changed.
606  void ThemeChanged();
607
608  // Notifies the view hierarchy contained in this widget that locale resources
609  // changed.
610  void LocaleChanged();
611
612  void SetFocusTraversableParent(FocusTraversable* parent);
613  void SetFocusTraversableParentView(View* parent_view);
614
615  // Clear native focus set to the Widget's NativeWidget.
616  void ClearNativeFocus();
617
618  void set_frame_type(FrameType frame_type) { frame_type_ = frame_type; }
619  FrameType frame_type() const { return frame_type_; }
620
621  // Creates an appropriate NonClientFrameView for this widget. The
622  // WidgetDelegate is given the first opportunity to create one, followed by
623  // the NativeWidget implementation. If both return NULL, a default one is
624  // created.
625  virtual NonClientFrameView* CreateNonClientFrameView();
626
627  // Whether we should be using a native frame.
628  bool ShouldUseNativeFrame() const;
629
630  // Determines whether the window contents should be rendered transparently
631  // (for example, so that they can overhang onto the window title bar).
632  bool ShouldWindowContentsBeTransparent() const;
633
634  // Forces the frame into the alternate frame type (custom or native) depending
635  // on its current state.
636  void DebugToggleFrameType();
637
638  // Tell the window that something caused the frame type to change.
639  void FrameTypeChanged();
640
641  NonClientView* non_client_view() {
642    return const_cast<NonClientView*>(
643        const_cast<const Widget*>(this)->non_client_view());
644  }
645  const NonClientView* non_client_view() const {
646    return non_client_view_;
647  }
648
649  ClientView* client_view() {
650    return const_cast<ClientView*>(
651        const_cast<const Widget*>(this)->client_view());
652  }
653  const ClientView* client_view() const {
654    // non_client_view_ may be NULL, especially during creation.
655    return non_client_view_ ? non_client_view_->client_view() : NULL;
656  }
657
658  const ui::Compositor* GetCompositor() const;
659  ui::Compositor* GetCompositor();
660
661  // Returns the widget's layer, if any.
662  ui::Layer* GetLayer();
663
664  // Reorders the widget's child NativeViews which are associated to the view
665  // tree (eg via a NativeViewHost) to match the z-order of the views in the
666  // view tree. The z-order of views with layers relative to views with
667  // associated NativeViews is used to reorder the NativeView layers. This
668  // method assumes that the widget's child layers which are owned by a view are
669  // already in the correct z-order relative to each other and does no
670  // reordering if there are no views with an associated NativeView.
671  void ReorderNativeViews();
672
673  // Schedules an update to the root layers. The actual processing occurs when
674  // GetRootLayers() is invoked.
675  void UpdateRootLayers();
676
677  const NativeWidget* native_widget() const;
678  NativeWidget* native_widget();
679
680  internal::NativeWidgetPrivate* native_widget_private() {
681    return native_widget_;
682  }
683  const internal::NativeWidgetPrivate* native_widget_private() const {
684    return native_widget_;
685  }
686
687  // Sets capture to the specified view. This makes it so that all mouse, touch
688  // and gesture events go to |view|. If |view| is NULL, the widget still
689  // obtains event capture, but the events will go to the view they'd normally
690  // go to.
691  void SetCapture(View* view);
692
693  // Releases capture.
694  void ReleaseCapture();
695
696  // Returns true if the widget has capture.
697  bool HasCapture();
698
699  void set_auto_release_capture(bool auto_release_capture) {
700    auto_release_capture_ = auto_release_capture;
701  }
702
703  // Returns the font used for tooltips.
704  TooltipManager* GetTooltipManager();
705  const TooltipManager* GetTooltipManager() const;
706
707  void set_focus_on_creation(bool focus_on_creation) {
708    focus_on_creation_ = focus_on_creation;
709  }
710
711  // True if the widget is considered top level widget. Top level widget
712  // is a widget of TYPE_WINDOW, TYPE_PANEL, TYPE_WINDOW_FRAMELESS, BUBBLE,
713  // POPUP or MENU, and has a focus manager and input method object associated
714  // with it. TYPE_CONTROL and TYPE_TOOLTIP is not considered top level.
715  bool is_top_level() const { return is_top_level_; }
716
717  // True when window movement via mouse interaction with the frame is disabled.
718  bool movement_disabled() const { return movement_disabled_; }
719  void set_movement_disabled(bool disabled) { movement_disabled_ = disabled; }
720
721  // Returns the work area bounds of the screen the Widget belongs to.
722  gfx::Rect GetWorkAreaBoundsInScreen() const;
723
724  // Creates and dispatches synthesized mouse move event using the current
725  // mouse location to refresh hovering status in the widget.
726  void SynthesizeMouseMoveEvent();
727
728  // Called by our RootView after it has performed a Layout. Used to forward
729  // window sizing information to the window server on some platforms.
730  void OnRootViewLayout();
731
732  // Whether the widget supports translucency.
733  bool IsTranslucentWindowOpacitySupported() const;
734
735  // Called when the delegate's CanResize or CanMaximize changes.
736  void OnSizeConstraintsChanged();
737
738  // Notification that our owner is closing.
739  // NOTE: this is not invoked for aura as it's currently not needed there.
740  // Under aura menus close by way of activation getting reset when the owner
741  // closes.
742  virtual void OnOwnerClosing();
743
744  // Overridden from NativeWidgetDelegate:
745  virtual bool IsModal() const OVERRIDE;
746  virtual bool IsDialogBox() const OVERRIDE;
747  virtual bool CanActivate() const OVERRIDE;
748  virtual bool IsInactiveRenderingDisabled() const OVERRIDE;
749  virtual void EnableInactiveRendering() OVERRIDE;
750  virtual void OnNativeWidgetActivationChanged(bool active) OVERRIDE;
751  virtual void OnNativeFocus(gfx::NativeView old_focused_view) OVERRIDE;
752  virtual void OnNativeBlur(gfx::NativeView new_focused_view) OVERRIDE;
753  virtual void OnNativeWidgetVisibilityChanging(bool visible) OVERRIDE;
754  virtual void OnNativeWidgetVisibilityChanged(bool visible) OVERRIDE;
755  virtual void OnNativeWidgetCreated(bool desktop_widget) OVERRIDE;
756  virtual void OnNativeWidgetDestroying() OVERRIDE;
757  virtual void OnNativeWidgetDestroyed() OVERRIDE;
758  virtual gfx::Size GetMinimumSize() const OVERRIDE;
759  virtual gfx::Size GetMaximumSize() const OVERRIDE;
760  virtual void OnNativeWidgetMove() OVERRIDE;
761  virtual void OnNativeWidgetSizeChanged(const gfx::Size& new_size) OVERRIDE;
762  virtual void OnNativeWidgetWindowShowStateChanged() OVERRIDE;
763  virtual void OnNativeWidgetBeginUserBoundsChange() OVERRIDE;
764  virtual void OnNativeWidgetEndUserBoundsChange() OVERRIDE;
765  virtual bool HasFocusManager() const OVERRIDE;
766  virtual bool OnNativeWidgetPaintAccelerated(
767      const gfx::Rect& dirty_region) OVERRIDE;
768  virtual void OnNativeWidgetPaint(gfx::Canvas* canvas) OVERRIDE;
769  virtual int GetNonClientComponent(const gfx::Point& point) OVERRIDE;
770  virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE;
771  virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE;
772  virtual void OnMouseCaptureLost() OVERRIDE;
773  virtual void OnScrollEvent(ui::ScrollEvent* event) OVERRIDE;
774  virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
775  virtual bool ExecuteCommand(int command_id) OVERRIDE;
776  virtual InputMethod* GetInputMethodDirect() OVERRIDE;
777  virtual const std::vector<ui::Layer*>& GetRootLayers() OVERRIDE;
778  virtual bool HasHitTestMask() const OVERRIDE;
779  virtual void GetHitTestMask(gfx::Path* mask) const OVERRIDE;
780  virtual Widget* AsWidget() OVERRIDE;
781  virtual const Widget* AsWidget() const OVERRIDE;
782  virtual bool SetInitialFocus(ui::WindowShowState show_state) OVERRIDE;
783
784  // Overridden from ui::EventSource:
785  virtual ui::EventProcessor* GetEventProcessor() OVERRIDE;
786
787  // Overridden from FocusTraversable:
788  virtual FocusSearch* GetFocusSearch() OVERRIDE;
789  virtual FocusTraversable* GetFocusTraversableParent() OVERRIDE;
790  virtual View* GetFocusTraversableParentView() OVERRIDE;
791
792  // Overridden from ui::NativeThemeObserver:
793  virtual void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) OVERRIDE;
794
795 protected:
796  // Creates the RootView to be used within this Widget. Subclasses may override
797  // to create custom RootViews that do specialized event processing.
798  // TODO(beng): Investigate whether or not this is needed.
799  virtual internal::RootView* CreateRootView();
800
801  // Provided to allow the NativeWidget implementations to destroy the RootView
802  // _before_ the focus manager/tooltip manager.
803  // TODO(beng): remove once we fold those objects onto this one.
804  void DestroyRootView();
805
806  // Notification that a drag will start. Default implementation does nothing.
807  virtual void OnDragWillStart();
808
809  // Notification that the drag performed by RunShellDrag() has completed.
810  virtual void OnDragComplete();
811
812 private:
813  friend class ComboboxTest;
814  friend class TextfieldTest;
815
816  // Sets the value of |disable_inactive_rendering_|. If the value changes,
817  // both the NonClientView and WidgetDelegate are notified.
818  void SetInactiveRenderingDisabled(bool value);
819
820  // Persists the window's restored position and "show" state using the
821  // window delegate.
822  void SaveWindowPlacement();
823
824  // Invokes SaveWindowPlacement() if the native widget has been initialized.
825  // This is called at times when the native widget may not have been
826  // initialized.
827  void SaveWindowPlacementIfInitialized();
828
829  // Sizes and positions the window just after it is created.
830  void SetInitialBounds(const gfx::Rect& bounds);
831
832  // Sizes and positions the frameless window just after it is created.
833  void SetInitialBoundsForFramelessWindow(const gfx::Rect& bounds);
834
835  // Returns the bounds and "show" state from the delegate. Returns true if
836  // the delegate wants to use a specified bounds.
837  bool GetSavedWindowPlacement(gfx::Rect* bounds,
838                               ui::WindowShowState* show_state);
839
840  // Creates and initializes a new InputMethod and returns it, otherwise null.
841  scoped_ptr<InputMethod> CreateInputMethod();
842
843  // Sets a different InputMethod instance to this widget. The instance
844  // must not be initialized, the ownership will be assumed by the widget.
845  // It's only for testing purpose.
846  void ReplaceInputMethod(InputMethod* input_method);
847
848  internal::NativeWidgetPrivate* native_widget_;
849
850  ObserverList<WidgetObserver> observers_;
851
852  ObserverList<WidgetRemovalsObserver> removals_observers_;
853
854  // Non-owned pointer to the Widget's delegate. If a NULL delegate is supplied
855  // to Init() a default WidgetDelegate is created.
856  WidgetDelegate* widget_delegate_;
857
858  // The root of the View hierarchy attached to this window.
859  // WARNING: see warning in tooltip_manager_ for ordering dependencies with
860  // this and tooltip_manager_.
861  scoped_ptr<internal::RootView> root_view_;
862
863  // The View that provides the non-client area of the window (title bar,
864  // window controls, sizing borders etc). To use an implementation other than
865  // the default, this class must be sub-classed and this value set to the
866  // desired implementation before calling |InitWindow()|.
867  NonClientView* non_client_view_;
868
869  // The focus manager keeping track of focus for this Widget and any of its
870  // children.  NULL for non top-level widgets.
871  // WARNING: RootView's destructor calls into the FocusManager. As such, this
872  // must be destroyed AFTER root_view_. This is enforced in DestroyRootView().
873  scoped_ptr<FocusManager> focus_manager_;
874
875  // A theme provider to use when no other theme provider is specified.
876  scoped_ptr<ui::DefaultThemeProvider> default_theme_provider_;
877
878  // Valid for the lifetime of RunShellDrag(), indicates the view the drag
879  // started from.
880  View* dragged_view_;
881
882  // See class documentation for Widget above for a note about ownership.
883  InitParams::Ownership ownership_;
884
885  // See set_is_secondary_widget().
886  bool is_secondary_widget_;
887
888  // The current frame type in use by this window. Defaults to
889  // FRAME_TYPE_DEFAULT.
890  FrameType frame_type_;
891
892  // True when the window should be rendered as active, regardless of whether
893  // or not it actually is.
894  bool disable_inactive_rendering_;
895
896  // Set to true if the widget is in the process of closing.
897  bool widget_closed_;
898
899  // The saved "show" state for this window. See note in SetInitialBounds
900  // that explains why we save this.
901  ui::WindowShowState saved_show_state_;
902
903  // The restored bounds used for the initial show. This is only used if
904  // |saved_show_state_| is maximized.
905  gfx::Rect initial_restored_bounds_;
906
907  // Focus is automatically set to the view provided by the delegate
908  // when the widget is shown. Set this value to false to override
909  // initial focus for the widget.
910  bool focus_on_creation_;
911
912  mutable scoped_ptr<InputMethod> input_method_;
913
914  // See |is_top_level()| accessor.
915  bool is_top_level_;
916
917  // Tracks whether native widget has been initialized.
918  bool native_widget_initialized_;
919
920  // Whether native widget has been destroyed.
921  bool native_widget_destroyed_;
922
923  // TODO(beng): Remove NativeWidgetGtk's dependence on these:
924  // If true, the mouse is currently down.
925  bool is_mouse_button_pressed_;
926
927  // True if capture losses should be ignored.
928  bool ignore_capture_loss_;
929
930  // TODO(beng): Remove NativeWidgetGtk's dependence on these:
931  // The following are used to detect duplicate mouse move events and not
932  // deliver them. Displaying a window may result in the system generating
933  // duplicate move events even though the mouse hasn't moved.
934  bool last_mouse_event_was_move_;
935  gfx::Point last_mouse_event_position_;
936
937  // True if event capture should be released on a mouse up event. Default is
938  // true.
939  bool auto_release_capture_;
940
941  // See description in GetRootLayers().
942  std::vector<ui::Layer*> root_layers_;
943
944  // Is |root_layers_| out of date?
945  bool root_layers_dirty_;
946
947  // True when window movement via mouse interaction with the frame should be
948  // disabled.
949  bool movement_disabled_;
950
951  ScopedObserver<ui::NativeTheme, ui::NativeThemeObserver> observer_manager_;
952
953  DISALLOW_COPY_AND_ASSIGN(Widget);
954};
955
956}  // namespace views
957
958#endif  // UI_VIEWS_WIDGET_WIDGET_H_
959