1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #define _USE_MATH_DEFINES // For VC++ to get M_PI. This has to be first.
7 #include "ui/views/view.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/trace_event/trace_event.h"
18 #include "third_party/skia/include/core/SkRect.h"
19 #include "ui/accessibility/ax_enums.h"
20 #include "ui/base/cursor/cursor.h"
21 #include "ui/base/dragdrop/drag_drop_types.h"
22 #include "ui/base/ime/input_method.h"
23 #include "ui/compositor/clip_transform_recorder.h"
24 #include "ui/compositor/compositor.h"
25 #include "ui/compositor/dip_util.h"
26 #include "ui/compositor/layer.h"
27 #include "ui/compositor/layer_animator.h"
28 #include "ui/compositor/paint_context.h"
29 #include "ui/compositor/paint_recorder.h"
30 #include "ui/events/event_target_iterator.h"
31 #include "ui/gfx/canvas.h"
32 #include "ui/gfx/geometry/point3_f.h"
33 #include "ui/gfx/geometry/point_conversions.h"
34 #include "ui/gfx/interpolated_transform.h"
35 #include "ui/gfx/path.h"
36 #include "ui/gfx/scoped_canvas.h"
37 #include "ui/gfx/screen.h"
38 #include "ui/gfx/skia_util.h"
39 #include "ui/gfx/transform.h"
40 #include "ui/native_theme/native_theme.h"
41 #include "ui/views/accessibility/native_view_accessibility.h"
42 #include "ui/views/background.h"
43 #include "ui/views/border.h"
44 #include "ui/views/context_menu_controller.h"
45 #include "ui/views/drag_controller.h"
46 #include "ui/views/focus/view_storage.h"
47 #include "ui/views/layout/layout_manager.h"
48 #include "ui/views/views_delegate.h"
49 #include "ui/views/widget/native_widget_private.h"
50 #include "ui/views/widget/root_view.h"
51 #include "ui/views/widget/tooltip_manager.h"
52 #include "ui/views/widget/widget.h"
55 #include "base/win/scoped_gdi_object.h"
63 const bool kContextMenuOnMousePress
= false;
65 const bool kContextMenuOnMousePress
= true;
68 // Default horizontal drag threshold in pixels.
69 // Same as what gtk uses.
70 const int kDefaultHorizontalDragThreshold
= 8;
72 // Default vertical drag threshold in pixels.
73 // Same as what gtk uses.
74 const int kDefaultVerticalDragThreshold
= 8;
76 // Returns the top view in |view|'s hierarchy.
77 const View
* GetHierarchyRoot(const View
* view
) {
78 const View
* root
= view
;
79 while (root
&& root
->parent())
80 root
= root
->parent();
87 const char View::kViewClassName
[] = "View";
89 ////////////////////////////////////////////////////////////////////////////////
92 // Creation and lifetime -------------------------------------------------------
95 : owned_by_client_(false),
101 notify_enter_exit_on_child_(false),
102 registered_for_visible_bounds_notification_(false),
103 clip_insets_(0, 0, 0, 0),
105 snap_layer_to_pixel_boundary_(false),
106 flip_canvas_on_paint_for_rtl_ui_(false),
107 paint_to_layer_(false),
108 accelerator_focus_manager_(NULL
),
109 registered_accelerator_count_(0),
110 next_focusable_view_(NULL
),
111 previous_focusable_view_(NULL
),
113 accessibility_focusable_(false),
114 context_menu_controller_(NULL
),
115 drag_controller_(NULL
),
116 native_view_accessibility_(NULL
) {
121 parent_
->RemoveChildView(this);
123 ViewStorage::GetInstance()->ViewRemoved(this);
125 for (Views::const_iterator
i(children_
.begin()); i
!= children_
.end(); ++i
) {
126 (*i
)->parent_
= NULL
;
127 if (!(*i
)->owned_by_client_
)
131 // Release ownership of the native accessibility object, but it's
132 // reference-counted on some platforms, so it may not be deleted right away.
133 if (native_view_accessibility_
)
134 native_view_accessibility_
->Destroy();
137 // Tree operations -------------------------------------------------------------
139 const Widget
* View::GetWidget() const {
140 // The root view holds a reference to this view hierarchy's Widget.
141 return parent_
? parent_
->GetWidget() : NULL
;
144 Widget
* View::GetWidget() {
145 return const_cast<Widget
*>(const_cast<const View
*>(this)->GetWidget());
148 void View::AddChildView(View
* view
) {
149 if (view
->parent_
== this)
151 AddChildViewAt(view
, child_count());
154 void View::AddChildViewAt(View
* view
, int index
) {
155 CHECK_NE(view
, this) << "You cannot add a view as its own child";
157 DCHECK_LE(index
, child_count());
159 // If |view| has a parent, remove it from its parent.
160 View
* parent
= view
->parent_
;
161 ui::NativeTheme
* old_theme
= NULL
;
163 old_theme
= view
->GetNativeTheme();
164 if (parent
== this) {
165 ReorderChildView(view
, index
);
168 parent
->DoRemoveChildView(view
, true, true, false, this);
171 // Sets the prev/next focus views.
172 InitFocusSiblings(view
, index
);
174 // Let's insert the view.
175 view
->parent_
= this;
176 children_
.insert(children_
.begin() + index
, view
);
178 views::Widget
* widget
= GetWidget();
180 const ui::NativeTheme
* new_theme
= view
->GetNativeTheme();
181 if (new_theme
!= old_theme
)
182 view
->PropagateNativeThemeChanged(new_theme
);
185 ViewHierarchyChangedDetails
details(true, this, view
, parent
);
187 for (View
* v
= this; v
; v
= v
->parent_
)
188 v
->ViewHierarchyChangedImpl(false, details
);
190 view
->PropagateAddNotifications(details
);
193 RegisterChildrenForVisibleBoundsNotification(view
);
195 view
->SchedulePaint();
198 if (layout_manager_
.get())
199 layout_manager_
->ViewAdded(this, view
);
203 // Make sure the visibility of the child layers are correct.
204 // If any of the parent View is hidden, then the layers of the subtree
205 // rooted at |this| should be hidden. Otherwise, all the child layers should
206 // inherit the visibility of the owner View.
207 UpdateLayerVisibility();
210 void View::ReorderChildView(View
* view
, int index
) {
211 DCHECK_EQ(view
->parent_
, this);
213 index
= child_count() - 1;
214 else if (index
>= child_count())
216 if (children_
[index
] == view
)
219 const Views::iterator
i(std::find(children_
.begin(), children_
.end(), view
));
220 DCHECK(i
!= children_
.end());
223 // Unlink the view first
224 View
* next_focusable
= view
->next_focusable_view_
;
225 View
* prev_focusable
= view
->previous_focusable_view_
;
227 prev_focusable
->next_focusable_view_
= next_focusable
;
229 next_focusable
->previous_focusable_view_
= prev_focusable
;
231 // Add it in the specified index now.
232 InitFocusSiblings(view
, index
);
233 children_
.insert(children_
.begin() + index
, view
);
238 void View::RemoveChildView(View
* view
) {
239 DoRemoveChildView(view
, true, true, false, NULL
);
242 void View::RemoveAllChildViews(bool delete_children
) {
243 while (!children_
.empty())
244 DoRemoveChildView(children_
.front(), false, false, delete_children
, NULL
);
248 bool View::Contains(const View
* view
) const {
249 for (const View
* v
= view
; v
; v
= v
->parent_
) {
256 int View::GetIndexOf(const View
* view
) const {
257 Views::const_iterator
i(std::find(children_
.begin(), children_
.end(), view
));
258 return i
!= children_
.end() ? static_cast<int>(i
- children_
.begin()) : -1;
261 // Size and disposition --------------------------------------------------------
263 void View::SetBounds(int x
, int y
, int width
, int height
) {
264 SetBoundsRect(gfx::Rect(x
, y
, std::max(0, width
), std::max(0, height
)));
267 void View::SetBoundsRect(const gfx::Rect
& bounds
) {
268 if (bounds
== bounds_
) {
270 needs_layout_
= false;
277 // Paint where the view is currently.
278 SchedulePaintBoundsChanged(
279 bounds_
.size() == bounds
.size() ? SCHEDULE_PAINT_SIZE_SAME
:
280 SCHEDULE_PAINT_SIZE_CHANGED
);
283 gfx::Rect prev
= bounds_
;
288 void View::SetSize(const gfx::Size
& size
) {
289 SetBounds(x(), y(), size
.width(), size
.height());
292 void View::SetPosition(const gfx::Point
& position
) {
293 SetBounds(position
.x(), position
.y(), width(), height());
296 void View::SetX(int x
) {
297 SetBounds(x
, y(), width(), height());
300 void View::SetY(int y
) {
301 SetBounds(x(), y
, width(), height());
304 gfx::Rect
View::GetContentsBounds() const {
305 gfx::Rect
contents_bounds(GetLocalBounds());
307 contents_bounds
.Inset(border_
->GetInsets());
308 return contents_bounds
;
311 gfx::Rect
View::GetLocalBounds() const {
312 return gfx::Rect(size());
315 gfx::Rect
View::GetLayerBoundsInPixel() const {
316 return layer()->GetTargetBounds();
319 gfx::Insets
View::GetInsets() const {
320 return border_
.get() ? border_
->GetInsets() : gfx::Insets();
323 gfx::Rect
View::GetVisibleBounds() const {
326 gfx::Rect
vis_bounds(GetLocalBounds());
327 gfx::Rect ancestor_bounds
;
328 const View
* view
= this;
329 gfx::Transform transform
;
331 while (view
!= NULL
&& !vis_bounds
.IsEmpty()) {
332 transform
.ConcatTransform(view
->GetTransform());
333 gfx::Transform translation
;
334 translation
.Translate(static_cast<float>(view
->GetMirroredX()),
335 static_cast<float>(view
->y()));
336 transform
.ConcatTransform(translation
);
338 vis_bounds
= view
->ConvertRectToParent(vis_bounds
);
339 const View
* ancestor
= view
->parent_
;
340 if (ancestor
!= NULL
) {
341 ancestor_bounds
.SetRect(0, 0, ancestor
->width(), ancestor
->height());
342 vis_bounds
.Intersect(ancestor_bounds
);
343 } else if (!view
->GetWidget()) {
344 // If the view has no Widget, we're not visible. Return an empty rect.
349 if (vis_bounds
.IsEmpty())
351 // Convert back to this views coordinate system.
352 gfx::RectF
views_vis_bounds(vis_bounds
);
353 transform
.TransformRectReverse(&views_vis_bounds
);
354 // Partially visible pixels should be considered visible.
355 return gfx::ToEnclosingRect(views_vis_bounds
);
358 gfx::Rect
View::GetBoundsInScreen() const {
360 View::ConvertPointToScreen(this, &origin
);
361 return gfx::Rect(origin
, size());
364 gfx::Size
View::GetPreferredSize() const {
365 if (layout_manager_
.get())
366 return layout_manager_
->GetPreferredSize(this);
370 int View::GetBaseline() const {
374 void View::SizeToPreferredSize() {
375 gfx::Size prefsize
= GetPreferredSize();
376 if ((prefsize
.width() != width()) || (prefsize
.height() != height()))
377 SetBounds(x(), y(), prefsize
.width(), prefsize
.height());
380 gfx::Size
View::GetMinimumSize() const {
381 return GetPreferredSize();
384 gfx::Size
View::GetMaximumSize() const {
388 int View::GetHeightForWidth(int w
) const {
389 if (layout_manager_
.get())
390 return layout_manager_
->GetPreferredHeightForWidth(this, w
);
391 return GetPreferredSize().height();
394 void View::SetVisible(bool visible
) {
395 if (visible
!= visible_
) {
396 // If the View is currently visible, schedule paint to refresh parent.
397 // TODO(beng): not sure we should be doing this if we have a layer.
402 AdvanceFocusIfNecessary();
404 // Notify the parent.
406 parent_
->ChildVisibilityChanged(this);
408 // This notifies all sub-views recursively.
409 PropagateVisibilityNotifications(this, visible_
);
410 UpdateLayerVisibility();
412 // If we are newly visible, schedule paint.
418 bool View::IsDrawn() const {
419 return visible_
&& parent_
? parent_
->IsDrawn() : false;
422 void View::SetEnabled(bool enabled
) {
423 if (enabled
!= enabled_
) {
425 AdvanceFocusIfNecessary();
430 void View::OnEnabledChanged() {
434 // Transformations -------------------------------------------------------------
436 gfx::Transform
View::GetTransform() const {
437 return layer() ? layer()->transform() : gfx::Transform();
440 void View::SetTransform(const gfx::Transform
& transform
) {
441 if (transform
.IsIdentity()) {
443 layer()->SetTransform(transform
);
444 if (!paint_to_layer_
)
452 layer()->SetTransform(transform
);
453 layer()->ScheduleDraw();
457 void View::SetPaintToLayer(bool paint_to_layer
) {
458 if (paint_to_layer_
== paint_to_layer
)
461 paint_to_layer_
= paint_to_layer
;
462 if (paint_to_layer_
&& !layer()) {
464 } else if (!paint_to_layer_
&& layer()) {
469 // RTL positioning -------------------------------------------------------------
471 gfx::Rect
View::GetMirroredBounds() const {
472 gfx::Rect
bounds(bounds_
);
473 bounds
.set_x(GetMirroredX());
477 gfx::Point
View::GetMirroredPosition() const {
478 return gfx::Point(GetMirroredX(), y());
481 int View::GetMirroredX() const {
482 return parent_
? parent_
->GetMirroredXForRect(bounds_
) : x();
485 int View::GetMirroredXForRect(const gfx::Rect
& bounds
) const {
486 return base::i18n::IsRTL() ?
487 (width() - bounds
.x() - bounds
.width()) : bounds
.x();
490 int View::GetMirroredXInView(int x
) const {
491 return base::i18n::IsRTL() ? width() - x
: x
;
494 int View::GetMirroredXWithWidthInView(int x
, int w
) const {
495 return base::i18n::IsRTL() ? width() - x
- w
: x
;
498 // Layout ----------------------------------------------------------------------
500 void View::Layout() {
501 needs_layout_
= false;
503 // If we have a layout manager, let it handle the layout for us.
504 if (layout_manager_
.get())
505 layout_manager_
->Layout(this);
507 // Make sure to propagate the Layout() call to any children that haven't
508 // received it yet through the layout manager and need to be laid out. This
509 // is needed for the case when the child requires a layout but its bounds
510 // weren't changed by the layout manager. If there is no layout manager, we
511 // just propagate the Layout() call down the hierarchy, so whoever receives
512 // the call can take appropriate action.
513 for (int i
= 0, count
= child_count(); i
< count
; ++i
) {
514 View
* child
= child_at(i
);
515 if (child
->needs_layout_
|| !layout_manager_
.get()) {
516 TRACE_EVENT1("views", "View::Layout", "class", child
->GetClassName());
517 child
->needs_layout_
= false;
523 void View::InvalidateLayout() {
524 // Always invalidate up. This is needed to handle the case of us already being
525 // valid, but not our parent.
526 needs_layout_
= true;
528 parent_
->InvalidateLayout();
531 LayoutManager
* View::GetLayoutManager() const {
532 return layout_manager_
.get();
535 void View::SetLayoutManager(LayoutManager
* layout_manager
) {
536 if (layout_manager_
.get())
537 layout_manager_
->Uninstalled(this);
539 layout_manager_
.reset(layout_manager
);
540 if (layout_manager_
.get())
541 layout_manager_
->Installed(this);
544 void View::SnapLayerToPixelBoundary() {
548 if (snap_layer_to_pixel_boundary_
&& layer()->parent() &&
549 layer()->GetCompositor()) {
550 ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer());
553 layer()->SetSubpixelPositionOffset(gfx::Vector2dF());
557 // Attributes ------------------------------------------------------------------
559 const char* View::GetClassName() const {
560 return kViewClassName
;
563 const View
* View::GetAncestorWithClassName(const std::string
& name
) const {
564 for (const View
* view
= this; view
; view
= view
->parent_
) {
565 if (!strcmp(view
->GetClassName(), name
.c_str()))
571 View
* View::GetAncestorWithClassName(const std::string
& name
) {
572 return const_cast<View
*>(const_cast<const View
*>(this)->
573 GetAncestorWithClassName(name
));
576 const View
* View::GetViewByID(int id
) const {
578 return const_cast<View
*>(this);
580 for (int i
= 0, count
= child_count(); i
< count
; ++i
) {
581 const View
* view
= child_at(i
)->GetViewByID(id
);
588 View
* View::GetViewByID(int id
) {
589 return const_cast<View
*>(const_cast<const View
*>(this)->GetViewByID(id
));
592 void View::SetGroup(int gid
) {
593 // Don't change the group id once it's set.
594 DCHECK(group_
== -1 || group_
== gid
);
598 int View::GetGroup() const {
602 bool View::IsGroupFocusTraversable() const {
606 void View::GetViewsInGroup(int group
, Views
* views
) {
608 views
->push_back(this);
610 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
611 child_at(i
)->GetViewsInGroup(group
, views
);
614 View
* View::GetSelectedViewForGroup(int group
) {
616 GetWidget()->GetRootView()->GetViewsInGroup(group
, &views
);
617 return views
.empty() ? NULL
: views
[0];
620 // Coordinate conversion -------------------------------------------------------
623 void View::ConvertPointToTarget(const View
* source
,
628 if (source
== target
)
631 const View
* root
= GetHierarchyRoot(target
);
632 CHECK_EQ(GetHierarchyRoot(source
), root
);
635 source
->ConvertPointForAncestor(root
, point
);
638 target
->ConvertPointFromAncestor(root
, point
);
642 void View::ConvertRectToTarget(const View
* source
,
647 if (source
== target
)
650 const View
* root
= GetHierarchyRoot(target
);
651 CHECK_EQ(GetHierarchyRoot(source
), root
);
654 source
->ConvertRectForAncestor(root
, rect
);
657 target
->ConvertRectFromAncestor(root
, rect
);
661 void View::ConvertPointToWidget(const View
* src
, gfx::Point
* p
) {
665 src
->ConvertPointForAncestor(NULL
, p
);
669 void View::ConvertPointFromWidget(const View
* dest
, gfx::Point
* p
) {
673 dest
->ConvertPointFromAncestor(NULL
, p
);
677 void View::ConvertPointToScreen(const View
* src
, gfx::Point
* p
) {
681 // If the view is not connected to a tree, there's nothing we can do.
682 const Widget
* widget
= src
->GetWidget();
684 ConvertPointToWidget(src
, p
);
685 *p
+= widget
->GetClientAreaBoundsInScreen().OffsetFromOrigin();
690 void View::ConvertPointFromScreen(const View
* dst
, gfx::Point
* p
) {
694 const views::Widget
* widget
= dst
->GetWidget();
697 *p
-= widget
->GetClientAreaBoundsInScreen().OffsetFromOrigin();
698 views::View::ConvertPointFromWidget(dst
, p
);
701 gfx::Rect
View::ConvertRectToParent(const gfx::Rect
& rect
) const {
702 gfx::RectF x_rect
= gfx::RectF(rect
);
703 GetTransform().TransformRect(&x_rect
);
704 x_rect
.Offset(GetMirroredPosition().OffsetFromOrigin());
705 // Pixels we partially occupy in the parent should be included.
706 return gfx::ToEnclosingRect(x_rect
);
709 gfx::Rect
View::ConvertRectToWidget(const gfx::Rect
& rect
) const {
710 gfx::Rect x_rect
= rect
;
711 for (const View
* v
= this; v
; v
= v
->parent_
)
712 x_rect
= v
->ConvertRectToParent(x_rect
);
716 // Painting --------------------------------------------------------------------
718 void View::SchedulePaint() {
719 SchedulePaintInRect(GetLocalBounds());
722 void View::SchedulePaintInRect(const gfx::Rect
& rect
) {
727 layer()->SchedulePaint(rect
);
728 } else if (parent_
) {
729 // Translate the requested paint rect to the parent's coordinate system
730 // then pass this notification up to the parent.
731 parent_
->SchedulePaintInRect(ConvertRectToParent(rect
));
735 void View::Paint(const ui::PaintContext
& parent_context
) {
738 if (size().IsEmpty())
741 gfx::Vector2d offset_to_parent
;
743 // If the View has a layer() then it is a paint root. Otherwise, we need to
744 // add the offset from the parent into the total offset from the paint root.
745 DCHECK_IMPLIES(!parent(), bounds().origin() == gfx::Point());
746 offset_to_parent
= GetMirroredPosition().OffsetFromOrigin();
748 ui::PaintContext
context(parent_context
, offset_to_parent
);
750 bool is_invalidated
= true;
751 if (context
.CanCheckInvalid()) {
753 gfx::Vector2d offset
;
754 context
.Visited(this);
756 while (view
->parent() && !view
->layer()) {
757 DCHECK(view
->GetTransform().IsIdentity());
758 offset
+= view
->GetMirroredPosition().OffsetFromOrigin();
759 view
= view
->parent();
761 // The offset in the PaintContext should be the offset up to the paint root,
762 // which we compute and verify here.
763 DCHECK_EQ(context
.PaintOffset().x(), offset
.x());
764 DCHECK_EQ(context
.PaintOffset().y(), offset
.y());
765 // The above loop will stop when |view| is the paint root, which should be
766 // the root of the current paint walk, as verified by storing the root in
768 DCHECK_EQ(context
.RootVisited(), view
);
771 // If the View wasn't invalidated, don't waste time painting it, the output
773 is_invalidated
= context
.IsRectInvalid(GetLocalBounds());
776 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
778 // If the view is backed by a layer, it should paint with itself as the origin
779 // rather than relative to its parent.
780 ui::ClipTransformRecorder
clip_transform_recorder(context
);
782 // Set the clip rect to the bounds of this View. Note that the X (or left)
783 // position we pass to ClipRect takes into consideration whether or not the
784 // View uses a right-to-left layout so that we paint the View in its
785 // mirrored position if need be.
786 gfx::Rect clip_rect_in_parent
= bounds();
787 clip_rect_in_parent
.Inset(clip_insets_
);
789 clip_rect_in_parent
.set_x(
790 parent_
->GetMirroredXForRect(clip_rect_in_parent
));
791 clip_transform_recorder
.ClipRect(clip_rect_in_parent
);
793 // Translate the graphics such that 0,0 corresponds to where
794 // this View is located relative to its parent.
795 gfx::Transform transform_from_parent
;
796 gfx::Vector2d offset_from_parent
= GetMirroredPosition().OffsetFromOrigin();
797 transform_from_parent
.Translate(offset_from_parent
.x(),
798 offset_from_parent
.y());
799 transform_from_parent
.PreconcatTransform(GetTransform());
800 clip_transform_recorder
.Transform(transform_from_parent
);
803 if (is_invalidated
|| !paint_cache_
.UseCache(context
)) {
804 ui::PaintRecorder
recorder(context
, size(), &paint_cache_
);
805 gfx::Canvas
* canvas
= recorder
.canvas();
807 // If the View we are about to paint requested the canvas to be flipped, we
808 // should change the transform appropriately.
809 // The canvas mirroring is undone once the View is done painting so that we
810 // don't pass the canvas with the mirrored transform to Views that didn't
811 // request the canvas to be flipped.
812 if (FlipCanvasOnPaintForRTLUI()) {
813 canvas
->Translate(gfx::Vector2d(width(), 0));
814 canvas
->Scale(-1, 1);
817 // Delegate painting the contents of the View to the virtual OnPaint method.
821 // View::Paint() recursion over the subtree.
822 PaintChildren(context
);
825 void View::set_background(Background
* b
) {
826 background_
.reset(b
);
829 void View::SetBorder(scoped_ptr
<Border
> b
) { border_
= b
.Pass(); }
831 ui::ThemeProvider
* View::GetThemeProvider() const {
832 const Widget
* widget
= GetWidget();
833 return widget
? widget
->GetThemeProvider() : NULL
;
836 const ui::NativeTheme
* View::GetNativeTheme() const {
837 const Widget
* widget
= GetWidget();
838 return widget
? widget
->GetNativeTheme() : ui::NativeTheme::instance();
841 // Input -----------------------------------------------------------------------
843 View
* View::GetEventHandlerForPoint(const gfx::Point
& point
) {
844 return GetEventHandlerForRect(gfx::Rect(point
, gfx::Size(1, 1)));
847 View
* View::GetEventHandlerForRect(const gfx::Rect
& rect
) {
848 return GetEffectiveViewTargeter()->TargetForRect(this, rect
);
851 bool View::CanProcessEventsWithinSubtree() const {
855 View
* View::GetTooltipHandlerForPoint(const gfx::Point
& point
) {
856 // TODO(tdanderson): Move this implementation into ViewTargetDelegate.
857 if (!HitTestPoint(point
) || !CanProcessEventsWithinSubtree())
860 // Walk the child Views recursively looking for the View that most
861 // tightly encloses the specified point.
862 for (int i
= child_count() - 1; i
>= 0; --i
) {
863 View
* child
= child_at(i
);
864 if (!child
->visible())
867 gfx::Point
point_in_child_coords(point
);
868 ConvertPointToTarget(this, child
, &point_in_child_coords
);
869 View
* handler
= child
->GetTooltipHandlerForPoint(point_in_child_coords
);
876 gfx::NativeCursor
View::GetCursor(const ui::MouseEvent
& event
) {
878 static ui::Cursor arrow
;
879 if (!arrow
.platform())
880 arrow
.SetPlatformCursor(LoadCursor(NULL
, IDC_ARROW
));
883 return gfx::kNullCursor
;
887 bool View::HitTestPoint(const gfx::Point
& point
) const {
888 return HitTestRect(gfx::Rect(point
, gfx::Size(1, 1)));
891 bool View::HitTestRect(const gfx::Rect
& rect
) const {
892 return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect
);
895 bool View::IsMouseHovered() {
896 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
901 // If mouse events are disabled, then the mouse cursor is invisible and
902 // is therefore not hovering over this button.
903 if (!GetWidget()->IsMouseEventsEnabled())
906 gfx::Point
cursor_pos(gfx::Screen::GetScreenFor(
907 GetWidget()->GetNativeView())->GetCursorScreenPoint());
908 ConvertPointFromScreen(this, &cursor_pos
);
909 return HitTestPoint(cursor_pos
);
912 bool View::OnMousePressed(const ui::MouseEvent
& event
) {
916 bool View::OnMouseDragged(const ui::MouseEvent
& event
) {
920 void View::OnMouseReleased(const ui::MouseEvent
& event
) {
923 void View::OnMouseCaptureLost() {
926 void View::OnMouseMoved(const ui::MouseEvent
& event
) {
929 void View::OnMouseEntered(const ui::MouseEvent
& event
) {
932 void View::OnMouseExited(const ui::MouseEvent
& event
) {
935 void View::SetMouseHandler(View
* new_mouse_handler
) {
936 // |new_mouse_handler| may be NULL.
938 parent_
->SetMouseHandler(new_mouse_handler
);
941 bool View::OnKeyPressed(const ui::KeyEvent
& event
) {
945 bool View::OnKeyReleased(const ui::KeyEvent
& event
) {
949 bool View::OnMouseWheel(const ui::MouseWheelEvent
& event
) {
953 void View::OnKeyEvent(ui::KeyEvent
* event
) {
954 bool consumed
= (event
->type() == ui::ET_KEY_PRESSED
) ? OnKeyPressed(*event
) :
955 OnKeyReleased(*event
);
957 event
->StopPropagation();
960 void View::OnMouseEvent(ui::MouseEvent
* event
) {
961 switch (event
->type()) {
962 case ui::ET_MOUSE_PRESSED
:
963 if (ProcessMousePressed(*event
))
967 case ui::ET_MOUSE_MOVED
:
968 if ((event
->flags() & (ui::EF_LEFT_MOUSE_BUTTON
|
969 ui::EF_RIGHT_MOUSE_BUTTON
|
970 ui::EF_MIDDLE_MOUSE_BUTTON
)) == 0) {
971 OnMouseMoved(*event
);
975 case ui::ET_MOUSE_DRAGGED
:
976 if (ProcessMouseDragged(*event
))
980 case ui::ET_MOUSE_RELEASED
:
981 ProcessMouseReleased(*event
);
984 case ui::ET_MOUSEWHEEL
:
985 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent
*>(event
)))
989 case ui::ET_MOUSE_ENTERED
:
990 if (event
->flags() & ui::EF_TOUCH_ACCESSIBILITY
)
991 NotifyAccessibilityEvent(ui::AX_EVENT_HOVER
, true);
992 OnMouseEntered(*event
);
995 case ui::ET_MOUSE_EXITED
:
996 OnMouseExited(*event
);
1004 void View::OnScrollEvent(ui::ScrollEvent
* event
) {
1007 void View::OnTouchEvent(ui::TouchEvent
* event
) {
1008 NOTREACHED() << "Views should not receive touch events.";
1011 void View::OnGestureEvent(ui::GestureEvent
* event
) {
1014 const ui::InputMethod
* View::GetInputMethod() const {
1015 Widget
* widget
= const_cast<Widget
*>(GetWidget());
1016 return widget
? const_cast<const ui::InputMethod
*>(widget
->GetInputMethod())
1020 scoped_ptr
<ViewTargeter
>
1021 View::SetEventTargeter(scoped_ptr
<ViewTargeter
> targeter
) {
1022 scoped_ptr
<ViewTargeter
> old_targeter
= targeter_
.Pass();
1023 targeter_
= targeter
.Pass();
1024 return old_targeter
.Pass();
1027 ViewTargeter
* View::GetEffectiveViewTargeter() const {
1028 DCHECK(GetWidget());
1029 ViewTargeter
* view_targeter
= targeter();
1031 view_targeter
= GetWidget()->GetRootView()->targeter();
1032 CHECK(view_targeter
);
1033 return view_targeter
;
1036 bool View::CanAcceptEvent(const ui::Event
& event
) {
1040 ui::EventTarget
* View::GetParentTarget() {
1044 scoped_ptr
<ui::EventTargetIterator
> View::GetChildIterator() const {
1045 return make_scoped_ptr(new ui::EventTargetIteratorImpl
<View
>(children_
));
1048 ui::EventTargeter
* View::GetEventTargeter() {
1049 return targeter_
.get();
1052 void View::ConvertEventToTarget(ui::EventTarget
* target
,
1053 ui::LocatedEvent
* event
) {
1054 event
->ConvertLocationToTarget(this, static_cast<View
*>(target
));
1057 // Accelerators ----------------------------------------------------------------
1059 void View::AddAccelerator(const ui::Accelerator
& accelerator
) {
1060 if (!accelerators_
.get())
1061 accelerators_
.reset(new std::vector
<ui::Accelerator
>());
1063 if (std::find(accelerators_
->begin(), accelerators_
->end(), accelerator
) ==
1064 accelerators_
->end()) {
1065 accelerators_
->push_back(accelerator
);
1067 RegisterPendingAccelerators();
1070 void View::RemoveAccelerator(const ui::Accelerator
& accelerator
) {
1071 if (!accelerators_
.get()) {
1072 NOTREACHED() << "Removing non-existing accelerator";
1076 std::vector
<ui::Accelerator
>::iterator
i(
1077 std::find(accelerators_
->begin(), accelerators_
->end(), accelerator
));
1078 if (i
== accelerators_
->end()) {
1079 NOTREACHED() << "Removing non-existing accelerator";
1083 size_t index
= i
- accelerators_
->begin();
1084 accelerators_
->erase(i
);
1085 if (index
>= registered_accelerator_count_
) {
1086 // The accelerator is not registered to FocusManager.
1089 --registered_accelerator_count_
;
1091 // Providing we are attached to a Widget and registered with a focus manager,
1092 // we should de-register from that focus manager now.
1093 if (GetWidget() && accelerator_focus_manager_
)
1094 accelerator_focus_manager_
->UnregisterAccelerator(accelerator
, this);
1097 void View::ResetAccelerators() {
1098 if (accelerators_
.get())
1099 UnregisterAccelerators(false);
1102 bool View::AcceleratorPressed(const ui::Accelerator
& accelerator
) {
1106 bool View::CanHandleAccelerators() const {
1107 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1110 // Focus -----------------------------------------------------------------------
1112 bool View::HasFocus() const {
1113 const FocusManager
* focus_manager
= GetFocusManager();
1114 return focus_manager
&& (focus_manager
->GetFocusedView() == this);
1117 View
* View::GetNextFocusableView() {
1118 return next_focusable_view_
;
1121 const View
* View::GetNextFocusableView() const {
1122 return next_focusable_view_
;
1125 View
* View::GetPreviousFocusableView() {
1126 return previous_focusable_view_
;
1129 void View::SetNextFocusableView(View
* view
) {
1131 view
->previous_focusable_view_
= this;
1132 next_focusable_view_
= view
;
1135 void View::SetFocusable(bool focusable
) {
1136 if (focusable_
== focusable
)
1139 focusable_
= focusable
;
1140 AdvanceFocusIfNecessary();
1143 bool View::IsFocusable() const {
1144 return focusable_
&& enabled_
&& IsDrawn();
1147 bool View::IsAccessibilityFocusable() const {
1148 return (focusable_
|| accessibility_focusable_
) && enabled_
&& IsDrawn();
1151 void View::SetAccessibilityFocusable(bool accessibility_focusable
) {
1152 if (accessibility_focusable_
== accessibility_focusable
)
1155 accessibility_focusable_
= accessibility_focusable
;
1156 AdvanceFocusIfNecessary();
1159 FocusManager
* View::GetFocusManager() {
1160 Widget
* widget
= GetWidget();
1161 return widget
? widget
->GetFocusManager() : NULL
;
1164 const FocusManager
* View::GetFocusManager() const {
1165 const Widget
* widget
= GetWidget();
1166 return widget
? widget
->GetFocusManager() : NULL
;
1169 void View::RequestFocus() {
1170 FocusManager
* focus_manager
= GetFocusManager();
1171 if (focus_manager
&& IsFocusable())
1172 focus_manager
->SetFocusedView(this);
1175 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent
& event
) {
1179 FocusTraversable
* View::GetFocusTraversable() {
1183 FocusTraversable
* View::GetPaneFocusTraversable() {
1187 // Tooltips --------------------------------------------------------------------
1189 bool View::GetTooltipText(const gfx::Point
& p
, base::string16
* tooltip
) const {
1193 bool View::GetTooltipTextOrigin(const gfx::Point
& p
, gfx::Point
* loc
) const {
1197 // Context menus ---------------------------------------------------------------
1199 void View::ShowContextMenu(const gfx::Point
& p
,
1200 ui::MenuSourceType source_type
) {
1201 if (!context_menu_controller_
)
1204 context_menu_controller_
->ShowContextMenuForView(this, p
, source_type
);
1208 bool View::ShouldShowContextMenuOnMousePress() {
1209 return kContextMenuOnMousePress
;
1212 gfx::Point
View::GetKeyboardContextMenuLocation() {
1213 gfx::Rect vis_bounds
= GetVisibleBounds();
1214 gfx::Point
screen_point(vis_bounds
.x() + vis_bounds
.width() / 2,
1215 vis_bounds
.y() + vis_bounds
.height() / 2);
1216 ConvertPointToScreen(this, &screen_point
);
1217 return screen_point
;
1220 // Drag and drop ---------------------------------------------------------------
1222 bool View::GetDropFormats(
1224 std::set
<OSExchangeData::CustomFormat
>* custom_formats
) {
1228 bool View::AreDropTypesRequired() {
1232 bool View::CanDrop(const OSExchangeData
& data
) {
1233 // TODO(sky): when I finish up migration, this should default to true.
1237 void View::OnDragEntered(const ui::DropTargetEvent
& event
) {
1240 int View::OnDragUpdated(const ui::DropTargetEvent
& event
) {
1241 return ui::DragDropTypes::DRAG_NONE
;
1244 void View::OnDragExited() {
1247 int View::OnPerformDrop(const ui::DropTargetEvent
& event
) {
1248 return ui::DragDropTypes::DRAG_NONE
;
1251 void View::OnDragDone() {
1255 bool View::ExceededDragThreshold(const gfx::Vector2d
& delta
) {
1256 return (abs(delta
.x()) > GetHorizontalDragThreshold() ||
1257 abs(delta
.y()) > GetVerticalDragThreshold());
1260 // Accessibility----------------------------------------------------------------
1262 gfx::NativeViewAccessible
View::GetNativeViewAccessible() {
1263 if (!native_view_accessibility_
)
1264 native_view_accessibility_
= NativeViewAccessibility::Create(this);
1265 if (native_view_accessibility_
)
1266 return native_view_accessibility_
->GetNativeObject();
1270 void View::NotifyAccessibilityEvent(
1271 ui::AXEvent event_type
,
1272 bool send_native_event
) {
1273 if (ViewsDelegate::GetInstance())
1274 ViewsDelegate::GetInstance()->NotifyAccessibilityEvent(this, event_type
);
1276 if (send_native_event
&& GetWidget()) {
1277 if (!native_view_accessibility_
)
1278 native_view_accessibility_
= NativeViewAccessibility::Create(this);
1279 if (native_view_accessibility_
)
1280 native_view_accessibility_
->NotifyAccessibilityEvent(event_type
);
1284 // Scrolling -------------------------------------------------------------------
1286 void View::ScrollRectToVisible(const gfx::Rect
& rect
) {
1287 // We must take RTL UI mirroring into account when adjusting the position of
1290 gfx::Rect
scroll_rect(rect
);
1291 scroll_rect
.Offset(GetMirroredX(), y());
1292 parent_
->ScrollRectToVisible(scroll_rect
);
1296 int View::GetPageScrollIncrement(ScrollView
* scroll_view
,
1297 bool is_horizontal
, bool is_positive
) {
1301 int View::GetLineScrollIncrement(ScrollView
* scroll_view
,
1302 bool is_horizontal
, bool is_positive
) {
1306 ////////////////////////////////////////////////////////////////////////////////
1309 // Size and disposition --------------------------------------------------------
1311 void View::OnBoundsChanged(const gfx::Rect
& previous_bounds
) {
1314 void View::PreferredSizeChanged() {
1317 parent_
->ChildPreferredSizeChanged(this);
1320 bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
1324 void View::OnVisibleBoundsChanged() {
1327 // Tree operations -------------------------------------------------------------
1329 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails
& details
) {
1332 void View::VisibilityChanged(View
* starting_from
, bool is_visible
) {
1335 void View::NativeViewHierarchyChanged() {
1336 FocusManager
* focus_manager
= GetFocusManager();
1337 if (accelerator_focus_manager_
!= focus_manager
) {
1338 UnregisterAccelerators(true);
1341 RegisterPendingAccelerators();
1345 // Painting --------------------------------------------------------------------
1347 void View::PaintChildren(const ui::PaintContext
& context
) {
1348 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1349 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1350 if (!child_at(i
)->layer())
1351 child_at(i
)->Paint(context
);
1354 void View::OnPaint(gfx::Canvas
* canvas
) {
1355 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1356 OnPaintBackground(canvas
);
1357 OnPaintBorder(canvas
);
1360 void View::OnPaintBackground(gfx::Canvas
* canvas
) {
1361 if (background_
.get()) {
1362 TRACE_EVENT2("views", "View::OnPaintBackground",
1363 "width", canvas
->sk_canvas()->getDevice()->width(),
1364 "height", canvas
->sk_canvas()->getDevice()->height());
1365 background_
->Paint(canvas
, this);
1369 void View::OnPaintBorder(gfx::Canvas
* canvas
) {
1370 if (border_
.get()) {
1371 TRACE_EVENT2("views", "View::OnPaintBorder",
1372 "width", canvas
->sk_canvas()->getDevice()->width(),
1373 "height", canvas
->sk_canvas()->getDevice()->height());
1374 border_
->Paint(*this, canvas
);
1378 // Accelerated Painting --------------------------------------------------------
1380 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely
) {
1381 // This method should not have the side-effect of creating the layer.
1383 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely
);
1386 gfx::Vector2d
View::CalculateOffsetToAncestorWithLayer(
1387 ui::Layer
** layer_parent
) {
1390 *layer_parent
= layer();
1391 return gfx::Vector2d();
1394 return gfx::Vector2d();
1396 return gfx::Vector2d(GetMirroredX(), y()) +
1397 parent_
->CalculateOffsetToAncestorWithLayer(layer_parent
);
1400 void View::UpdateParentLayer() {
1404 ui::Layer
* parent_layer
= NULL
;
1405 gfx::Vector2d
offset(GetMirroredX(), y());
1408 offset
+= parent_
->CalculateOffsetToAncestorWithLayer(&parent_layer
);
1410 ReparentLayer(offset
, parent_layer
);
1413 void View::MoveLayerToParent(ui::Layer
* parent_layer
,
1414 const gfx::Point
& point
) {
1415 gfx::Point
local_point(point
);
1416 if (parent_layer
!= layer())
1417 local_point
.Offset(GetMirroredX(), y());
1418 if (layer() && parent_layer
!= layer()) {
1419 parent_layer
->Add(layer());
1420 SetLayerBounds(gfx::Rect(local_point
.x(), local_point
.y(),
1421 width(), height()));
1423 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1424 child_at(i
)->MoveLayerToParent(parent_layer
, local_point
);
1428 void View::UpdateLayerVisibility() {
1429 bool visible
= visible_
;
1430 for (const View
* v
= parent_
; visible
&& v
&& !v
->layer(); v
= v
->parent_
)
1431 visible
= v
->visible();
1433 UpdateChildLayerVisibility(visible
);
1436 void View::UpdateChildLayerVisibility(bool ancestor_visible
) {
1438 layer()->SetVisible(ancestor_visible
&& visible_
);
1440 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1441 child_at(i
)->UpdateChildLayerVisibility(ancestor_visible
&& visible_
);
1445 void View::UpdateChildLayerBounds(const gfx::Vector2d
& offset
) {
1447 SetLayerBounds(GetLocalBounds() + offset
);
1449 for (int i
= 0, count
= child_count(); i
< count
; ++i
) {
1450 View
* child
= child_at(i
);
1451 child
->UpdateChildLayerBounds(
1452 offset
+ gfx::Vector2d(child
->GetMirroredX(), child
->y()));
1457 void View::OnPaintLayer(const ui::PaintContext
& context
) {
1461 void View::OnDelegatedFrameDamage(
1462 const gfx::Rect
& damage_rect_in_dip
) {
1465 void View::OnDeviceScaleFactorChanged(float device_scale_factor
) {
1466 snap_layer_to_pixel_boundary_
=
1467 (device_scale_factor
- std::floor(device_scale_factor
)) != 0.0f
;
1468 SnapLayerToPixelBoundary();
1469 // Repainting with new scale factor will paint the content at the right scale.
1472 base::Closure
View::PrepareForLayerBoundsChange() {
1473 return base::Closure();
1476 void View::ReorderLayers() {
1478 while (v
&& !v
->layer())
1481 Widget
* widget
= GetWidget();
1484 ui::Layer
* layer
= widget
->GetLayer();
1486 widget
->GetRootView()->ReorderChildLayers(layer
);
1489 v
->ReorderChildLayers(v
->layer());
1493 // Reorder the widget's child NativeViews in case a child NativeView is
1494 // associated with a view (eg via a NativeViewHost). Always do the
1495 // reordering because the associated NativeView's layer (if it has one)
1496 // is parented to the widget's layer regardless of whether the host view has
1497 // an ancestor with a layer.
1498 widget
->ReorderNativeViews();
1502 void View::ReorderChildLayers(ui::Layer
* parent_layer
) {
1503 if (layer() && layer() != parent_layer
) {
1504 DCHECK_EQ(parent_layer
, layer()->parent());
1505 parent_layer
->StackAtBottom(layer());
1507 // Iterate backwards through the children so that a child with a layer
1508 // which is further to the back is stacked above one which is further to
1510 for (Views::reverse_iterator
it(children_
.rbegin());
1511 it
!= children_
.rend(); ++it
) {
1512 (*it
)->ReorderChildLayers(parent_layer
);
1517 // Input -----------------------------------------------------------------------
1519 View::DragInfo
* View::GetDragInfo() {
1520 return parent_
? parent_
->GetDragInfo() : NULL
;
1523 // Focus -----------------------------------------------------------------------
1525 void View::OnFocus() {
1526 // TODO(beng): Investigate whether it's possible for us to move this to
1528 // By default, we clear the native focus. This ensures that no visible native
1529 // view as the focus and that we still receive keyboard inputs.
1530 FocusManager
* focus_manager
= GetFocusManager();
1532 focus_manager
->ClearNativeFocus();
1534 // TODO(beng): Investigate whether it's possible for us to move this to
1536 // Notify assistive technologies of the focus change.
1537 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS
, true);
1540 void View::OnBlur() {
1543 void View::Focus() {
1551 // Tooltips --------------------------------------------------------------------
1553 void View::TooltipTextChanged() {
1554 Widget
* widget
= GetWidget();
1555 // TooltipManager may be null if there is a problem creating it.
1556 if (widget
&& widget
->GetTooltipManager())
1557 widget
->GetTooltipManager()->TooltipTextChanged(this);
1560 // Drag and drop ---------------------------------------------------------------
1562 int View::GetDragOperations(const gfx::Point
& press_pt
) {
1563 return drag_controller_
?
1564 drag_controller_
->GetDragOperationsForView(this, press_pt
) :
1565 ui::DragDropTypes::DRAG_NONE
;
1568 void View::WriteDragData(const gfx::Point
& press_pt
, OSExchangeData
* data
) {
1569 DCHECK(drag_controller_
);
1570 drag_controller_
->WriteDragDataForView(this, press_pt
, data
);
1573 bool View::InDrag() {
1574 Widget
* widget
= GetWidget();
1575 return widget
? widget
->dragged_view() == this : false;
1578 int View::GetHorizontalDragThreshold() {
1579 // TODO(jennyz): This value may need to be adjusted for different platforms
1580 // and for different display density.
1581 return kDefaultHorizontalDragThreshold
;
1584 int View::GetVerticalDragThreshold() {
1585 // TODO(jennyz): This value may need to be adjusted for different platforms
1586 // and for different display density.
1587 return kDefaultVerticalDragThreshold
;
1590 // Debugging -------------------------------------------------------------------
1592 #if !defined(NDEBUG)
1594 std::string
View::PrintViewGraph(bool first
) {
1595 return DoPrintViewGraph(first
, this);
1598 std::string
View::DoPrintViewGraph(bool first
, View
* view_with_children
) {
1599 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1600 const size_t kMaxPointerStringLength
= 19;
1605 result
.append("digraph {\n");
1607 // Node characteristics.
1608 char p
[kMaxPointerStringLength
];
1610 const std::string
class_name(GetClassName());
1611 size_t base_name_index
= class_name
.find_last_of('/');
1612 if (base_name_index
== std::string::npos
)
1613 base_name_index
= 0;
1617 char bounds_buffer
[512];
1619 // Information about current node.
1620 base::snprintf(p
, arraysize(bounds_buffer
), "%p", view_with_children
);
1621 result
.append(" N");
1622 result
.append(p
+ 2);
1623 result
.append(" [label=\"");
1625 result
.append(class_name
.substr(base_name_index
).c_str());
1627 base::snprintf(bounds_buffer
,
1628 arraysize(bounds_buffer
),
1629 "\\n bounds: (%d, %d), (%dx%d)",
1634 result
.append(bounds_buffer
);
1636 gfx::DecomposedTransform decomp
;
1637 if (!GetTransform().IsIdentity() &&
1638 gfx::DecomposeTransform(&decomp
, GetTransform())) {
1639 base::snprintf(bounds_buffer
,
1640 arraysize(bounds_buffer
),
1641 "\\n translation: (%f, %f)",
1642 decomp
.translate
[0],
1643 decomp
.translate
[1]);
1644 result
.append(bounds_buffer
);
1646 base::snprintf(bounds_buffer
,
1647 arraysize(bounds_buffer
),
1648 "\\n rotation: %3.2f",
1649 std::acos(decomp
.quaternion
[3]) * 360.0 / M_PI
);
1650 result
.append(bounds_buffer
);
1652 base::snprintf(bounds_buffer
,
1653 arraysize(bounds_buffer
),
1654 "\\n scale: (%2.4f, %2.4f)",
1657 result
.append(bounds_buffer
);
1660 result
.append("\"");
1662 result
.append(", shape=box");
1664 if (layer()->has_external_content())
1665 result
.append(", color=green");
1667 result
.append(", color=red");
1669 if (layer()->fills_bounds_opaquely())
1670 result
.append(", style=filled");
1672 result
.append("]\n");
1676 char pp
[kMaxPointerStringLength
];
1678 base::snprintf(pp
, kMaxPointerStringLength
, "%p", parent_
);
1679 result
.append(" N");
1680 result
.append(pp
+ 2);
1681 result
.append(" -> N");
1682 result
.append(p
+ 2);
1683 result
.append("\n");
1687 for (int i
= 0, count
= view_with_children
->child_count(); i
< count
; ++i
)
1688 result
.append(view_with_children
->child_at(i
)->PrintViewGraph(false));
1691 result
.append("}\n");
1697 ////////////////////////////////////////////////////////////////////////////////
1700 // DropInfo --------------------------------------------------------------------
1702 void View::DragInfo::Reset() {
1703 possible_drag
= false;
1704 start_pt
= gfx::Point();
1707 void View::DragInfo::PossibleDrag(const gfx::Point
& p
) {
1708 possible_drag
= true;
1712 // Painting --------------------------------------------------------------------
1714 void View::SchedulePaintBoundsChanged(SchedulePaintType type
) {
1715 // If we have a layer and the View's size did not change, we do not need to
1716 // schedule any paints since the layer will be redrawn at its new location
1717 // during the next Draw() cycle in the compositor.
1718 if (!layer() || type
== SCHEDULE_PAINT_SIZE_CHANGED
) {
1719 // Otherwise, if the size changes or we don't have a layer then we need to
1720 // use SchedulePaint to invalidate the area occupied by the View.
1722 } else if (parent_
&& type
== SCHEDULE_PAINT_SIZE_SAME
) {
1723 // The compositor doesn't Draw() until something on screen changes, so
1724 // if our position changes but nothing is being animated on screen, then
1725 // tell the compositor to redraw the scene. We know layer() exists due to
1726 // the above if clause.
1727 layer()->ScheduleDraw();
1731 // Tree operations -------------------------------------------------------------
1733 void View::DoRemoveChildView(View
* view
,
1734 bool update_focus_cycle
,
1735 bool update_tool_tip
,
1736 bool delete_removed_view
,
1740 const Views::iterator
i(std::find(children_
.begin(), children_
.end(), view
));
1741 scoped_ptr
<View
> view_to_be_deleted
;
1742 if (i
!= children_
.end()) {
1743 if (update_focus_cycle
) {
1744 // Let's remove the view from the focus traversal.
1745 View
* next_focusable
= view
->next_focusable_view_
;
1746 View
* prev_focusable
= view
->previous_focusable_view_
;
1748 prev_focusable
->next_focusable_view_
= next_focusable
;
1750 next_focusable
->previous_focusable_view_
= prev_focusable
;
1754 UnregisterChildrenForVisibleBoundsNotification(view
);
1755 if (view
->visible())
1756 view
->SchedulePaint();
1757 GetWidget()->NotifyWillRemoveView(view
);
1760 view
->PropagateRemoveNotifications(this, new_parent
);
1761 view
->parent_
= NULL
;
1762 view
->UpdateLayerVisibility();
1764 if (delete_removed_view
&& !view
->owned_by_client_
)
1765 view_to_be_deleted
.reset(view
);
1770 if (update_tool_tip
)
1773 if (layout_manager_
.get())
1774 layout_manager_
->ViewRemoved(this, view
);
1777 void View::PropagateRemoveNotifications(View
* old_parent
, View
* new_parent
) {
1778 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1779 child_at(i
)->PropagateRemoveNotifications(old_parent
, new_parent
);
1781 ViewHierarchyChangedDetails
details(false, old_parent
, this, new_parent
);
1782 for (View
* v
= this; v
; v
= v
->parent_
)
1783 v
->ViewHierarchyChangedImpl(true, details
);
1786 void View::PropagateAddNotifications(
1787 const ViewHierarchyChangedDetails
& details
) {
1788 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1789 child_at(i
)->PropagateAddNotifications(details
);
1790 ViewHierarchyChangedImpl(true, details
);
1793 void View::PropagateNativeViewHierarchyChanged() {
1794 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1795 child_at(i
)->PropagateNativeViewHierarchyChanged();
1796 NativeViewHierarchyChanged();
1799 void View::ViewHierarchyChangedImpl(
1800 bool register_accelerators
,
1801 const ViewHierarchyChangedDetails
& details
) {
1802 if (register_accelerators
) {
1803 if (details
.is_add
) {
1804 // If you get this registration, you are part of a subtree that has been
1805 // added to the view hierarchy.
1806 if (GetFocusManager())
1807 RegisterPendingAccelerators();
1809 if (details
.child
== this)
1810 UnregisterAccelerators(true);
1814 if (details
.is_add
&& layer() && !layer()->parent()) {
1815 UpdateParentLayer();
1816 Widget
* widget
= GetWidget();
1818 widget
->UpdateRootLayers();
1819 } else if (!details
.is_add
&& details
.child
== this) {
1820 // Make sure the layers belonging to the subtree rooted at |child| get
1821 // removed from layers that do not belong in the same subtree.
1823 Widget
* widget
= GetWidget();
1825 widget
->UpdateRootLayers();
1828 ViewHierarchyChanged(details
);
1829 details
.parent
->needs_layout_
= true;
1832 void View::PropagateNativeThemeChanged(const ui::NativeTheme
* theme
) {
1833 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1834 child_at(i
)->PropagateNativeThemeChanged(theme
);
1835 OnNativeThemeChanged(theme
);
1838 // Size and disposition --------------------------------------------------------
1840 void View::PropagateVisibilityNotifications(View
* start
, bool is_visible
) {
1841 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1842 child_at(i
)->PropagateVisibilityNotifications(start
, is_visible
);
1843 VisibilityChangedImpl(start
, is_visible
);
1846 void View::VisibilityChangedImpl(View
* starting_from
, bool is_visible
) {
1847 VisibilityChanged(starting_from
, is_visible
);
1850 void View::BoundsChanged(const gfx::Rect
& previous_bounds
) {
1852 // Paint the new bounds.
1853 SchedulePaintBoundsChanged(
1854 bounds_
.size() == previous_bounds
.size() ? SCHEDULE_PAINT_SIZE_SAME
:
1855 SCHEDULE_PAINT_SIZE_CHANGED
);
1860 SetLayerBounds(GetLocalBounds() +
1861 gfx::Vector2d(GetMirroredX(), y()) +
1862 parent_
->CalculateOffsetToAncestorWithLayer(NULL
));
1864 SetLayerBounds(bounds_
);
1867 // In RTL mode, if our width has changed, our children's mirrored bounds
1868 // will have changed. Update the child's layer bounds, or if it is not a
1869 // layer, the bounds of any layers inside the child.
1870 if (base::i18n::IsRTL() && bounds_
.width() != previous_bounds
.width()) {
1871 for (int i
= 0; i
< child_count(); ++i
) {
1872 View
* child
= child_at(i
);
1873 child
->UpdateChildLayerBounds(
1874 gfx::Vector2d(child
->GetMirroredX(), child
->y()));
1878 // If our bounds have changed, then any descendant layer bounds may have
1879 // changed. Update them accordingly.
1880 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL
));
1883 OnBoundsChanged(previous_bounds
);
1885 if (previous_bounds
.size() != size()) {
1886 needs_layout_
= false;
1890 if (GetNeedsNotificationWhenVisibleBoundsChange())
1891 OnVisibleBoundsChanged();
1893 // Notify interested Views that visible bounds within the root view may have
1895 if (descendants_to_notify_
.get()) {
1896 for (Views::iterator
i(descendants_to_notify_
->begin());
1897 i
!= descendants_to_notify_
->end(); ++i
) {
1898 (*i
)->OnVisibleBoundsChanged();
1904 void View::RegisterChildrenForVisibleBoundsNotification(View
* view
) {
1905 if (view
->GetNeedsNotificationWhenVisibleBoundsChange())
1906 view
->RegisterForVisibleBoundsNotification();
1907 for (int i
= 0; i
< view
->child_count(); ++i
)
1908 RegisterChildrenForVisibleBoundsNotification(view
->child_at(i
));
1912 void View::UnregisterChildrenForVisibleBoundsNotification(View
* view
) {
1913 if (view
->GetNeedsNotificationWhenVisibleBoundsChange())
1914 view
->UnregisterForVisibleBoundsNotification();
1915 for (int i
= 0; i
< view
->child_count(); ++i
)
1916 UnregisterChildrenForVisibleBoundsNotification(view
->child_at(i
));
1919 void View::RegisterForVisibleBoundsNotification() {
1920 if (registered_for_visible_bounds_notification_
)
1923 registered_for_visible_bounds_notification_
= true;
1924 for (View
* ancestor
= parent_
; ancestor
; ancestor
= ancestor
->parent_
)
1925 ancestor
->AddDescendantToNotify(this);
1928 void View::UnregisterForVisibleBoundsNotification() {
1929 if (!registered_for_visible_bounds_notification_
)
1932 registered_for_visible_bounds_notification_
= false;
1933 for (View
* ancestor
= parent_
; ancestor
; ancestor
= ancestor
->parent_
)
1934 ancestor
->RemoveDescendantToNotify(this);
1937 void View::AddDescendantToNotify(View
* view
) {
1939 if (!descendants_to_notify_
.get())
1940 descendants_to_notify_
.reset(new Views
);
1941 descendants_to_notify_
->push_back(view
);
1944 void View::RemoveDescendantToNotify(View
* view
) {
1945 DCHECK(view
&& descendants_to_notify_
.get());
1946 Views::iterator
i(std::find(
1947 descendants_to_notify_
->begin(), descendants_to_notify_
->end(), view
));
1948 DCHECK(i
!= descendants_to_notify_
->end());
1949 descendants_to_notify_
->erase(i
);
1950 if (descendants_to_notify_
->empty())
1951 descendants_to_notify_
.reset();
1954 void View::SetLayerBounds(const gfx::Rect
& bounds
) {
1955 layer()->SetBounds(bounds
);
1956 SnapLayerToPixelBoundary();
1959 // Transformations -------------------------------------------------------------
1961 bool View::GetTransformRelativeTo(const View
* ancestor
,
1962 gfx::Transform
* transform
) const {
1963 const View
* p
= this;
1965 while (p
&& p
!= ancestor
) {
1966 transform
->ConcatTransform(p
->GetTransform());
1967 gfx::Transform translation
;
1968 translation
.Translate(static_cast<float>(p
->GetMirroredX()),
1969 static_cast<float>(p
->y()));
1970 transform
->ConcatTransform(translation
);
1975 return p
== ancestor
;
1978 // Coordinate conversion -------------------------------------------------------
1980 bool View::ConvertPointForAncestor(const View
* ancestor
,
1981 gfx::Point
* point
) const {
1982 gfx::Transform trans
;
1983 // TODO(sad): Have some way of caching the transformation results.
1984 bool result
= GetTransformRelativeTo(ancestor
, &trans
);
1985 gfx::Point3F
p(*point
);
1986 trans
.TransformPoint(&p
);
1987 *point
= gfx::ToFlooredPoint(p
.AsPointF());
1991 bool View::ConvertPointFromAncestor(const View
* ancestor
,
1992 gfx::Point
* point
) const {
1993 gfx::Transform trans
;
1994 bool result
= GetTransformRelativeTo(ancestor
, &trans
);
1995 gfx::Point3F
p(*point
);
1996 trans
.TransformPointReverse(&p
);
1997 *point
= gfx::ToFlooredPoint(p
.AsPointF());
2001 bool View::ConvertRectForAncestor(const View
* ancestor
,
2002 gfx::RectF
* rect
) const {
2003 gfx::Transform trans
;
2004 // TODO(sad): Have some way of caching the transformation results.
2005 bool result
= GetTransformRelativeTo(ancestor
, &trans
);
2006 trans
.TransformRect(rect
);
2010 bool View::ConvertRectFromAncestor(const View
* ancestor
,
2011 gfx::RectF
* rect
) const {
2012 gfx::Transform trans
;
2013 bool result
= GetTransformRelativeTo(ancestor
, &trans
);
2014 trans
.TransformRectReverse(rect
);
2018 // Accelerated painting --------------------------------------------------------
2020 void View::CreateLayer() {
2021 // A new layer is being created for the view. So all the layers of the
2022 // sub-tree can inherit the visibility of the corresponding view.
2023 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
2024 child_at(i
)->UpdateChildLayerVisibility(true);
2026 SetLayer(new ui::Layer());
2027 layer()->set_delegate(this);
2028 #if !defined(NDEBUG)
2029 layer()->set_name(GetClassName());
2032 UpdateParentLayers();
2033 UpdateLayerVisibility();
2035 // The new layer needs to be ordered in the layer tree according
2036 // to the view tree. Children of this layer were added in order
2037 // in UpdateParentLayers().
2039 parent()->ReorderLayers();
2041 Widget
* widget
= GetWidget();
2043 widget
->UpdateRootLayers();
2046 void View::UpdateParentLayers() {
2047 // Attach all top-level un-parented layers.
2048 if (layer() && !layer()->parent()) {
2049 UpdateParentLayer();
2051 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
2052 child_at(i
)->UpdateParentLayers();
2056 void View::OrphanLayers() {
2058 if (layer()->parent())
2059 layer()->parent()->Remove(layer());
2061 // The layer belonging to this View has already been orphaned. It is not
2062 // necessary to orphan the child layers.
2065 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
2066 child_at(i
)->OrphanLayers();
2069 void View::ReparentLayer(const gfx::Vector2d
& offset
, ui::Layer
* parent_layer
) {
2070 layer()->SetBounds(GetLocalBounds() + offset
);
2071 DCHECK_NE(layer(), parent_layer
);
2073 parent_layer
->Add(layer());
2074 layer()->SchedulePaint(GetLocalBounds());
2075 MoveLayerToParent(layer(), gfx::Point());
2078 void View::DestroyLayer() {
2079 ui::Layer
* new_parent
= layer()->parent();
2080 std::vector
<ui::Layer
*> children
= layer()->children();
2081 for (size_t i
= 0; i
< children
.size(); ++i
) {
2082 layer()->Remove(children
[i
]);
2084 new_parent
->Add(children
[i
]);
2087 LayerOwner::DestroyLayer();
2092 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL
));
2096 Widget
* widget
= GetWidget();
2098 widget
->UpdateRootLayers();
2101 // Input -----------------------------------------------------------------------
2103 bool View::ProcessMousePressed(const ui::MouseEvent
& event
) {
2104 int drag_operations
=
2105 (enabled_
&& event
.IsOnlyLeftMouseButton() &&
2106 HitTestPoint(event
.location())) ?
2107 GetDragOperations(event
.location()) : 0;
2108 ContextMenuController
* context_menu_controller
= event
.IsRightMouseButton() ?
2109 context_menu_controller_
: 0;
2110 View::DragInfo
* drag_info
= GetDragInfo();
2112 // TODO(sky): for debugging 360238.
2114 if (event
.IsOnlyRightMouseButton() && context_menu_controller
&&
2115 kContextMenuOnMousePress
&& HitTestPoint(event
.location())) {
2116 ViewStorage
* view_storage
= ViewStorage::GetInstance();
2117 storage_id
= view_storage
->CreateStorageID();
2118 view_storage
->StoreView(storage_id
, this);
2121 const bool enabled
= enabled_
;
2122 const bool result
= OnMousePressed(event
);
2127 if (event
.IsOnlyRightMouseButton() && context_menu_controller
&&
2128 kContextMenuOnMousePress
) {
2129 // Assume that if there is a context menu controller we won't be deleted
2130 // from mouse pressed.
2131 gfx::Point
location(event
.location());
2132 if (HitTestPoint(location
)) {
2133 if (storage_id
!= 0)
2134 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id
));
2135 ConvertPointToScreen(this, &location
);
2136 ShowContextMenu(location
, ui::MENU_SOURCE_MOUSE
);
2141 // WARNING: we may have been deleted, don't use any View variables.
2142 if (drag_operations
!= ui::DragDropTypes::DRAG_NONE
) {
2143 drag_info
->PossibleDrag(event
.location());
2146 return !!context_menu_controller
|| result
;
2149 bool View::ProcessMouseDragged(const ui::MouseEvent
& event
) {
2150 // Copy the field, that way if we're deleted after drag and drop no harm is
2152 ContextMenuController
* context_menu_controller
= context_menu_controller_
;
2153 const bool possible_drag
= GetDragInfo()->possible_drag
;
2154 if (possible_drag
&&
2155 ExceededDragThreshold(GetDragInfo()->start_pt
- event
.location()) &&
2156 (!drag_controller_
||
2157 drag_controller_
->CanStartDragForView(
2158 this, GetDragInfo()->start_pt
, event
.location()))) {
2159 DoDrag(event
, GetDragInfo()->start_pt
,
2160 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE
);
2162 if (OnMouseDragged(event
))
2164 // Fall through to return value based on context menu controller.
2166 // WARNING: we may have been deleted.
2167 return (context_menu_controller
!= NULL
) || possible_drag
;
2170 void View::ProcessMouseReleased(const ui::MouseEvent
& event
) {
2171 if (!kContextMenuOnMousePress
&& context_menu_controller_
&&
2172 event
.IsOnlyRightMouseButton()) {
2173 // Assume that if there is a context menu controller we won't be deleted
2174 // from mouse released.
2175 gfx::Point
location(event
.location());
2176 OnMouseReleased(event
);
2177 if (HitTestPoint(location
)) {
2178 ConvertPointToScreen(this, &location
);
2179 ShowContextMenu(location
, ui::MENU_SOURCE_MOUSE
);
2182 OnMouseReleased(event
);
2184 // WARNING: we may have been deleted.
2187 // Accelerators ----------------------------------------------------------------
2189 void View::RegisterPendingAccelerators() {
2190 if (!accelerators_
.get() ||
2191 registered_accelerator_count_
== accelerators_
->size()) {
2192 // No accelerators are waiting for registration.
2197 // The view is not yet attached to a widget, defer registration until then.
2201 accelerator_focus_manager_
= GetFocusManager();
2202 if (!accelerator_focus_manager_
) {
2203 // Some crash reports seem to show that we may get cases where we have no
2204 // focus manager (see bug #1291225). This should never be the case, just
2205 // making sure we don't crash.
2209 for (std::vector
<ui::Accelerator
>::const_iterator
i(
2210 accelerators_
->begin() + registered_accelerator_count_
);
2211 i
!= accelerators_
->end(); ++i
) {
2212 accelerator_focus_manager_
->RegisterAccelerator(
2213 *i
, ui::AcceleratorManager::kNormalPriority
, this);
2215 registered_accelerator_count_
= accelerators_
->size();
2218 void View::UnregisterAccelerators(bool leave_data_intact
) {
2219 if (!accelerators_
.get())
2223 if (accelerator_focus_manager_
) {
2224 accelerator_focus_manager_
->UnregisterAccelerators(this);
2225 accelerator_focus_manager_
= NULL
;
2227 if (!leave_data_intact
) {
2228 accelerators_
->clear();
2229 accelerators_
.reset();
2231 registered_accelerator_count_
= 0;
2235 // Focus -----------------------------------------------------------------------
2237 void View::InitFocusSiblings(View
* v
, int index
) {
2238 int count
= child_count();
2241 v
->next_focusable_view_
= NULL
;
2242 v
->previous_focusable_view_
= NULL
;
2244 if (index
== count
) {
2245 // We are inserting at the end, but the end of the child list may not be
2246 // the last focusable element. Let's try to find an element with no next
2247 // focusable element to link to.
2248 View
* last_focusable_view
= NULL
;
2249 for (Views::iterator
i(children_
.begin()); i
!= children_
.end(); ++i
) {
2250 if (!(*i
)->next_focusable_view_
) {
2251 last_focusable_view
= *i
;
2255 if (last_focusable_view
== NULL
) {
2256 // Hum... there is a cycle in the focus list. Let's just insert ourself
2257 // after the last child.
2258 View
* prev
= children_
[index
- 1];
2259 v
->previous_focusable_view_
= prev
;
2260 v
->next_focusable_view_
= prev
->next_focusable_view_
;
2261 prev
->next_focusable_view_
->previous_focusable_view_
= v
;
2262 prev
->next_focusable_view_
= v
;
2264 last_focusable_view
->next_focusable_view_
= v
;
2265 v
->next_focusable_view_
= NULL
;
2266 v
->previous_focusable_view_
= last_focusable_view
;
2269 View
* prev
= children_
[index
]->GetPreviousFocusableView();
2270 v
->previous_focusable_view_
= prev
;
2271 v
->next_focusable_view_
= children_
[index
];
2273 prev
->next_focusable_view_
= v
;
2274 children_
[index
]->previous_focusable_view_
= v
;
2279 void View::AdvanceFocusIfNecessary() {
2280 // Focus should only be advanced if this is the focused view and has become
2281 // unfocusable. If the view is still focusable or is not focused, we can
2282 // return early avoiding furthur unnecessary checks. Focusability check is
2283 // performed first as it tends to be faster.
2284 if (IsAccessibilityFocusable() || !HasFocus())
2287 FocusManager
* focus_manager
= GetFocusManager();
2289 focus_manager
->AdvanceFocusIfNecessary();
2292 // System events ---------------------------------------------------------------
2294 void View::PropagateThemeChanged() {
2295 for (int i
= child_count() - 1; i
>= 0; --i
)
2296 child_at(i
)->PropagateThemeChanged();
2300 void View::PropagateLocaleChanged() {
2301 for (int i
= child_count() - 1; i
>= 0; --i
)
2302 child_at(i
)->PropagateLocaleChanged();
2306 void View::PropagateDeviceScaleFactorChanged(float device_scale_factor
) {
2307 for (int i
= child_count() - 1; i
>= 0; --i
)
2308 child_at(i
)->PropagateDeviceScaleFactorChanged(device_scale_factor
);
2310 // If the view is drawing to the layer, OnDeviceScaleFactorChanged() is called
2311 // through LayerDelegate callback.
2313 OnDeviceScaleFactorChanged(device_scale_factor
);
2316 // Tooltips --------------------------------------------------------------------
2318 void View::UpdateTooltip() {
2319 Widget
* widget
= GetWidget();
2320 // TODO(beng): The TooltipManager NULL check can be removed when we
2321 // consolidate Init() methods and make views_unittests Init() all
2322 // Widgets that it uses.
2323 if (widget
&& widget
->GetTooltipManager())
2324 widget
->GetTooltipManager()->UpdateTooltip();
2327 // Drag and drop ---------------------------------------------------------------
2329 bool View::DoDrag(const ui::LocatedEvent
& event
,
2330 const gfx::Point
& press_pt
,
2331 ui::DragDropTypes::DragEventSource source
) {
2332 int drag_operations
= GetDragOperations(press_pt
);
2333 if (drag_operations
== ui::DragDropTypes::DRAG_NONE
)
2336 Widget
* widget
= GetWidget();
2337 // We should only start a drag from an event, implying we have a widget.
2340 // Don't attempt to start a drag while in the process of dragging. This is
2341 // especially important on X where we can get multiple mouse move events when
2342 // we start the drag.
2343 if (widget
->dragged_view())
2346 OSExchangeData data
;
2347 WriteDragData(press_pt
, &data
);
2349 // Message the RootView to do the drag and drop. That way if we're removed
2350 // the RootView can detect it and avoid calling us back.
2351 gfx::Point
widget_location(event
.location());
2352 ConvertPointToWidget(this, &widget_location
);
2353 widget
->RunShellDrag(this, data
, widget_location
, drag_operations
, source
);
2354 // WARNING: we may have been deleted.
2358 } // namespace views