1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef UI_VIEWS_VIEW_H_
6 #define UI_VIEWS_VIEW_H_
17 #include "base/callback.h"
18 #include "base/callback_list.h"
19 #include "base/gtest_prod_util.h"
20 #include "base/memory/ptr_util.h"
21 #include "base/memory/raw_ptr.h"
22 #include "base/observer_list.h"
23 #include "base/strings/string_piece.h"
24 #include "build/build_config.h"
25 #include "third_party/abseil-cpp/absl/types/optional.h"
26 #include "third_party/skia/include/core/SkPath.h"
27 #include "ui/accessibility/ax_enums.mojom-forward.h"
28 #include "ui/base/accelerators/accelerator.h"
29 #include "ui/base/class_property.h"
30 #include "ui/base/clipboard/clipboard_format_type.h"
31 #include "ui/base/cursor/cursor.h"
32 #include "ui/base/dragdrop/drop_target_event.h"
33 #include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
34 #include "ui/base/dragdrop/os_exchange_data.h"
35 #include "ui/base/metadata/metadata_header_macros.h"
36 #include "ui/base/metadata/metadata_types.h"
37 #include "ui/base/ui_base_types.h"
38 #include "ui/compositor/layer_delegate.h"
39 #include "ui/compositor/layer_observer.h"
40 #include "ui/compositor/layer_owner.h"
41 #include "ui/compositor/layer_type.h"
42 #include "ui/compositor/paint_cache.h"
43 #include "ui/events/event.h"
44 #include "ui/events/event_target.h"
45 #include "ui/gfx/geometry/insets.h"
46 #include "ui/gfx/geometry/point.h"
47 #include "ui/gfx/geometry/rect.h"
48 #include "ui/gfx/geometry/transform.h"
49 #include "ui/gfx/geometry/vector2d.h"
50 #include "ui/gfx/geometry/vector2d_conversions.h"
51 #include "ui/gfx/native_widget_types.h"
52 #include "ui/views/layout/layout_manager.h"
53 #include "ui/views/layout/layout_types.h"
54 #include "ui/views/metadata/view_factory.h"
55 #include "ui/views/paint_info.h"
56 #include "ui/views/view_targeter.h"
57 #include "ui/views/views_export.h"
59 using ui::OSExchangeData;
76 class TransformRecorder;
83 class ContextMenuController;
86 class FocusTraversable;
90 class ViewAccessibility;
94 class WordLookupClient;
97 class PreEventDispatchHandler;
98 class PostEventDispatchHandler;
100 class ScopedChildrenLock;
101 } // namespace internal
103 // Struct used to describe how a View hierarchy has changed. See
104 // View::ViewHierarchyChanged.
105 // TODO(pbos): Move to a separate view_hierarchy_changed_details.h header.
106 struct VIEWS_EXPORT ViewHierarchyChangedDetails {
107 ViewHierarchyChangedDetails() = default;
109 ViewHierarchyChangedDetails(bool is_add,
113 : is_add(is_add), parent(parent), child(child), move_view(move_view) {}
116 // New parent if |is_add| is true, old parent if |is_add| is false.
117 raw_ptr<View> parent = nullptr;
118 // The view being added or removed.
119 raw_ptr<View> child = nullptr;
120 // If this is a move (reparent), meaning AddChildViewAt() is invoked with an
121 // existing parent, then a notification for the remove is sent first,
122 // followed by one for the add. This case can be distinguished by a
123 // non-null |move_view|.
124 // For the remove part of move, |move_view| is the new parent of the View
126 // For the add part of move, |move_view| is the old parent of the View being
128 raw_ptr<View> move_view = nullptr;
131 using PropertyChangedCallback = ui::metadata::PropertyChangedCallback;
133 // The elements in PropertyEffects represent bits which define what effect(s) a
134 // changed Property has on the containing class. Additional elements should
135 // use the next most significant bit.
136 enum PropertyEffects {
137 kPropertyEffectsNone = 0,
138 // Any changes to the property should cause the container to invalidate the
139 // current layout state.
140 kPropertyEffectsLayout = 0x00000001,
141 // Changes to the property should cause the container to schedule a painting
143 kPropertyEffectsPaint = 0x00000002,
144 // Changes to the property should cause the preferred size to change. This
145 // implies kPropertyEffectsLayout.
146 kPropertyEffectsPreferredSizeChanged = 0x00000004,
149 /////////////////////////////////////////////////////////////////////////////
153 // A View is a rectangle within the views View hierarchy. It is the base
154 // class for all Views.
156 // A View is a container of other Views (there is no such thing as a Leaf
157 // View - makes code simpler, reduces type conversion headaches, design
160 // The View contains basic properties for sizing (bounds), layout (flex,
161 // orientation, etc), painting of children and event dispatch.
163 // The View also uses a simple Box Layout Manager similar to XUL's
164 // SprocketLayout system. Alternative Layout Managers implementing the
165 // LayoutManager interface can be used to lay out children if required.
167 // It is up to the subclass to implement Painting and storage of subclass -
168 // specific properties and functionality.
170 // Unless otherwise documented, views is not thread safe and should only be
171 // accessed from the main thread.
173 // Properties ------------------
175 // Properties which are intended to be dynamically visible through metadata to
176 // other subsystems, such as dev-tools must adhere to a naming convention,
177 // usage and implementation patterns.
179 // Properties start with their base name, such as "Frobble" (note the
180 // capitalization). The method to set the property must be called SetXXXX and
181 // the method to retrieve the value is called GetXXXX. For the aforementioned
182 // Frobble property, this would be SetFrobble and GetFrobble.
184 // void SetFrobble(bool is_frobble);
185 // bool GetFrobble() const;
187 // In the SetXXXX method, after the value storage location has been updated,
188 // OnPropertyChanged() must be called using the address of the storage
189 // location as a key. Additionally, any combination of PropertyEffects are
190 // also passed in. This will ensure that any desired side effects are properly
193 // void View::SetFrobble(bool is_frobble) {
194 // if (is_frobble == frobble_)
196 // frobble_ = is_frobble;
197 // OnPropertyChanged(&frobble_, kPropertyEffectsPaint);
200 // Each property should also have a way to "listen" to changes by registering
203 // base::CallbackListSubscription AddFrobbleChangedCallback(
204 // PropertyChangedCallback callback);
206 // Each callback uses the the existing base::Bind mechanisms which allow for
207 // various kinds of callbacks; object methods, normal functions and lambdas.
211 // class FrobbleView : public View {
214 // void OnFrobbleChanged();
215 // base::CallbackListSubscription frobble_changed_subscription_;
219 // frobble_changed_subscription_ = AddFrobbleChangedCallback(
220 // base::BindRepeating(&FrobbleView::OnFrobbleChanged,
221 // base::Unretained(this)));
225 // void MyView::ValidateFrobbleChanged() {
226 // bool frobble_changed = false;
227 // base::CallbackListSubscription subscription =
228 // frobble_view_->AddFrobbleChangedCallback(
229 // base::BindRepeating([](bool* frobble_changed_ptr) {
230 // *frobble_changed_ptr = true;
231 // }, &frobble_changed));
232 // frobble_view_->SetFrobble(!frobble_view_->GetFrobble());
233 // LOG() << frobble_changed ? "Frobble changed" : "Frobble NOT changed!";
236 // Property metadata -----------
238 // For Views that expose properties which are intended to be dynamically
239 // discoverable by other subsystems, each View and its descendants must
240 // include metadata. These other subsystems, such as dev tools or a delarative
241 // layout system, can then enumerate the properties on any given instance or
242 // class. Using the enumerated information, the actual values of the
243 // properties can be read or written. This will be done by getting and setting
244 // the values using string representations. The metadata can also be used to
245 // instantiate and initialize a View (or descendant) class from a declarative
248 // For each View class in their respective header declaration, place the macro
249 // METADATA_HEADER(<classname>) in the public section.
251 // In the implementing .cc file, add the following macros to the same
252 // namespace in which the class resides.
254 // BEGIN_METADATA(View, ParentView)
255 // ADD_PROPERTY_METADATA(bool, Frobble)
258 // For each property, add a definition using ADD_PROPERTY_METADATA() between
259 // the begin and end macros.
261 // Descendant classes must specify the parent class as a macro parameter.
263 // BEGIN_METADATA(MyView, views::View)
264 // ADD_PROPERTY_METADATA(int, Bobble)
266 /////////////////////////////////////////////////////////////////////////////
267 class VIEWS_EXPORT View : public ui::LayerDelegate,
268 public ui::LayerObserver,
269 public ui::LayerOwner,
270 public ui::AcceleratorTarget,
271 public ui::EventTarget,
272 public ui::EventHandler,
273 public ui::PropertyHandler,
274 public ui::metadata::MetaDataProvider {
276 using Views = std::vector<View*>;
278 // TODO(crbug.com/1289902): The |event| parameter is being removed. Do not add
281 base::OnceCallback<void(const ui::DropTargetEvent& event,
282 ui::mojom::DragOperation& output_drag_op)>;
284 METADATA_HEADER_BASE(View);
286 enum class FocusBehavior {
287 // Use when the View is never focusable. Default.
290 // Use when the View is to be focusable both in regular and accessibility
294 // Use when the View is focusable only during accessibility mode.
298 // During paint, the origin of each view in physical pixel is calculated by
299 // view_origin_pixel = ROUND(view.origin() * device_scale_factor)
301 // Thus in a view hierarchy, the offset between two views, view_i and view_j,
303 // view_offset_ij_pixel = SUM [view_origin_pixel.OffsetFromOrigin()]
304 // {For all views along the path from view_i to view_j}
306 // But the offset between the two layers, the layer in view_i and the layer in
307 // view_j, is computed by
308 // view_offset_ij_dip = SUM [view.origin().OffsetFromOrigin()]
309 // {For all views along the path from view_i to view_j}
311 // layer_offset_ij_pixel = ROUND (view_offset_ij_dip * device_scale_factor)
313 // Due to this difference in the logic for computation of offset, the values
314 // view_offset_ij_pixel and layer_offset_ij_pixel may not always be equal.
315 // They will differ by some subpixel_offset. This leads to bugs like
317 // The subpixel offset needs to be applied to the layer to get the correct
318 // output during paint.
320 // This class manages the computation of subpixel offset internally when
321 // working with offsets.
322 class LayerOffsetData {
324 explicit LayerOffsetData(float device_scale_factor = 1.f,
325 const gfx::Vector2d& offset = gfx::Vector2d())
326 : device_scale_factor_(device_scale_factor) {
330 const gfx::Vector2d& offset() const { return offset_; }
332 const gfx::Vector2dF GetSubpixelOffset() const {
333 // |rounded_pixel_offset_| is stored in physical pixel space. Convert it
334 // into DIP space before returning.
335 gfx::Vector2dF subpixel_offset(rounded_pixel_offset_);
336 subpixel_offset.Scale(1.f / device_scale_factor_);
337 return subpixel_offset;
340 LayerOffsetData& operator+=(const gfx::Vector2d& offset) {
345 LayerOffsetData operator+(const gfx::Vector2d& offset) const {
346 LayerOffsetData offset_data(*this);
347 offset_data.AddOffset(offset);
352 // Adds the |offset_to_parent| to the total |offset_| and updates the
353 // |rounded_pixel_offset_| value.
354 void AddOffset(const gfx::Vector2d& offset_to_parent) {
355 // Add the DIP |offset_to_parent| amount to the total offset.
356 offset_ += offset_to_parent;
358 // Convert |offset_to_parent| to physical pixel coordinates.
359 gfx::Vector2dF fractional_pixel_offset(
360 offset_to_parent.x() * device_scale_factor_,
361 offset_to_parent.y() * device_scale_factor_);
363 // Since pixels cannot be fractional, we need to round the offset to get
364 // the correct physical pixel coordinate.
365 gfx::Vector2d integral_pixel_offset =
366 gfx::ToRoundedVector2d(fractional_pixel_offset);
368 // |integral_pixel_offset - fractional_pixel_offset| gives the subpixel
369 // offset amount for |offset_to_parent|. This is added to
370 // |rounded_pixel_offset_| to update the total subpixel offset.
371 rounded_pixel_offset_ += integral_pixel_offset - fractional_pixel_offset;
374 // Total offset so far. This stores the offset between two nodes in the view
376 gfx::Vector2d offset_;
378 // This stores the value such that if added to
379 // |offset_ * device_scale_factor| will give the correct aligned offset in
381 gfx::Vector2dF rounded_pixel_offset_;
383 // The device scale factor at which the subpixel offset is being computed.
384 float device_scale_factor_;
387 // Creation and lifetime -----------------------------------------------------
390 View(const View&) = delete;
391 View& operator=(const View&) = delete;
394 // By default a View is owned by its parent unless specified otherwise here.
395 void set_owned_by_client() { owned_by_client_ = true; }
396 bool owned_by_client() const { return owned_by_client_; }
398 // Tree operations -----------------------------------------------------------
400 // Get the Widget that hosts this View, if any.
401 virtual const Widget* GetWidget() const;
402 virtual Widget* GetWidget();
404 // Adds |view| as a child of this view, optionally at |index|.
405 // Returns the raw pointer for callers which want to hold a pointer to the
406 // added view. This requires declaring the function as a template in order to
407 // return the actual passed-in type.
408 template <typename T>
409 T* AddChildView(std::unique_ptr<T> view) {
410 DCHECK(!view->owned_by_client())
411 << "This should only be called if the client is passing ownership of "
412 "|view| to the parent View.";
413 return AddChildView<T>(view.release());
415 template <typename T>
416 T* AddChildViewAt(std::unique_ptr<T> view, size_t index) {
417 DCHECK(!view->owned_by_client())
418 << "This should only be called if the client is passing ownership of "
419 "|view| to the parent View.";
420 return AddChildViewAt<T>(view.release(), index);
423 // Prefer using the AddChildView(std::unique_ptr) overloads over raw pointers
425 template <typename T>
426 T* AddChildView(T* view) {
427 AddChildViewAtImpl(view, children_.size());
430 template <typename T>
431 T* AddChildViewAt(T* view, size_t index) {
432 AddChildViewAtImpl(view, index);
436 // Moves |view| to the specified |index|. An |index| at least as large as that
437 // of the last child moves the view to the end.
438 void ReorderChildView(View* view, size_t index);
440 // Removes |view| from this view. The view's parent will change to null.
441 void RemoveChildView(View* view);
443 // Removes |view| from this view and transfers ownership back to the caller in
444 // the form of a std::unique_ptr<T>.
445 // TODO(kylixrd): Rename back to RemoveChildView() once the code is refactored
446 // to eliminate the uses of the old RemoveChildView().
447 template <typename T>
448 std::unique_ptr<T> RemoveChildViewT(T* view) {
449 DCHECK(!view->owned_by_client())
450 << "This should only be called if the client doesn't already have "
451 "ownership of |view|.";
452 DCHECK(std::find(children_.cbegin(), children_.cend(), view) !=
454 RemoveChildView(view);
455 return base::WrapUnique(view);
458 // Partially specialized version to directly take a raw_ptr<T>.
459 template <typename T>
460 std::unique_ptr<T> RemoveChildViewT(raw_ptr<T> view) {
461 return RemoveChildViewT(view.get());
464 // Removes all the children from this view. This deletes all children that are
465 // not set_owned_by_client(), which is deprecated.
466 void RemoveAllChildViews();
468 // TODO(pbos): Remove this method, deleting children when removing them should
469 // not be optional. If ownership needs to be preserved, use RemoveChildViewT()
470 // to retain ownership of the removed children.
471 void RemoveAllChildViewsWithoutDeleting();
473 const Views& children() const { return children_; }
475 // Returns the parent view.
476 const View* parent() const { return parent_; }
477 View* parent() { return parent_; }
479 // Returns true if |view| is contained within this View's hierarchy, even as
480 // an indirect descendant. Will return true if child is also this view.
481 bool Contains(const View* view) const;
483 // Returns an iterator pointing to |view|, or children_.cend() if |view| is
484 // not a child of this view.
485 Views::const_iterator FindChild(const View* view) const;
487 // Returns the index of |view|, or nullopt if |view| is not a child of this
489 absl::optional<size_t> GetIndexOf(const View* view) const;
491 // Size and disposition ------------------------------------------------------
492 // Methods for obtaining and modifying the position and size of the view.
493 // Position is in the coordinate system of the view's parent.
494 // Position is NOT flipped for RTL. See "RTL positioning" for RTL-sensitive
495 // position accessors.
496 // Transformations are not applied on the size/position. For example, if
497 // bounds is (0, 0, 100, 100) and it is scaled by 0.5 along the X axis, the
498 // width will still be 100 (although when painted, it will be 50x100, painted
499 // at location (0, 0)).
501 void SetBounds(int x, int y, int width, int height);
502 void SetBoundsRect(const gfx::Rect& bounds);
503 void SetSize(const gfx::Size& size);
504 void SetPosition(const gfx::Point& position);
508 // No transformation is applied on the size or the locations.
509 const gfx::Rect& bounds() const { return bounds_; }
510 int x() const { return bounds_.x(); }
511 int y() const { return bounds_.y(); }
512 int width() const { return bounds_.width(); }
513 int height() const { return bounds_.height(); }
514 const gfx::Point& origin() const { return bounds_.origin(); }
515 const gfx::Size& size() const { return bounds_.size(); }
517 // Returns the bounds of the content area of the view, i.e. the rectangle
518 // enclosed by the view's border.
519 gfx::Rect GetContentsBounds() const;
521 // Returns the bounds of the view in its own coordinates (i.e. position is
523 gfx::Rect GetLocalBounds() const;
525 // Returns the insets of the current border. If there is no border an empty
526 // insets is returned.
527 virtual gfx::Insets GetInsets() const;
529 // Returns the visible bounds of the receiver in the receivers coordinate
532 // When traversing the View hierarchy in order to compute the bounds, the
533 // function takes into account the mirroring setting and transformation for
534 // each View and therefore it will return the mirrored and transformed version
535 // of the visible bounds if need be.
536 gfx::Rect GetVisibleBounds() const;
538 // Return the bounds of the View in screen coordinate system.
539 gfx::Rect GetBoundsInScreen() const;
541 // Return the bounds that an anchored widget should anchor to. These can be
542 // different from |GetBoundsInScreen()| when a view is larger than its visible
543 // size, for instance to provide a larger hittable area.
544 virtual gfx::Rect GetAnchorBoundsInScreen() const;
546 // Returns the baseline of this view, or -1 if this view has no baseline. The
547 // return value is relative to the preferred height.
548 virtual int GetBaseline() const;
550 // Get the size the View would like to be under the current bounds.
551 // If the View is never laid out before, assume it to be laid out in an
553 // TODO(crbug.com/1346889): Don't use this. Use the size-constrained
554 // GetPreferredSize(const SizeBounds&) instead.
555 gfx::Size GetPreferredSize() const;
557 // Get the size the View would like to be given `available_size`, ignoring the
559 gfx::Size GetPreferredSize(const SizeBounds& available_size) const;
561 // Sets or unsets the size that this View will request during layout. The
562 // actual size may differ. It should rarely be necessary to set this; usually
563 // the right approach is controlling the parent's layout via a LayoutManager.
564 void SetPreferredSize(absl::optional<gfx::Size> size);
566 // Convenience method that sizes this view to its preferred size.
567 void SizeToPreferredSize();
569 // Gets the minimum size of the view. View's implementation invokes
571 virtual gfx::Size GetMinimumSize() const;
573 // Gets the maximum size of the view. Currently only used for sizing shell
575 virtual gfx::Size GetMaximumSize() const;
577 // Return the preferred height for a specific width. Override if the
578 // preferred height depends upon the width (such as a multi-line label). If
579 // a LayoutManger has been installed this returns the value of
580 // LayoutManager::GetPreferredHeightForWidth(), otherwise this returns
581 // GetPreferredSize().height().
582 virtual int GetHeightForWidth(int w) const;
584 // Returns a bound on the available space for a child view, for example, in
585 // case the child view wants to play an animation that would cause it to
586 // become larger. Default is not to bound the available size; it is the
587 // responsibility of specific view/layout manager implementations to determine
588 // if and when a bound applies.
589 virtual SizeBounds GetAvailableSize(const View* child) const;
591 // The |Visible| property. See comment above for instructions on declaring and
592 // implementing a property.
594 // Sets whether this view is visible. Painting is scheduled as needed. Also,
595 // clears focus if the focused view or one of its ancestors is set to be
597 virtual void SetVisible(bool visible);
598 // Return whether a view is visible.
599 bool GetVisible() const;
601 // Adds a callback associated with the above Visible property. The callback
602 // will be invoked whenever the Visible property changes.
603 [[nodiscard]] base::CallbackListSubscription AddVisibleChangedCallback(
604 PropertyChangedCallback callback);
606 // Returns true if this view is drawn on screen.
607 virtual bool IsDrawn() const;
609 // The |Enabled| property. See comment above for instructions on declaring and
610 // implementing a property.
612 // Set whether this view is enabled. A disabled view does not receive keyboard
613 // or mouse inputs. If |enabled| differs from the current value, SchedulePaint
614 // is invoked. Also, clears focus if the focused view is disabled.
615 void SetEnabled(bool enabled);
616 // Returns whether the view is enabled.
617 bool GetEnabled() const;
619 // Adds a callback associated with the above |Enabled| property. The callback
620 // will be invoked whenever the property changes.
621 [[nodiscard]] base::CallbackListSubscription AddEnabledChangedCallback(
622 PropertyChangedCallback callback);
624 // Returns the child views ordered in reverse z-order. That is, views later in
625 // the returned vector have a higher z-order (are painted later) than those
626 // early in the vector. The returned vector has exactly the same number of
627 // Views as |children_|. The default implementation returns |children_|,
628 // subclass if the paint order should differ from that of |children_|.
629 // This order is taken into account by painting and targeting implementations.
630 // NOTE: see SetPaintToLayer() for details on painting and views with layers.
631 virtual Views GetChildrenInZOrder();
633 // Transformations -----------------------------------------------------------
635 // Methods for setting transformations for a view (e.g. rotation, scaling).
636 // Care should be taken not to transform a view in such a way that its bounds
637 // lie outside those of its parent, or else the default ViewTargeterDelegate
638 // implementation will not pass mouse events to the view.
640 gfx::Transform GetTransform() const;
642 // Clipping is done relative to the view's local bounds.
643 void SetClipPath(const SkPath& path);
644 const SkPath& clip_path() const { return clip_path_; }
646 // Sets the transform to the supplied transform.
647 void SetTransform(const gfx::Transform& transform);
649 // Accelerated painting ------------------------------------------------------
651 // Sets whether this view paints to a layer. A view paints to a layer if
652 // either of the following are true:
653 // . the view has a non-identity transform.
654 // . SetPaintToLayer(ui::LayerType) has been invoked.
655 // View creates the Layer only when it exists in a Widget with a non-NULL
657 // Enabling a view to have a layer impacts painting of sibling views.
658 // Specifically views with layers effectively paint in a z-order that is
659 // always above any sibling views that do not have layers. This happens
660 // regardless of the ordering returned by GetChildrenInZOrder().
661 void SetPaintToLayer(ui::LayerType layer_type = ui::LAYER_TEXTURED);
663 // Cancels layer painting triggered by a call to |SetPaintToLayer()|. Note
664 // that this will not actually destroy the layer if the view paints to a layer
665 // for another reason.
668 // Add or remove layers below this view. This view does not take ownership of
669 // the layers. It is the caller's responsibility to keep track of this View's
670 // size and update their layer accordingly.
672 // In very rare cases, it may be necessary to override these. If any of this
673 // view's contents must be painted to the same layer as its parent, or can't
674 // handle being painted with transparency, overriding might be appropriate.
675 // One example is LabelButton, where the label must paint below any added
676 // layers for subpixel rendering reasons. Overrides should be made
677 // judiciously, and generally they should just forward the calls to a child
678 // view. They must be overridden together for correctness.
679 virtual void AddLayerBeneathView(ui::Layer* new_layer);
680 virtual void RemoveLayerBeneathView(ui::Layer* old_layer);
682 // This is like RemoveLayerBeneathView() but doesn't remove |old_layer| from
683 // its parent. This is useful for when a layer beneth this view is owned by a
684 // ui::LayerOwner which just recreated it (by calling RecreateLayer()). In
685 // this case, this function can be called to remove it from |layers_beneath_|,
686 // and to stop observing it, but it remains in the layer tree since the
687 // expectation of ui::LayerOwner::RecreateLayer() is that the old layer
688 // remains under the same parent, and stacked above the newly cloned layer.
689 void RemoveLayerBeneathViewKeepInLayerTree(ui::Layer* old_layer);
691 // Gets the layers associated with this view that should be immediate children
692 // of the parent layer. They are returned in bottom-to-top order. This
693 // includes |this->layer()| and any layers added with |AddLayerBeneathView()|.
694 // Returns an empty vector if this view doesn't paint to a layer.
695 std::vector<ui::Layer*> GetLayersInOrder();
697 // ui::LayerObserver:
698 void LayerDestroyed(ui::Layer* layer) override;
700 // Overridden from ui::LayerOwner:
701 std::unique_ptr<ui::Layer> RecreateLayer() override;
703 // RTL positioning -----------------------------------------------------------
705 // Methods for accessing the bounds and position of the view, relative to its
706 // parent. The position returned is mirrored if the parent view is using a RTL
709 // NOTE: in the vast majority of the cases, the mirroring implementation is
710 // transparent to the View subclasses and therefore you should use the
711 // bounds() accessor instead.
712 gfx::Rect GetMirroredBounds() const;
713 gfx::Rect GetMirroredContentsBounds() const;
714 gfx::Point GetMirroredPosition() const;
715 int GetMirroredX() const;
717 // Given a rectangle specified in this View's coordinate system, the function
718 // computes the 'left' value for the mirrored rectangle within this View. If
719 // the View's UI layout is not right-to-left, then bounds.x() is returned.
721 // UI mirroring is transparent to most View subclasses and therefore there is
722 // no need to call this routine from anywhere within your subclass
724 int GetMirroredXForRect(const gfx::Rect& rect) const;
726 // Given a rectangle specified in this View's coordinate system, the function
727 // computes the mirrored rectangle.
728 gfx::Rect GetMirroredRect(const gfx::Rect& rect) const;
730 // Given the X coordinate of a point inside the View, this function returns
731 // the mirrored X coordinate of the point if the View's UI layout is
732 // right-to-left. If the layout is left-to-right, the same X coordinate is
735 // Following are a few examples of the values returned by this function for
736 // a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
738 // GetMirroredXCoordinateInView(0) -> 100
739 // GetMirroredXCoordinateInView(20) -> 80
740 // GetMirroredXCoordinateInView(99) -> 1
741 int GetMirroredXInView(int x) const;
743 // Given a X coordinate and a width inside the View, this function returns
744 // the mirrored X coordinate if the View's UI layout is right-to-left. If the
745 // layout is left-to-right, the same X coordinate is returned.
747 // Following are a few examples of the values returned by this function for
748 // a View with the bounds {0, 0, 100, 100} and a right-to-left layout:
750 // GetMirroredXCoordinateInView(0, 10) -> 90
751 // GetMirroredXCoordinateInView(20, 20) -> 60
752 int GetMirroredXWithWidthInView(int x, int w) const;
754 // Layout --------------------------------------------------------------------
756 // Lay out the child Views (set their bounds based on sizing heuristics
757 // specific to the current Layout Manager)
758 virtual void Layout();
760 bool needs_layout() const { return needs_layout_; }
762 // Mark this view and all parents to require a relayout. This ensures the
763 // next call to Layout() will propagate to this view, even if the bounds of
764 // parent views do not change.
765 void InvalidateLayout();
767 // TODO(kylixrd): Update comment once UseDefaultFillLayout is true by default.
768 // UseDefaultFillLayout will be set to true by default once the codebase is
769 // audited and refactored.
771 // Gets/Sets the Layout Manager used by this view to size and place its
772 // children. NOTE: This will force UseDefaultFillLayout to false if it had
775 // The LayoutManager is owned by the View and is deleted when the view is
776 // deleted, or when a new LayoutManager is installed. Call
777 // SetLayoutManager(nullptr) to clear it.
779 // SetLayoutManager returns a bare pointer version of the input parameter
780 // (now owned by the view). If code needs to use the layout manager after
781 // being assigned, use this pattern:
783 // views::BoxLayout* box_layout = SetLayoutManager(
784 // std::make_unique<views::BoxLayout>(...));
785 // box_layout->Foo();
786 LayoutManager* GetLayoutManager() const;
787 template <typename LayoutManager>
788 LayoutManager* SetLayoutManager(
789 std::unique_ptr<LayoutManager> layout_manager) {
790 LayoutManager* lm = layout_manager.get();
791 SetLayoutManagerImpl(std::move(layout_manager));
794 void SetLayoutManager(std::nullptr_t);
796 // Sets whether or not the default layout manager should be used for this
797 // view. NOTE: this can only be set if |layout_manager_| isn't assigned.
798 bool GetUseDefaultFillLayout() const;
799 void SetUseDefaultFillLayout(bool value);
801 // Attributes ----------------------------------------------------------------
803 // Recursively descends the view tree starting at this view, and returns
804 // the first child that it encounters that has the given ID.
805 // Returns NULL if no matching child view is found.
806 const View* GetViewByID(int id) const;
807 View* GetViewByID(int id);
809 // Gets and sets the ID for this view. ID should be unique within the subtree
810 // that you intend to search for it. 0 is the default ID for views.
811 int GetID() const { return id_; }
814 // Adds a callback associated with the above |ID| property. The callback will
815 // be invoked whenever the property changes.
816 [[nodiscard]] base::CallbackListSubscription AddIDChangedCallback(
817 PropertyChangedCallback callback);
819 // A group id is used to tag views which are part of the same logical group.
820 // Focus can be moved between views with the same group using the arrow keys.
821 // Groups are currently used to implement radio button mutual exclusion.
822 // The group id is immutable once it's set.
823 void SetGroup(int gid);
824 // Returns the group id of the view, or -1 if the id is not set yet.
825 int GetGroup() const;
827 // Adds a callback associated with the above |Group| property. The callback
828 // will be invoked whenever the property changes.
829 [[nodiscard]] base::CallbackListSubscription AddGroupChangedCallback(
830 PropertyChangedCallback callback);
832 // If this returns true, the views from the same group can each be focused
833 // when moving focus with the Tab/Shift-Tab key. If this returns false,
834 // only the selected view from the group (obtained with
835 // GetSelectedViewForGroup()) is focused.
836 virtual bool IsGroupFocusTraversable() const;
838 // Fills |views| with all the available views which belong to the provided
840 void GetViewsInGroup(int group, Views* views);
842 // Returns the View that is currently selected in |group|.
843 // The default implementation simply returns the first View found for that
845 virtual View* GetSelectedViewForGroup(int group);
847 // Coordinate conversion -----------------------------------------------------
849 // Note that the utility coordinate conversions functions always operate on
850 // the mirrored position of the child Views if the parent View uses a
851 // right-to-left UI layout.
853 // Convert a point from the coordinate system of one View to another.
855 // |source| and |target| must be in the same widget, but doesn't need to be in
856 // the same view hierarchy.
857 // Neither |source| nor |target| can be NULL.
858 static void ConvertPointToTarget(const View* source,
862 [[nodiscard]] static gfx::Point ConvertPointToTarget(const View* source,
864 const gfx::Point& point);
866 // Convert |rect| from the coordinate system of |source| to the coordinate
867 // system of |target|.
869 // |source| and |target| must be in the same widget, but doesn't need to be in
870 // the same view hierarchy.
871 // Neither |source| nor |target| can be NULL.
872 static void ConvertRectToTarget(const View* source,
875 [[nodiscard]] static gfx::RectF ConvertRectToTarget(const View* source,
877 const gfx::RectF& rect);
879 // Convert a point from a View's coordinate system to that of its Widget.
880 static void ConvertPointToWidget(const View* src, gfx::Point* point);
882 // Convert a point from the coordinate system of a View's Widget to that
883 // View's coordinate system.
884 static void ConvertPointFromWidget(const View* dest, gfx::Point* p);
886 // Convert a point from a View's coordinate system to that of the screen.
887 static void ConvertPointToScreen(const View* src, gfx::Point* point);
889 // Convert a point from the screen coordinate system to that View's coordinate
891 static void ConvertPointFromScreen(const View* dst, gfx::Point* point);
893 // Convert a rect from a View's coordinate system to that of the screen.
894 static void ConvertRectToScreen(const View* src, gfx::Rect* rect);
896 // Applies transformation on the rectangle, which is in the view's coordinate
897 // system, to convert it into the parent's coordinate system.
898 gfx::Rect ConvertRectToParent(const gfx::Rect& rect) const;
900 // Converts a rectangle from this views coordinate system to its widget
901 // coordinate system.
902 gfx::Rect ConvertRectToWidget(const gfx::Rect& rect) const;
904 // Painting ------------------------------------------------------------------
906 // Mark all or part of the View's bounds as dirty (needing repaint).
907 // |r| is in the View's coordinates.
908 // TODO(beng): Make protected.
909 void SchedulePaint();
910 void SchedulePaintInRect(const gfx::Rect& r);
912 // Called by the framework to paint a View. Performs translation and clipping
913 // for View coordinates and language direction as required, allows the View
914 // to paint itself via the various OnPaint*() event handlers and then paints
915 // the hierarchy beneath it.
916 void Paint(const PaintInfo& parent_paint_info);
918 // The background object may be null.
919 void SetBackground(std::unique_ptr<Background> b);
920 Background* GetBackground() const;
921 const Background* background() const { return background_.get(); }
922 Background* background() { return background_.get(); }
924 // The border object may be null.
925 virtual void SetBorder(std::unique_ptr<Border> b);
926 Border* GetBorder() const;
928 // Get the theme provider from the parent widget.
929 const ui::ThemeProvider* GetThemeProvider() const;
931 // Get the layout provider for the View.
932 const LayoutProvider* GetLayoutProvider() const;
934 // Returns the ColorProvider from the ColorProviderManager.
935 ui::ColorProvider* GetColorProvider() {
936 return const_cast<ui::ColorProvider*>(
937 std::as_const(*this).GetColorProvider());
939 const ui::ColorProvider* GetColorProvider() const;
941 // Returns the NativeTheme to use for this View. This calls through to
942 // GetNativeTheme() on the Widget this View is in, or provides a default
943 // theme if there's no widget, or returns |native_theme_| if that's
944 // set. Warning: the default theme might not be correct; you should probably
945 // override OnThemeChanged().
946 ui::NativeTheme* GetNativeTheme() {
947 return const_cast<ui::NativeTheme*>(std::as_const(*this).GetNativeTheme());
949 const ui::NativeTheme* GetNativeTheme() const;
951 // Sets the native theme and informs descendants.
952 void SetNativeThemeForTesting(ui::NativeTheme* theme);
954 // RTL painting --------------------------------------------------------------
956 // Returns whether the gfx::Canvas object passed to Paint() needs to be
957 // transformed such that anything drawn on the canvas object during Paint()
958 // is flipped horizontally.
959 bool GetFlipCanvasOnPaintForRTLUI() const;
960 // Enables or disables flipping of the gfx::Canvas during Paint(). Note that
961 // if canvas flipping is enabled, the canvas will be flipped only if the UI
962 // layout is right-to-left; that is, the canvas will be flipped only if
963 // GetMirrored() is true.
965 // Enabling canvas flipping is useful for leaf views that draw an image that
966 // needs to be flipped horizontally when the UI layout is right-to-left
967 // (views::Button, for example). This method is helpful for such classes
968 // because their drawing logic stays the same and they can become agnostic to
969 // the UI directionality.
970 void SetFlipCanvasOnPaintForRTLUI(bool enable);
972 // Adds a callback associated with the above FlipCanvasOnPaintForRTLUI
973 // property. The callback will be invoked whenever the
974 // FlipCanvasOnPaintForRTLUI property changes.
975 [[nodiscard]] base::CallbackListSubscription
976 AddFlipCanvasOnPaintForRTLUIChangedCallback(PropertyChangedCallback callback);
978 // When set, this view will ignore base::l18n::IsRTL() and instead be drawn
979 // according to |is_mirrored|.
981 // This is useful for views that should be displayed the same regardless of UI
982 // direction. Unlike SetFlipCanvasOnPaintForRTLUI this setting has an effect
983 // on the visual order of child views.
985 // This setting does not propagate to child views. So while the visual order
986 // of this view's children may change, the visual order of this view's
987 // grandchildren in relation to their parents are unchanged.
988 void SetMirrored(bool is_mirrored);
989 bool GetMirrored() const;
991 // Input ---------------------------------------------------------------------
992 // The points, rects, mouse locations, and touch locations in the following
993 // functions are in the view's coordinates, except for a RootView.
995 // A convenience function which calls into GetEventHandlerForRect() with
996 // a 1x1 rect centered at |point|. |point| is in the local coordinate
998 View* GetEventHandlerForPoint(const gfx::Point& point);
1000 // Returns the View that should be the target of an event having |rect| as
1001 // its location, or NULL if no such target exists. |rect| is in the local
1002 // coordinate space of |this|.
1003 View* GetEventHandlerForRect(const gfx::Rect& rect);
1005 // Returns the deepest visible descendant that contains the specified point
1006 // and supports tooltips. If the view does not contain the point, returns
1008 virtual View* GetTooltipHandlerForPoint(const gfx::Point& point);
1010 // Return the cursor that should be used for this view or the default cursor.
1011 // The event location is in the receiver's coordinate system. The caller is
1012 // responsible for managing the lifetime of the returned object, though that
1013 // lifetime may vary from platform to platform. On Windows and Aura,
1014 // the cursor is a shared resource.
1015 virtual ui::Cursor GetCursor(const ui::MouseEvent& event);
1017 // A convenience function which calls HitTestRect() with a rect of size
1018 // 1x1 and an origin of |point|. |point| is in the local coordinate space
1020 bool HitTestPoint(const gfx::Point& point) const;
1022 // Returns true if |rect| intersects this view's bounds. |rect| is in the
1023 // local coordinate space of |this|.
1024 bool HitTestRect(const gfx::Rect& rect) const;
1026 // Returns true if this view or any of its descendants are permitted to
1027 // be the target of an event.
1028 virtual bool GetCanProcessEventsWithinSubtree() const;
1030 // Sets whether this view or any of its descendants are permitted to be the
1031 // target of an event.
1032 void SetCanProcessEventsWithinSubtree(bool can_process);
1034 // Returns true if the mouse cursor is over |view| and mouse events are
1036 bool IsMouseHovered() const;
1038 // This method is invoked when the user clicks on this view.
1039 // The provided event is in the receiver's coordinate system.
1041 // Return true if you processed the event and want to receive subsequent
1042 // MouseDragged and MouseReleased events. This also stops the event from
1043 // bubbling. If you return false, the event will bubble through parent
1046 // If you remove yourself from the tree while processing this, event bubbling
1047 // stops as if you returned true, but you will not receive future events.
1048 // The return value is ignored in this case.
1050 // Default implementation returns true if a ContextMenuController has been
1051 // set, false otherwise. Override as needed.
1053 virtual bool OnMousePressed(const ui::MouseEvent& event);
1055 // This method is invoked when the user clicked on this control.
1056 // and is still moving the mouse with a button pressed.
1057 // The provided event is in the receiver's coordinate system.
1059 // Return true if you processed the event and want to receive
1060 // subsequent MouseDragged and MouseReleased events.
1062 // Default implementation returns true if a ContextMenuController has been
1063 // set, false otherwise. Override as needed.
1065 virtual bool OnMouseDragged(const ui::MouseEvent& event);
1067 // This method is invoked when the user releases the mouse
1068 // button. The event is in the receiver's coordinate system.
1070 // Default implementation notifies the ContextMenuController is appropriate.
1071 // Subclasses that wish to honor the ContextMenuController should invoke
1073 virtual void OnMouseReleased(const ui::MouseEvent& event);
1075 // This method is invoked when the mouse press/drag was canceled by a
1076 // system/user gesture.
1077 virtual void OnMouseCaptureLost();
1079 // This method is invoked when the mouse is above this control
1080 // The event is in the receiver's coordinate system.
1082 // Default implementation does nothing. Override as needed.
1083 virtual void OnMouseMoved(const ui::MouseEvent& event);
1085 // This method is invoked when the mouse enters this control.
1087 // Default implementation does nothing. Override as needed.
1088 virtual void OnMouseEntered(const ui::MouseEvent& event);
1090 // This method is invoked when the mouse exits this control
1091 // The provided event location is always (0, 0)
1092 // Default implementation does nothing. Override as needed.
1093 virtual void OnMouseExited(const ui::MouseEvent& event);
1095 // Set both the MouseHandler and the GestureHandler for a drag session.
1097 // A drag session is a stream of mouse events starting
1098 // with a MousePressed event, followed by several MouseDragged
1099 // events and finishing with a MouseReleased event.
1101 // This method should be only invoked while processing a
1102 // MouseDragged or MousePressed event.
1104 // All further mouse dragged and mouse up events will be sent
1105 // the MouseHandler, even if it is reparented to another window.
1107 // The MouseHandler is automatically cleared when the control
1108 // comes back from processing the MouseReleased event.
1110 // Note: if the mouse handler is no longer connected to a
1111 // view hierarchy, events won't be sent.
1112 virtual void SetMouseAndGestureHandler(View* new_handler);
1114 // Sets a new mouse handler.
1115 virtual void SetMouseHandler(View* new_handler);
1117 // Invoked when a key is pressed or released.
1118 // Subclasses should return true if the event has been processed and false
1119 // otherwise. If the event has not been processed, the parent will be given a
1121 virtual bool OnKeyPressed(const ui::KeyEvent& event);
1122 virtual bool OnKeyReleased(const ui::KeyEvent& event);
1124 // Invoked when the user uses the mousewheel. Implementors should return true
1125 // if the event has been processed and false otherwise. This message is sent
1126 // if the view is focused. If the event has not been processed, the parent
1127 // will be given a chance.
1128 virtual bool OnMouseWheel(const ui::MouseWheelEvent& event);
1130 // See field for description.
1131 void SetNotifyEnterExitOnChild(bool notify);
1132 bool GetNotifyEnterExitOnChild() const;
1134 // Convenience method to retrieve the InputMethod associated with the
1135 // Widget that contains this view.
1136 ui::InputMethod* GetInputMethod() {
1137 return const_cast<ui::InputMethod*>(std::as_const(*this).GetInputMethod());
1139 const ui::InputMethod* GetInputMethod() const;
1141 // Sets a new ViewTargeter for the view, and returns the previous
1143 std::unique_ptr<ViewTargeter> SetEventTargeter(
1144 std::unique_ptr<ViewTargeter> targeter);
1146 // Returns the ViewTargeter installed on |this| if one exists,
1147 // otherwise returns the ViewTargeter installed on our root view.
1148 // The return value is guaranteed to be non-null.
1149 ViewTargeter* GetEffectiveViewTargeter() const;
1151 ViewTargeter* targeter() const { return targeter_.get(); }
1153 // Returns the WordLookupClient associated with this view.
1154 virtual WordLookupClient* GetWordLookupClient();
1156 // Overridden from ui::EventTarget:
1157 bool CanAcceptEvent(const ui::Event& event) override;
1158 ui::EventTarget* GetParentTarget() override;
1159 std::unique_ptr<ui::EventTargetIterator> GetChildIterator() const override;
1160 ui::EventTargeter* GetEventTargeter() override;
1161 void ConvertEventToTarget(const ui::EventTarget* target,
1162 ui::LocatedEvent* event) const override;
1163 gfx::PointF GetScreenLocationF(const ui::LocatedEvent& event) const override;
1165 // Overridden from ui::EventHandler:
1166 void OnKeyEvent(ui::KeyEvent* event) override;
1167 void OnMouseEvent(ui::MouseEvent* event) override;
1168 void OnScrollEvent(ui::ScrollEvent* event) override;
1169 void OnTouchEvent(ui::TouchEvent* event) final;
1170 void OnGestureEvent(ui::GestureEvent* event) override;
1171 base::StringPiece GetLogContext() const override;
1173 // Accelerators --------------------------------------------------------------
1175 // Sets a keyboard accelerator for that view. When the user presses the
1176 // accelerator key combination, the AcceleratorPressed method is invoked.
1177 // Note that you can set multiple accelerators for a view by invoking this
1178 // method several times. Note also that AcceleratorPressed is invoked only
1179 // when CanHandleAccelerators() is true.
1180 void AddAccelerator(const ui::Accelerator& accelerator);
1182 // Removes the specified accelerator for this view.
1183 void RemoveAccelerator(const ui::Accelerator& accelerator);
1185 // Removes all the keyboard accelerators for this view.
1186 void ResetAccelerators();
1188 // Overridden from AcceleratorTarget:
1189 bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
1191 // Returns whether accelerators are enabled for this view. Accelerators are
1192 // enabled if the containing widget is visible and the view is enabled() and
1194 bool CanHandleAccelerators() const override;
1196 // Focus ---------------------------------------------------------------------
1198 // Returns whether this view currently has the focus.
1199 virtual bool HasFocus() const;
1201 // Returns the view that is a candidate to be focused next when pressing Tab.
1203 // The returned view might not be `IsFocusable`, but it's children can be
1204 // traversed to evaluate if one of them `IsFocusable`.
1206 // If this returns `nullptr` then it is the last focusable candidate view in
1207 // the list including its siblings.
1208 View* GetNextFocusableView();
1209 const View* GetNextFocusableView() const;
1211 // Returns the view that is a candidate to be focused next when pressing
1214 // The returned view might not be `IsFocusable`, but it's children can be
1215 // traversed to evaluate if one of them `IsFocusable`.
1217 // If this returns `nullptr` then it is the first focusable candidate view in
1218 // the list including its siblings.
1219 View* GetPreviousFocusableView();
1221 // Removes |this| from its focus list, updating the previous and next
1222 // views' points accordingly.
1223 void RemoveFromFocusList();
1225 // Insert |this| before or after |view| in the focus list.
1226 void InsertBeforeInFocusList(View* view);
1227 void InsertAfterInFocusList(View* view);
1229 // Returns the list of children in the order of their focus. Each child might
1230 // not be `IsFocusable`. Children that are not `IsFocusable` might still have
1231 // children of its own that are `IsFocusable`.
1232 Views GetChildrenFocusList();
1234 // Gets/sets |FocusBehavior|. SetFocusBehavior() advances focus if necessary.
1235 virtual FocusBehavior GetFocusBehavior() const;
1236 void SetFocusBehavior(FocusBehavior focus_behavior);
1238 // Set this to suppress default handling of focus for this View. By default
1239 // native focus will be cleared and a11y events announced based on the new
1241 // TODO(pbos): This is here to make removing focus behavior from the base
1242 // implementation of OnFocus a no-op. Try to avoid new uses of this. Also
1243 // investigate if this can be configured with more granularity (which event
1244 // to fire on focus etc.).
1245 void set_suppress_default_focus_handling() {
1246 suppress_default_focus_handling_ = true;
1249 // Returns true if this view is focusable, |enabled_| and drawn.
1250 bool IsFocusable() const;
1252 // Return whether this view is focusable when the user requires full keyboard
1253 // access, even though it may not be normally focusable.
1254 bool IsAccessibilityFocusable() const;
1256 // Convenience method to retrieve the FocusManager associated with the
1257 // Widget that contains this view. This can return NULL if this view is not
1258 // part of a view hierarchy with a Widget.
1259 FocusManager* GetFocusManager();
1260 const FocusManager* GetFocusManager() const;
1262 // Request keyboard focus. The receiving view will become the focused view.
1263 virtual void RequestFocus();
1265 // Invoked when a view is about to be requested for focus due to the focus
1266 // traversal. Reverse is this request was generated going backward
1268 virtual void AboutToRequestFocusFromTabTraversal(bool reverse) {}
1270 // Invoked when a key is pressed before the key event is processed (and
1271 // potentially eaten) by the focus manager for tab traversal, accelerators and
1272 // other focus related actions.
1273 // The default implementation returns false, ensuring that tab traversal and
1274 // accelerators processing is performed.
1275 // Subclasses should return true if they want to process the key event and not
1276 // have it processed as an accelerator (if any) or as a tab traversal (if the
1277 // key event is for the TAB key). In that case, OnKeyPressed will
1278 // subsequently be invoked for that event.
1279 virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event);
1281 // Subclasses that contain traversable children that are not directly
1282 // accessible through the children hierarchy should return the associated
1283 // FocusTraversable for the focus traversal to work properly.
1284 virtual FocusTraversable* GetFocusTraversable();
1286 // Subclasses that can act as a "pane" must implement their own
1287 // FocusTraversable to keep the focus trapped within the pane.
1288 // If this method returns an object, any view that's a direct or
1289 // indirect child of this view will always use this FocusTraversable
1290 // rather than the one from the widget.
1291 virtual FocusTraversable* GetPaneFocusTraversable();
1293 // Tooltips ------------------------------------------------------------------
1295 // Gets the tooltip for this View. If the View does not have a tooltip,
1296 // the returned value should be empty.
1297 // Any time the tooltip text that a View is displaying changes, it must
1298 // invoke TooltipTextChanged.
1299 // |p| provides the coordinates of the mouse (relative to this view).
1300 virtual std::u16string GetTooltipText(const gfx::Point& p) const;
1302 // Context menus -------------------------------------------------------------
1304 // Sets the ContextMenuController. Setting this to non-null makes the View
1305 // process mouse events.
1306 ContextMenuController* context_menu_controller() {
1307 return context_menu_controller_;
1309 void set_context_menu_controller(ContextMenuController* menu_controller) {
1310 context_menu_controller_ = menu_controller;
1313 // Provides default implementation for context menu handling. The default
1314 // implementation calls the ShowContextMenu of the current
1315 // ContextMenuController (if it is not NULL). Overridden in subclassed views
1316 // to provide right-click menu display triggered by the keyboard (i.e. for the
1317 // Chrome toolbar Back and Forward buttons). No source needs to be specified,
1318 // as it is always equal to the current View.
1319 // Note that this call is asynchronous for views menu and synchronous for
1320 // mac's native menu.
1321 virtual void ShowContextMenu(const gfx::Point& p,
1322 ui::MenuSourceType source_type);
1324 // Returns the location, in screen coordinates, to show the context menu at
1325 // when the context menu is shown from the keyboard. This implementation
1326 // returns the middle of the visible region of this view.
1328 // This method is invoked when the context menu is shown by way of the
1330 virtual gfx::Point GetKeyboardContextMenuLocation();
1332 // Drag and drop -------------------------------------------------------------
1334 DragController* drag_controller() { return drag_controller_; }
1335 void set_drag_controller(DragController* drag_controller) {
1336 drag_controller_ = drag_controller;
1339 // During a drag and drop session when the mouse moves the view under the
1340 // mouse is queried for the drop types it supports by way of the
1341 // GetDropFormats methods. If the view returns true and the drag site can
1342 // provide data in one of the formats, the view is asked if the drop data
1343 // is required before any other drop events are sent. Once the
1344 // data is available the view is asked if it supports the drop (by way of
1345 // the CanDrop method). If a view returns true from CanDrop,
1346 // OnDragEntered is sent to the view when the mouse first enters the view,
1347 // as the mouse moves around within the view OnDragUpdated is invoked.
1348 // If the user releases the mouse over the view and OnDragUpdated returns a
1349 // valid drop, then GetDropCallback is invoked. If the mouse moves outside the
1350 // view or over another view that wants the drag, OnDragExited is invoked.
1352 // Similar to mouse events, the deepest view under the mouse is first checked
1353 // if it supports the drop (Drop). If the deepest view under
1354 // the mouse does not support the drop, the ancestors are walked until one
1355 // is found that supports the drop.
1357 // Override and return the set of formats that can be dropped on this view.
1358 // |formats| is a bitmask of the formats defined bye OSExchangeData::Format.
1359 // The default implementation returns false, which means the view doesn't
1360 // support dropping.
1361 virtual bool GetDropFormats(int* formats,
1362 std::set<ui::ClipboardFormatType>* format_types);
1364 // Override and return true if the data must be available before any drop
1365 // methods should be invoked. The default is false.
1366 virtual bool AreDropTypesRequired();
1368 // A view that supports drag and drop must override this and return true if
1369 // data contains a type that may be dropped on this view.
1370 virtual bool CanDrop(const OSExchangeData& data);
1372 // OnDragEntered is invoked when the mouse enters this view during a drag and
1373 // drop session and CanDrop returns true. This is immediately
1374 // followed by an invocation of OnDragUpdated, and eventually one of
1375 // OnDragExited or GetDropCallback.
1376 virtual void OnDragEntered(const ui::DropTargetEvent& event);
1378 // Invoked during a drag and drop session while the mouse is over the view.
1379 // This should return a bitmask of the DragDropTypes::DragOperation supported
1380 // based on the location of the event. Return 0 to indicate the drop should
1382 virtual int OnDragUpdated(const ui::DropTargetEvent& event);
1384 // Invoked during a drag and drop session when the mouse exits the views, or
1385 // when the drag session was canceled and the mouse was over the view.
1386 virtual void OnDragExited();
1388 // Invoked from DoDrag after the drag completes. This implementation does
1389 // nothing, and is intended for subclasses to do cleanup.
1390 virtual void OnDragDone();
1392 // Invoked during a drag and drop session when OnDragUpdated returns a valid
1393 // operation and the user release the mouse but the drop is held because of
1394 // DataTransferPolicyController. When calling, ensure that the |event|
1395 // uses View local coordinates.
1396 virtual DropCallback GetDropCallback(const ui::DropTargetEvent& event);
1398 // Returns true if the mouse was dragged enough to start a drag operation.
1399 // delta_x and y are the distance the mouse was dragged.
1400 static bool ExceededDragThreshold(const gfx::Vector2d& delta);
1402 // Accessibility -------------------------------------------------------------
1404 // Get the object managing the accessibility interface for this View.
1405 ViewAccessibility& GetViewAccessibility() const;
1407 // Modifies |node_data| to reflect the current accessible state of this
1409 virtual void GetAccessibleNodeData(ui::AXNodeData* node_data) {}
1411 // Handle a request from assistive technology to perform an action on this
1412 // view. Returns true on success, but note that the success/failure is
1413 // not propagated to the client that requested the action, since the
1414 // request is sometimes asynchronous. The right way to send a response is
1415 // via NotifyAccessibilityEvent(), below.
1416 virtual bool HandleAccessibleAction(const ui::AXActionData& action_data);
1418 // Returns an instance of the native accessibility interface for this view.
1419 virtual gfx::NativeViewAccessible GetNativeViewAccessible();
1421 // Notifies assistive technology that an accessibility event has
1422 // occurred on this view, such as when the view is focused or when its
1423 // value changes. Pass true for |send_native_event| except for rare
1424 // cases where the view is a native control that's already sending a
1425 // native accessibility event and the duplicate event would cause
1427 void NotifyAccessibilityEvent(ax::mojom::Event event_type,
1428 bool send_native_event);
1430 // Views may override this function to know when an accessibility
1431 // event is fired. This will be called by NotifyAccessibilityEvent.
1432 virtual void OnAccessibilityEvent(ax::mojom::Event event_type);
1434 // Scrolling -----------------------------------------------------------------
1435 // TODO(beng): Figure out if this can live somewhere other than View, i.e.
1436 // closer to ScrollView.
1438 // Scrolls the specified region, in this View's coordinate system, to be
1439 // visible. View's implementation passes the call onto the parent View (after
1440 // adjusting the coordinates). It is up to views that only show a portion of
1441 // the child view, such as Viewport, to override appropriately.
1442 virtual void ScrollRectToVisible(const gfx::Rect& rect);
1444 // Scrolls the view's bounds or some subset thereof to be visible. By default
1445 // this function calls ScrollRectToVisible(GetLocalBounds()).
1446 void ScrollViewToVisible();
1448 void AddObserver(ViewObserver* observer);
1449 void RemoveObserver(ViewObserver* observer);
1450 bool HasObserver(const ViewObserver* observer) const;
1452 // http://crbug.com/1162949 : Instrumentation that indicates if this is alive.
1453 // Callers should not depend on this as it is meant to be temporary.
1454 enum class LifeCycleState : uint32_t {
1455 kAlive = 0x600D600D,
1456 kDestroying = 0x90141013,
1457 kDestroyed = 0xBAADBAAD,
1460 LifeCycleState life_cycle_state() const { return life_cycle_state_; }
1463 // Used to track a drag. RootView passes this into
1464 // ProcessMousePressed/Dragged.
1466 // Sets possible_drag to false and start_x/y to 0. This is invoked by
1467 // RootView prior to invoke ProcessMousePressed.
1470 // Sets possible_drag to true and start_pt to the specified point.
1471 // This is invoked by the target view if it detects the press may generate
1473 void PossibleDrag(const gfx::Point& p);
1475 // Whether the press may generate a drag.
1476 bool possible_drag = false;
1478 // Coordinates of the mouse press.
1479 gfx::Point start_pt;
1482 // Size and disposition ------------------------------------------------------
1484 // Calculates the natural size for the View, to be taken into consideration
1485 // when the parent is performing layout.
1486 // `preferred_size_` will take precedence over CalculatePreferredSize() if
1488 virtual gfx::Size CalculatePreferredSize() const;
1490 // Calculates the preferred size for the View given `available_size`.
1491 // `preferred_size_` will take precedence over CalculatePreferredSize() if
1493 virtual gfx::Size CalculatePreferredSize(
1494 const SizeBounds& available_size) const;
1496 // Override to be notified when the bounds of the view have changed.
1497 virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) {}
1499 // Called when the preferred size of a child view changed. This gives the
1500 // parent an opportunity to do a fresh layout if that makes sense.
1501 virtual void ChildPreferredSizeChanged(View* child) {}
1503 // Called when the visibility of a child view changed. This gives the parent
1504 // an opportunity to do a fresh layout if that makes sense.
1505 virtual void ChildVisibilityChanged(View* child) {}
1507 // Invalidates the layout and calls ChildPreferredSizeChanged() on the parent
1508 // if there is one. Be sure to call PreferredSizeChanged() when overriding
1509 // such that the layout is properly invalidated.
1510 virtual void PreferredSizeChanged();
1512 // Override returning true when the view needs to be notified when its visible
1513 // bounds relative to the root view may have changed. Only used by
1515 virtual bool GetNeedsNotificationWhenVisibleBoundsChange() const;
1517 // Notification that this View's visible bounds relative to the root view may
1518 // have changed. The visible bounds are the region of the View not clipped by
1519 // its ancestors. This is used for clipping NativeViewHost.
1520 virtual void OnVisibleBoundsChanged();
1522 // Tree operations -----------------------------------------------------------
1524 // This method is invoked when the tree changes.
1526 // When a view is removed, it is invoked for all children and grand
1527 // children. For each of these views, a notification is sent to the
1528 // view and all parents.
1530 // When a view is added, a notification is sent to the view, all its
1531 // parents, and all its children (and grand children)
1533 // Default implementation does nothing. Override to perform operations
1534 // required when a view is added or removed from a view hierarchy
1536 // Refer to comments in struct |ViewHierarchyChangedDetails| for |details|.
1538 // See also AddedToWidget() and RemovedFromWidget() for detecting when the
1539 // view is added to/removed from a widget.
1540 virtual void ViewHierarchyChanged(const ViewHierarchyChangedDetails& details);
1542 // When SetVisible() changes the visibility of a view, this method is
1543 // invoked for that view as well as all the children recursively.
1544 virtual void VisibilityChanged(View* starting_from, bool is_visible);
1546 // This method is invoked when the parent NativeView of the widget that the
1547 // view is attached to has changed and the view hierarchy has not changed.
1548 // ViewHierarchyChanged() is called when the parent NativeView of the widget
1549 // that the view is attached to is changed as a result of changing the view
1550 // hierarchy. Overriding this method is useful for tracking which
1551 // FocusManager manages this view.
1552 virtual void NativeViewHierarchyChanged();
1554 // This method is invoked for a view when it is attached to a hierarchy with
1555 // a widget, i.e. GetWidget() starts returning a non-null result.
1556 // It is also called when the view is moved to a different widget.
1557 virtual void AddedToWidget();
1559 // This method is invoked for a view when it is removed from a hierarchy with
1560 // a widget or moved to a different widget.
1561 virtual void RemovedFromWidget();
1563 // Painting ------------------------------------------------------------------
1565 // Override to control paint redirection or to provide a different Rectangle
1566 // |r| to be repainted. This is a function with an empty implementation in
1567 // view.cc and is purely intended for subclasses to override.
1568 virtual void OnDidSchedulePaint(const gfx::Rect& r);
1570 // Responsible for calling Paint() on child Views. Override to control the
1571 // order child Views are painted.
1572 virtual void PaintChildren(const PaintInfo& info);
1574 // Override to provide rendering in any part of the View's bounds. Typically
1575 // this is the "contents" of the view. If you override this method you will
1576 // have to call the subsequent OnPaint*() methods manually.
1577 virtual void OnPaint(gfx::Canvas* canvas);
1579 // Override to paint a background before any content is drawn. Typically this
1580 // is done if you are satisfied with a default OnPaint handler but wish to
1581 // supply a different background.
1582 virtual void OnPaintBackground(gfx::Canvas* canvas);
1584 // Override to paint a border not specified by SetBorder().
1585 virtual void OnPaintBorder(gfx::Canvas* canvas);
1587 // Returns the type of scaling to be done for this View. Override this to
1588 // change the default scaling type from |kScaleToFit|. You would want to
1589 // override this for a view and return |kScaleToScaleFactor| in cases where
1590 // scaling should cause no distortion. Such as in the case of an image or
1592 virtual PaintInfo::ScaleType GetPaintScaleType() const;
1594 // Accelerated painting ------------------------------------------------------
1596 // Returns the offset from this view to the nearest ancestor with a layer. If
1597 // |layer_parent| is non-NULL it is set to the nearest ancestor with a layer.
1598 virtual LayerOffsetData CalculateOffsetToAncestorWithLayer(
1599 ui::Layer** layer_parent);
1601 // Updates the view's layer's parent. Called when a view is added to a view
1602 // hierarchy, responsible for parenting the view's layer to the enclosing
1603 // layer in the hierarchy.
1604 virtual void UpdateParentLayer();
1606 // If this view has a layer, the layer is reparented to |parent_layer| and its
1607 // bounds is set based on |point|. If this view does not have a layer, then
1608 // recurses through all children. This is used when adding a layer to an
1609 // existing view to make sure all descendants that have layers are parented to
1611 void MoveLayerToParent(ui::Layer* parent_layer,
1612 const LayerOffsetData& offset_data);
1614 // Called to update the bounds of any child layers within this View's
1615 // hierarchy when something happens to the hierarchy.
1616 void UpdateChildLayerBounds(const LayerOffsetData& offset_data);
1618 // Overridden from ui::LayerDelegate:
1619 void OnPaintLayer(const ui::PaintContext& context) override;
1620 void OnLayerTransformed(const gfx::Transform& old_transform,
1621 ui::PropertyChangeReason reason) final;
1622 void OnLayerClipRectChanged(const gfx::Rect& old_rect,
1623 ui::PropertyChangeReason reason) override;
1624 void OnDeviceScaleFactorChanged(float old_device_scale_factor,
1625 float new_device_scale_factor) override;
1627 // Finds the layer that this view paints to (it may belong to an ancestor
1628 // view), then reorders the immediate children of that layer to match the
1629 // order of the view tree.
1630 void ReorderLayers();
1632 // This reorders the immediate children of |*parent_layer| to match the
1633 // order of the view tree. Child layers which are owned by a view are
1634 // reordered so that they are below any child layers not owned by a view.
1635 // Widget::ReorderNativeViews() should be called to reorder any child layers
1636 // with an associated view. Widget::ReorderNativeViews() may reorder layers
1637 // below layers owned by a view.
1638 virtual void ReorderChildLayers(ui::Layer* parent_layer);
1640 // Notifies parents about a layer being created or destroyed in a child. An
1641 // example where a subclass may override this method is when it wants to clip
1642 // the child by adding its own layer.
1643 virtual void OnChildLayerChanged(View* child);
1645 // Input ---------------------------------------------------------------------
1647 virtual DragInfo* GetDragInfo();
1649 // Focus ---------------------------------------------------------------------
1651 // Override to be notified when focus has changed either to or from this View.
1652 virtual void OnFocus();
1653 virtual void OnBlur();
1655 // Handle view focus/blur events for this view.
1659 // System events -------------------------------------------------------------
1661 // Called when either the UI theme or the NativeTheme associated with this
1662 // View changes. This is also called when the NativeTheme first becomes
1663 // available (after the view is added to a widget hierarchy). Overriding
1664 // allows individual Views to do special cleanup and processing (such as
1665 // dropping resource caches). To dispatch a theme changed notification, call
1666 // Widget::ThemeChanged().
1667 virtual void OnThemeChanged();
1669 // Tooltips ------------------------------------------------------------------
1671 // Views must invoke this when the tooltip text they are to display changes.
1672 void TooltipTextChanged();
1674 // Drag and drop -------------------------------------------------------------
1676 // These are cover methods that invoke the method of the same name on
1677 // the DragController. Subclasses may wish to override rather than install
1678 // a DragController.
1679 // See DragController for a description of these methods.
1680 virtual int GetDragOperations(const gfx::Point& press_pt);
1681 virtual void WriteDragData(const gfx::Point& press_pt, OSExchangeData* data);
1683 // Returns whether we're in the middle of a drag session that was initiated
1685 bool InDrag() const;
1687 // Returns how much the mouse needs to move in one direction to start a
1688 // drag. These methods cache in a platform-appropriate way. These values are
1689 // used by the public static method ExceededDragThreshold().
1690 static int GetHorizontalDragThreshold();
1691 static int GetVerticalDragThreshold();
1693 // PropertyHandler -----------------------------------------------------------
1695 // Note: you MUST call this base method from derived classes that override it
1696 // or else your class will not properly register for ElementTrackerViews and
1697 // won't be available for interactive tests or in-product help/tutorials which
1699 void AfterPropertyChange(const void* key, int64_t old_value) override;
1701 // Property Support ----------------------------------------------------------
1703 void OnPropertyChanged(ui::metadata::PropertyKey property,
1704 PropertyEffects property_effects);
1707 friend class internal::PreEventDispatchHandler;
1708 friend class internal::PostEventDispatchHandler;
1709 friend class internal::RootView;
1710 friend class internal::ScopedChildrenLock;
1711 friend class FocusManager;
1712 friend class ViewDebugWrapperImpl;
1713 friend class ViewLayerTest;
1714 friend class ViewLayerPixelCanvasTest;
1715 friend class ViewTestApi;
1716 friend class Widget;
1717 FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithMovedViewUsesCache);
1718 FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithMovedViewUsesCacheInRTL);
1719 FRIEND_TEST_ALL_PREFIXES(ViewTest, PaintWithUnknownInvalidation);
1721 // This is the default view layout. It is a very simple version of FillLayout,
1722 // which merely sets the bounds of the children to the content bounds. The
1723 // actual FillLayout isn't used here because it supports a couple of features
1724 // not used in the vast majority of instances. It also descends from
1725 // LayoutManagerBase which adds some extra overhead not needed here.
1727 class DefaultFillLayout : public LayoutManager {
1729 DefaultFillLayout();
1730 ~DefaultFillLayout() override;
1731 void Layout(View* host) override;
1732 gfx::Size GetPreferredSize(const View* host) const override;
1733 int GetPreferredHeightForWidth(const View* host, int width) const override;
1736 // Painting -----------------------------------------------------------------
1738 // Responsible for propagating SchedulePaint() to the view's layer. If there
1739 // is no associated layer, the requested paint rect is propagated up the
1740 // view hierarchy by calling this function on the parent view. Rectangle |r|
1741 // is in the view's coordinate system. The transformations are applied to it
1742 // to convert it into the parent coordinate system before propagating
1743 // SchedulePaint() up the view hierarchy. This function should NOT be directly
1744 // called. Instead call SchedulePaint() or SchedulePaintInRect(), which will
1745 // call into this as necessary.
1746 void SchedulePaintInRectImpl(const gfx::Rect& r);
1748 // Invoked before and after the bounds change to schedule painting the old and
1750 void SchedulePaintBoundsChanged(bool size_changed);
1752 // Schedules a paint on the parent View if it exists.
1753 void SchedulePaintOnParent();
1755 // Returns whether this view is eligible for painting, i.e. is visible and
1756 // nonempty. Note that this does not behave like IsDrawn(), since it doesn't
1757 // check ancestors recursively; rather, it's used to prune subtrees of views
1759 bool ShouldPaint() const;
1761 // Adjusts the transform of |recorder| in advance of painting.
1762 void SetUpTransformRecorderForPainting(
1763 const gfx::Vector2d& offset_from_parent,
1764 ui::TransformRecorder* recorder) const;
1766 // Recursively calls the painting method |func| on all non-layered children,
1768 void RecursivePaintHelper(void (View::*func)(const PaintInfo&),
1769 const PaintInfo& info);
1771 // Invokes Paint() and, if necessary, PaintDebugRects(). Should be called
1772 // only on the root of a widget/layer. PaintDebugRects() is invoked as a
1773 // separate pass, instead of being rolled into Paint(), so that siblings will
1774 // not obscure debug rects.
1775 void PaintFromPaintRoot(const ui::PaintContext& parent_context);
1777 // Draws a semitransparent rect to indicate the bounds of this view.
1778 // Recursively does the same for all children. Invoked only with
1779 // --draw-view-bounds-rects.
1780 void PaintDebugRects(const PaintInfo& paint_info);
1782 // Tree operations -----------------------------------------------------------
1784 // Adds |view| as a child of this view at |index|.
1785 void AddChildViewAtImpl(View* view, size_t index);
1787 // Removes |view| from the hierarchy tree. If |update_tool_tip| is
1788 // true, the tooltip is updated. If |delete_removed_view| is true, the
1789 // view is also deleted (if it is parent owned). If |new_parent| is
1790 // not null, the remove is the result of AddChildView() to a new
1791 // parent. For this case, |new_parent| is the View that |view| is
1792 // going to be added to after the remove completes.
1793 void DoRemoveChildView(View* view,
1794 bool update_tool_tip,
1795 bool delete_removed_view,
1798 // Call ViewHierarchyChanged() for all child views and all parents.
1799 // |old_parent| is the original parent of the View that was removed.
1800 // If |new_parent| is not null, the View that was removed will be reparented
1801 // to |new_parent| after the remove operation.
1802 // If is_removed_from_widget is true, calls RemovedFromWidget for all
1804 void PropagateRemoveNotifications(View* old_parent,
1806 bool is_removed_from_widget);
1808 // Call ViewHierarchyChanged() for all children.
1809 // If is_added_to_widget is true, calls AddedToWidget for all children.
1810 void PropagateAddNotifications(const ViewHierarchyChangedDetails& details,
1811 bool is_added_to_widget);
1813 // Propagates NativeViewHierarchyChanged() notification through all the
1815 void PropagateNativeViewHierarchyChanged();
1817 // Calls ViewHierarchyChanged() and notifies observers.
1818 void ViewHierarchyChangedImpl(const ViewHierarchyChangedDetails& details);
1820 // Size and disposition ------------------------------------------------------
1822 // Call VisibilityChanged() recursively for all children.
1823 void PropagateVisibilityNotifications(View* from, bool is_visible);
1825 // Registers/unregisters accelerators as necessary and calls
1826 // VisibilityChanged().
1827 void VisibilityChangedImpl(View* starting_from, bool is_visible);
1829 // Visible bounds notification registration.
1830 // When a view is added to a hierarchy, it and all its children are asked if
1831 // they need to be registered for "visible bounds within root" notifications
1832 // (see comment on OnVisibleBoundsChanged()). If they do, they are registered
1833 // with every ancestor between them and the root of the hierarchy.
1834 static void RegisterChildrenForVisibleBoundsNotification(View* view);
1835 static void UnregisterChildrenForVisibleBoundsNotification(View* view);
1836 void RegisterForVisibleBoundsNotification();
1837 void UnregisterForVisibleBoundsNotification();
1839 // Adds/removes view to the list of descendants that are notified any time
1840 // this views location and possibly size are changed.
1841 void AddDescendantToNotify(View* view);
1842 void RemoveDescendantToNotify(View* view);
1844 // Non-templatized backend for SetLayoutManager().
1845 void SetLayoutManagerImpl(std::unique_ptr<LayoutManager> layout);
1847 // Transformations -----------------------------------------------------------
1849 // Returns in |transform| the transform to get from coordinates of |ancestor|
1850 // to this. Returns true if |ancestor| is found. If |ancestor| is not found,
1851 // or NULL, |transform| is set to convert from root view coordinates to this.
1852 bool GetTransformRelativeTo(const View* ancestor,
1853 gfx::Transform* transform) const;
1855 // Coordinate conversion -----------------------------------------------------
1857 // Convert a point in the view's coordinate to an ancestor view's coordinate
1858 // system using necessary transformations. Returns whether the point was
1859 // successfully converted to the ancestor's coordinate system.
1860 bool ConvertPointForAncestor(const View* ancestor, gfx::Point* point) const;
1862 // Convert a point in the ancestor's coordinate system to the view's
1863 // coordinate system using necessary transformations. Returns whether the
1864 // point was successfully converted from the ancestor's coordinate system
1865 // to the view's coordinate system.
1866 bool ConvertPointFromAncestor(const View* ancestor, gfx::Point* point) const;
1868 // Convert a rect in the view's coordinate to an ancestor view's coordinate
1869 // system using necessary transformations. Returns whether the rect was
1870 // successfully converted to the ancestor's coordinate system.
1871 bool ConvertRectForAncestor(const View* ancestor, gfx::RectF* rect) const;
1873 // Convert a rect in the ancestor's coordinate system to the view's
1874 // coordinate system using necessary transformations. Returns whether the
1875 // rect was successfully converted from the ancestor's coordinate system
1876 // to the view's coordinate system.
1877 bool ConvertRectFromAncestor(const View* ancestor, gfx::RectF* rect) const;
1879 // Accelerated painting ------------------------------------------------------
1881 // Creates the layer and related fields for this view.
1882 void CreateLayer(ui::LayerType layer_type);
1884 // Recursively calls UpdateParentLayers() on all descendants, stopping at any
1885 // Views that have layers. Calls UpdateParentLayer() for any Views that have
1886 // a layer with no parent. If at least one descendant had an unparented layer
1887 // true is returned.
1888 bool UpdateParentLayers();
1890 // Parents this view's layer to |parent_layer|, and sets its bounds and other
1891 // properties in accordance to the layer hierarchy.
1892 void ReparentLayer(ui::Layer* parent_layer);
1894 // Called to update the layer visibility. The layer will be visible if the
1895 // View itself, and all its parent Views are visible. This also updates
1896 // visibility of the child layers.
1897 void UpdateLayerVisibility();
1898 void UpdateChildLayerVisibility(bool visible);
1900 enum class LayerChangeNotifyBehavior {
1901 // Notify the parent chain about the layer change.
1903 // Don't notify the parent chain about the layer change.
1907 // Destroys the layer associated with this view, and reparents any descendants
1908 // to the destroyed layer's parent. If the view does not currently have a
1909 // layer, this has no effect.
1910 // The |notify_parents| enum controls whether a notification about the layer
1911 // change is sent to the parents.
1912 void DestroyLayerImpl(LayerChangeNotifyBehavior notify_parents);
1914 // Determines whether we need to be painting to a layer, checks whether we
1915 // currently have a layer, and creates or destroys the layer if necessary.
1916 void CreateOrDestroyLayer();
1918 // Notifies parents about layering changes in the view. This includes layer
1919 // creation and destruction.
1920 void NotifyParentsOfLayerChange();
1922 // Orphans the layers in this subtree that are parented to layers outside of
1924 void OrphanLayers();
1926 // Adjust the layer's offset so that it snaps to the physical pixel boundary.
1927 // This has no effect if the view does not have an associated layer.
1928 void SnapLayerToPixelBoundary(const LayerOffsetData& offset_data);
1930 // Sets the layer's bounds given in DIP coordinates.
1931 void SetLayerBounds(const gfx::Size& size_in_dip,
1932 const LayerOffsetData& layer_offset_data);
1934 // Creates a mask layer for the current view using |clip_path_|.
1935 void CreateMaskLayer();
1937 // Layout --------------------------------------------------------------------
1939 // Returns whether a layout is deferred to a layout manager, either the
1940 // default fill layout or the assigned layout manager.
1941 bool HasLayoutManager() const;
1943 // Input ---------------------------------------------------------------------
1945 bool ProcessMousePressed(const ui::MouseEvent& event);
1946 void ProcessMouseDragged(ui::MouseEvent* event);
1947 void ProcessMouseReleased(const ui::MouseEvent& event);
1949 // Accelerators --------------------------------------------------------------
1951 // Registers this view's keyboard accelerators that are not registered to
1952 // FocusManager yet, if possible.
1953 void RegisterPendingAccelerators();
1955 // Unregisters all the keyboard accelerators associated with this view.
1956 // |leave_data_intact| if true does not remove data from accelerators_ array,
1957 // so it could be re-registered with other focus manager
1958 void UnregisterAccelerators(bool leave_data_intact);
1960 // Focus ---------------------------------------------------------------------
1962 // Sets previous/next focusable views for both |view| and other children
1963 // assuming we've just inserted |view| at |pos|.
1964 void SetFocusSiblings(View* view, Views::const_iterator pos);
1966 // Helper function to advance focus, in case the currently focused view has
1967 // become unfocusable.
1968 void AdvanceFocusIfNecessary();
1970 // System events -------------------------------------------------------------
1972 // Used to propagate UI theme changed or NativeTheme changed notifications
1973 // from the root view to all views in the hierarchy.
1974 void PropagateThemeChanged();
1976 // Used to propagate device scale factor changed notifications from the root
1977 // view to all views in the hierarchy.
1978 void PropagateDeviceScaleFactorChanged(float old_device_scale_factor,
1979 float new_device_scale_factor);
1981 // Tooltips ------------------------------------------------------------------
1983 // Propagates UpdateTooltip() to the TooltipManager for the Widget.
1984 // This must be invoked any time the View hierarchy changes in such a way
1985 // the view under the mouse differs. For example, if the bounds of a View is
1986 // changed, this is invoked. Similarly, as Views are added/removed, this
1988 void UpdateTooltip();
1990 // Drag and drop -------------------------------------------------------------
1992 // Starts a drag and drop operation originating from this view. This invokes
1993 // WriteDragData to write the data and GetDragOperations to determine the
1994 // supported drag operations. When done, OnDragDone is invoked. |press_pt| is
1995 // in the view's coordinate system.
1996 // Returns true if a drag was started.
1997 bool DoDrag(const ui::LocatedEvent& event,
1998 const gfx::Point& press_pt,
1999 ui::mojom::DragEventSource source);
2001 // Property support ----------------------------------------------------------
2003 // Called from OnPropertyChanged with the given set of property effects. This
2004 // function is NOT called if effects == kPropertyEffectsNone.
2005 void HandlePropertyChangeEffects(PropertyEffects effects);
2007 // The following methods are used by the property access system described in
2008 // the comments above. They follow the required naming convention in order to
2009 // allow them to be visible via the metadata.
2012 int GetWidth() const;
2013 int GetHeight() const;
2014 void SetWidth(int width);
2015 void SetHeight(int height);
2016 bool GetIsDrawn() const;
2018 // Special property accessor used by metadata to get the ToolTip text.
2019 std::u16string GetTooltip() const;
2021 //////////////////////////////////////////////////////////////////////////////
2023 // Creation and lifetime -----------------------------------------------------
2025 // False if this View is owned by its parent - i.e. it will be deleted by its
2026 // parent during its parents destruction. False is the default.
2027 bool owned_by_client_ = false;
2029 // Attributes ----------------------------------------------------------------
2031 // The id of this View. Used to find this View.
2034 // The group of this view. Some view subclasses use this id to find other
2035 // views of the same group. For example radio button uses this information
2036 // to find other radio buttons.
2039 // Tree operations -----------------------------------------------------------
2041 // This view's parent.
2042 raw_ptr<View> parent_ = nullptr;
2044 // This view's children.
2048 // True while iterating over |children_|. Used to detect and DCHECK when
2049 // |children_| is mutated during iteration.
2050 mutable bool iterating_ = false;
2053 bool can_process_events_within_subtree_ = true;
2055 // Size and disposition ------------------------------------------------------
2057 absl::optional<gfx::Size> preferred_size_;
2059 // This View's bounds in the parent coordinate system.
2062 // Whether this view is visible.
2063 bool visible_ = true;
2065 // Whether this view is enabled.
2066 bool enabled_ = true;
2068 // When this flag is on, a View receives a mouse-enter and mouse-leave event
2069 // even if a descendant View is the event-recipient for the real mouse
2070 // events. When this flag is turned on, and mouse moves from outside of the
2071 // view into a child view, both the child view and this view receives
2072 // mouse-enter event. Similarly, if the mouse moves from inside a child view
2073 // and out of this view, then both views receive a mouse-leave event.
2074 // When this flag is turned off, if the mouse moves from inside this view into
2075 // a child view, then this view receives a mouse-leave event. When this flag
2076 // is turned on, it does not receive the mouse-leave event in this case.
2077 // When the mouse moves from inside the child view out of the child view but
2078 // still into this view, this view receives a mouse-enter event if this flag
2079 // is turned off, but doesn't if this flag is turned on.
2080 // This flag is initialized to false.
2081 bool notify_enter_exit_on_child_ = false;
2083 // Whether or not RegisterViewForVisibleBoundsNotification on the RootView
2084 // has been invoked.
2085 bool registered_for_visible_bounds_notification_ = false;
2087 // List of descendants wanting notification when their visible bounds change.
2088 std::unique_ptr<Views> descendants_to_notify_;
2090 // Transformations -----------------------------------------------------------
2092 // Painting will be clipped to this path.
2095 // Layout --------------------------------------------------------------------
2097 // Whether the view needs to be laid out.
2098 bool needs_layout_ = true;
2100 // The View's LayoutManager defines the sizing heuristics applied to child
2101 // Views. The default is absolute positioning according to bounds_.
2102 std::unique_ptr<LayoutManager> layout_manager_;
2104 // The default "fill" layout manager. This is set only if |layout_manager_|
2105 // isn't set and SetUseDefaultFillLayout(true) is called or
2106 // |kUseDefaultFillLayout| is true.
2107 absl::optional<DefaultFillLayout> default_fill_layout_;
2109 // Whether this View's layer should be snapped to the pixel boundary.
2110 bool snap_layer_to_pixel_boundary_ = false;
2112 // Painting ------------------------------------------------------------------
2115 std::unique_ptr<Border> border_;
2117 // Background may rely on Border, so it must be declared last and destroyed
2119 std::unique_ptr<Background> background_;
2121 // Cached output of painting to be reused in future frames until invalidated.
2122 ui::PaintCache paint_cache_;
2124 // Whether SchedulePaintInRect() was invoked on this View.
2125 bool needs_paint_ = false;
2127 // Native theme --------------------------------------------------------------
2129 // A native theme for this view and its descendants. Typically null, in which
2130 // case the native theme is drawn from the parent view (eventually the
2132 raw_ptr<ui::NativeTheme> native_theme_ = nullptr;
2134 // RTL painting --------------------------------------------------------------
2136 // Indicates whether or not the gfx::Canvas object passed to Paint() is going
2137 // to be flipped horizontally (using the appropriate transform) on
2138 // right-to-left locales for this View.
2139 bool flip_canvas_on_paint_for_rtl_ui_ = false;
2141 // Controls whether GetTransform(), the mirroring functions, and the like
2142 // horizontally mirror. This controls how child views are physically
2143 // positioned onscreen. The default behavior should be correct in most cases,
2144 // but can be overridden if a particular view must always be laid out in some
2145 // direction regardless of the application's default UI direction.
2146 absl::optional<bool> is_mirrored_;
2148 // Accelerated painting ------------------------------------------------------
2150 // Whether layer painting was explicitly set by a call to |SetPaintToLayer()|.
2151 bool paint_to_layer_explicitly_set_ = false;
2153 // Whether we are painting to a layer because of a non-identity transform.
2154 bool paint_to_layer_for_transform_ = false;
2156 // Set of layers that should be painted beneath this View's layer. These
2157 // layers are maintained as siblings of this View's layer and are stacked
2159 std::vector<ui::Layer*> layers_beneath_;
2161 // If painting to a layer |mask_layer_| will mask the current layer and all
2162 // child layers to within the |clip_path_|.
2163 std::unique_ptr<views::ViewMaskLayer> mask_layer_;
2165 // Accelerators --------------------------------------------------------------
2167 // Focus manager accelerators registered on.
2168 raw_ptr<FocusManager> accelerator_focus_manager_ = nullptr;
2170 // The list of accelerators. List elements in the range
2171 // [0, registered_accelerator_count_) are already registered to FocusManager,
2172 // and the rest are not yet.
2173 std::unique_ptr<std::vector<ui::Accelerator>> accelerators_;
2174 size_t registered_accelerator_count_ = 0;
2176 // Focus ---------------------------------------------------------------------
2178 // Next view to be focused when the Tab key is pressed.
2179 raw_ptr<View> next_focusable_view_ = nullptr;
2181 // Next view to be focused when the Shift-Tab key combination is pressed.
2182 raw_ptr<View> previous_focusable_view_ = nullptr;
2184 // The focus behavior of the view in regular and accessibility mode.
2185 FocusBehavior focus_behavior_ = FocusBehavior::NEVER;
2187 // This is set when focus events should be skipped after focus reaches this
2189 bool suppress_default_focus_handling_ = false;
2191 // Context menus -------------------------------------------------------------
2193 // The menu controller.
2194 raw_ptr<ContextMenuController> context_menu_controller_ = nullptr;
2196 // Drag and drop -------------------------------------------------------------
2198 raw_ptr<DragController> drag_controller_ = nullptr;
2200 // Input --------------------------------------------------------------------
2202 std::unique_ptr<ViewTargeter> targeter_;
2204 // System events -------------------------------------------------------------
2207 bool on_theme_changed_called_ = false;
2210 // Accessibility -------------------------------------------------------------
2212 // Manages the accessibility interface for this View.
2213 mutable std::unique_ptr<ViewAccessibility> view_accessibility_;
2215 // Keeps track of whether accessibility checks for this View have run yet.
2216 // They run once inside ::OnPaint() to keep overhead low. The idea is that if
2217 // a View is ready to paint it should also be set up to be accessible.
2218 bool has_run_accessibility_paint_checks_ = false;
2220 // Observers -----------------------------------------------------------------
2222 base::ObserverList<ViewObserver>::Unchecked observers_;
2224 // http://crbug.com/1162949 : Instrumentation that indicates if this is alive.
2225 LifeCycleState life_cycle_state_ = LifeCycleState::kAlive;
2228 BEGIN_VIEW_BUILDER(VIEWS_EXPORT, View, BaseView)
2229 template <typename LayoutManager>
2230 BuilderT& SetLayoutManager(std::unique_ptr<LayoutManager> layout_manager) & {
2231 auto setter = std::make_unique<::views::internal::PropertySetter<
2232 ViewClass_, std::unique_ptr<LayoutManager>,
2233 decltype((static_cast<LayoutManager* (
2234 ViewClass_::*)(std::unique_ptr<LayoutManager>)>(
2235 &ViewClass_::SetLayoutManager))),
2236 &ViewClass_::SetLayoutManager>>(std::move(layout_manager));
2237 ::views::internal::ViewBuilderCore::AddPropertySetter(std::move(setter));
2238 return *static_cast<BuilderT*>(this);
2240 template <typename LayoutManager>
2241 BuilderT&& SetLayoutManager(std::unique_ptr<LayoutManager> layout_manager) && {
2242 return std::move(this->SetLayoutManager(std::move(layout_manager)));
2244 VIEW_BUILDER_PROPERTY(std::unique_ptr<Background>, Background)
2245 VIEW_BUILDER_PROPERTY(std::unique_ptr<Border>, Border)
2246 VIEW_BUILDER_PROPERTY(gfx::Rect, BoundsRect)
2247 VIEW_BUILDER_PROPERTY(gfx::Size, Size)
2248 VIEW_BUILDER_PROPERTY(gfx::Point, Position)
2249 VIEW_BUILDER_PROPERTY(int, X)
2250 VIEW_BUILDER_PROPERTY(int, Y)
2251 VIEW_BUILDER_PROPERTY(gfx::Size, PreferredSize)
2252 VIEW_BUILDER_PROPERTY(SkPath, ClipPath)
2253 VIEW_BUILDER_PROPERTY_DEFAULT(ui::LayerType, PaintToLayer, ui::LAYER_TEXTURED)
2254 VIEW_BUILDER_PROPERTY(bool, Enabled)
2255 VIEW_BUILDER_PROPERTY(bool, FlipCanvasOnPaintForRTLUI)
2256 VIEW_BUILDER_PROPERTY(views::View::FocusBehavior, FocusBehavior)
2257 VIEW_BUILDER_PROPERTY(int, Group)
2258 VIEW_BUILDER_PROPERTY(int, ID)
2259 VIEW_BUILDER_PROPERTY(bool, Mirrored)
2260 VIEW_BUILDER_PROPERTY(bool, NotifyEnterExitOnChild)
2261 VIEW_BUILDER_PROPERTY(gfx::Transform, Transform)
2262 VIEW_BUILDER_PROPERTY(bool, Visible)
2263 VIEW_BUILDER_PROPERTY(bool, CanProcessEventsWithinSubtree)
2264 VIEW_BUILDER_PROPERTY(bool, UseDefaultFillLayout)
2267 } // namespace views
2269 DEFINE_VIEW_BUILDER(VIEWS_EXPORT, View)
2271 #endif // UI_VIEWS_VIEW_H_