view.h revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
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_VIEW_H_
6#define UI_VIEWS_VIEW_H_
7
8#include <algorithm>
9#include <map>
10#include <set>
11#include <string>
12#include <vector>
13
14#include "base/compiler_specific.h"
15#include "base/i18n/rtl.h"
16#include "base/logging.h"
17#include "base/memory/scoped_ptr.h"
18#include "build/build_config.h"
19#include "ui/base/accelerators/accelerator.h"
20#include "ui/base/accessibility/accessibility_types.h"
21#include "ui/base/dragdrop/drag_drop_types.h"
22#include "ui/base/dragdrop/os_exchange_data.h"
23#include "ui/base/ui_base_types.h"
24#include "ui/compositor/layer_delegate.h"
25#include "ui/compositor/layer_owner.h"
26#include "ui/events/event.h"
27#include "ui/events/event_target.h"
28#include "ui/gfx/native_widget_types.h"
29#include "ui/gfx/rect.h"
30#include "ui/gfx/vector2d.h"
31#include "ui/views/background.h"
32#include "ui/views/border.h"
33#include "ui/views/focus_border.h"
34
35#if defined(OS_WIN)
36#include "base/win/scoped_comptr.h"
37#endif
38
39using ui::OSExchangeData;
40
41namespace gfx {
42class Canvas;
43class Insets;
44class Path;
45class Transform;
46}
47
48namespace ui {
49struct AccessibleViewState;
50class Compositor;
51class Layer;
52class NativeTheme;
53class TextInputClient;
54class Texture;
55class ThemeProvider;
56}
57
58namespace views {
59
60class Background;
61class Border;
62class ContextMenuController;
63class DragController;
64class FocusBorder;
65class FocusManager;
66class FocusTraversable;
67class InputMethod;
68class LayoutManager;
69class NativeViewAccessibility;
70class ScrollView;
71class Widget;
72
73namespace internal {
74class PostEventDispatchHandler;
75class RootView;
76}
77
78/////////////////////////////////////////////////////////////////////////////
79//
80// View class
81//
82//   A View is a rectangle within the views View hierarchy. It is the base
83//   class for all Views.
84//
85//   A View is a container of other Views (there is no such thing as a Leaf
86//   View - makes code simpler, reduces type conversion headaches, design
87//   mistakes etc)
88//
89//   The View contains basic properties for sizing (bounds), layout (flex,
90//   orientation, etc), painting of children and event dispatch.
91//
92//   The View also uses a simple Box Layout Manager similar to XUL's
93//   SprocketLayout system. Alternative Layout Managers implementing the
94//   LayoutManager interface can be used to lay out children if required.
95//
96//   It is up to the subclass to implement Painting and storage of subclass -
97//   specific properties and functionality.
98//
99//   Unless otherwise documented, views is not thread safe and should only be
100//   accessed from the main thread.
101//
102/////////////////////////////////////////////////////////////////////////////
103class VIEWS_EXPORT View : public ui::LayerDelegate,
104                          public ui::LayerOwner,
105                          public ui::AcceleratorTarget,
106                          public ui::EventTarget {
107 public:
108  typedef std::vector<View*> Views;
109
110  struct ViewHierarchyChangedDetails {
111    ViewHierarchyChangedDetails()
112        : is_add(false),
113          parent(NULL),
114          child(NULL),
115          move_view(NULL) {}
116
117    ViewHierarchyChangedDetails(bool is_add,
118                                View* parent,
119                                View* child,
120                                View* move_view)
121        : is_add(is_add),
122          parent(parent),
123          child(child),
124          move_view(move_view) {}
125
126    bool is_add;
127    // New parent if |is_add| is true, old parent if |is_add| is false.
128    View* parent;
129    // The view being added or removed.
130    View* child;
131    // If this is a move (reparent), meaning AddChildViewAt() is invoked with an
132    // existing parent, then a notification for the remove is sent first,
133    // followed by one for the add.  This case can be distinguished by a
134    // non-NULL |move_view|.
135    // For the remove part of move, |move_view| is the new parent of the View
136    // being removed.
137    // For the add part of move, |move_view| is the old parent of the View being
138    // added.
139    View* move_view;
140  };
141
142  // Creation and lifetime -----------------------------------------------------
143
144  View();
145  virtual ~View();
146
147  // By default a View is owned by its parent unless specified otherwise here.
148  void set_owned_by_client() { owned_by_client_ = true; }
149
150  // Tree operations -----------------------------------------------------------
151
152  // Get the Widget that hosts this View, if any.
153  virtual const Widget* GetWidget() const;
154  virtual Widget* GetWidget();
155
156  // Adds |view| as a child of this view, optionally at |index|.
157  void AddChildView(View* view);
158  void AddChildViewAt(View* view, int index);
159
160  // Moves |view| to the specified |index|. A negative value for |index| moves
161  // the view at the end.
162  void ReorderChildView(View* view, int index);
163
164  // Removes |view| from this view. The view's parent will change to NULL.
165  void RemoveChildView(View* view);
166
167  // Removes all the children from this view. If |delete_children| is true,
168  // the views are deleted, unless marked as not parent owned.
169  void RemoveAllChildViews(bool delete_children);
170
171  int child_count() const { return static_cast<int>(children_.size()); }
172  bool has_children() const { return !children_.empty(); }
173
174  // Returns the child view at |index|.
175  const View* child_at(int index) const {
176    DCHECK_GE(index, 0);
177    DCHECK_LT(index, child_count());
178    return children_[index];
179  }
180  View* child_at(int index) {
181    return const_cast<View*>(const_cast<const View*>(this)->child_at(index));
182  }
183
184  // Returns the parent view.
185  const View* parent() const { return parent_; }
186  View* parent() { return parent_; }
187
188  // Returns true if |view| is contained within this View's hierarchy, even as
189  // an indirect descendant. Will return true if child is also this view.
190  bool Contains(const View* view) const;
191
192  // Returns the index of |view|, or -1 if |view| is not a child of this view.
193  int GetIndexOf(const View* view) const;
194
195  // Size and disposition ------------------------------------------------------
196  // Methods for obtaining and modifying the position and size of the view.
197  // Position is in the coordinate system of the view's parent.
198  // Position is NOT flipped for RTL. See "RTL positioning" for RTL-sensitive
199  // position accessors.
200  // Transformations are not applied on the size/position. For example, if
201  // bounds is (0, 0, 100, 100) and it is scaled by 0.5 along the X axis, the
202  // width will still be 100 (although when painted, it will be 50x50, painted
203  // at location (0, 0)).
204
205  void SetBounds(int x, int y, int width, int height);
206  void SetBoundsRect(const gfx::Rect& bounds);
207  void SetSize(const gfx::Size& size);
208  void SetPosition(const gfx::Point& position);
209  void SetX(int x);
210  void SetY(int y);
211
212  // No transformation is applied on the size or the locations.
213  const gfx::Rect& bounds() const { return bounds_; }
214  int x() const { return bounds_.x(); }
215  int y() const { return bounds_.y(); }
216  int width() const { return bounds_.width(); }
217  int height() const { return bounds_.height(); }
218  const gfx::Size& size() const { return bounds_.size(); }
219
220  // Returns the bounds of the content area of the view, i.e. the rectangle
221  // enclosed by the view's border.
222  gfx::Rect GetContentsBounds() const;
223
224  // Returns the bounds of the view in its own coordinates (i.e. position is
225  // 0, 0).
226  gfx::Rect GetLocalBounds() const;
227
228  // Returns the bounds of the layer in its own pixel coordinates.
229  gfx::Rect GetLayerBoundsInPixel() const;
230
231  // Returns the insets of the current border. If there is no border an empty
232  // insets is returned.
233  virtual gfx::Insets GetInsets() const;
234
235  // Returns the visible bounds of the receiver in the receivers coordinate
236  // system.
237  //
238  // When traversing the View hierarchy in order to compute the bounds, the
239  // function takes into account the mirroring setting and transformation for
240  // each View and therefore it will return the mirrored and transformed version
241  // of the visible bounds if need be.
242  gfx::Rect GetVisibleBounds() const;
243
244  // Return the bounds of the View in screen coordinate system.
245  gfx::Rect GetBoundsInScreen() const;
246
247  // Returns the baseline of this view, or -1 if this view has no baseline. The
248  // return value is relative to the preferred height.
249  virtual int GetBaseline() const;
250
251  // Get the size the View would like to be, if enough space were available.
252  virtual gfx::Size GetPreferredSize();
253
254  // Convenience method that sizes this view to its preferred size.
255  void SizeToPreferredSize();
256
257  // Gets the minimum size of the view. View's implementation invokes
258  // GetPreferredSize.
259  virtual gfx::Size GetMinimumSize();
260
261  // Gets the maximum size of the view. Currently only used for sizing shell
262  // windows.
263  virtual gfx::Size GetMaximumSize();
264
265  // Return the height necessary to display this view with the provided width.
266  // View's implementation returns the value from getPreferredSize.cy.
267  // Override if your View's preferred height depends upon the width (such
268  // as with Labels).
269  virtual int GetHeightForWidth(int w);
270
271  // Set whether this view is visible. Painting is scheduled as needed.
272  virtual void SetVisible(bool visible);
273
274  // Return whether a view is visible
275  bool visible() const { return visible_; }
276
277  // Returns true if this view is drawn on screen.
278  virtual bool IsDrawn() const;
279
280  // Set whether this view is enabled. A disabled view does not receive keyboard
281  // or mouse inputs. If |enabled| differs from the current value, SchedulePaint
282  // is invoked.
283  void SetEnabled(bool enabled);
284
285  // Returns whether the view is enabled.
286  bool enabled() const { return enabled_; }
287
288  // This indicates that the view completely fills its bounds in an opaque
289  // color. This doesn't affect compositing but is a hint to the compositor to
290  // optimize painting.
291  // Note that this method does not implicitly create a layer if one does not
292  // already exist for the View, but is a no-op in that case.
293  void SetFillsBoundsOpaquely(bool fills_bounds_opaquely);
294
295  // Transformations -----------------------------------------------------------
296
297  // Methods for setting transformations for a view (e.g. rotation, scaling).
298
299  gfx::Transform GetTransform() const;
300
301  // Clipping parameters. Clipping is done relative to the view bounds.
302  void set_clip_insets(gfx::Insets clip_insets) { clip_insets_ = clip_insets; }
303
304  // Sets the transform to the supplied transform.
305  void SetTransform(const gfx::Transform& transform);
306
307  // Sets whether this view paints to a layer. A view paints to a layer if
308  // either of the following are true:
309  // . the view has a non-identity transform.
310  // . SetPaintToLayer(true) has been invoked.
311  // View creates the Layer only when it exists in a Widget with a non-NULL
312  // Compositor.
313  void SetPaintToLayer(bool paint_to_layer);
314
315  // Recreates a layer for the view and returns the old layer. After this call,
316  // the View no longer has a pointer to the old layer (so it won't be able to
317  // update the old layer or destroy it). The caller must free the returned
318  // layer.
319  // Returns NULL and does not recreate layer if view does not own its layer.
320  ui::Layer* RecreateLayer() WARN_UNUSED_RESULT;
321
322  // RTL positioning -----------------------------------------------------------
323
324  // Methods for accessing the bounds and position of the view, relative to its
325  // parent. The position returned is mirrored if the parent view is using a RTL
326  // layout.
327  //
328  // NOTE: in the vast majority of the cases, the mirroring implementation is
329  //       transparent to the View subclasses and therefore you should use the
330  //       bounds() accessor instead.
331  gfx::Rect GetMirroredBounds() const;
332  gfx::Point GetMirroredPosition() const;
333  int GetMirroredX() const;
334
335  // Given a rectangle specified in this View's coordinate system, the function
336  // computes the 'left' value for the mirrored rectangle within this View. If
337  // the View's UI layout is not right-to-left, then bounds.x() is returned.
338  //
339  // UI mirroring is transparent to most View subclasses and therefore there is
340  // no need to call this routine from anywhere within your subclass
341  // implementation.
342  int GetMirroredXForRect(const gfx::Rect& rect) const;
343
344  // Given the X coordinate of a point inside the View, this function returns
345  // the mirrored X coordinate of the point if the View's UI layout is
346  // right-to-left. If the layout is left-to-right, the same X coordinate is
347  // returned.
348  //
349  // Following are a few examples of the values returned by this function for
350  // a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
351  //
352  // GetMirroredXCoordinateInView(0) -> 100
353  // GetMirroredXCoordinateInView(20) -> 80
354  // GetMirroredXCoordinateInView(99) -> 1
355  int GetMirroredXInView(int x) const;
356
357  // Given a X coordinate and a width inside the View, this function returns
358  // the mirrored X coordinate if the View's UI layout is right-to-left. If the
359  // layout is left-to-right, the same X coordinate is returned.
360  //
361  // Following are a few examples of the values returned by this function for
362  // a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
363  //
364  // GetMirroredXCoordinateInView(0, 10) -> 90
365  // GetMirroredXCoordinateInView(20, 20) -> 60
366  int GetMirroredXWithWidthInView(int x, int w) const;
367
368  // Layout --------------------------------------------------------------------
369
370  // Lay out the child Views (set their bounds based on sizing heuristics
371  // specific to the current Layout Manager)
372  virtual void Layout();
373
374  // TODO(beng): I think we should remove this.
375  // Mark this view and all parents to require a relayout. This ensures the
376  // next call to Layout() will propagate to this view, even if the bounds of
377  // parent views do not change.
378  void InvalidateLayout();
379
380  // Gets/Sets the Layout Manager used by this view to size and place its
381  // children.
382  // The LayoutManager is owned by the View and is deleted when the view is
383  // deleted, or when a new LayoutManager is installed.
384  LayoutManager* GetLayoutManager() const;
385  void SetLayoutManager(LayoutManager* layout);
386
387  // Attributes ----------------------------------------------------------------
388
389  // The view class name.
390  static const char kViewClassName[];
391
392  // Return the receiving view's class name. A view class is a string which
393  // uniquely identifies the view class. It is intended to be used as a way to
394  // find out during run time if a view can be safely casted to a specific view
395  // subclass. The default implementation returns kViewClassName.
396  virtual const char* GetClassName() const;
397
398  // Returns the first ancestor, starting at this, whose class name is |name|.
399  // Returns null if no ancestor has the class name |name|.
400  View* GetAncestorWithClassName(const std::string& name);
401
402  // Recursively descends the view tree starting at this view, and returns
403  // the first child that it encounters that has the given ID.
404  // Returns NULL if no matching child view is found.
405  virtual const View* GetViewByID(int id) const;
406  virtual View* GetViewByID(int id);
407
408  // Gets and sets the ID for this view. ID should be unique within the subtree
409  // that you intend to search for it. 0 is the default ID for views.
410  int id() const { return id_; }
411  void set_id(int id) { id_ = id; }
412
413  // A group id is used to tag views which are part of the same logical group.
414  // Focus can be moved between views with the same group using the arrow keys.
415  // Groups are currently used to implement radio button mutual exclusion.
416  // The group id is immutable once it's set.
417  void SetGroup(int gid);
418  // Returns the group id of the view, or -1 if the id is not set yet.
419  int GetGroup() const;
420
421  // If this returns true, the views from the same group can each be focused
422  // when moving focus with the Tab/Shift-Tab key.  If this returns false,
423  // only the selected view from the group (obtained with
424  // GetSelectedViewForGroup()) is focused.
425  virtual bool IsGroupFocusTraversable() const;
426
427  // Fills |views| with all the available views which belong to the provided
428  // |group|.
429  void GetViewsInGroup(int group, Views* views);
430
431  // Returns the View that is currently selected in |group|.
432  // The default implementation simply returns the first View found for that
433  // group.
434  virtual View* GetSelectedViewForGroup(int group);
435
436  // Coordinate conversion -----------------------------------------------------
437
438  // Note that the utility coordinate conversions functions always operate on
439  // the mirrored position of the child Views if the parent View uses a
440  // right-to-left UI layout.
441
442  // Convert a point from the coordinate system of one View to another.
443  //
444  // |source| and |target| must be in the same widget, but doesn't need to be in
445  // the same view hierarchy.
446  // |source| can be NULL in which case it means the screen coordinate system.
447  static void ConvertPointToTarget(const View* source,
448                                   const View* target,
449                                   gfx::Point* point);
450
451  // Convert a point from a View's coordinate system to that of its Widget.
452  static void ConvertPointToWidget(const View* src, gfx::Point* point);
453
454  // Convert a point from the coordinate system of a View's Widget to that
455  // View's coordinate system.
456  static void ConvertPointFromWidget(const View* dest, gfx::Point* p);
457
458  // Convert a point from a View's coordinate system to that of the screen.
459  static void ConvertPointToScreen(const View* src, gfx::Point* point);
460
461  // Convert a point from a View's coordinate system to that of the screen.
462  static void ConvertPointFromScreen(const View* dst, gfx::Point* point);
463
464  // Applies transformation on the rectangle, which is in the view's coordinate
465  // system, to convert it into the parent's coordinate system.
466  gfx::Rect ConvertRectToParent(const gfx::Rect& rect) const;
467
468  // Converts a rectangle from this views coordinate system to its widget
469  // coordinate system.
470  gfx::Rect ConvertRectToWidget(const gfx::Rect& rect) const;
471
472  // Painting ------------------------------------------------------------------
473
474  // Mark all or part of the View's bounds as dirty (needing repaint).
475  // |r| is in the View's coordinates.
476  // Rectangle |r| should be in the view's coordinate system. The
477  // transformations are applied to it to convert it into the parent coordinate
478  // system before propagating SchedulePaint up the view hierarchy.
479  // TODO(beng): Make protected.
480  virtual void SchedulePaint();
481  virtual void SchedulePaintInRect(const gfx::Rect& r);
482
483  // Called by the framework to paint a View. Performs translation and clipping
484  // for View coordinates and language direction as required, allows the View
485  // to paint itself via the various OnPaint*() event handlers and then paints
486  // the hierarchy beneath it.
487  virtual void Paint(gfx::Canvas* canvas);
488
489  // The background object is owned by this object and may be NULL.
490  void set_background(Background* b) { background_.reset(b); }
491  const Background* background() const { return background_.get(); }
492  Background* background() { return background_.get(); }
493
494  // The border object is owned by this object and may be NULL.
495  void set_border(Border* b) { border_.reset(b); }
496  const Border* border() const { return border_.get(); }
497  Border* border() { return border_.get(); }
498
499  // The focus_border object is owned by this object and may be NULL.
500  void set_focus_border(FocusBorder* b) { focus_border_.reset(b); }
501  const FocusBorder* focus_border() const { return focus_border_.get(); }
502  FocusBorder* focus_border() { return focus_border_.get(); }
503
504  // Get the theme provider from the parent widget.
505  virtual ui::ThemeProvider* GetThemeProvider() const;
506
507  // Returns the NativeTheme to use for this View. This calls through to
508  // GetNativeTheme() on the Widget this View is in. If this View is not in a
509  // Widget this returns ui::NativeTheme::instance().
510  ui::NativeTheme* GetNativeTheme() {
511    return const_cast<ui::NativeTheme*>(
512        const_cast<const View*>(this)->GetNativeTheme());
513  }
514  const ui::NativeTheme* GetNativeTheme() const;
515
516  // RTL painting --------------------------------------------------------------
517
518  // This method determines whether the gfx::Canvas object passed to
519  // View::Paint() needs to be transformed such that anything drawn on the
520  // canvas object during View::Paint() is flipped horizontally.
521  //
522  // By default, this function returns false (which is the initial value of
523  // |flip_canvas_on_paint_for_rtl_ui_|). View subclasses that need to paint on
524  // a flipped gfx::Canvas when the UI layout is right-to-left need to call
525  // EnableCanvasFlippingForRTLUI().
526  bool FlipCanvasOnPaintForRTLUI() const {
527    return flip_canvas_on_paint_for_rtl_ui_ ? base::i18n::IsRTL() : false;
528  }
529
530  // Enables or disables flipping of the gfx::Canvas during View::Paint().
531  // Note that if canvas flipping is enabled, the canvas will be flipped only
532  // if the UI layout is right-to-left; that is, the canvas will be flipped
533  // only if base::i18n::IsRTL() returns true.
534  //
535  // Enabling canvas flipping is useful for leaf views that draw an image that
536  // needs to be flipped horizontally when the UI layout is right-to-left
537  // (views::Button, for example). This method is helpful for such classes
538  // because their drawing logic stays the same and they can become agnostic to
539  // the UI directionality.
540  void EnableCanvasFlippingForRTLUI(bool enable) {
541    flip_canvas_on_paint_for_rtl_ui_ = enable;
542  }
543
544  // Accelerated painting ------------------------------------------------------
545
546  // Enable/Disable accelerated compositing.
547  static void set_use_acceleration_when_possible(bool use);
548  static bool get_use_acceleration_when_possible();
549
550  // Input ---------------------------------------------------------------------
551  // The points (and mouse locations) in the following functions are in the
552  // view's coordinates, except for a RootView.
553
554  // Returns the deepest visible descendant that contains the specified point
555  // and supports event handling.
556  virtual View* GetEventHandlerForPoint(const gfx::Point& point);
557
558  // Returns the deepest visible descendant that contains the specified point
559  // and supports tooltips. If the view does not contain the point, returns
560  // NULL.
561  virtual View* GetTooltipHandlerForPoint(const gfx::Point& point);
562
563  // Return the cursor that should be used for this view or the default cursor.
564  // The event location is in the receiver's coordinate system. The caller is
565  // responsible for managing the lifetime of the returned object, though that
566  // lifetime may vary from platform to platform. On Windows and Aura,
567  // the cursor is a shared resource.
568  virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event);
569
570  // A convenience function which calls HitTestRect() with a rect of size
571  // 1x1 and an origin of |point|.
572  bool HitTestPoint(const gfx::Point& point) const;
573
574  // Tests whether |rect| intersects this view's bounds.
575  virtual bool HitTestRect(const gfx::Rect& rect) const;
576
577  // Returns true if the mouse cursor is over |view| and mouse events are
578  // enabled.
579  bool IsMouseHovered();
580
581  // This method is invoked when the user clicks on this view.
582  // The provided event is in the receiver's coordinate system.
583  //
584  // Return true if you processed the event and want to receive subsequent
585  // MouseDraggged and MouseReleased events.  This also stops the event from
586  // bubbling.  If you return false, the event will bubble through parent
587  // views.
588  //
589  // If you remove yourself from the tree while processing this, event bubbling
590  // stops as if you returned true, but you will not receive future events.
591  // The return value is ignored in this case.
592  //
593  // Default implementation returns true if a ContextMenuController has been
594  // set, false otherwise. Override as needed.
595  //
596  virtual bool OnMousePressed(const ui::MouseEvent& event);
597
598  // This method is invoked when the user clicked on this control.
599  // and is still moving the mouse with a button pressed.
600  // The provided event is in the receiver's coordinate system.
601  //
602  // Return true if you processed the event and want to receive
603  // subsequent MouseDragged and MouseReleased events.
604  //
605  // Default implementation returns true if a ContextMenuController has been
606  // set, false otherwise. Override as needed.
607  //
608  virtual bool OnMouseDragged(const ui::MouseEvent& event);
609
610  // This method is invoked when the user releases the mouse
611  // button. The event is in the receiver's coordinate system.
612  //
613  // Default implementation notifies the ContextMenuController is appropriate.
614  // Subclasses that wish to honor the ContextMenuController should invoke
615  // super.
616  virtual void OnMouseReleased(const ui::MouseEvent& event);
617
618  // This method is invoked when the mouse press/drag was canceled by a
619  // system/user gesture.
620  virtual void OnMouseCaptureLost();
621
622  // This method is invoked when the mouse is above this control
623  // The event is in the receiver's coordinate system.
624  //
625  // Default implementation does nothing. Override as needed.
626  virtual void OnMouseMoved(const ui::MouseEvent& event);
627
628  // This method is invoked when the mouse enters this control.
629  //
630  // Default implementation does nothing. Override as needed.
631  virtual void OnMouseEntered(const ui::MouseEvent& event);
632
633  // This method is invoked when the mouse exits this control
634  // The provided event location is always (0, 0)
635  // Default implementation does nothing. Override as needed.
636  virtual void OnMouseExited(const ui::MouseEvent& event);
637
638  // Set the MouseHandler for a drag session.
639  //
640  // A drag session is a stream of mouse events starting
641  // with a MousePressed event, followed by several MouseDragged
642  // events and finishing with a MouseReleased event.
643  //
644  // This method should be only invoked while processing a
645  // MouseDragged or MousePressed event.
646  //
647  // All further mouse dragged and mouse up events will be sent
648  // the MouseHandler, even if it is reparented to another window.
649  //
650  // The MouseHandler is automatically cleared when the control
651  // comes back from processing the MouseReleased event.
652  //
653  // Note: if the mouse handler is no longer connected to a
654  // view hierarchy, events won't be sent.
655  //
656  // TODO(sky): rename this.
657  virtual void SetMouseHandler(View* new_mouse_handler);
658
659  // Invoked when a key is pressed or released.
660  // Subclasser should return true if the event has been processed and false
661  // otherwise. If the event has not been processed, the parent will be given a
662  // chance.
663  virtual bool OnKeyPressed(const ui::KeyEvent& event);
664  virtual bool OnKeyReleased(const ui::KeyEvent& event);
665
666  // Invoked when the user uses the mousewheel. Implementors should return true
667  // if the event has been processed and false otherwise. This message is sent
668  // if the view is focused. If the event has not been processed, the parent
669  // will be given a chance.
670  virtual bool OnMouseWheel(const ui::MouseWheelEvent& event);
671
672
673  // See field for description.
674  void set_notify_enter_exit_on_child(bool notify) {
675    notify_enter_exit_on_child_ = notify;
676  }
677  bool notify_enter_exit_on_child() const {
678    return notify_enter_exit_on_child_;
679  }
680
681  // Returns the View's TextInputClient instance or NULL if the View doesn't
682  // support text input.
683  virtual ui::TextInputClient* GetTextInputClient();
684
685  // Convenience method to retrieve the InputMethod associated with the
686  // Widget that contains this view. Returns NULL if this view is not part of a
687  // view hierarchy with a Widget.
688  virtual InputMethod* GetInputMethod();
689  virtual const InputMethod* GetInputMethod() const;
690
691  // Overridden from ui::EventTarget:
692  virtual bool CanAcceptEvent(const ui::Event& event) OVERRIDE;
693  virtual ui::EventTarget* GetParentTarget() OVERRIDE;
694
695  // Overridden from ui::EventHandler:
696  virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE;
697  virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE;
698  virtual void OnScrollEvent(ui::ScrollEvent* event) OVERRIDE;
699  virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE;
700  virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
701
702  // Accelerators --------------------------------------------------------------
703
704  // Sets a keyboard accelerator for that view. When the user presses the
705  // accelerator key combination, the AcceleratorPressed method is invoked.
706  // Note that you can set multiple accelerators for a view by invoking this
707  // method several times. Note also that AcceleratorPressed is invoked only
708  // when CanHandleAccelerators() is true.
709  virtual void AddAccelerator(const ui::Accelerator& accelerator);
710
711  // Removes the specified accelerator for this view.
712  virtual void RemoveAccelerator(const ui::Accelerator& accelerator);
713
714  // Removes all the keyboard accelerators for this view.
715  virtual void ResetAccelerators();
716
717  // Overridden from AcceleratorTarget:
718  virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE;
719
720  // Returns whether accelerators are enabled for this view. Accelerators are
721  // enabled if the containing widget is visible and the view is enabled() and
722  // IsDrawn()
723  virtual bool CanHandleAccelerators() const OVERRIDE;
724
725  // Focus ---------------------------------------------------------------------
726
727  // Returns whether this view currently has the focus.
728  virtual bool HasFocus() const;
729
730  // Returns the view that should be selected next when pressing Tab.
731  View* GetNextFocusableView();
732  const View* GetNextFocusableView() const;
733
734  // Returns the view that should be selected next when pressing Shift-Tab.
735  View* GetPreviousFocusableView();
736
737  // Sets the component that should be selected next when pressing Tab, and
738  // makes the current view the precedent view of the specified one.
739  // Note that by default views are linked in the order they have been added to
740  // their container. Use this method if you want to modify the order.
741  // IMPORTANT NOTE: loops in the focus hierarchy are not supported.
742  void SetNextFocusableView(View* view);
743
744  // Sets whether this view is capable of taking focus.
745  // Note that this is false by default so that a view used as a container does
746  // not get the focus.
747  void set_focusable(bool focusable) { focusable_ = focusable; }
748
749  // Returns true if this view is capable of taking focus.
750  bool focusable() const { return focusable_ && enabled_ && visible_; }
751
752  // Returns true if this view is |focusable_|, |enabled_| and drawn.
753  virtual bool IsFocusable() const;
754
755  // Return whether this view is focusable when the user requires full keyboard
756  // access, even though it may not be normally focusable.
757  bool IsAccessibilityFocusable() const;
758
759  // Set whether this view can be made focusable if the user requires
760  // full keyboard access, even though it's not normally focusable.
761  // Note that this is false by default.
762  void set_accessibility_focusable(bool accessibility_focusable) {
763    accessibility_focusable_ = accessibility_focusable;
764  }
765
766  // Convenience method to retrieve the FocusManager associated with the
767  // Widget that contains this view.  This can return NULL if this view is not
768  // part of a view hierarchy with a Widget.
769  virtual FocusManager* GetFocusManager();
770  virtual const FocusManager* GetFocusManager() const;
771
772  // Request keyboard focus. The receiving view will become the focused view.
773  virtual void RequestFocus();
774
775  // Invoked when a view is about to be requested for focus due to the focus
776  // traversal. Reverse is this request was generated going backward
777  // (Shift-Tab).
778  virtual void AboutToRequestFocusFromTabTraversal(bool reverse) {}
779
780  // Invoked when a key is pressed before the key event is processed (and
781  // potentially eaten) by the focus manager for tab traversal, accelerators and
782  // other focus related actions.
783  // The default implementation returns false, ensuring that tab traversal and
784  // accelerators processing is performed.
785  // Subclasses should return true if they want to process the key event and not
786  // have it processed as an accelerator (if any) or as a tab traversal (if the
787  // key event is for the TAB key).  In that case, OnKeyPressed will
788  // subsequently be invoked for that event.
789  virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event);
790
791  // Subclasses that contain traversable children that are not directly
792  // accessible through the children hierarchy should return the associated
793  // FocusTraversable for the focus traversal to work properly.
794  virtual FocusTraversable* GetFocusTraversable();
795
796  // Subclasses that can act as a "pane" must implement their own
797  // FocusTraversable to keep the focus trapped within the pane.
798  // If this method returns an object, any view that's a direct or
799  // indirect child of this view will always use this FocusTraversable
800  // rather than the one from the widget.
801  virtual FocusTraversable* GetPaneFocusTraversable();
802
803  // Tooltips ------------------------------------------------------------------
804
805  // Gets the tooltip for this View. If the View does not have a tooltip,
806  // return false. If the View does have a tooltip, copy the tooltip into
807  // the supplied string and return true.
808  // Any time the tooltip text that a View is displaying changes, it must
809  // invoke TooltipTextChanged.
810  // |p| provides the coordinates of the mouse (relative to this view).
811  virtual bool GetTooltipText(const gfx::Point& p, string16* tooltip) const;
812
813  // Returns the location (relative to this View) for the text on the tooltip
814  // to display. If false is returned (the default), the tooltip is placed at
815  // a default position.
816  virtual bool GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const;
817
818  // Context menus -------------------------------------------------------------
819
820  // Sets the ContextMenuController. Setting this to non-null makes the View
821  // process mouse events.
822  ContextMenuController* context_menu_controller() {
823    return context_menu_controller_;
824  }
825  void set_context_menu_controller(ContextMenuController* menu_controller) {
826    context_menu_controller_ = menu_controller;
827  }
828
829  // Provides default implementation for context menu handling. The default
830  // implementation calls the ShowContextMenu of the current
831  // ContextMenuController (if it is not NULL). Overridden in subclassed views
832  // to provide right-click menu display triggerd by the keyboard (i.e. for the
833  // Chrome toolbar Back and Forward buttons). No source needs to be specified,
834  // as it is always equal to the current View.
835  virtual void ShowContextMenu(const gfx::Point& p,
836                               ui::MenuSourceType source_type);
837
838  // On some platforms, we show context menu on mouse press instead of release.
839  // This method returns true for those platforms.
840  static bool ShouldShowContextMenuOnMousePress();
841
842  // Drag and drop -------------------------------------------------------------
843
844  DragController* drag_controller() { return drag_controller_; }
845  void set_drag_controller(DragController* drag_controller) {
846    drag_controller_ = drag_controller;
847  }
848
849  // During a drag and drop session when the mouse moves the view under the
850  // mouse is queried for the drop types it supports by way of the
851  // GetDropFormats methods. If the view returns true and the drag site can
852  // provide data in one of the formats, the view is asked if the drop data
853  // is required before any other drop events are sent. Once the
854  // data is available the view is asked if it supports the drop (by way of
855  // the CanDrop method). If a view returns true from CanDrop,
856  // OnDragEntered is sent to the view when the mouse first enters the view,
857  // as the mouse moves around within the view OnDragUpdated is invoked.
858  // If the user releases the mouse over the view and OnDragUpdated returns a
859  // valid drop, then OnPerformDrop is invoked. If the mouse moves outside the
860  // view or over another view that wants the drag, OnDragExited is invoked.
861  //
862  // Similar to mouse events, the deepest view under the mouse is first checked
863  // if it supports the drop (Drop). If the deepest view under
864  // the mouse does not support the drop, the ancestors are walked until one
865  // is found that supports the drop.
866
867  // Override and return the set of formats that can be dropped on this view.
868  // |formats| is a bitmask of the formats defined bye OSExchangeData::Format.
869  // The default implementation returns false, which means the view doesn't
870  // support dropping.
871  virtual bool GetDropFormats(
872      int* formats,
873      std::set<OSExchangeData::CustomFormat>* custom_formats);
874
875  // Override and return true if the data must be available before any drop
876  // methods should be invoked. The default is false.
877  virtual bool AreDropTypesRequired();
878
879  // A view that supports drag and drop must override this and return true if
880  // data contains a type that may be dropped on this view.
881  virtual bool CanDrop(const OSExchangeData& data);
882
883  // OnDragEntered is invoked when the mouse enters this view during a drag and
884  // drop session and CanDrop returns true. This is immediately
885  // followed by an invocation of OnDragUpdated, and eventually one of
886  // OnDragExited or OnPerformDrop.
887  virtual void OnDragEntered(const ui::DropTargetEvent& event);
888
889  // Invoked during a drag and drop session while the mouse is over the view.
890  // This should return a bitmask of the DragDropTypes::DragOperation supported
891  // based on the location of the event. Return 0 to indicate the drop should
892  // not be accepted.
893  virtual int OnDragUpdated(const ui::DropTargetEvent& event);
894
895  // Invoked during a drag and drop session when the mouse exits the views, or
896  // when the drag session was canceled and the mouse was over the view.
897  virtual void OnDragExited();
898
899  // Invoked during a drag and drop session when OnDragUpdated returns a valid
900  // operation and the user release the mouse.
901  virtual int OnPerformDrop(const ui::DropTargetEvent& event);
902
903  // Invoked from DoDrag after the drag completes. This implementation does
904  // nothing, and is intended for subclasses to do cleanup.
905  virtual void OnDragDone();
906
907  // Returns true if the mouse was dragged enough to start a drag operation.
908  // delta_x and y are the distance the mouse was dragged.
909  static bool ExceededDragThreshold(const gfx::Vector2d& delta);
910
911  // Accessibility -------------------------------------------------------------
912
913  // Modifies |state| to reflect the current accessible state of this view.
914  virtual void GetAccessibleState(ui::AccessibleViewState* state) { }
915
916  // Returns an instance of the native accessibility interface for this view.
917  virtual gfx::NativeViewAccessible GetNativeViewAccessible();
918
919  // Notifies assistive technology that an accessibility event has
920  // occurred on this view, such as when the view is focused or when its
921  // value changes. Pass true for |send_native_event| except for rare
922  // cases where the view is a native control that's already sending a
923  // native accessibility event and the duplicate event would cause
924  // problems.
925  void NotifyAccessibilityEvent(ui::AccessibilityTypes::Event event_type,
926                                bool send_native_event);
927
928  // Scrolling -----------------------------------------------------------------
929  // TODO(beng): Figure out if this can live somewhere other than View, i.e.
930  //             closer to ScrollView.
931
932  // Scrolls the specified region, in this View's coordinate system, to be
933  // visible. View's implementation passes the call onto the parent View (after
934  // adjusting the coordinates). It is up to views that only show a portion of
935  // the child view, such as Viewport, to override appropriately.
936  virtual void ScrollRectToVisible(const gfx::Rect& rect);
937
938  // The following methods are used by ScrollView to determine the amount
939  // to scroll relative to the visible bounds of the view. For example, a
940  // return value of 10 indicates the scrollview should scroll 10 pixels in
941  // the appropriate direction.
942  //
943  // Each method takes the following parameters:
944  //
945  // is_horizontal: if true, scrolling is along the horizontal axis, otherwise
946  //                the vertical axis.
947  // is_positive: if true, scrolling is by a positive amount. Along the
948  //              vertical axis scrolling by a positive amount equates to
949  //              scrolling down.
950  //
951  // The return value should always be positive and gives the number of pixels
952  // to scroll. ScrollView interprets a return value of 0 (or negative)
953  // to scroll by a default amount.
954  //
955  // See VariableRowHeightScrollHelper and FixedRowHeightScrollHelper for
956  // implementations of common cases.
957  virtual int GetPageScrollIncrement(ScrollView* scroll_view,
958                                     bool is_horizontal, bool is_positive);
959  virtual int GetLineScrollIncrement(ScrollView* scroll_view,
960                                     bool is_horizontal, bool is_positive);
961
962 protected:
963  // Used to track a drag. RootView passes this into
964  // ProcessMousePressed/Dragged.
965  struct DragInfo {
966    // Sets possible_drag to false and start_x/y to 0. This is invoked by
967    // RootView prior to invoke ProcessMousePressed.
968    void Reset();
969
970    // Sets possible_drag to true and start_pt to the specified point.
971    // This is invoked by the target view if it detects the press may generate
972    // a drag.
973    void PossibleDrag(const gfx::Point& p);
974
975    // Whether the press may generate a drag.
976    bool possible_drag;
977
978    // Coordinates of the mouse press.
979    gfx::Point start_pt;
980  };
981
982  // Size and disposition ------------------------------------------------------
983
984  // Override to be notified when the bounds of the view have changed.
985  virtual void OnBoundsChanged(const gfx::Rect& previous_bounds);
986
987  // Called when the preferred size of a child view changed.  This gives the
988  // parent an opportunity to do a fresh layout if that makes sense.
989  virtual void ChildPreferredSizeChanged(View* child) {}
990
991  // Called when the visibility of a child view changed.  This gives the parent
992  // an opportunity to do a fresh layout if that makes sense.
993  virtual void ChildVisibilityChanged(View* child) {}
994
995  // Invalidates the layout and calls ChildPreferredSizeChanged on the parent
996  // if there is one. Be sure to call View::PreferredSizeChanged when
997  // overriding such that the layout is properly invalidated.
998  virtual void PreferredSizeChanged();
999
1000  // Override returning true when the view needs to be notified when its visible
1001  // bounds relative to the root view may have changed. Only used by
1002  // NativeViewHost.
1003  virtual bool NeedsNotificationWhenVisibleBoundsChange() const;
1004
1005  // Notification that this View's visible bounds relative to the root view may
1006  // have changed. The visible bounds are the region of the View not clipped by
1007  // its ancestors. This is used for clipping NativeViewHost.
1008  virtual void OnVisibleBoundsChanged();
1009
1010  // Override to be notified when the enabled state of this View has
1011  // changed. The default implementation calls SchedulePaint() on this View.
1012  virtual void OnEnabledChanged();
1013
1014  // Tree operations -----------------------------------------------------------
1015
1016  // This method is invoked when the tree changes.
1017  //
1018  // When a view is removed, it is invoked for all children and grand
1019  // children. For each of these views, a notification is sent to the
1020  // view and all parents.
1021  //
1022  // When a view is added, a notification is sent to the view, all its
1023  // parents, and all its children (and grand children)
1024  //
1025  // Default implementation does nothing. Override to perform operations
1026  // required when a view is added or removed from a view hierarchy
1027  //
1028  // Refer to comments in struct |ViewHierarchyChangedDetails| for |details|.
1029  virtual void ViewHierarchyChanged(const ViewHierarchyChangedDetails& details);
1030
1031  // When SetVisible() changes the visibility of a view, this method is
1032  // invoked for that view as well as all the children recursively.
1033  virtual void VisibilityChanged(View* starting_from, bool is_visible);
1034
1035  // This method is invoked when the parent NativeView of the widget that the
1036  // view is attached to has changed and the view hierarchy has not changed.
1037  // ViewHierarchyChanged() is called when the parent NativeView of the widget
1038  // that the view is attached to is changed as a result of changing the view
1039  // hierarchy. Overriding this method is useful for tracking which
1040  // FocusManager manages this view.
1041  virtual void NativeViewHierarchyChanged();
1042
1043  // Painting ------------------------------------------------------------------
1044
1045  // Responsible for calling Paint() on child Views. Override to control the
1046  // order child Views are painted.
1047  virtual void PaintChildren(gfx::Canvas* canvas);
1048
1049  // Override to provide rendering in any part of the View's bounds. Typically
1050  // this is the "contents" of the view. If you override this method you will
1051  // have to call the subsequent OnPaint*() methods manually.
1052  virtual void OnPaint(gfx::Canvas* canvas);
1053
1054  // Override to paint a background before any content is drawn. Typically this
1055  // is done if you are satisfied with a default OnPaint handler but wish to
1056  // supply a different background.
1057  virtual void OnPaintBackground(gfx::Canvas* canvas);
1058
1059  // Override to paint a border not specified by SetBorder().
1060  virtual void OnPaintBorder(gfx::Canvas* canvas);
1061
1062  // Override to paint a focus border not specified by set_focus_border() around
1063  // relevant contents.  The focus border is usually a dotted rectangle.
1064  virtual void OnPaintFocusBorder(gfx::Canvas* canvas);
1065
1066  // Accelerated painting ------------------------------------------------------
1067
1068  // This creates a layer for the view, if one does not exist. It then
1069  // passes the texture to a layer associated with the view. While an external
1070  // texture is set, the view will not update the layer contents.
1071  //
1072  // |texture| cannot be NULL.
1073  //
1074  // Returns false if it cannot create a layer to which to assign the texture.
1075  bool SetExternalTexture(ui::Texture* texture);
1076
1077  // Returns the offset from this view to the nearest ancestor with a layer. If
1078  // |layer_parent| is non-NULL it is set to the nearest ancestor with a layer.
1079  virtual gfx::Vector2d CalculateOffsetToAncestorWithLayer(
1080      ui::Layer** layer_parent);
1081
1082  // Updates the view's layer's parent. Called when a view is added to a view
1083  // hierarchy, responsible for parenting the view's layer to the enclosing
1084  // layer in the hierarchy.
1085  virtual void UpdateParentLayer();
1086
1087  // If this view has a layer, the layer is reparented to |parent_layer| and its
1088  // bounds is set based on |point|. If this view does not have a layer, then
1089  // recurses through all children. This is used when adding a layer to an
1090  // existing view to make sure all descendants that have layers are parented to
1091  // the right layer.
1092  virtual void MoveLayerToParent(ui::Layer* parent_layer,
1093                                 const gfx::Point& point);
1094
1095  // Called to update the bounds of any child layers within this View's
1096  // hierarchy when something happens to the hierarchy.
1097  virtual void UpdateChildLayerBounds(const gfx::Vector2d& offset);
1098
1099  // Overridden from ui::LayerDelegate:
1100  virtual void OnPaintLayer(gfx::Canvas* canvas) OVERRIDE;
1101  virtual void OnDeviceScaleFactorChanged(float device_scale_factor) OVERRIDE;
1102  virtual base::Closure PrepareForLayerBoundsChange() OVERRIDE;
1103
1104  // Finds the layer that this view paints to (it may belong to an ancestor
1105  // view), then reorders the immediate children of that layer to match the
1106  // order of the view tree.
1107  virtual void ReorderLayers();
1108
1109  // This reorders the immediate children of |*parent_layer| to match the
1110  // order of the view tree. Child layers which are owned by a view are
1111  // reordered so that they are below any child layers not owned by a view.
1112  // Widget::ReorderNativeViews() should be called to reorder any child layers
1113  // with an associated view. Widget::ReorderNativeViews() may reorder layers
1114  // below layers owned by a view.
1115  virtual void ReorderChildLayers(ui::Layer* parent_layer);
1116
1117  // Input ---------------------------------------------------------------------
1118
1119  // Called by HitTestRect() to see if this View has a custom hit test mask. If
1120  // the return value is true, GetHitTestMask() will be called to obtain the
1121  // mask. Default value is false, in which case the View will hit-test against
1122  // its bounds.
1123  virtual bool HasHitTestMask() const;
1124
1125  // Called by HitTestRect() to retrieve a mask for hit-testing against.
1126  // Subclasses override to provide custom shaped hit test regions.
1127  virtual void GetHitTestMask(gfx::Path* mask) const;
1128
1129  virtual DragInfo* GetDragInfo();
1130
1131  // Focus ---------------------------------------------------------------------
1132
1133  // Override to be notified when focus has changed either to or from this View.
1134  virtual void OnFocus();
1135  virtual void OnBlur();
1136
1137  // Handle view focus/blur events for this view.
1138  void Focus();
1139  void Blur();
1140
1141  // System events -------------------------------------------------------------
1142
1143  // Called when the UI theme (not the NativeTheme) has changed, overriding
1144  // allows individual Views to do special cleanup and processing (such as
1145  // dropping resource caches).  To dispatch a theme changed notification, call
1146  // Widget::ThemeChanged().
1147  virtual void OnThemeChanged() {}
1148
1149  // Called when the locale has changed, overriding allows individual Views to
1150  // update locale-dependent strings.
1151  // To dispatch a locale changed notification, call Widget::LocaleChanged().
1152  virtual void OnLocaleChanged() {}
1153
1154  // Tooltips ------------------------------------------------------------------
1155
1156  // Views must invoke this when the tooltip text they are to display changes.
1157  void TooltipTextChanged();
1158
1159  // Context menus -------------------------------------------------------------
1160
1161  // Returns the location, in screen coordinates, to show the context menu at
1162  // when the context menu is shown from the keyboard. This implementation
1163  // returns the middle of the visible region of this view.
1164  //
1165  // This method is invoked when the context menu is shown by way of the
1166  // keyboard.
1167  virtual gfx::Point GetKeyboardContextMenuLocation();
1168
1169  // Drag and drop -------------------------------------------------------------
1170
1171  // These are cover methods that invoke the method of the same name on
1172  // the DragController. Subclasses may wish to override rather than install
1173  // a DragController.
1174  // See DragController for a description of these methods.
1175  virtual int GetDragOperations(const gfx::Point& press_pt);
1176  virtual void WriteDragData(const gfx::Point& press_pt, OSExchangeData* data);
1177
1178  // Returns whether we're in the middle of a drag session that was initiated
1179  // by us.
1180  bool InDrag();
1181
1182  // Returns how much the mouse needs to move in one direction to start a
1183  // drag. These methods cache in a platform-appropriate way. These values are
1184  // used by the public static method ExceededDragThreshold().
1185  static int GetHorizontalDragThreshold();
1186  static int GetVerticalDragThreshold();
1187
1188  // NativeTheme ---------------------------------------------------------------
1189
1190  // Invoked when the NativeTheme associated with this View changes.
1191  virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) {}
1192
1193  // Debugging -----------------------------------------------------------------
1194
1195#if !defined(NDEBUG)
1196  // Returns string containing a graph of the views hierarchy in graphViz DOT
1197  // language (http://graphviz.org/). Can be called within debugger and save
1198  // to a file to compile/view.
1199  // Note: Assumes initial call made with first = true.
1200  virtual std::string PrintViewGraph(bool first);
1201
1202  // Some classes may own an object which contains the children to displayed in
1203  // the views hierarchy. The above function gives the class the flexibility to
1204  // decide which object should be used to obtain the children, but this
1205  // function makes the decision explicit.
1206  std::string DoPrintViewGraph(bool first, View* view_with_children);
1207#endif
1208
1209 private:
1210  friend class internal::PostEventDispatchHandler;
1211  friend class internal::RootView;
1212  friend class FocusManager;
1213  friend class Widget;
1214
1215  // Painting  -----------------------------------------------------------------
1216
1217  enum SchedulePaintType {
1218    // Indicates the size is the same (only the origin changed).
1219    SCHEDULE_PAINT_SIZE_SAME,
1220
1221    // Indicates the size changed (and possibly the origin).
1222    SCHEDULE_PAINT_SIZE_CHANGED
1223  };
1224
1225  // Invoked before and after the bounds change to schedule painting the old and
1226  // new bounds.
1227  void SchedulePaintBoundsChanged(SchedulePaintType type);
1228
1229  // Common Paint() code shared by accelerated and non-accelerated code paths to
1230  // invoke OnPaint() on the View.
1231  void PaintCommon(gfx::Canvas* canvas);
1232
1233  // Tree operations -----------------------------------------------------------
1234
1235  // Removes |view| from the hierarchy tree.  If |update_focus_cycle| is true,
1236  // the next and previous focusable views of views pointing to this view are
1237  // updated.  If |update_tool_tip| is true, the tooltip is updated.  If
1238  // |delete_removed_view| is true, the view is also deleted (if it is parent
1239  // owned).  If |new_parent| is not NULL, the remove is the result of
1240  // AddChildView() to a new parent.  For this case, |new_parent| is the View
1241  // that |view| is going to be added to after the remove completes.
1242  void DoRemoveChildView(View* view,
1243                         bool update_focus_cycle,
1244                         bool update_tool_tip,
1245                         bool delete_removed_view,
1246                         View* new_parent);
1247
1248  // Call ViewHierarchyChanged() for all child views and all parents.
1249  // |old_parent| is the original parent of the View that was removed.
1250  // If |new_parent| is not NULL, the View that was removed will be reparented
1251  // to |new_parent| after the remove operation.
1252  void PropagateRemoveNotifications(View* old_parent, View* new_parent);
1253
1254  // Call ViewHierarchyChanged() for all children.
1255  void PropagateAddNotifications(const ViewHierarchyChangedDetails& details);
1256
1257  // Propagates NativeViewHierarchyChanged() notification through all the
1258  // children.
1259  void PropagateNativeViewHierarchyChanged();
1260
1261  // Takes care of registering/unregistering accelerators if
1262  // |register_accelerators| true and calls ViewHierarchyChanged().
1263  void ViewHierarchyChangedImpl(bool register_accelerators,
1264                                const ViewHierarchyChangedDetails& details);
1265
1266  // Invokes OnNativeThemeChanged() on this and all descendants.
1267  void PropagateNativeThemeChanged(const ui::NativeTheme* theme);
1268
1269  // Size and disposition ------------------------------------------------------
1270
1271  // Call VisibilityChanged() recursively for all children.
1272  void PropagateVisibilityNotifications(View* from, bool is_visible);
1273
1274  // Registers/unregisters accelerators as necessary and calls
1275  // VisibilityChanged().
1276  void VisibilityChangedImpl(View* starting_from, bool is_visible);
1277
1278  // Responsible for propagating bounds change notifications to relevant
1279  // views.
1280  void BoundsChanged(const gfx::Rect& previous_bounds);
1281
1282  // Visible bounds notification registration.
1283  // When a view is added to a hierarchy, it and all its children are asked if
1284  // they need to be registered for "visible bounds within root" notifications
1285  // (see comment on OnVisibleBoundsChanged()). If they do, they are registered
1286  // with every ancestor between them and the root of the hierarchy.
1287  static void RegisterChildrenForVisibleBoundsNotification(View* view);
1288  static void UnregisterChildrenForVisibleBoundsNotification(View* view);
1289  void RegisterForVisibleBoundsNotification();
1290  void UnregisterForVisibleBoundsNotification();
1291
1292  // Adds/removes view to the list of descendants that are notified any time
1293  // this views location and possibly size are changed.
1294  void AddDescendantToNotify(View* view);
1295  void RemoveDescendantToNotify(View* view);
1296
1297  // Sets the layer's bounds given in DIP coordinates.
1298  void SetLayerBounds(const gfx::Rect& bounds_in_dip);
1299
1300  // Transformations -----------------------------------------------------------
1301
1302  // Returns in |transform| the transform to get from coordinates of |ancestor|
1303  // to this. Returns true if |ancestor| is found. If |ancestor| is not found,
1304  // or NULL, |transform| is set to convert from root view coordinates to this.
1305  bool GetTransformRelativeTo(const View* ancestor,
1306                              gfx::Transform* transform) const;
1307
1308  // Coordinate conversion -----------------------------------------------------
1309
1310  // Convert a point in the view's coordinate to an ancestor view's coordinate
1311  // system using necessary transformations. Returns whether the point was
1312  // successfully converted to the ancestor's coordinate system.
1313  bool ConvertPointForAncestor(const View* ancestor, gfx::Point* point) const;
1314
1315  // Convert a point in the ancestor's coordinate system to the view's
1316  // coordinate system using necessary transformations. Returns whether the
1317  // point was successfully from the ancestor's coordinate system to the view's
1318  // coordinate system.
1319  bool ConvertPointFromAncestor(const View* ancestor, gfx::Point* point) const;
1320
1321  // Accelerated painting ------------------------------------------------------
1322
1323  // Creates the layer and related fields for this view.
1324  void CreateLayer();
1325
1326  // Parents all un-parented layers within this view's hierarchy to this view's
1327  // layer.
1328  void UpdateParentLayers();
1329
1330  // Parents this view's layer to |parent_layer|, and sets its bounds and other
1331  // properties in accordance to |offset|, the view's offset from the
1332  // |parent_layer|.
1333  void ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer);
1334
1335  // Called to update the layer visibility. The layer will be visible if the
1336  // View itself, and all its parent Views are visible. This also updates
1337  // visibility of the child layers.
1338  void UpdateLayerVisibility();
1339  void UpdateChildLayerVisibility(bool visible);
1340
1341  // Orphans the layers in this subtree that are parented to layers outside of
1342  // this subtree.
1343  void OrphanLayers();
1344
1345  // Destroys the layer associated with this view, and reparents any descendants
1346  // to the destroyed layer's parent.
1347  void DestroyLayer();
1348
1349  // Input ---------------------------------------------------------------------
1350
1351  bool ProcessMousePressed(const ui::MouseEvent& event);
1352  bool ProcessMouseDragged(const ui::MouseEvent& event);
1353  void ProcessMouseReleased(const ui::MouseEvent& event);
1354
1355  // Accelerators --------------------------------------------------------------
1356
1357  // Registers this view's keyboard accelerators that are not registered to
1358  // FocusManager yet, if possible.
1359  void RegisterPendingAccelerators();
1360
1361  // Unregisters all the keyboard accelerators associated with this view.
1362  // |leave_data_intact| if true does not remove data from accelerators_ array,
1363  // so it could be re-registered with other focus manager
1364  void UnregisterAccelerators(bool leave_data_intact);
1365
1366  // Focus ---------------------------------------------------------------------
1367
1368  // Initialize the previous/next focusable views of the specified view relative
1369  // to the view at the specified index.
1370  void InitFocusSiblings(View* view, int index);
1371
1372  // System events -------------------------------------------------------------
1373
1374  // Used to propagate theme changed notifications from the root view to all
1375  // views in the hierarchy.
1376  virtual void PropagateThemeChanged();
1377
1378  // Used to propagate locale changed notifications from the root view to all
1379  // views in the hierarchy.
1380  virtual void PropagateLocaleChanged();
1381
1382  // Tooltips ------------------------------------------------------------------
1383
1384  // Propagates UpdateTooltip() to the TooltipManager for the Widget.
1385  // This must be invoked any time the View hierarchy changes in such a way
1386  // the view under the mouse differs. For example, if the bounds of a View is
1387  // changed, this is invoked. Similarly, as Views are added/removed, this
1388  // is invoked.
1389  void UpdateTooltip();
1390
1391  // Drag and drop -------------------------------------------------------------
1392
1393  // Starts a drag and drop operation originating from this view. This invokes
1394  // WriteDragData to write the data and GetDragOperations to determine the
1395  // supported drag operations. When done, OnDragDone is invoked. |press_pt| is
1396  // in the view's coordinate system.
1397  // Returns true if a drag was started.
1398  bool DoDrag(const ui::LocatedEvent& event,
1399              const gfx::Point& press_pt,
1400              ui::DragDropTypes::DragEventSource source);
1401
1402  //////////////////////////////////////////////////////////////////////////////
1403
1404  // Creation and lifetime -----------------------------------------------------
1405
1406  // False if this View is owned by its parent - i.e. it will be deleted by its
1407  // parent during its parents destruction. False is the default.
1408  bool owned_by_client_;
1409
1410  // Attributes ----------------------------------------------------------------
1411
1412  // The id of this View. Used to find this View.
1413  int id_;
1414
1415  // The group of this view. Some view subclasses use this id to find other
1416  // views of the same group. For example radio button uses this information
1417  // to find other radio buttons.
1418  int group_;
1419
1420  // Tree operations -----------------------------------------------------------
1421
1422  // This view's parent.
1423  View* parent_;
1424
1425  // This view's children.
1426  Views children_;
1427
1428  // Size and disposition ------------------------------------------------------
1429
1430  // This View's bounds in the parent coordinate system.
1431  gfx::Rect bounds_;
1432
1433  // Whether this view is visible.
1434  bool visible_;
1435
1436  // Whether this view is enabled.
1437  bool enabled_;
1438
1439  // When this flag is on, a View receives a mouse-enter and mouse-leave event
1440  // even if a descendant View is the event-recipient for the real mouse
1441  // events. When this flag is turned on, and mouse moves from outside of the
1442  // view into a child view, both the child view and this view receives
1443  // mouse-enter event. Similarly, if the mouse moves from inside a child view
1444  // and out of this view, then both views receive a mouse-leave event.
1445  // When this flag is turned off, if the mouse moves from inside this view into
1446  // a child view, then this view receives a mouse-leave event. When this flag
1447  // is turned on, it does not receive the mouse-leave event in this case.
1448  // When the mouse moves from inside the child view out of the child view but
1449  // still into this view, this view receives a mouse-enter event if this flag
1450  // is turned off, but doesn't if this flag is turned on.
1451  // This flag is initialized to false.
1452  bool notify_enter_exit_on_child_;
1453
1454  // Whether or not RegisterViewForVisibleBoundsNotification on the RootView
1455  // has been invoked.
1456  bool registered_for_visible_bounds_notification_;
1457
1458  // List of descendants wanting notification when their visible bounds change.
1459  scoped_ptr<Views> descendants_to_notify_;
1460
1461  // Transformations -----------------------------------------------------------
1462
1463  // Clipping parameters. skia transformation matrix does not give us clipping.
1464  // So we do it ourselves.
1465  gfx::Insets clip_insets_;
1466
1467  // Layout --------------------------------------------------------------------
1468
1469  // Whether the view needs to be laid out.
1470  bool needs_layout_;
1471
1472  // The View's LayoutManager defines the sizing heuristics applied to child
1473  // Views. The default is absolute positioning according to bounds_.
1474  scoped_ptr<LayoutManager> layout_manager_;
1475
1476  // Painting ------------------------------------------------------------------
1477
1478  // Background
1479  scoped_ptr<Background> background_;
1480
1481  // Border.
1482  scoped_ptr<Border> border_;
1483
1484  // Focus border.
1485  scoped_ptr<FocusBorder> focus_border_;
1486
1487  // RTL painting --------------------------------------------------------------
1488
1489  // Indicates whether or not the gfx::Canvas object passed to View::Paint()
1490  // is going to be flipped horizontally (using the appropriate transform) on
1491  // right-to-left locales for this View.
1492  bool flip_canvas_on_paint_for_rtl_ui_;
1493
1494  // Accelerated painting ------------------------------------------------------
1495
1496  bool paint_to_layer_;
1497
1498  // Accelerators --------------------------------------------------------------
1499
1500  // Focus manager accelerators registered on.
1501  FocusManager* accelerator_focus_manager_;
1502
1503  // The list of accelerators. List elements in the range
1504  // [0, registered_accelerator_count_) are already registered to FocusManager,
1505  // and the rest are not yet.
1506  scoped_ptr<std::vector<ui::Accelerator> > accelerators_;
1507  size_t registered_accelerator_count_;
1508
1509  // Focus ---------------------------------------------------------------------
1510
1511  // Next view to be focused when the Tab key is pressed.
1512  View* next_focusable_view_;
1513
1514  // Next view to be focused when the Shift-Tab key combination is pressed.
1515  View* previous_focusable_view_;
1516
1517  // Whether this view can be focused.
1518  bool focusable_;
1519
1520  // Whether this view is focusable if the user requires full keyboard access,
1521  // even though it may not be normally focusable.
1522  bool accessibility_focusable_;
1523
1524  // Context menus -------------------------------------------------------------
1525
1526  // The menu controller.
1527  ContextMenuController* context_menu_controller_;
1528
1529  // Drag and drop -------------------------------------------------------------
1530
1531  DragController* drag_controller_;
1532
1533  // Input  --------------------------------------------------------------------
1534
1535  scoped_ptr<internal::PostEventDispatchHandler> post_dispatch_handler_;
1536
1537  // Accessibility -------------------------------------------------------------
1538
1539  // Belongs to this view, but it's reference-counted on some platforms
1540  // so we can't use a scoped_ptr. It's dereferenced in the destructor.
1541  NativeViewAccessibility* native_view_accessibility_;
1542
1543  DISALLOW_COPY_AND_ASSIGN(View);
1544};
1545
1546}  // namespace views
1547
1548#endif  // UI_VIEWS_VIEW_H_
1549