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/debug/trace_event.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/message_loop.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "third_party/skia/include/core/SkRect.h"
19 #include "ui/base/accessibility/accessibility_types.h"
20 #include "ui/base/dragdrop/drag_drop_types.h"
21 #include "ui/base/ui_base_switches_util.h"
22 #include "ui/compositor/compositor.h"
23 #include "ui/compositor/layer.h"
24 #include "ui/compositor/layer_animator.h"
25 #include "ui/gfx/canvas.h"
26 #include "ui/gfx/interpolated_transform.h"
27 #include "ui/gfx/path.h"
28 #include "ui/gfx/point3_f.h"
29 #include "ui/gfx/point_conversions.h"
30 #include "ui/gfx/rect_conversions.h"
31 #include "ui/gfx/screen.h"
32 #include "ui/gfx/skia_util.h"
33 #include "ui/gfx/transform.h"
34 #include "ui/native_theme/native_theme.h"
35 #include "ui/views/accessibility/native_view_accessibility.h"
36 #include "ui/views/background.h"
37 #include "ui/views/context_menu_controller.h"
38 #include "ui/views/drag_controller.h"
39 #include "ui/views/layout/layout_manager.h"
40 #include "ui/views/views_delegate.h"
41 #include "ui/views/widget/native_widget_private.h"
42 #include "ui/views/widget/root_view.h"
43 #include "ui/views/widget/tooltip_manager.h"
44 #include "ui/views/widget/widget.h"
47 #include "base/win/scoped_gdi_object.h"
52 // Whether to use accelerated compositing when necessary (e.g. when a view has a
55 bool use_acceleration_when_possible
= true;
57 bool use_acceleration_when_possible
= false;
61 const bool kContextMenuOnMousePress
= false;
63 const bool kContextMenuOnMousePress
= true;
66 // Saves the drawing state, and restores the state when going out of scope.
69 explicit ScopedCanvas(gfx::Canvas
* canvas
) : canvas_(canvas
) {
77 void SetCanvas(gfx::Canvas
* canvas
) {
87 DISALLOW_COPY_AND_ASSIGN(ScopedCanvas
);
90 // Returns the top view in |view|'s hierarchy.
91 const views::View
* GetHierarchyRoot(const views::View
* view
) {
92 const views::View
* root
= view
;
93 while (root
&& root
->parent())
94 root
= root
->parent();
104 // This event handler receives events in the post-target phase and takes care of
106 // - Generates context menu, or initiates drag-and-drop, from gesture events.
107 class PostEventDispatchHandler
: public ui::EventHandler
{
109 explicit PostEventDispatchHandler(View
* owner
)
111 touch_dnd_enabled_(switches::IsTouchDragDropEnabled()) {
113 virtual ~PostEventDispatchHandler() {}
116 // Overridden from ui::EventHandler:
117 virtual void OnGestureEvent(ui::GestureEvent
* event
) OVERRIDE
{
118 DCHECK_EQ(ui::EP_POSTTARGET
, event
->phase());
119 if (event
->handled())
122 if (touch_dnd_enabled_
) {
123 if (event
->type() == ui::ET_GESTURE_LONG_PRESS
&&
124 (!owner_
->drag_controller() ||
125 owner_
->drag_controller()->CanStartDragForView(
126 owner_
, event
->location(), event
->location()))) {
127 if (owner_
->DoDrag(*event
, event
->location(),
128 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH
)) {
129 event
->StopPropagation();
135 if (owner_
->context_menu_controller() &&
136 (event
->type() == ui::ET_GESTURE_LONG_PRESS
||
137 event
->type() == ui::ET_GESTURE_LONG_TAP
||
138 event
->type() == ui::ET_GESTURE_TWO_FINGER_TAP
)) {
139 gfx::Point
location(event
->location());
140 View::ConvertPointToScreen(owner_
, &location
);
141 owner_
->ShowContextMenu(location
, ui::MENU_SOURCE_TOUCH
);
142 event
->StopPropagation();
147 bool touch_dnd_enabled_
;
149 DISALLOW_COPY_AND_ASSIGN(PostEventDispatchHandler
);
152 } // namespace internal
155 ViewsDelegate
* ViewsDelegate::views_delegate
= NULL
;
158 const char View::kViewClassName
[] = "View";
160 ////////////////////////////////////////////////////////////////////////////////
163 // Creation and lifetime -------------------------------------------------------
166 : owned_by_client_(false),
172 notify_enter_exit_on_child_(false),
173 registered_for_visible_bounds_notification_(false),
174 clip_insets_(0, 0, 0, 0),
176 focus_border_(FocusBorder::CreateDashedFocusBorder()),
177 flip_canvas_on_paint_for_rtl_ui_(false),
178 paint_to_layer_(false),
179 accelerator_registration_delayed_(false),
180 accelerator_focus_manager_(NULL
),
181 registered_accelerator_count_(0),
182 next_focusable_view_(NULL
),
183 previous_focusable_view_(NULL
),
185 accessibility_focusable_(false),
186 context_menu_controller_(NULL
),
187 drag_controller_(NULL
),
188 post_dispatch_handler_(new internal::PostEventDispatchHandler(this)),
189 native_view_accessibility_(NULL
) {
190 AddPostTargetHandler(post_dispatch_handler_
.get());
195 parent_
->RemoveChildView(this);
197 for (Views::const_iterator
i(children_
.begin()); i
!= children_
.end(); ++i
) {
198 (*i
)->parent_
= NULL
;
199 if (!(*i
)->owned_by_client_
)
203 // Release ownership of the native accessibility object, but it's
204 // reference-counted on some platforms, so it may not be deleted right away.
205 if (native_view_accessibility_
)
206 native_view_accessibility_
->Destroy();
209 // Tree operations -------------------------------------------------------------
211 const Widget
* View::GetWidget() const {
212 // The root view holds a reference to this view hierarchy's Widget.
213 return parent_
? parent_
->GetWidget() : NULL
;
216 Widget
* View::GetWidget() {
217 return const_cast<Widget
*>(const_cast<const View
*>(this)->GetWidget());
220 void View::AddChildView(View
* view
) {
221 if (view
->parent_
== this)
223 AddChildViewAt(view
, child_count());
226 void View::AddChildViewAt(View
* view
, int index
) {
227 CHECK_NE(view
, this) << "You cannot add a view as its own child";
229 DCHECK_LE(index
, child_count());
231 // If |view| has a parent, remove it from its parent.
232 View
* parent
= view
->parent_
;
233 const ui::NativeTheme
* old_theme
= view
->GetNativeTheme();
235 if (parent
== this) {
236 ReorderChildView(view
, index
);
239 parent
->DoRemoveChildView(view
, true, true, false, this);
242 // Sets the prev/next focus views.
243 InitFocusSiblings(view
, index
);
245 // Let's insert the view.
246 view
->parent_
= this;
247 children_
.insert(children_
.begin() + index
, view
);
249 ViewHierarchyChangedDetails
details(true, this, view
, parent
);
251 for (View
* v
= this; v
; v
= v
->parent_
)
252 v
->ViewHierarchyChangedImpl(false, details
);
254 view
->PropagateAddNotifications(details
);
256 views::Widget
* widget
= GetWidget();
258 RegisterChildrenForVisibleBoundsNotification(view
);
259 const ui::NativeTheme
* new_theme
= widget
->GetNativeTheme();
260 if (new_theme
!= old_theme
)
261 PropagateNativeThemeChanged(new_theme
);
264 if (layout_manager_
.get())
265 layout_manager_
->ViewAdded(this, view
);
267 if (use_acceleration_when_possible
)
270 // Make sure the visibility of the child layers are correct.
271 // If any of the parent View is hidden, then the layers of the subtree
272 // rooted at |this| should be hidden. Otherwise, all the child layers should
273 // inherit the visibility of the owner View.
274 UpdateLayerVisibility();
277 void View::ReorderChildView(View
* view
, int index
) {
278 DCHECK_EQ(view
->parent_
, this);
280 index
= child_count() - 1;
281 else if (index
>= child_count())
283 if (children_
[index
] == view
)
286 const Views::iterator
i(std::find(children_
.begin(), children_
.end(), view
));
287 DCHECK(i
!= children_
.end());
290 // Unlink the view first
291 View
* next_focusable
= view
->next_focusable_view_
;
292 View
* prev_focusable
= view
->previous_focusable_view_
;
294 prev_focusable
->next_focusable_view_
= next_focusable
;
296 next_focusable
->previous_focusable_view_
= prev_focusable
;
298 // Add it in the specified index now.
299 InitFocusSiblings(view
, index
);
300 children_
.insert(children_
.begin() + index
, view
);
302 if (use_acceleration_when_possible
)
306 void View::RemoveChildView(View
* view
) {
307 DoRemoveChildView(view
, true, true, false, NULL
);
310 void View::RemoveAllChildViews(bool delete_children
) {
311 while (!children_
.empty())
312 DoRemoveChildView(children_
.front(), false, false, delete_children
, NULL
);
316 bool View::Contains(const View
* view
) const {
317 for (const View
* v
= view
; v
; v
= v
->parent_
) {
324 int View::GetIndexOf(const View
* view
) const {
325 Views::const_iterator
i(std::find(children_
.begin(), children_
.end(), view
));
326 return i
!= children_
.end() ? static_cast<int>(i
- children_
.begin()) : -1;
329 // Size and disposition --------------------------------------------------------
331 void View::SetBounds(int x
, int y
, int width
, int height
) {
332 SetBoundsRect(gfx::Rect(x
, y
, std::max(0, width
), std::max(0, height
)));
335 void View::SetBoundsRect(const gfx::Rect
& bounds
) {
336 if (bounds
== bounds_
) {
338 needs_layout_
= false;
346 // Paint where the view is currently.
347 SchedulePaintBoundsChanged(
348 bounds_
.size() == bounds
.size() ? SCHEDULE_PAINT_SIZE_SAME
:
349 SCHEDULE_PAINT_SIZE_CHANGED
);
352 gfx::Rect prev
= bounds_
;
357 void View::SetSize(const gfx::Size
& size
) {
358 SetBounds(x(), y(), size
.width(), size
.height());
361 void View::SetPosition(const gfx::Point
& position
) {
362 SetBounds(position
.x(), position
.y(), width(), height());
365 void View::SetX(int x
) {
366 SetBounds(x
, y(), width(), height());
369 void View::SetY(int y
) {
370 SetBounds(x(), y
, width(), height());
373 gfx::Rect
View::GetContentsBounds() const {
374 gfx::Rect
contents_bounds(GetLocalBounds());
376 contents_bounds
.Inset(border_
->GetInsets());
377 return contents_bounds
;
380 gfx::Rect
View::GetLocalBounds() const {
381 return gfx::Rect(size());
384 gfx::Rect
View::GetLayerBoundsInPixel() const {
385 return layer()->GetTargetBounds();
388 gfx::Insets
View::GetInsets() const {
389 return border_
.get() ? border_
->GetInsets() : gfx::Insets();
392 gfx::Rect
View::GetVisibleBounds() const {
395 gfx::Rect
vis_bounds(GetLocalBounds());
396 gfx::Rect ancestor_bounds
;
397 const View
* view
= this;
398 gfx::Transform transform
;
400 while (view
!= NULL
&& !vis_bounds
.IsEmpty()) {
401 transform
.ConcatTransform(view
->GetTransform());
402 gfx::Transform translation
;
403 translation
.Translate(static_cast<float>(view
->GetMirroredX()),
404 static_cast<float>(view
->y()));
405 transform
.ConcatTransform(translation
);
407 vis_bounds
= view
->ConvertRectToParent(vis_bounds
);
408 const View
* ancestor
= view
->parent_
;
409 if (ancestor
!= NULL
) {
410 ancestor_bounds
.SetRect(0, 0, ancestor
->width(), ancestor
->height());
411 vis_bounds
.Intersect(ancestor_bounds
);
412 } else if (!view
->GetWidget()) {
413 // If the view has no Widget, we're not visible. Return an empty rect.
418 if (vis_bounds
.IsEmpty())
420 // Convert back to this views coordinate system.
421 gfx::RectF
views_vis_bounds(vis_bounds
);
422 transform
.TransformRectReverse(&views_vis_bounds
);
423 // Partially visible pixels should be considered visible.
424 return gfx::ToEnclosingRect(views_vis_bounds
);
427 gfx::Rect
View::GetBoundsInScreen() const {
429 View::ConvertPointToScreen(this, &origin
);
430 return gfx::Rect(origin
, size());
433 gfx::Size
View::GetPreferredSize() {
434 if (layout_manager_
.get())
435 return layout_manager_
->GetPreferredSize(this);
439 int View::GetBaseline() const {
443 void View::SizeToPreferredSize() {
444 gfx::Size prefsize
= GetPreferredSize();
445 if ((prefsize
.width() != width()) || (prefsize
.height() != height()))
446 SetBounds(x(), y(), prefsize
.width(), prefsize
.height());
449 gfx::Size
View::GetMinimumSize() {
450 return GetPreferredSize();
453 gfx::Size
View::GetMaximumSize() {
457 int View::GetHeightForWidth(int w
) {
458 if (layout_manager_
.get())
459 return layout_manager_
->GetPreferredHeightForWidth(this, w
);
460 return GetPreferredSize().height();
463 void View::SetVisible(bool visible
) {
464 if (visible
!= visible_
) {
465 // If the View is currently visible, schedule paint to refresh parent.
466 // TODO(beng): not sure we should be doing this if we have a layer.
472 // Notify the parent.
474 parent_
->ChildVisibilityChanged(this);
476 // This notifies all sub-views recursively.
477 PropagateVisibilityNotifications(this, visible_
);
478 UpdateLayerVisibility();
480 // If we are newly visible, schedule paint.
486 bool View::IsDrawn() const {
487 return visible_
&& parent_
? parent_
->IsDrawn() : false;
490 void View::SetEnabled(bool enabled
) {
491 if (enabled
!= enabled_
) {
497 void View::OnEnabledChanged() {
501 // Transformations -------------------------------------------------------------
503 gfx::Transform
View::GetTransform() const {
504 return layer() ? layer()->transform() : gfx::Transform();
507 void View::SetTransform(const gfx::Transform
& transform
) {
508 if (transform
.IsIdentity()) {
510 layer()->SetTransform(transform
);
511 if (!paint_to_layer_
)
519 layer()->SetTransform(transform
);
520 layer()->ScheduleDraw();
524 void View::SetPaintToLayer(bool paint_to_layer
) {
525 paint_to_layer_
= paint_to_layer
;
526 if (paint_to_layer_
&& !layer()) {
528 } else if (!paint_to_layer_
&& layer()) {
533 ui::Layer
* View::RecreateLayer() {
534 ui::Layer
* layer
= AcquireLayer();
539 layer_
->set_scale_content(layer
->scale_content());
543 // RTL positioning -------------------------------------------------------------
545 gfx::Rect
View::GetMirroredBounds() const {
546 gfx::Rect
bounds(bounds_
);
547 bounds
.set_x(GetMirroredX());
551 gfx::Point
View::GetMirroredPosition() const {
552 return gfx::Point(GetMirroredX(), y());
555 int View::GetMirroredX() const {
556 return parent_
? parent_
->GetMirroredXForRect(bounds_
) : x();
559 int View::GetMirroredXForRect(const gfx::Rect
& bounds
) const {
560 return base::i18n::IsRTL() ?
561 (width() - bounds
.x() - bounds
.width()) : bounds
.x();
564 int View::GetMirroredXInView(int x
) const {
565 return base::i18n::IsRTL() ? width() - x
: x
;
568 int View::GetMirroredXWithWidthInView(int x
, int w
) const {
569 return base::i18n::IsRTL() ? width() - x
- w
: x
;
572 // Layout ----------------------------------------------------------------------
574 void View::Layout() {
575 needs_layout_
= false;
577 // If we have a layout manager, let it handle the layout for us.
578 if (layout_manager_
.get())
579 layout_manager_
->Layout(this);
581 // Make sure to propagate the Layout() call to any children that haven't
582 // received it yet through the layout manager and need to be laid out. This
583 // is needed for the case when the child requires a layout but its bounds
584 // weren't changed by the layout manager. If there is no layout manager, we
585 // just propagate the Layout() call down the hierarchy, so whoever receives
586 // the call can take appropriate action.
587 for (int i
= 0, count
= child_count(); i
< count
; ++i
) {
588 View
* child
= child_at(i
);
589 if (child
->needs_layout_
|| !layout_manager_
.get()) {
590 child
->needs_layout_
= false;
596 void View::InvalidateLayout() {
597 // Always invalidate up. This is needed to handle the case of us already being
598 // valid, but not our parent.
599 needs_layout_
= true;
601 parent_
->InvalidateLayout();
604 LayoutManager
* View::GetLayoutManager() const {
605 return layout_manager_
.get();
608 void View::SetLayoutManager(LayoutManager
* layout_manager
) {
609 if (layout_manager_
.get())
610 layout_manager_
->Uninstalled(this);
612 layout_manager_
.reset(layout_manager
);
613 if (layout_manager_
.get())
614 layout_manager_
->Installed(this);
617 // Attributes ------------------------------------------------------------------
619 const char* View::GetClassName() const {
620 return kViewClassName
;
623 View
* View::GetAncestorWithClassName(const std::string
& name
) {
624 for (View
* view
= this; view
; view
= view
->parent_
) {
625 if (!strcmp(view
->GetClassName(), name
.c_str()))
631 const View
* View::GetViewByID(int id
) const {
633 return const_cast<View
*>(this);
635 for (int i
= 0, count
= child_count(); i
< count
; ++i
) {
636 const View
* view
= child_at(i
)->GetViewByID(id
);
643 View
* View::GetViewByID(int id
) {
644 return const_cast<View
*>(const_cast<const View
*>(this)->GetViewByID(id
));
647 void View::SetGroup(int gid
) {
648 // Don't change the group id once it's set.
649 DCHECK(group_
== -1 || group_
== gid
);
653 int View::GetGroup() const {
657 bool View::IsGroupFocusTraversable() const {
661 void View::GetViewsInGroup(int group
, Views
* views
) {
663 views
->push_back(this);
665 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
666 child_at(i
)->GetViewsInGroup(group
, views
);
669 View
* View::GetSelectedViewForGroup(int group
) {
671 GetWidget()->GetRootView()->GetViewsInGroup(group
, &views
);
672 return views
.empty() ? NULL
: views
[0];
675 // Coordinate conversion -------------------------------------------------------
678 void View::ConvertPointToTarget(const View
* source
,
681 if (source
== target
)
684 // |source| can be NULL.
685 const View
* root
= GetHierarchyRoot(target
);
687 CHECK_EQ(GetHierarchyRoot(source
), root
);
690 source
->ConvertPointForAncestor(root
, point
);
694 target
->ConvertPointFromAncestor(root
, point
);
696 // API defines NULL |source| as returning the point in screen coordinates.
699 root
->GetWidget()->GetClientAreaBoundsInScreen().OffsetFromOrigin();
704 void View::ConvertPointToWidget(const View
* src
, gfx::Point
* p
) {
708 src
->ConvertPointForAncestor(NULL
, p
);
712 void View::ConvertPointFromWidget(const View
* dest
, gfx::Point
* p
) {
716 dest
->ConvertPointFromAncestor(NULL
, p
);
720 void View::ConvertPointToScreen(const View
* src
, gfx::Point
* p
) {
724 // If the view is not connected to a tree, there's nothing we can do.
725 const Widget
* widget
= src
->GetWidget();
727 ConvertPointToWidget(src
, p
);
728 *p
+= widget
->GetClientAreaBoundsInScreen().OffsetFromOrigin();
733 void View::ConvertPointFromScreen(const View
* dst
, gfx::Point
* p
) {
737 const views::Widget
* widget
= dst
->GetWidget();
740 *p
-= widget
->GetClientAreaBoundsInScreen().OffsetFromOrigin();
741 views::View::ConvertPointFromWidget(dst
, p
);
744 gfx::Rect
View::ConvertRectToParent(const gfx::Rect
& rect
) const {
745 gfx::RectF x_rect
= rect
;
746 GetTransform().TransformRect(&x_rect
);
747 x_rect
.Offset(GetMirroredPosition().OffsetFromOrigin());
748 // Pixels we partially occupy in the parent should be included.
749 return gfx::ToEnclosingRect(x_rect
);
752 gfx::Rect
View::ConvertRectToWidget(const gfx::Rect
& rect
) const {
753 gfx::Rect x_rect
= rect
;
754 for (const View
* v
= this; v
; v
= v
->parent_
)
755 x_rect
= v
->ConvertRectToParent(x_rect
);
759 // Painting --------------------------------------------------------------------
761 void View::SchedulePaint() {
762 SchedulePaintInRect(GetLocalBounds());
765 void View::SchedulePaintInRect(const gfx::Rect
& rect
) {
770 layer()->SchedulePaint(rect
);
771 } else if (parent_
) {
772 // Translate the requested paint rect to the parent's coordinate system
773 // then pass this notification up to the parent.
774 parent_
->SchedulePaintInRect(ConvertRectToParent(rect
));
778 void View::Paint(gfx::Canvas
* canvas
) {
779 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
781 ScopedCanvas
scoped_canvas(canvas
);
783 // Paint this View and its children, setting the clip rect to the bounds
784 // of this View and translating the origin to the local bounds' top left
787 // Note that the X (or left) position we pass to ClipRectInt takes into
788 // consideration whether or not the view uses a right-to-left layout so that
789 // we paint our view in its mirrored position if need be.
790 gfx::Rect clip_rect
= bounds();
791 clip_rect
.Inset(clip_insets_
);
793 clip_rect
.set_x(parent_
->GetMirroredXForRect(clip_rect
));
794 if (!canvas
->ClipRect(clip_rect
))
797 // Non-empty clip, translate the graphics such that 0,0 corresponds to
798 // where this view is located (related to its parent).
799 canvas
->Translate(GetMirroredPosition().OffsetFromOrigin());
800 canvas
->Transform(GetTransform());
805 ui::ThemeProvider
* View::GetThemeProvider() const {
806 const Widget
* widget
= GetWidget();
807 return widget
? widget
->GetThemeProvider() : NULL
;
810 const ui::NativeTheme
* View::GetNativeTheme() const {
811 const Widget
* widget
= GetWidget();
812 return widget
? widget
->GetNativeTheme() : ui::NativeTheme::instance();
815 // Accelerated Painting --------------------------------------------------------
818 void View::set_use_acceleration_when_possible(bool use
) {
819 use_acceleration_when_possible
= use
;
823 bool View::get_use_acceleration_when_possible() {
824 return use_acceleration_when_possible
;
827 // Input -----------------------------------------------------------------------
829 View
* View::GetEventHandlerForPoint(const gfx::Point
& point
) {
830 // Walk the child Views recursively looking for the View that most
831 // tightly encloses the specified point.
832 for (int i
= child_count() - 1; i
>= 0; --i
) {
833 View
* child
= child_at(i
);
834 if (!child
->visible())
837 gfx::Point
point_in_child_coords(point
);
838 ConvertPointToTarget(this, child
, &point_in_child_coords
);
839 if (child
->HitTestPoint(point_in_child_coords
))
840 return child
->GetEventHandlerForPoint(point_in_child_coords
);
845 View
* View::GetTooltipHandlerForPoint(const gfx::Point
& point
) {
846 if (!HitTestPoint(point
))
849 // Walk the child Views recursively looking for the View that most
850 // tightly encloses the specified point.
851 for (int i
= child_count() - 1; i
>= 0; --i
) {
852 View
* child
= child_at(i
);
853 if (!child
->visible())
856 gfx::Point
point_in_child_coords(point
);
857 ConvertPointToTarget(this, child
, &point_in_child_coords
);
858 View
* handler
= child
->GetTooltipHandlerForPoint(point_in_child_coords
);
865 gfx::NativeCursor
View::GetCursor(const ui::MouseEvent
& event
) {
867 #if defined(USE_AURA)
868 static ui::Cursor arrow
;
869 if (!arrow
.platform())
870 arrow
.SetPlatformCursor(LoadCursor(NULL
, IDC_ARROW
));
873 static HCURSOR arrow
= LoadCursor(NULL
, IDC_ARROW
);
877 return gfx::kNullCursor
;
881 bool View::HitTestPoint(const gfx::Point
& point
) const {
882 return HitTestRect(gfx::Rect(point
, gfx::Size(1, 1)));
885 bool View::HitTestRect(const gfx::Rect
& rect
) const {
886 if (GetLocalBounds().Intersects(rect
)) {
887 if (HasHitTestMask()) {
889 GetHitTestMask(&mask
);
890 #if defined(USE_AURA)
891 // TODO: should we use this every where?
892 SkRegion clip_region
;
893 clip_region
.setRect(0, 0, width(), height());
894 SkRegion mask_region
;
895 return mask_region
.setPath(mask
, clip_region
) &&
896 mask_region
.intersects(RectToSkIRect(rect
));
897 #elif defined(OS_WIN)
898 base::win::ScopedRegion
rgn(mask
.CreateNativeRegion());
899 const RECT
r(rect
.ToRECT());
900 return RectInRegion(rgn
, &r
) != 0;
903 // No mask, but inside our bounds.
906 // Outside our bounds.
910 bool View::IsMouseHovered() {
911 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
916 // If mouse events are disabled, then the mouse cursor is invisible and
917 // is therefore not hovering over this button.
918 if (!GetWidget()->IsMouseEventsEnabled())
921 gfx::Point
cursor_pos(gfx::Screen::GetScreenFor(
922 GetWidget()->GetNativeView())->GetCursorScreenPoint());
923 ConvertPointToTarget(NULL
, this, &cursor_pos
);
924 return HitTestPoint(cursor_pos
);
927 bool View::OnMousePressed(const ui::MouseEvent
& event
) {
931 bool View::OnMouseDragged(const ui::MouseEvent
& event
) {
935 void View::OnMouseReleased(const ui::MouseEvent
& event
) {
938 void View::OnMouseCaptureLost() {
941 void View::OnMouseMoved(const ui::MouseEvent
& event
) {
944 void View::OnMouseEntered(const ui::MouseEvent
& event
) {
947 void View::OnMouseExited(const ui::MouseEvent
& event
) {
950 void View::SetMouseHandler(View
* new_mouse_handler
) {
951 // |new_mouse_handler| may be NULL.
953 parent_
->SetMouseHandler(new_mouse_handler
);
956 bool View::OnKeyPressed(const ui::KeyEvent
& event
) {
960 bool View::OnKeyReleased(const ui::KeyEvent
& event
) {
964 bool View::OnMouseWheel(const ui::MouseWheelEvent
& event
) {
968 void View::OnKeyEvent(ui::KeyEvent
* event
) {
969 bool consumed
= (event
->type() == ui::ET_KEY_PRESSED
) ? OnKeyPressed(*event
) :
970 OnKeyReleased(*event
);
972 event
->StopPropagation();
975 void View::OnMouseEvent(ui::MouseEvent
* event
) {
976 switch (event
->type()) {
977 case ui::ET_MOUSE_PRESSED
:
978 if (ProcessMousePressed(*event
))
982 case ui::ET_MOUSE_MOVED
:
983 if ((event
->flags() & (ui::EF_LEFT_MOUSE_BUTTON
|
984 ui::EF_RIGHT_MOUSE_BUTTON
|
985 ui::EF_MIDDLE_MOUSE_BUTTON
)) == 0) {
986 OnMouseMoved(*event
);
990 case ui::ET_MOUSE_DRAGGED
:
991 if (ProcessMouseDragged(*event
))
995 case ui::ET_MOUSE_RELEASED
:
996 ProcessMouseReleased(*event
);
999 case ui::ET_MOUSEWHEEL
:
1000 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent
*>(event
)))
1001 event
->SetHandled();
1004 case ui::ET_MOUSE_ENTERED
:
1005 OnMouseEntered(*event
);
1008 case ui::ET_MOUSE_EXITED
:
1009 OnMouseExited(*event
);
1017 void View::OnScrollEvent(ui::ScrollEvent
* event
) {
1020 void View::OnTouchEvent(ui::TouchEvent
* event
) {
1023 void View::OnGestureEvent(ui::GestureEvent
* event
) {
1026 ui::TextInputClient
* View::GetTextInputClient() {
1030 InputMethod
* View::GetInputMethod() {
1031 Widget
* widget
= GetWidget();
1032 return widget
? widget
->GetInputMethod() : NULL
;
1035 bool View::CanAcceptEvent(const ui::Event
& event
) {
1036 return event
.dispatch_to_hidden_targets() || IsDrawn();
1039 ui::EventTarget
* View::GetParentTarget() {
1043 // Accelerators ----------------------------------------------------------------
1045 void View::AddAccelerator(const ui::Accelerator
& accelerator
) {
1046 if (!accelerators_
.get())
1047 accelerators_
.reset(new std::vector
<ui::Accelerator
>());
1049 if (std::find(accelerators_
->begin(), accelerators_
->end(), accelerator
) ==
1050 accelerators_
->end()) {
1051 accelerators_
->push_back(accelerator
);
1053 RegisterPendingAccelerators();
1056 void View::RemoveAccelerator(const ui::Accelerator
& accelerator
) {
1057 if (!accelerators_
.get()) {
1058 NOTREACHED() << "Removing non-existing accelerator";
1062 std::vector
<ui::Accelerator
>::iterator
i(
1063 std::find(accelerators_
->begin(), accelerators_
->end(), accelerator
));
1064 if (i
== accelerators_
->end()) {
1065 NOTREACHED() << "Removing non-existing accelerator";
1069 size_t index
= i
- accelerators_
->begin();
1070 accelerators_
->erase(i
);
1071 if (index
>= registered_accelerator_count_
) {
1072 // The accelerator is not registered to FocusManager.
1075 --registered_accelerator_count_
;
1077 // Providing we are attached to a Widget and registered with a focus manager,
1078 // we should de-register from that focus manager now.
1079 if (GetWidget() && accelerator_focus_manager_
)
1080 accelerator_focus_manager_
->UnregisterAccelerator(accelerator
, this);
1083 void View::ResetAccelerators() {
1084 if (accelerators_
.get())
1085 UnregisterAccelerators(false);
1088 bool View::AcceleratorPressed(const ui::Accelerator
& accelerator
) {
1092 bool View::CanHandleAccelerators() const {
1093 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1096 // Focus -----------------------------------------------------------------------
1098 bool View::HasFocus() const {
1099 const FocusManager
* focus_manager
= GetFocusManager();
1100 return focus_manager
&& (focus_manager
->GetFocusedView() == this);
1103 View
* View::GetNextFocusableView() {
1104 return next_focusable_view_
;
1107 const View
* View::GetNextFocusableView() const {
1108 return next_focusable_view_
;
1111 View
* View::GetPreviousFocusableView() {
1112 return previous_focusable_view_
;
1115 void View::SetNextFocusableView(View
* view
) {
1117 view
->previous_focusable_view_
= this;
1118 next_focusable_view_
= view
;
1121 bool View::IsFocusable() const {
1122 return focusable_
&& enabled_
&& IsDrawn();
1125 bool View::IsAccessibilityFocusable() const {
1126 return (focusable_
|| accessibility_focusable_
) && enabled_
&& IsDrawn();
1129 FocusManager
* View::GetFocusManager() {
1130 Widget
* widget
= GetWidget();
1131 return widget
? widget
->GetFocusManager() : NULL
;
1134 const FocusManager
* View::GetFocusManager() const {
1135 const Widget
* widget
= GetWidget();
1136 return widget
? widget
->GetFocusManager() : NULL
;
1139 void View::RequestFocus() {
1140 FocusManager
* focus_manager
= GetFocusManager();
1141 if (focus_manager
&& IsFocusable())
1142 focus_manager
->SetFocusedView(this);
1145 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent
& event
) {
1149 FocusTraversable
* View::GetFocusTraversable() {
1153 FocusTraversable
* View::GetPaneFocusTraversable() {
1157 // Tooltips --------------------------------------------------------------------
1159 bool View::GetTooltipText(const gfx::Point
& p
, string16
* tooltip
) const {
1163 bool View::GetTooltipTextOrigin(const gfx::Point
& p
, gfx::Point
* loc
) const {
1167 // Context menus ---------------------------------------------------------------
1169 void View::ShowContextMenu(const gfx::Point
& p
,
1170 ui::MenuSourceType source_type
) {
1171 if (!context_menu_controller_
)
1174 context_menu_controller_
->ShowContextMenuForView(this, p
, source_type
);
1178 bool View::ShouldShowContextMenuOnMousePress() {
1179 return kContextMenuOnMousePress
;
1182 // Drag and drop ---------------------------------------------------------------
1184 bool View::GetDropFormats(
1186 std::set
<OSExchangeData::CustomFormat
>* custom_formats
) {
1190 bool View::AreDropTypesRequired() {
1194 bool View::CanDrop(const OSExchangeData
& data
) {
1195 // TODO(sky): when I finish up migration, this should default to true.
1199 void View::OnDragEntered(const ui::DropTargetEvent
& event
) {
1202 int View::OnDragUpdated(const ui::DropTargetEvent
& event
) {
1203 return ui::DragDropTypes::DRAG_NONE
;
1206 void View::OnDragExited() {
1209 int View::OnPerformDrop(const ui::DropTargetEvent
& event
) {
1210 return ui::DragDropTypes::DRAG_NONE
;
1213 void View::OnDragDone() {
1217 bool View::ExceededDragThreshold(const gfx::Vector2d
& delta
) {
1218 return (abs(delta
.x()) > GetHorizontalDragThreshold() ||
1219 abs(delta
.y()) > GetVerticalDragThreshold());
1222 // Accessibility----------------------------------------------------------------
1224 gfx::NativeViewAccessible
View::GetNativeViewAccessible() {
1225 if (!native_view_accessibility_
)
1226 native_view_accessibility_
= NativeViewAccessibility::Create(this);
1227 if (native_view_accessibility_
)
1228 return native_view_accessibility_
->GetNativeObject();
1232 void View::NotifyAccessibilityEvent(
1233 ui::AccessibilityTypes::Event event_type
,
1234 bool send_native_event
) {
1235 if (ViewsDelegate::views_delegate
)
1236 ViewsDelegate::views_delegate
->NotifyAccessibilityEvent(this, event_type
);
1238 if (send_native_event
) {
1239 if (!native_view_accessibility_
)
1240 native_view_accessibility_
= NativeViewAccessibility::Create(this);
1241 if (native_view_accessibility_
)
1242 native_view_accessibility_
->NotifyAccessibilityEvent(event_type
);
1246 // Scrolling -------------------------------------------------------------------
1248 void View::ScrollRectToVisible(const gfx::Rect
& rect
) {
1249 // We must take RTL UI mirroring into account when adjusting the position of
1252 gfx::Rect
scroll_rect(rect
);
1253 scroll_rect
.Offset(GetMirroredX(), y());
1254 parent_
->ScrollRectToVisible(scroll_rect
);
1258 int View::GetPageScrollIncrement(ScrollView
* scroll_view
,
1259 bool is_horizontal
, bool is_positive
) {
1263 int View::GetLineScrollIncrement(ScrollView
* scroll_view
,
1264 bool is_horizontal
, bool is_positive
) {
1268 ////////////////////////////////////////////////////////////////////////////////
1271 // Size and disposition --------------------------------------------------------
1273 void View::OnBoundsChanged(const gfx::Rect
& previous_bounds
) {
1276 void View::PreferredSizeChanged() {
1279 parent_
->ChildPreferredSizeChanged(this);
1282 bool View::NeedsNotificationWhenVisibleBoundsChange() const {
1286 void View::OnVisibleBoundsChanged() {
1289 // Tree operations -------------------------------------------------------------
1291 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails
& details
) {
1294 void View::VisibilityChanged(View
* starting_from
, bool is_visible
) {
1297 void View::NativeViewHierarchyChanged(bool attached
,
1298 gfx::NativeView native_view
,
1299 internal::RootView
* root_view
) {
1300 FocusManager
* focus_manager
= GetFocusManager();
1301 if (!accelerator_registration_delayed_
&&
1302 accelerator_focus_manager_
&&
1303 accelerator_focus_manager_
!= focus_manager
) {
1304 UnregisterAccelerators(true);
1305 accelerator_registration_delayed_
= true;
1307 if (accelerator_registration_delayed_
&& attached
) {
1308 if (focus_manager
) {
1309 RegisterPendingAccelerators();
1310 accelerator_registration_delayed_
= false;
1315 // Painting --------------------------------------------------------------------
1317 void View::PaintChildren(gfx::Canvas
* canvas
) {
1318 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1319 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1320 if (!child_at(i
)->layer())
1321 child_at(i
)->Paint(canvas
);
1324 void View::OnPaint(gfx::Canvas
* canvas
) {
1325 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1326 OnPaintBackground(canvas
);
1327 OnPaintFocusBorder(canvas
);
1328 OnPaintBorder(canvas
);
1331 void View::OnPaintBackground(gfx::Canvas
* canvas
) {
1332 if (background_
.get()) {
1333 TRACE_EVENT2("views", "View::OnPaintBackground",
1334 "width", canvas
->sk_canvas()->getDevice()->width(),
1335 "height", canvas
->sk_canvas()->getDevice()->height());
1336 background_
->Paint(canvas
, this);
1340 void View::OnPaintBorder(gfx::Canvas
* canvas
) {
1341 if (border_
.get()) {
1342 TRACE_EVENT2("views", "View::OnPaintBorder",
1343 "width", canvas
->sk_canvas()->getDevice()->width(),
1344 "height", canvas
->sk_canvas()->getDevice()->height());
1345 border_
->Paint(*this, canvas
);
1349 void View::OnPaintFocusBorder(gfx::Canvas
* canvas
) {
1350 if (focus_border_
.get() &&
1351 HasFocus() && (focusable() || IsAccessibilityFocusable())) {
1352 TRACE_EVENT2("views", "views::OnPaintFocusBorder",
1353 "width", canvas
->sk_canvas()->getDevice()->width(),
1354 "height", canvas
->sk_canvas()->getDevice()->height());
1355 focus_border_
->Paint(*this, canvas
);
1359 // Accelerated Painting --------------------------------------------------------
1361 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely
) {
1362 // This method should not have the side-effect of creating the layer.
1364 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely
);
1367 bool View::SetExternalTexture(ui::Texture
* texture
) {
1369 SetPaintToLayer(true);
1371 layer()->SetExternalTexture(texture
);
1373 // Child views must not paint into the external texture. So make sure each
1374 // child view has its own layer to paint into.
1375 for (Views::iterator i
= children_
.begin(); i
!= children_
.end(); ++i
)
1376 (*i
)->SetPaintToLayer(true);
1378 SchedulePaintInRect(GetLocalBounds());
1382 gfx::Vector2d
View::CalculateOffsetToAncestorWithLayer(
1383 ui::Layer
** layer_parent
) {
1386 *layer_parent
= layer();
1387 return gfx::Vector2d();
1390 return gfx::Vector2d();
1392 return gfx::Vector2d(GetMirroredX(), y()) +
1393 parent_
->CalculateOffsetToAncestorWithLayer(layer_parent
);
1396 void View::UpdateParentLayer() {
1400 ui::Layer
* parent_layer
= NULL
;
1401 gfx::Vector2d
offset(GetMirroredX(), y());
1404 offset
+= parent_
->CalculateOffsetToAncestorWithLayer(&parent_layer
);
1406 ReparentLayer(offset
, parent_layer
);
1409 void View::MoveLayerToParent(ui::Layer
* parent_layer
,
1410 const gfx::Point
& point
) {
1411 gfx::Point
local_point(point
);
1412 if (parent_layer
!= layer())
1413 local_point
.Offset(GetMirroredX(), y());
1414 if (layer() && parent_layer
!= layer()) {
1415 parent_layer
->Add(layer());
1416 SetLayerBounds(gfx::Rect(local_point
.x(), local_point
.y(),
1417 width(), height()));
1419 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1420 child_at(i
)->MoveLayerToParent(parent_layer
, local_point
);
1424 void View::UpdateLayerVisibility() {
1425 if (!use_acceleration_when_possible
)
1427 bool visible
= visible_
;
1428 for (const View
* v
= parent_
; visible
&& v
&& !v
->layer(); v
= v
->parent_
)
1429 visible
= v
->visible();
1431 UpdateChildLayerVisibility(visible
);
1434 void View::UpdateChildLayerVisibility(bool ancestor_visible
) {
1436 layer()->SetVisible(ancestor_visible
&& visible_
);
1438 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1439 child_at(i
)->UpdateChildLayerVisibility(ancestor_visible
&& visible_
);
1443 void View::UpdateChildLayerBounds(const gfx::Vector2d
& offset
) {
1445 SetLayerBounds(GetLocalBounds() + offset
);
1447 for (int i
= 0, count
= child_count(); i
< count
; ++i
) {
1448 View
* child
= child_at(i
);
1449 child
->UpdateChildLayerBounds(
1450 offset
+ gfx::Vector2d(child
->GetMirroredX(), child
->y()));
1455 void View::OnPaintLayer(gfx::Canvas
* canvas
) {
1456 if (!layer() || !layer()->fills_bounds_opaquely())
1457 canvas
->DrawColor(SK_ColorBLACK
, SkXfermode::kClear_Mode
);
1458 PaintCommon(canvas
);
1461 void View::OnDeviceScaleFactorChanged(float device_scale_factor
) {
1462 // Repainting with new scale factor will paint the content at the right scale.
1465 base::Closure
View::PrepareForLayerBoundsChange() {
1466 return base::Closure();
1469 void View::ReorderLayers() {
1471 while (v
&& !v
->layer())
1474 Widget
* widget
= GetWidget();
1477 ui::Layer
* layer
= widget
->GetLayer();
1479 widget
->GetRootView()->ReorderChildLayers(layer
);
1482 v
->ReorderChildLayers(v
->layer());
1486 // Reorder the widget's child NativeViews in case a child NativeView is
1487 // associated with a view (eg via a NativeViewHost). Always do the
1488 // reordering because the associated NativeView's layer (if it has one)
1489 // is parented to the widget's layer regardless of whether the host view has
1490 // an ancestor with a layer.
1491 widget
->ReorderNativeViews();
1495 void View::ReorderChildLayers(ui::Layer
* parent_layer
) {
1496 if (layer() && layer() != parent_layer
) {
1497 DCHECK_EQ(parent_layer
, layer()->parent());
1498 parent_layer
->StackAtBottom(layer());
1500 // Iterate backwards through the children so that a child with a layer
1501 // which is further to the back is stacked above one which is further to
1503 for (Views::const_reverse_iterator
it(children_
.rbegin());
1504 it
!= children_
.rend(); ++it
) {
1505 (*it
)->ReorderChildLayers(parent_layer
);
1510 // Input -----------------------------------------------------------------------
1512 bool View::HasHitTestMask() const {
1516 void View::GetHitTestMask(gfx::Path
* mask
) const {
1520 View::DragInfo
* View::GetDragInfo() {
1521 return parent_
? parent_
->GetDragInfo() : NULL
;
1524 // Focus -----------------------------------------------------------------------
1526 void View::OnFocus() {
1527 // TODO(beng): Investigate whether it's possible for us to move this to
1529 // By default, we clear the native focus. This ensures that no visible native
1530 // view as the focus and that we still receive keyboard inputs.
1531 FocusManager
* focus_manager
= GetFocusManager();
1533 focus_manager
->ClearNativeFocus();
1535 // TODO(beng): Investigate whether it's possible for us to move this to
1537 // Notify assistive technologies of the focus change.
1538 NotifyAccessibilityEvent(ui::AccessibilityTypes::EVENT_FOCUS
, true);
1541 void View::OnBlur() {
1544 void View::Focus() {
1554 // Tooltips --------------------------------------------------------------------
1556 void View::TooltipTextChanged() {
1557 Widget
* widget
= GetWidget();
1558 // TooltipManager may be null if there is a problem creating it.
1559 if (widget
&& widget
->native_widget_private()->GetTooltipManager()) {
1560 widget
->native_widget_private()->GetTooltipManager()->
1561 TooltipTextChanged(this);
1565 // Context menus ---------------------------------------------------------------
1567 gfx::Point
View::GetKeyboardContextMenuLocation() {
1568 gfx::Rect vis_bounds
= GetVisibleBounds();
1569 gfx::Point
screen_point(vis_bounds
.x() + vis_bounds
.width() / 2,
1570 vis_bounds
.y() + vis_bounds
.height() / 2);
1571 ConvertPointToScreen(this, &screen_point
);
1572 return screen_point
;
1575 // Drag and drop ---------------------------------------------------------------
1577 int View::GetDragOperations(const gfx::Point
& press_pt
) {
1578 return drag_controller_
?
1579 drag_controller_
->GetDragOperationsForView(this, press_pt
) :
1580 ui::DragDropTypes::DRAG_NONE
;
1583 void View::WriteDragData(const gfx::Point
& press_pt
, OSExchangeData
* data
) {
1584 DCHECK(drag_controller_
);
1585 drag_controller_
->WriteDragDataForView(this, press_pt
, data
);
1588 bool View::InDrag() {
1589 Widget
* widget
= GetWidget();
1590 return widget
? widget
->dragged_view() == this : false;
1593 // Debugging -------------------------------------------------------------------
1595 #if !defined(NDEBUG)
1597 std::string
View::PrintViewGraph(bool first
) {
1598 return DoPrintViewGraph(first
, this);
1601 std::string
View::DoPrintViewGraph(bool first
, View
* view_with_children
) {
1602 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1603 const size_t kMaxPointerStringLength
= 19;
1608 result
.append("digraph {\n");
1610 // Node characteristics.
1611 char p
[kMaxPointerStringLength
];
1613 const std::string
class_name(GetClassName());
1614 size_t base_name_index
= class_name
.find_last_of('/');
1615 if (base_name_index
== std::string::npos
)
1616 base_name_index
= 0;
1620 char bounds_buffer
[512];
1622 // Information about current node.
1623 base::snprintf(p
, arraysize(bounds_buffer
), "%p", view_with_children
);
1624 result
.append(" N");
1625 result
.append(p
+ 2);
1626 result
.append(" [label=\"");
1628 result
.append(class_name
.substr(base_name_index
).c_str());
1630 base::snprintf(bounds_buffer
,
1631 arraysize(bounds_buffer
),
1632 "\\n bounds: (%d, %d), (%dx%d)",
1637 result
.append(bounds_buffer
);
1639 gfx::DecomposedTransform decomp
;
1640 if (!GetTransform().IsIdentity() &&
1641 gfx::DecomposeTransform(&decomp
, GetTransform())) {
1642 base::snprintf(bounds_buffer
,
1643 arraysize(bounds_buffer
),
1644 "\\n translation: (%f, %f)",
1645 decomp
.translate
[0],
1646 decomp
.translate
[1]);
1647 result
.append(bounds_buffer
);
1649 base::snprintf(bounds_buffer
,
1650 arraysize(bounds_buffer
),
1651 "\\n rotation: %3.2f",
1652 std::acos(decomp
.quaternion
[3]) * 360.0 / M_PI
);
1653 result
.append(bounds_buffer
);
1655 base::snprintf(bounds_buffer
,
1656 arraysize(bounds_buffer
),
1657 "\\n scale: (%2.4f, %2.4f)",
1660 result
.append(bounds_buffer
);
1663 result
.append("\"");
1665 result
.append(", shape=box");
1667 if (layer()->texture())
1668 result
.append(", color=green");
1670 result
.append(", color=red");
1672 if (layer()->fills_bounds_opaquely())
1673 result
.append(", style=filled");
1675 result
.append("]\n");
1679 char pp
[kMaxPointerStringLength
];
1681 base::snprintf(pp
, kMaxPointerStringLength
, "%p", parent_
);
1682 result
.append(" N");
1683 result
.append(pp
+ 2);
1684 result
.append(" -> N");
1685 result
.append(p
+ 2);
1686 result
.append("\n");
1690 for (int i
= 0, count
= view_with_children
->child_count(); i
< count
; ++i
)
1691 result
.append(view_with_children
->child_at(i
)->PrintViewGraph(false));
1694 result
.append("}\n");
1701 ////////////////////////////////////////////////////////////////////////////////
1704 // DropInfo --------------------------------------------------------------------
1706 void View::DragInfo::Reset() {
1707 possible_drag
= false;
1708 start_pt
= gfx::Point();
1711 void View::DragInfo::PossibleDrag(const gfx::Point
& p
) {
1712 possible_drag
= true;
1716 // Painting --------------------------------------------------------------------
1718 void View::SchedulePaintBoundsChanged(SchedulePaintType type
) {
1719 // If we have a layer and the View's size did not change, we do not need to
1720 // schedule any paints since the layer will be redrawn at its new location
1721 // during the next Draw() cycle in the compositor.
1722 if (!layer() || type
== SCHEDULE_PAINT_SIZE_CHANGED
) {
1723 // Otherwise, if the size changes or we don't have a layer then we need to
1724 // use SchedulePaint to invalidate the area occupied by the View.
1726 } else if (parent_
&& type
== SCHEDULE_PAINT_SIZE_SAME
) {
1727 // The compositor doesn't Draw() until something on screen changes, so
1728 // if our position changes but nothing is being animated on screen, then
1729 // tell the compositor to redraw the scene. We know layer() exists due to
1730 // the above if clause.
1731 layer()->ScheduleDraw();
1735 void View::PaintCommon(gfx::Canvas
* canvas
) {
1740 // If the View we are about to paint requested the canvas to be flipped, we
1741 // should change the transform appropriately.
1742 // The canvas mirroring is undone once the View is done painting so that we
1743 // don't pass the canvas with the mirrored transform to Views that didn't
1744 // request the canvas to be flipped.
1745 ScopedCanvas
scoped(canvas
);
1746 if (FlipCanvasOnPaintForRTLUI()) {
1747 canvas
->Translate(gfx::Vector2d(width(), 0));
1748 canvas
->Scale(-1, 1);
1754 PaintChildren(canvas
);
1757 // Tree operations -------------------------------------------------------------
1759 void View::DoRemoveChildView(View
* view
,
1760 bool update_focus_cycle
,
1761 bool update_tool_tip
,
1762 bool delete_removed_view
,
1765 const Views::iterator
i(std::find(children_
.begin(), children_
.end(), view
));
1766 scoped_ptr
<View
> view_to_be_deleted
;
1767 if (i
!= children_
.end()) {
1768 if (update_focus_cycle
) {
1769 // Let's remove the view from the focus traversal.
1770 View
* next_focusable
= view
->next_focusable_view_
;
1771 View
* prev_focusable
= view
->previous_focusable_view_
;
1773 prev_focusable
->next_focusable_view_
= next_focusable
;
1775 next_focusable
->previous_focusable_view_
= prev_focusable
;
1779 UnregisterChildrenForVisibleBoundsNotification(view
);
1780 view
->PropagateRemoveNotifications(this, new_parent
);
1781 view
->parent_
= NULL
;
1782 view
->UpdateLayerVisibility();
1784 if (delete_removed_view
&& !view
->owned_by_client_
)
1785 view_to_be_deleted
.reset(view
);
1790 if (update_tool_tip
)
1793 if (layout_manager_
.get())
1794 layout_manager_
->ViewRemoved(this, view
);
1797 void View::PropagateRemoveNotifications(View
* old_parent
, View
* new_parent
) {
1798 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1799 child_at(i
)->PropagateRemoveNotifications(old_parent
, new_parent
);
1801 ViewHierarchyChangedDetails
details(false, old_parent
, this, new_parent
);
1802 for (View
* v
= this; v
; v
= v
->parent_
)
1803 v
->ViewHierarchyChangedImpl(true, details
);
1806 void View::PropagateAddNotifications(
1807 const ViewHierarchyChangedDetails
& details
) {
1808 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1809 child_at(i
)->PropagateAddNotifications(details
);
1810 ViewHierarchyChangedImpl(true, details
);
1813 void View::PropagateNativeViewHierarchyChanged(bool attached
,
1814 gfx::NativeView native_view
,
1815 internal::RootView
* root_view
) {
1816 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1817 child_at(i
)->PropagateNativeViewHierarchyChanged(attached
,
1820 NativeViewHierarchyChanged(attached
, native_view
, root_view
);
1823 void View::ViewHierarchyChangedImpl(
1824 bool register_accelerators
,
1825 const ViewHierarchyChangedDetails
& details
) {
1826 if (register_accelerators
) {
1827 if (details
.is_add
) {
1828 // If you get this registration, you are part of a subtree that has been
1829 // added to the view hierarchy.
1830 if (GetFocusManager()) {
1831 RegisterPendingAccelerators();
1833 // Delay accelerator registration until visible as we do not have
1834 // focus manager until then.
1835 accelerator_registration_delayed_
= true;
1838 if (details
.child
== this)
1839 UnregisterAccelerators(true);
1843 if (details
.is_add
&& layer() && !layer()->parent()) {
1844 UpdateParentLayer();
1845 Widget
* widget
= GetWidget();
1847 widget
->UpdateRootLayers();
1848 } else if (!details
.is_add
&& details
.child
== this) {
1849 // Make sure the layers beloning to the subtree rooted at |child| get
1850 // removed from layers that do not belong in the same subtree.
1852 if (use_acceleration_when_possible
) {
1853 Widget
* widget
= GetWidget();
1855 widget
->UpdateRootLayers();
1859 ViewHierarchyChanged(details
);
1860 details
.parent
->needs_layout_
= true;
1863 void View::PropagateNativeThemeChanged(const ui::NativeTheme
* theme
) {
1864 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1865 child_at(i
)->PropagateNativeThemeChanged(theme
);
1866 OnNativeThemeChanged(theme
);
1869 // Size and disposition --------------------------------------------------------
1871 void View::PropagateVisibilityNotifications(View
* start
, bool is_visible
) {
1872 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
1873 child_at(i
)->PropagateVisibilityNotifications(start
, is_visible
);
1874 VisibilityChangedImpl(start
, is_visible
);
1877 void View::VisibilityChangedImpl(View
* starting_from
, bool is_visible
) {
1878 VisibilityChanged(starting_from
, is_visible
);
1881 void View::BoundsChanged(const gfx::Rect
& previous_bounds
) {
1883 // Paint the new bounds.
1884 SchedulePaintBoundsChanged(
1885 bounds_
.size() == previous_bounds
.size() ? SCHEDULE_PAINT_SIZE_SAME
:
1886 SCHEDULE_PAINT_SIZE_CHANGED
);
1889 if (use_acceleration_when_possible
) {
1892 SetLayerBounds(GetLocalBounds() +
1893 gfx::Vector2d(GetMirroredX(), y()) +
1894 parent_
->CalculateOffsetToAncestorWithLayer(NULL
));
1896 SetLayerBounds(bounds_
);
1898 // TODO(beng): this seems redundant with the SchedulePaint at the top of
1899 // this function. explore collapsing.
1900 if (previous_bounds
.size() != bounds_
.size() &&
1901 !layer()->layer_updated_externally()) {
1902 // If our bounds have changed then we need to update the complete
1904 layer()->SchedulePaint(GetLocalBounds());
1907 // If our bounds have changed, then any descendant layer bounds may
1908 // have changed. Update them accordingly.
1909 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL
));
1913 OnBoundsChanged(previous_bounds
);
1915 if (previous_bounds
.size() != size()) {
1916 needs_layout_
= false;
1920 if (NeedsNotificationWhenVisibleBoundsChange())
1921 OnVisibleBoundsChanged();
1923 // Notify interested Views that visible bounds within the root view may have
1925 if (descendants_to_notify_
.get()) {
1926 for (Views::iterator
i(descendants_to_notify_
->begin());
1927 i
!= descendants_to_notify_
->end(); ++i
) {
1928 (*i
)->OnVisibleBoundsChanged();
1934 void View::RegisterChildrenForVisibleBoundsNotification(View
* view
) {
1935 if (view
->NeedsNotificationWhenVisibleBoundsChange())
1936 view
->RegisterForVisibleBoundsNotification();
1937 for (int i
= 0; i
< view
->child_count(); ++i
)
1938 RegisterChildrenForVisibleBoundsNotification(view
->child_at(i
));
1942 void View::UnregisterChildrenForVisibleBoundsNotification(View
* view
) {
1943 if (view
->NeedsNotificationWhenVisibleBoundsChange())
1944 view
->UnregisterForVisibleBoundsNotification();
1945 for (int i
= 0; i
< view
->child_count(); ++i
)
1946 UnregisterChildrenForVisibleBoundsNotification(view
->child_at(i
));
1949 void View::RegisterForVisibleBoundsNotification() {
1950 if (registered_for_visible_bounds_notification_
)
1953 registered_for_visible_bounds_notification_
= true;
1954 for (View
* ancestor
= parent_
; ancestor
; ancestor
= ancestor
->parent_
)
1955 ancestor
->AddDescendantToNotify(this);
1958 void View::UnregisterForVisibleBoundsNotification() {
1959 if (!registered_for_visible_bounds_notification_
)
1962 registered_for_visible_bounds_notification_
= false;
1963 for (View
* ancestor
= parent_
; ancestor
; ancestor
= ancestor
->parent_
)
1964 ancestor
->RemoveDescendantToNotify(this);
1967 void View::AddDescendantToNotify(View
* view
) {
1969 if (!descendants_to_notify_
.get())
1970 descendants_to_notify_
.reset(new Views
);
1971 descendants_to_notify_
->push_back(view
);
1974 void View::RemoveDescendantToNotify(View
* view
) {
1975 DCHECK(view
&& descendants_to_notify_
.get());
1976 Views::iterator
i(std::find(
1977 descendants_to_notify_
->begin(), descendants_to_notify_
->end(), view
));
1978 DCHECK(i
!= descendants_to_notify_
->end());
1979 descendants_to_notify_
->erase(i
);
1980 if (descendants_to_notify_
->empty())
1981 descendants_to_notify_
.reset();
1984 void View::SetLayerBounds(const gfx::Rect
& bounds
) {
1985 layer()->SetBounds(bounds
);
1988 // Transformations -------------------------------------------------------------
1990 bool View::GetTransformRelativeTo(const View
* ancestor
,
1991 gfx::Transform
* transform
) const {
1992 const View
* p
= this;
1994 while (p
&& p
!= ancestor
) {
1995 transform
->ConcatTransform(p
->GetTransform());
1996 gfx::Transform translation
;
1997 translation
.Translate(static_cast<float>(p
->GetMirroredX()),
1998 static_cast<float>(p
->y()));
1999 transform
->ConcatTransform(translation
);
2004 return p
== ancestor
;
2007 // Coordinate conversion -------------------------------------------------------
2009 bool View::ConvertPointForAncestor(const View
* ancestor
,
2010 gfx::Point
* point
) const {
2011 gfx::Transform trans
;
2012 // TODO(sad): Have some way of caching the transformation results.
2013 bool result
= GetTransformRelativeTo(ancestor
, &trans
);
2014 gfx::Point3F
p(*point
);
2015 trans
.TransformPoint(p
);
2016 *point
= gfx::ToFlooredPoint(p
.AsPointF());
2020 bool View::ConvertPointFromAncestor(const View
* ancestor
,
2021 gfx::Point
* point
) const {
2022 gfx::Transform trans
;
2023 bool result
= GetTransformRelativeTo(ancestor
, &trans
);
2024 gfx::Point3F
p(*point
);
2025 trans
.TransformPointReverse(p
);
2026 *point
= gfx::ToFlooredPoint(p
.AsPointF());
2030 // Accelerated painting --------------------------------------------------------
2032 void View::CreateLayer() {
2033 // A new layer is being created for the view. So all the layers of the
2034 // sub-tree can inherit the visibility of the corresponding view.
2035 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
2036 child_at(i
)->UpdateChildLayerVisibility(true);
2038 layer_
= new ui::Layer();
2039 layer_owner_
.reset(layer_
);
2040 layer_
->set_delegate(this);
2041 #if !defined(NDEBUG)
2042 layer_
->set_name(GetClassName());
2045 UpdateParentLayers();
2046 UpdateLayerVisibility();
2048 // The new layer needs to be ordered in the layer tree according
2049 // to the view tree. Children of this layer were added in order
2050 // in UpdateParentLayers().
2052 parent()->ReorderLayers();
2054 Widget
* widget
= GetWidget();
2056 widget
->UpdateRootLayers();
2059 void View::UpdateParentLayers() {
2060 // Attach all top-level un-parented layers.
2061 if (layer() && !layer()->parent()) {
2062 UpdateParentLayer();
2064 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
2065 child_at(i
)->UpdateParentLayers();
2069 void View::OrphanLayers() {
2071 if (layer()->parent())
2072 layer()->parent()->Remove(layer());
2074 // The layer belonging to this View has already been orphaned. It is not
2075 // necessary to orphan the child layers.
2078 for (int i
= 0, count
= child_count(); i
< count
; ++i
)
2079 child_at(i
)->OrphanLayers();
2082 void View::ReparentLayer(const gfx::Vector2d
& offset
, ui::Layer
* parent_layer
) {
2083 layer_
->SetBounds(GetLocalBounds() + offset
);
2084 DCHECK_NE(layer(), parent_layer
);
2086 parent_layer
->Add(layer());
2087 layer_
->SchedulePaint(GetLocalBounds());
2088 MoveLayerToParent(layer(), gfx::Point());
2091 void View::DestroyLayer() {
2092 ui::Layer
* new_parent
= layer()->parent();
2093 std::vector
<ui::Layer
*> children
= layer()->children();
2094 for (size_t i
= 0; i
< children
.size(); ++i
) {
2095 layer()->Remove(children
[i
]);
2097 new_parent
->Add(children
[i
]);
2101 layer_owner_
.reset();
2106 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL
));
2110 Widget
* widget
= GetWidget();
2112 widget
->UpdateRootLayers();
2115 // Input -----------------------------------------------------------------------
2117 bool View::ProcessMousePressed(const ui::MouseEvent
& event
) {
2118 int drag_operations
=
2119 (enabled_
&& event
.IsOnlyLeftMouseButton() &&
2120 HitTestPoint(event
.location())) ?
2121 GetDragOperations(event
.location()) : 0;
2122 ContextMenuController
* context_menu_controller
= event
.IsRightMouseButton() ?
2123 context_menu_controller_
: 0;
2124 View::DragInfo
* drag_info
= GetDragInfo();
2126 const bool enabled
= enabled_
;
2127 const bool result
= OnMousePressed(event
);
2132 if (event
.IsOnlyRightMouseButton() && context_menu_controller
&&
2133 kContextMenuOnMousePress
) {
2134 // Assume that if there is a context menu controller we won't be deleted
2135 // from mouse pressed.
2136 gfx::Point
location(event
.location());
2137 if (HitTestPoint(location
)) {
2138 ConvertPointToScreen(this, &location
);
2139 ShowContextMenu(location
, ui::MENU_SOURCE_MOUSE
);
2144 // WARNING: we may have been deleted, don't use any View variables.
2145 if (drag_operations
!= ui::DragDropTypes::DRAG_NONE
) {
2146 drag_info
->PossibleDrag(event
.location());
2149 return !!context_menu_controller
|| result
;
2152 bool View::ProcessMouseDragged(const ui::MouseEvent
& event
) {
2153 // Copy the field, that way if we're deleted after drag and drop no harm is
2155 ContextMenuController
* context_menu_controller
= context_menu_controller_
;
2156 const bool possible_drag
= GetDragInfo()->possible_drag
;
2157 if (possible_drag
&&
2158 ExceededDragThreshold(GetDragInfo()->start_pt
- event
.location()) &&
2159 (!drag_controller_
||
2160 drag_controller_
->CanStartDragForView(
2161 this, GetDragInfo()->start_pt
, event
.location()))) {
2162 DoDrag(event
, GetDragInfo()->start_pt
,
2163 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE
);
2165 if (OnMouseDragged(event
))
2167 // Fall through to return value based on context menu controller.
2169 // WARNING: we may have been deleted.
2170 return (context_menu_controller
!= NULL
) || possible_drag
;
2173 void View::ProcessMouseReleased(const ui::MouseEvent
& event
) {
2174 if (!kContextMenuOnMousePress
&& context_menu_controller_
&&
2175 event
.IsOnlyRightMouseButton()) {
2176 // Assume that if there is a context menu controller we won't be deleted
2177 // from mouse released.
2178 gfx::Point
location(event
.location());
2179 OnMouseReleased(event
);
2180 if (HitTestPoint(location
)) {
2181 ConvertPointToScreen(this, &location
);
2182 ShowContextMenu(location
, ui::MENU_SOURCE_MOUSE
);
2185 OnMouseReleased(event
);
2187 // WARNING: we may have been deleted.
2190 // Accelerators ----------------------------------------------------------------
2192 void View::RegisterPendingAccelerators() {
2193 if (!accelerators_
.get() ||
2194 registered_accelerator_count_
== accelerators_
->size()) {
2195 // No accelerators are waiting for registration.
2200 // The view is not yet attached to a widget, defer registration until then.
2204 accelerator_focus_manager_
= GetFocusManager();
2205 if (!accelerator_focus_manager_
) {
2206 // Some crash reports seem to show that we may get cases where we have no
2207 // focus manager (see bug #1291225). This should never be the case, just
2208 // making sure we don't crash.
2212 for (std::vector
<ui::Accelerator
>::const_iterator
i(
2213 accelerators_
->begin() + registered_accelerator_count_
);
2214 i
!= accelerators_
->end(); ++i
) {
2215 accelerator_focus_manager_
->RegisterAccelerator(
2216 *i
, ui::AcceleratorManager::kNormalPriority
, this);
2218 registered_accelerator_count_
= accelerators_
->size();
2221 void View::UnregisterAccelerators(bool leave_data_intact
) {
2222 if (!accelerators_
.get())
2226 if (accelerator_focus_manager_
) {
2227 // We may not have a FocusManager if the window containing us is being
2228 // closed, in which case the FocusManager is being deleted so there is
2229 // nothing to unregister.
2230 accelerator_focus_manager_
->UnregisterAccelerators(this);
2231 accelerator_focus_manager_
= NULL
;
2233 if (!leave_data_intact
) {
2234 accelerators_
->clear();
2235 accelerators_
.reset();
2237 registered_accelerator_count_
= 0;
2241 // Focus -----------------------------------------------------------------------
2243 void View::InitFocusSiblings(View
* v
, int index
) {
2244 int count
= child_count();
2247 v
->next_focusable_view_
= NULL
;
2248 v
->previous_focusable_view_
= NULL
;
2250 if (index
== count
) {
2251 // We are inserting at the end, but the end of the child list may not be
2252 // the last focusable element. Let's try to find an element with no next
2253 // focusable element to link to.
2254 View
* last_focusable_view
= NULL
;
2255 for (Views::iterator
i(children_
.begin()); i
!= children_
.end(); ++i
) {
2256 if (!(*i
)->next_focusable_view_
) {
2257 last_focusable_view
= *i
;
2261 if (last_focusable_view
== NULL
) {
2262 // Hum... there is a cycle in the focus list. Let's just insert ourself
2263 // after the last child.
2264 View
* prev
= children_
[index
- 1];
2265 v
->previous_focusable_view_
= prev
;
2266 v
->next_focusable_view_
= prev
->next_focusable_view_
;
2267 prev
->next_focusable_view_
->previous_focusable_view_
= v
;
2268 prev
->next_focusable_view_
= v
;
2270 last_focusable_view
->next_focusable_view_
= v
;
2271 v
->next_focusable_view_
= NULL
;
2272 v
->previous_focusable_view_
= last_focusable_view
;
2275 View
* prev
= children_
[index
]->GetPreviousFocusableView();
2276 v
->previous_focusable_view_
= prev
;
2277 v
->next_focusable_view_
= children_
[index
];
2279 prev
->next_focusable_view_
= v
;
2280 children_
[index
]->previous_focusable_view_
= v
;
2285 // System events ---------------------------------------------------------------
2287 void View::PropagateThemeChanged() {
2288 for (int i
= child_count() - 1; i
>= 0; --i
)
2289 child_at(i
)->PropagateThemeChanged();
2293 void View::PropagateLocaleChanged() {
2294 for (int i
= child_count() - 1; i
>= 0; --i
)
2295 child_at(i
)->PropagateLocaleChanged();
2299 // Tooltips --------------------------------------------------------------------
2301 void View::UpdateTooltip() {
2302 Widget
* widget
= GetWidget();
2303 // TODO(beng): The TooltipManager NULL check can be removed when we
2304 // consolidate Init() methods and make views_unittests Init() all
2305 // Widgets that it uses.
2306 if (widget
&& widget
->native_widget_private()->GetTooltipManager())
2307 widget
->native_widget_private()->GetTooltipManager()->UpdateTooltip();
2310 // Drag and drop ---------------------------------------------------------------
2312 bool View::DoDrag(const ui::LocatedEvent
& event
,
2313 const gfx::Point
& press_pt
,
2314 ui::DragDropTypes::DragEventSource source
) {
2315 #if !defined(OS_MACOSX)
2316 int drag_operations
= GetDragOperations(press_pt
);
2317 if (drag_operations
== ui::DragDropTypes::DRAG_NONE
)
2320 OSExchangeData data
;
2321 WriteDragData(press_pt
, &data
);
2323 // Message the RootView to do the drag and drop. That way if we're removed
2324 // the RootView can detect it and avoid calling us back.
2325 gfx::Point
widget_location(event
.location());
2326 ConvertPointToWidget(this, &widget_location
);
2327 GetWidget()->RunShellDrag(this, data
, widget_location
, drag_operations
,
2332 #endif // !defined(OS_MACOSX)
2335 } // namespace views