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