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/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/accessibility/ax_enums.h"
20 #include "ui/base/cursor/cursor.h"
21 #include "ui/base/dragdrop/drag_drop_types.h"
22 #include "ui/base/ui_base_switches_util.h"
23 #include "ui/compositor/compositor.h"
24 #include "ui/compositor/layer.h"
25 #include "ui/compositor/layer_animator.h"
26 #include "ui/events/event_target_iterator.h"
27 #include "ui/gfx/canvas.h"
28 #include "ui/gfx/interpolated_transform.h"
29 #include "ui/gfx/path.h"
30 #include "ui/gfx/point3_f.h"
31 #include "ui/gfx/point_conversions.h"
32 #include "ui/gfx/rect_conversions.h"
33 #include "ui/gfx/scoped_canvas.h"
34 #include "ui/gfx/screen.h"
35 #include "ui/gfx/skia_util.h"
36 #include "ui/gfx/transform.h"
37 #include "ui/native_theme/native_theme.h"
38 #include "ui/views/accessibility/native_view_accessibility.h"
39 #include "ui/views/background.h"
40 #include "ui/views/border.h"
41 #include "ui/views/context_menu_controller.h"
42 #include "ui/views/drag_controller.h"
43 #include "ui/views/focus/view_storage.h"
44 #include "ui/views/layout/layout_manager.h"
45 #include "ui/views/rect_based_targeting_utils.h"
46 #include "ui/views/views_delegate.h"
47 #include "ui/views/widget/native_widget_private.h"
48 #include "ui/views/widget/root_view.h"
49 #include "ui/views/widget/tooltip_manager.h"
50 #include "ui/views/widget/widget.h"
53 #include "base/win/scoped_gdi_object.h"
59 const bool kContextMenuOnMousePress = false;
61 const bool kContextMenuOnMousePress = true;
64 // The minimum percentage of a view's area that needs to be covered by a rect
65 // representing a touch region in order for that view to be considered by the
66 // rect-based targeting algorithm.
67 static const float kRectTargetOverlap = 0.6f;
69 // Default horizontal drag threshold in pixels.
70 // Same as what gtk uses.
71 const int kDefaultHorizontalDragThreshold = 8;
73 // Default vertical drag threshold in pixels.
74 // Same as what gtk uses.
75 const int kDefaultVerticalDragThreshold = 8;
77 // Returns the top view in |view|'s hierarchy.
78 const views::View* GetHierarchyRoot(const views::View* view) {
79 const views::View* root = view;
80 while (root && root->parent())
81 root = root->parent();
91 // This event handler receives events in the post-target phase and takes care of
93 // - Generates context menu, or initiates drag-and-drop, from gesture events.
94 class PostEventDispatchHandler : public ui::EventHandler {
96 explicit PostEventDispatchHandler(View* owner)
98 touch_dnd_enabled_(switches::IsTouchDragDropEnabled()) {
100 virtual ~PostEventDispatchHandler() {}
103 // Overridden from ui::EventHandler:
104 virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
105 DCHECK_EQ(ui::EP_POSTTARGET, event->phase());
106 if (event->handled())
109 if (touch_dnd_enabled_) {
110 if (event->type() == ui::ET_GESTURE_LONG_PRESS &&
111 (!owner_->drag_controller() ||
112 owner_->drag_controller()->CanStartDragForView(
113 owner_, event->location(), event->location()))) {
114 if (owner_->DoDrag(*event, event->location(),
115 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH)) {
116 event->StopPropagation();
122 if (owner_->context_menu_controller() &&
123 (event->type() == ui::ET_GESTURE_LONG_PRESS ||
124 event->type() == ui::ET_GESTURE_LONG_TAP ||
125 event->type() == ui::ET_GESTURE_TWO_FINGER_TAP)) {
126 gfx::Point location(event->location());
127 View::ConvertPointToScreen(owner_, &location);
128 owner_->ShowContextMenu(location, ui::MENU_SOURCE_TOUCH);
129 event->StopPropagation();
134 bool touch_dnd_enabled_;
136 DISALLOW_COPY_AND_ASSIGN(PostEventDispatchHandler);
139 } // namespace internal
142 ViewsDelegate* ViewsDelegate::views_delegate = NULL;
145 const char View::kViewClassName[] = "View";
147 ////////////////////////////////////////////////////////////////////////////////
150 // Creation and lifetime -------------------------------------------------------
153 : owned_by_client_(false),
159 notify_enter_exit_on_child_(false),
160 registered_for_visible_bounds_notification_(false),
161 clip_insets_(0, 0, 0, 0),
163 flip_canvas_on_paint_for_rtl_ui_(false),
164 paint_to_layer_(false),
165 accelerator_focus_manager_(NULL),
166 registered_accelerator_count_(0),
167 next_focusable_view_(NULL),
168 previous_focusable_view_(NULL),
170 accessibility_focusable_(false),
171 context_menu_controller_(NULL),
172 drag_controller_(NULL),
173 post_dispatch_handler_(new internal::PostEventDispatchHandler(this)),
174 native_view_accessibility_(NULL) {
175 AddPostTargetHandler(post_dispatch_handler_.get());
180 parent_->RemoveChildView(this);
182 ViewStorage::GetInstance()->ViewRemoved(this);
184 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
185 (*i)->parent_ = NULL;
186 if (!(*i)->owned_by_client_)
190 // Release ownership of the native accessibility object, but it's
191 // reference-counted on some platforms, so it may not be deleted right away.
192 if (native_view_accessibility_)
193 native_view_accessibility_->Destroy();
196 // Tree operations -------------------------------------------------------------
198 const Widget* View::GetWidget() const {
199 // The root view holds a reference to this view hierarchy's Widget.
200 return parent_ ? parent_->GetWidget() : NULL;
203 Widget* View::GetWidget() {
204 return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
207 void View::AddChildView(View* view) {
208 if (view->parent_ == this)
210 AddChildViewAt(view, child_count());
213 void View::AddChildViewAt(View* view, int index) {
214 CHECK_NE(view, this) << "You cannot add a view as its own child";
216 DCHECK_LE(index, child_count());
218 // If |view| has a parent, remove it from its parent.
219 View* parent = view->parent_;
220 ui::NativeTheme* old_theme = NULL;
222 old_theme = view->GetNativeTheme();
223 if (parent == this) {
224 ReorderChildView(view, index);
227 parent->DoRemoveChildView(view, true, true, false, this);
230 // Sets the prev/next focus views.
231 InitFocusSiblings(view, index);
233 // Let's insert the view.
234 view->parent_ = this;
235 children_.insert(children_.begin() + index, view);
237 views::Widget* widget = GetWidget();
239 const ui::NativeTheme* new_theme = view->GetNativeTheme();
240 if (new_theme != old_theme)
241 view->PropagateNativeThemeChanged(new_theme);
244 ViewHierarchyChangedDetails details(true, this, view, parent);
246 for (View* v = this; v; v = v->parent_)
247 v->ViewHierarchyChangedImpl(false, details);
249 view->PropagateAddNotifications(details);
252 RegisterChildrenForVisibleBoundsNotification(view);
254 view->SchedulePaint();
257 if (layout_manager_.get())
258 layout_manager_->ViewAdded(this, view);
262 // Make sure the visibility of the child layers are correct.
263 // If any of the parent View is hidden, then the layers of the subtree
264 // rooted at |this| should be hidden. Otherwise, all the child layers should
265 // inherit the visibility of the owner View.
266 UpdateLayerVisibility();
269 void View::ReorderChildView(View* view, int index) {
270 DCHECK_EQ(view->parent_, this);
272 index = child_count() - 1;
273 else if (index >= child_count())
275 if (children_[index] == view)
278 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
279 DCHECK(i != children_.end());
282 // Unlink the view first
283 View* next_focusable = view->next_focusable_view_;
284 View* prev_focusable = view->previous_focusable_view_;
286 prev_focusable->next_focusable_view_ = next_focusable;
288 next_focusable->previous_focusable_view_ = prev_focusable;
290 // Add it in the specified index now.
291 InitFocusSiblings(view, index);
292 children_.insert(children_.begin() + index, view);
297 void View::RemoveChildView(View* view) {
298 DoRemoveChildView(view, true, true, false, NULL);
301 void View::RemoveAllChildViews(bool delete_children) {
302 while (!children_.empty())
303 DoRemoveChildView(children_.front(), false, false, delete_children, NULL);
307 bool View::Contains(const View* view) const {
308 for (const View* v = view; v; v = v->parent_) {
315 int View::GetIndexOf(const View* view) const {
316 Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
317 return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
320 // Size and disposition --------------------------------------------------------
322 void View::SetBounds(int x, int y, int width, int height) {
323 SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
326 void View::SetBoundsRect(const gfx::Rect& bounds) {
327 if (bounds == bounds_) {
329 needs_layout_ = false;
336 // Paint where the view is currently.
337 SchedulePaintBoundsChanged(
338 bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
339 SCHEDULE_PAINT_SIZE_CHANGED);
342 gfx::Rect prev = bounds_;
347 void View::SetSize(const gfx::Size& size) {
348 SetBounds(x(), y(), size.width(), size.height());
351 void View::SetPosition(const gfx::Point& position) {
352 SetBounds(position.x(), position.y(), width(), height());
355 void View::SetX(int x) {
356 SetBounds(x, y(), width(), height());
359 void View::SetY(int y) {
360 SetBounds(x(), y, width(), height());
363 gfx::Rect View::GetContentsBounds() const {
364 gfx::Rect contents_bounds(GetLocalBounds());
366 contents_bounds.Inset(border_->GetInsets());
367 return contents_bounds;
370 gfx::Rect View::GetLocalBounds() const {
371 return gfx::Rect(size());
374 gfx::Rect View::GetLayerBoundsInPixel() const {
375 return layer()->GetTargetBounds();
378 gfx::Insets View::GetInsets() const {
379 return border_.get() ? border_->GetInsets() : gfx::Insets();
382 gfx::Rect View::GetVisibleBounds() const {
385 gfx::Rect vis_bounds(GetLocalBounds());
386 gfx::Rect ancestor_bounds;
387 const View* view = this;
388 gfx::Transform transform;
390 while (view != NULL && !vis_bounds.IsEmpty()) {
391 transform.ConcatTransform(view->GetTransform());
392 gfx::Transform translation;
393 translation.Translate(static_cast<float>(view->GetMirroredX()),
394 static_cast<float>(view->y()));
395 transform.ConcatTransform(translation);
397 vis_bounds = view->ConvertRectToParent(vis_bounds);
398 const View* ancestor = view->parent_;
399 if (ancestor != NULL) {
400 ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
401 vis_bounds.Intersect(ancestor_bounds);
402 } else if (!view->GetWidget()) {
403 // If the view has no Widget, we're not visible. Return an empty rect.
408 if (vis_bounds.IsEmpty())
410 // Convert back to this views coordinate system.
411 gfx::RectF views_vis_bounds(vis_bounds);
412 transform.TransformRectReverse(&views_vis_bounds);
413 // Partially visible pixels should be considered visible.
414 return gfx::ToEnclosingRect(views_vis_bounds);
417 gfx::Rect View::GetBoundsInScreen() const {
419 View::ConvertPointToScreen(this, &origin);
420 return gfx::Rect(origin, size());
423 gfx::Size View::GetPreferredSize() {
424 if (layout_manager_.get())
425 return layout_manager_->GetPreferredSize(this);
429 int View::GetBaseline() const {
433 void View::SizeToPreferredSize() {
434 gfx::Size prefsize = GetPreferredSize();
435 if ((prefsize.width() != width()) || (prefsize.height() != height()))
436 SetBounds(x(), y(), prefsize.width(), prefsize.height());
439 gfx::Size View::GetMinimumSize() {
440 return GetPreferredSize();
443 gfx::Size View::GetMaximumSize() {
447 int View::GetHeightForWidth(int w) {
448 if (layout_manager_.get())
449 return layout_manager_->GetPreferredHeightForWidth(this, w);
450 return GetPreferredSize().height();
453 void View::SetVisible(bool visible) {
454 if (visible != visible_) {
455 // If the View is currently visible, schedule paint to refresh parent.
456 // TODO(beng): not sure we should be doing this if we have a layer.
462 // Notify the parent.
464 parent_->ChildVisibilityChanged(this);
466 // This notifies all sub-views recursively.
467 PropagateVisibilityNotifications(this, visible_);
468 UpdateLayerVisibility();
470 // If we are newly visible, schedule paint.
476 bool View::IsDrawn() const {
477 return visible_ && parent_ ? parent_->IsDrawn() : false;
480 void View::SetEnabled(bool enabled) {
481 if (enabled != enabled_) {
487 void View::OnEnabledChanged() {
491 // Transformations -------------------------------------------------------------
493 gfx::Transform View::GetTransform() const {
494 return layer() ? layer()->transform() : gfx::Transform();
497 void View::SetTransform(const gfx::Transform& transform) {
498 if (transform.IsIdentity()) {
500 layer()->SetTransform(transform);
501 if (!paint_to_layer_)
509 layer()->SetTransform(transform);
510 layer()->ScheduleDraw();
514 void View::SetPaintToLayer(bool paint_to_layer) {
515 paint_to_layer_ = paint_to_layer;
516 if (paint_to_layer_ && !layer()) {
518 } else if (!paint_to_layer_ && layer()) {
523 // RTL positioning -------------------------------------------------------------
525 gfx::Rect View::GetMirroredBounds() const {
526 gfx::Rect bounds(bounds_);
527 bounds.set_x(GetMirroredX());
531 gfx::Point View::GetMirroredPosition() const {
532 return gfx::Point(GetMirroredX(), y());
535 int View::GetMirroredX() const {
536 return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
539 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
540 return base::i18n::IsRTL() ?
541 (width() - bounds.x() - bounds.width()) : bounds.x();
544 int View::GetMirroredXInView(int x) const {
545 return base::i18n::IsRTL() ? width() - x : x;
548 int View::GetMirroredXWithWidthInView(int x, int w) const {
549 return base::i18n::IsRTL() ? width() - x - w : x;
552 // Layout ----------------------------------------------------------------------
554 void View::Layout() {
555 needs_layout_ = false;
557 // If we have a layout manager, let it handle the layout for us.
558 if (layout_manager_.get())
559 layout_manager_->Layout(this);
561 // Make sure to propagate the Layout() call to any children that haven't
562 // received it yet through the layout manager and need to be laid out. This
563 // is needed for the case when the child requires a layout but its bounds
564 // weren't changed by the layout manager. If there is no layout manager, we
565 // just propagate the Layout() call down the hierarchy, so whoever receives
566 // the call can take appropriate action.
567 for (int i = 0, count = child_count(); i < count; ++i) {
568 View* child = child_at(i);
569 if (child->needs_layout_ || !layout_manager_.get()) {
570 child->needs_layout_ = false;
576 void View::InvalidateLayout() {
577 // Always invalidate up. This is needed to handle the case of us already being
578 // valid, but not our parent.
579 needs_layout_ = true;
581 parent_->InvalidateLayout();
584 LayoutManager* View::GetLayoutManager() const {
585 return layout_manager_.get();
588 void View::SetLayoutManager(LayoutManager* layout_manager) {
589 if (layout_manager_.get())
590 layout_manager_->Uninstalled(this);
592 layout_manager_.reset(layout_manager);
593 if (layout_manager_.get())
594 layout_manager_->Installed(this);
597 // Attributes ------------------------------------------------------------------
599 const char* View::GetClassName() const {
600 return kViewClassName;
603 const View* View::GetAncestorWithClassName(const std::string& name) const {
604 for (const View* view = this; view; view = view->parent_) {
605 if (!strcmp(view->GetClassName(), name.c_str()))
611 View* View::GetAncestorWithClassName(const std::string& name) {
612 return const_cast<View*>(const_cast<const View*>(this)->
613 GetAncestorWithClassName(name));
616 const View* View::GetViewByID(int id) const {
618 return const_cast<View*>(this);
620 for (int i = 0, count = child_count(); i < count; ++i) {
621 const View* view = child_at(i)->GetViewByID(id);
628 View* View::GetViewByID(int id) {
629 return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
632 void View::SetGroup(int gid) {
633 // Don't change the group id once it's set.
634 DCHECK(group_ == -1 || group_ == gid);
638 int View::GetGroup() const {
642 bool View::IsGroupFocusTraversable() const {
646 void View::GetViewsInGroup(int group, Views* views) {
648 views->push_back(this);
650 for (int i = 0, count = child_count(); i < count; ++i)
651 child_at(i)->GetViewsInGroup(group, views);
654 View* View::GetSelectedViewForGroup(int group) {
656 GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
657 return views.empty() ? NULL : views[0];
660 // Coordinate conversion -------------------------------------------------------
663 void View::ConvertPointToTarget(const View* source,
668 if (source == target)
671 const View* root = GetHierarchyRoot(target);
672 CHECK_EQ(GetHierarchyRoot(source), root);
675 source->ConvertPointForAncestor(root, point);
678 target->ConvertPointFromAncestor(root, point);
682 void View::ConvertRectToTarget(const View* source,
687 if (source == target)
690 const View* root = GetHierarchyRoot(target);
691 CHECK_EQ(GetHierarchyRoot(source), root);
694 source->ConvertRectForAncestor(root, rect);
697 target->ConvertRectFromAncestor(root, rect);
701 void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
705 src->ConvertPointForAncestor(NULL, p);
709 void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
713 dest->ConvertPointFromAncestor(NULL, p);
717 void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
721 // If the view is not connected to a tree, there's nothing we can do.
722 const Widget* widget = src->GetWidget();
724 ConvertPointToWidget(src, p);
725 *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
730 void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
734 const views::Widget* widget = dst->GetWidget();
737 *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
738 views::View::ConvertPointFromWidget(dst, p);
741 gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
742 gfx::RectF x_rect = rect;
743 GetTransform().TransformRect(&x_rect);
744 x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
745 // Pixels we partially occupy in the parent should be included.
746 return gfx::ToEnclosingRect(x_rect);
749 gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
750 gfx::Rect x_rect = rect;
751 for (const View* v = this; v; v = v->parent_)
752 x_rect = v->ConvertRectToParent(x_rect);
756 // Painting --------------------------------------------------------------------
758 void View::SchedulePaint() {
759 SchedulePaintInRect(GetLocalBounds());
762 void View::SchedulePaintInRect(const gfx::Rect& rect) {
767 layer()->SchedulePaint(rect);
768 } else if (parent_) {
769 // Translate the requested paint rect to the parent's coordinate system
770 // then pass this notification up to the parent.
771 parent_->SchedulePaintInRect(ConvertRectToParent(rect));
775 void View::Paint(gfx::Canvas* canvas) {
776 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
778 gfx::ScopedCanvas scoped_canvas(canvas);
780 // Paint this View and its children, setting the clip rect to the bounds
781 // of this View and translating the origin to the local bounds' top left
784 // Note that the X (or left) position we pass to ClipRectInt takes into
785 // consideration whether or not the view uses a right-to-left layout so that
786 // we paint our view in its mirrored position if need be.
787 gfx::Rect clip_rect = bounds();
788 clip_rect.Inset(clip_insets_);
790 clip_rect.set_x(parent_->GetMirroredXForRect(clip_rect));
791 canvas->ClipRect(clip_rect);
792 if (canvas->IsClipEmpty())
795 // Non-empty clip, translate the graphics such that 0,0 corresponds to
796 // where this view is located (related to its parent).
797 canvas->Translate(GetMirroredPosition().OffsetFromOrigin());
798 canvas->Transform(GetTransform());
803 void View::set_background(Background* b) {
804 background_.reset(b);
807 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
809 ui::ThemeProvider* View::GetThemeProvider() const {
810 const Widget* widget = GetWidget();
811 return widget ? widget->GetThemeProvider() : NULL;
814 const ui::NativeTheme* View::GetNativeTheme() const {
815 const Widget* widget = GetWidget();
816 return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
819 // Input -----------------------------------------------------------------------
821 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
822 return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
825 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
826 // |rect_view| represents the current best candidate to return
827 // if rect-based targeting (i.e., fuzzing) is used.
828 // |rect_view_distance| is used to keep track of the distance
829 // between the center point of |rect_view| and the center
831 View* rect_view = NULL;
832 int rect_view_distance = INT_MAX;
834 // |point_view| represents the view that would have been returned
835 // from this function call if point-based targeting were used.
836 View* point_view = NULL;
838 for (int i = child_count() - 1; i >= 0; --i) {
839 View* child = child_at(i);
841 // Ignore any children which are invisible or do not intersect |rect|.
842 if (!child->visible())
844 gfx::RectF rect_in_child_coords_f(rect);
845 ConvertRectToTarget(this, child, &rect_in_child_coords_f);
846 gfx::Rect rect_in_child_coords = gfx::ToEnclosingRect(
847 rect_in_child_coords_f);
848 if (!child->HitTestRect(rect_in_child_coords))
851 View* cur_view = child->GetEventHandlerForRect(rect_in_child_coords);
853 if (views::UsePointBasedTargeting(rect))
856 gfx::RectF cur_view_bounds_f(cur_view->GetLocalBounds());
857 ConvertRectToTarget(cur_view, this, &cur_view_bounds_f);
858 gfx::Rect cur_view_bounds = gfx::ToEnclosingRect(
860 if (views::PercentCoveredBy(cur_view_bounds, rect) >= kRectTargetOverlap) {
861 // |cur_view| is a suitable candidate for rect-based targeting.
862 // Check to see if it is the closest suitable candidate so far.
863 gfx::Point touch_center(rect.CenterPoint());
864 int cur_dist = views::DistanceSquaredFromCenterToPoint(touch_center,
866 if (!rect_view || cur_dist < rect_view_distance) {
867 rect_view = cur_view;
868 rect_view_distance = cur_dist;
870 } else if (!rect_view && !point_view) {
871 // Rect-based targeting has not yielded any candidates so far. Check
872 // if point-based targeting would have selected |cur_view|.
873 gfx::Point point_in_child_coords(rect_in_child_coords.CenterPoint());
874 if (child->HitTestPoint(point_in_child_coords))
875 point_view = child->GetEventHandlerForPoint(point_in_child_coords);
879 if (views::UsePointBasedTargeting(rect) || (!rect_view && !point_view))
882 // If |this| is a suitable candidate for rect-based targeting, check to
883 // see if it is closer than the current best suitable candidate so far.
884 gfx::Rect local_bounds(GetLocalBounds());
885 if (views::PercentCoveredBy(local_bounds, rect) >= kRectTargetOverlap) {
886 gfx::Point touch_center(rect.CenterPoint());
887 int cur_dist = views::DistanceSquaredFromCenterToPoint(touch_center,
889 if (!rect_view || cur_dist < rect_view_distance)
893 return rect_view ? rect_view : point_view;
896 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
897 if (!HitTestPoint(point))
900 // Walk the child Views recursively looking for the View that most
901 // tightly encloses the specified point.
902 for (int i = child_count() - 1; i >= 0; --i) {
903 View* child = child_at(i);
904 if (!child->visible())
907 gfx::Point point_in_child_coords(point);
908 ConvertPointToTarget(this, child, &point_in_child_coords);
909 View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
916 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
918 static ui::Cursor arrow;
919 if (!arrow.platform())
920 arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
923 return gfx::kNullCursor;
927 bool View::HitTestPoint(const gfx::Point& point) const {
928 return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
931 bool View::HitTestRect(const gfx::Rect& rect) const {
932 if (GetLocalBounds().Intersects(rect)) {
933 if (HasHitTestMask()) {
935 HitTestSource source = HIT_TEST_SOURCE_MOUSE;
936 if (!views::UsePointBasedTargeting(rect))
937 source = HIT_TEST_SOURCE_TOUCH;
938 GetHitTestMask(source, &mask);
939 SkRegion clip_region;
940 clip_region.setRect(0, 0, width(), height());
941 SkRegion mask_region;
942 return mask_region.setPath(mask, clip_region) &&
943 mask_region.intersects(RectToSkIRect(rect));
945 // No mask, but inside our bounds.
948 // Outside our bounds.
952 bool View::IsMouseHovered() {
953 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
958 // If mouse events are disabled, then the mouse cursor is invisible and
959 // is therefore not hovering over this button.
960 if (!GetWidget()->IsMouseEventsEnabled())
963 gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
964 GetWidget()->GetNativeView())->GetCursorScreenPoint());
965 ConvertPointFromScreen(this, &cursor_pos);
966 return HitTestPoint(cursor_pos);
969 bool View::OnMousePressed(const ui::MouseEvent& event) {
973 bool View::OnMouseDragged(const ui::MouseEvent& event) {
977 void View::OnMouseReleased(const ui::MouseEvent& event) {
980 void View::OnMouseCaptureLost() {
983 void View::OnMouseMoved(const ui::MouseEvent& event) {
986 void View::OnMouseEntered(const ui::MouseEvent& event) {
989 void View::OnMouseExited(const ui::MouseEvent& event) {
992 void View::SetMouseHandler(View* new_mouse_handler) {
993 // |new_mouse_handler| may be NULL.
995 parent_->SetMouseHandler(new_mouse_handler);
998 bool View::OnKeyPressed(const ui::KeyEvent& event) {
1002 bool View::OnKeyReleased(const ui::KeyEvent& event) {
1006 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
1010 void View::OnKeyEvent(ui::KeyEvent* event) {
1011 bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
1012 OnKeyReleased(*event);
1014 event->StopPropagation();
1017 void View::OnMouseEvent(ui::MouseEvent* event) {
1018 switch (event->type()) {
1019 case ui::ET_MOUSE_PRESSED:
1020 if (ProcessMousePressed(*event))
1021 event->SetHandled();
1024 case ui::ET_MOUSE_MOVED:
1025 if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
1026 ui::EF_RIGHT_MOUSE_BUTTON |
1027 ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
1028 OnMouseMoved(*event);
1032 case ui::ET_MOUSE_DRAGGED:
1033 if (ProcessMouseDragged(*event))
1034 event->SetHandled();
1037 case ui::ET_MOUSE_RELEASED:
1038 ProcessMouseReleased(*event);
1041 case ui::ET_MOUSEWHEEL:
1042 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
1043 event->SetHandled();
1046 case ui::ET_MOUSE_ENTERED:
1047 OnMouseEntered(*event);
1050 case ui::ET_MOUSE_EXITED:
1051 OnMouseExited(*event);
1059 void View::OnScrollEvent(ui::ScrollEvent* event) {
1062 void View::OnTouchEvent(ui::TouchEvent* event) {
1063 NOTREACHED() << "Views should not receive touch events.";
1066 void View::OnGestureEvent(ui::GestureEvent* event) {
1069 ui::TextInputClient* View::GetTextInputClient() {
1073 InputMethod* View::GetInputMethod() {
1074 Widget* widget = GetWidget();
1075 return widget ? widget->GetInputMethod() : NULL;
1078 const InputMethod* View::GetInputMethod() const {
1079 const Widget* widget = GetWidget();
1080 return widget ? widget->GetInputMethod() : NULL;
1083 scoped_ptr<ui::EventTargeter>
1084 View::SetEventTargeter(scoped_ptr<ui::EventTargeter> targeter) {
1085 scoped_ptr<ui::EventTargeter> old_targeter = targeter_.Pass();
1086 targeter_ = targeter.Pass();
1087 return old_targeter.Pass();
1090 bool View::CanAcceptEvent(const ui::Event& event) {
1094 ui::EventTarget* View::GetParentTarget() {
1098 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1099 return scoped_ptr<ui::EventTargetIterator>(
1100 new ui::EventTargetIteratorImpl<View>(children_));
1103 ui::EventTargeter* View::GetEventTargeter() {
1104 return targeter_.get();
1107 void View::ConvertEventToTarget(ui::EventTarget* target,
1108 ui::LocatedEvent* event) {
1109 event->ConvertLocationToTarget(this, static_cast<View*>(target));
1112 // Accelerators ----------------------------------------------------------------
1114 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1115 if (!accelerators_.get())
1116 accelerators_.reset(new std::vector<ui::Accelerator>());
1118 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1119 accelerators_->end()) {
1120 accelerators_->push_back(accelerator);
1122 RegisterPendingAccelerators();
1125 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1126 if (!accelerators_.get()) {
1127 NOTREACHED() << "Removing non-existing accelerator";
1131 std::vector<ui::Accelerator>::iterator i(
1132 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1133 if (i == accelerators_->end()) {
1134 NOTREACHED() << "Removing non-existing accelerator";
1138 size_t index = i - accelerators_->begin();
1139 accelerators_->erase(i);
1140 if (index >= registered_accelerator_count_) {
1141 // The accelerator is not registered to FocusManager.
1144 --registered_accelerator_count_;
1146 // Providing we are attached to a Widget and registered with a focus manager,
1147 // we should de-register from that focus manager now.
1148 if (GetWidget() && accelerator_focus_manager_)
1149 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1152 void View::ResetAccelerators() {
1153 if (accelerators_.get())
1154 UnregisterAccelerators(false);
1157 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1161 bool View::CanHandleAccelerators() const {
1162 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1165 // Focus -----------------------------------------------------------------------
1167 bool View::HasFocus() const {
1168 const FocusManager* focus_manager = GetFocusManager();
1169 return focus_manager && (focus_manager->GetFocusedView() == this);
1172 View* View::GetNextFocusableView() {
1173 return next_focusable_view_;
1176 const View* View::GetNextFocusableView() const {
1177 return next_focusable_view_;
1180 View* View::GetPreviousFocusableView() {
1181 return previous_focusable_view_;
1184 void View::SetNextFocusableView(View* view) {
1186 view->previous_focusable_view_ = this;
1187 next_focusable_view_ = view;
1190 void View::SetFocusable(bool focusable) {
1191 if (focusable_ == focusable)
1194 focusable_ = focusable;
1197 bool View::IsFocusable() const {
1198 return focusable_ && enabled_ && IsDrawn();
1201 bool View::IsAccessibilityFocusable() const {
1202 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1205 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1206 if (accessibility_focusable_ == accessibility_focusable)
1209 accessibility_focusable_ = accessibility_focusable;
1212 FocusManager* View::GetFocusManager() {
1213 Widget* widget = GetWidget();
1214 return widget ? widget->GetFocusManager() : NULL;
1217 const FocusManager* View::GetFocusManager() const {
1218 const Widget* widget = GetWidget();
1219 return widget ? widget->GetFocusManager() : NULL;
1222 void View::RequestFocus() {
1223 FocusManager* focus_manager = GetFocusManager();
1224 if (focus_manager && IsFocusable())
1225 focus_manager->SetFocusedView(this);
1228 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1232 FocusTraversable* View::GetFocusTraversable() {
1236 FocusTraversable* View::GetPaneFocusTraversable() {
1240 // Tooltips --------------------------------------------------------------------
1242 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1246 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1250 // Context menus ---------------------------------------------------------------
1252 void View::ShowContextMenu(const gfx::Point& p,
1253 ui::MenuSourceType source_type) {
1254 if (!context_menu_controller_)
1257 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1261 bool View::ShouldShowContextMenuOnMousePress() {
1262 return kContextMenuOnMousePress;
1265 // Drag and drop ---------------------------------------------------------------
1267 bool View::GetDropFormats(
1269 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1273 bool View::AreDropTypesRequired() {
1277 bool View::CanDrop(const OSExchangeData& data) {
1278 // TODO(sky): when I finish up migration, this should default to true.
1282 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1285 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1286 return ui::DragDropTypes::DRAG_NONE;
1289 void View::OnDragExited() {
1292 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1293 return ui::DragDropTypes::DRAG_NONE;
1296 void View::OnDragDone() {
1300 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1301 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1302 abs(delta.y()) > GetVerticalDragThreshold());
1305 // Accessibility----------------------------------------------------------------
1307 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1308 if (!native_view_accessibility_)
1309 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1310 if (native_view_accessibility_)
1311 return native_view_accessibility_->GetNativeObject();
1315 void View::NotifyAccessibilityEvent(
1316 ui::AXEvent event_type,
1317 bool send_native_event) {
1318 if (ViewsDelegate::views_delegate)
1319 ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1321 if (send_native_event && GetWidget()) {
1322 if (!native_view_accessibility_)
1323 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1324 if (native_view_accessibility_)
1325 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1329 // Scrolling -------------------------------------------------------------------
1331 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1332 // We must take RTL UI mirroring into account when adjusting the position of
1335 gfx::Rect scroll_rect(rect);
1336 scroll_rect.Offset(GetMirroredX(), y());
1337 parent_->ScrollRectToVisible(scroll_rect);
1341 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1342 bool is_horizontal, bool is_positive) {
1346 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1347 bool is_horizontal, bool is_positive) {
1351 ////////////////////////////////////////////////////////////////////////////////
1354 // Size and disposition --------------------------------------------------------
1356 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1359 void View::PreferredSizeChanged() {
1362 parent_->ChildPreferredSizeChanged(this);
1365 bool View::NeedsNotificationWhenVisibleBoundsChange() const {
1369 void View::OnVisibleBoundsChanged() {
1372 // Tree operations -------------------------------------------------------------
1374 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1377 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1380 void View::NativeViewHierarchyChanged() {
1381 FocusManager* focus_manager = GetFocusManager();
1382 if (accelerator_focus_manager_ != focus_manager) {
1383 UnregisterAccelerators(true);
1386 RegisterPendingAccelerators();
1390 // Painting --------------------------------------------------------------------
1392 void View::PaintChildren(gfx::Canvas* canvas) {
1393 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1394 for (int i = 0, count = child_count(); i < count; ++i)
1395 if (!child_at(i)->layer())
1396 child_at(i)->Paint(canvas);
1399 void View::OnPaint(gfx::Canvas* canvas) {
1400 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1401 OnPaintBackground(canvas);
1402 OnPaintBorder(canvas);
1405 void View::OnPaintBackground(gfx::Canvas* canvas) {
1406 if (background_.get()) {
1407 TRACE_EVENT2("views", "View::OnPaintBackground",
1408 "width", canvas->sk_canvas()->getDevice()->width(),
1409 "height", canvas->sk_canvas()->getDevice()->height());
1410 background_->Paint(canvas, this);
1414 void View::OnPaintBorder(gfx::Canvas* canvas) {
1415 if (border_.get()) {
1416 TRACE_EVENT2("views", "View::OnPaintBorder",
1417 "width", canvas->sk_canvas()->getDevice()->width(),
1418 "height", canvas->sk_canvas()->getDevice()->height());
1419 border_->Paint(*this, canvas);
1423 // Accelerated Painting --------------------------------------------------------
1425 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1426 // This method should not have the side-effect of creating the layer.
1428 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1431 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1432 ui::Layer** layer_parent) {
1435 *layer_parent = layer();
1436 return gfx::Vector2d();
1439 return gfx::Vector2d();
1441 return gfx::Vector2d(GetMirroredX(), y()) +
1442 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1445 void View::UpdateParentLayer() {
1449 ui::Layer* parent_layer = NULL;
1450 gfx::Vector2d offset(GetMirroredX(), y());
1453 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1455 ReparentLayer(offset, parent_layer);
1458 void View::MoveLayerToParent(ui::Layer* parent_layer,
1459 const gfx::Point& point) {
1460 gfx::Point local_point(point);
1461 if (parent_layer != layer())
1462 local_point.Offset(GetMirroredX(), y());
1463 if (layer() && parent_layer != layer()) {
1464 parent_layer->Add(layer());
1465 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1466 width(), height()));
1468 for (int i = 0, count = child_count(); i < count; ++i)
1469 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1473 void View::UpdateLayerVisibility() {
1474 bool visible = visible_;
1475 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1476 visible = v->visible();
1478 UpdateChildLayerVisibility(visible);
1481 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1483 layer()->SetVisible(ancestor_visible && visible_);
1485 for (int i = 0, count = child_count(); i < count; ++i)
1486 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1490 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1492 SetLayerBounds(GetLocalBounds() + offset);
1494 for (int i = 0, count = child_count(); i < count; ++i) {
1495 View* child = child_at(i);
1496 child->UpdateChildLayerBounds(
1497 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1502 void View::OnPaintLayer(gfx::Canvas* canvas) {
1503 if (!layer() || !layer()->fills_bounds_opaquely())
1504 canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1505 PaintCommon(canvas);
1508 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1509 // Repainting with new scale factor will paint the content at the right scale.
1512 base::Closure View::PrepareForLayerBoundsChange() {
1513 return base::Closure();
1516 void View::ReorderLayers() {
1518 while (v && !v->layer())
1521 Widget* widget = GetWidget();
1524 ui::Layer* layer = widget->GetLayer();
1526 widget->GetRootView()->ReorderChildLayers(layer);
1529 v->ReorderChildLayers(v->layer());
1533 // Reorder the widget's child NativeViews in case a child NativeView is
1534 // associated with a view (eg via a NativeViewHost). Always do the
1535 // reordering because the associated NativeView's layer (if it has one)
1536 // is parented to the widget's layer regardless of whether the host view has
1537 // an ancestor with a layer.
1538 widget->ReorderNativeViews();
1542 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1543 if (layer() && layer() != parent_layer) {
1544 DCHECK_EQ(parent_layer, layer()->parent());
1545 parent_layer->StackAtBottom(layer());
1547 // Iterate backwards through the children so that a child with a layer
1548 // which is further to the back is stacked above one which is further to
1550 for (Views::reverse_iterator it(children_.rbegin());
1551 it != children_.rend(); ++it) {
1552 (*it)->ReorderChildLayers(parent_layer);
1557 // Input -----------------------------------------------------------------------
1559 bool View::HasHitTestMask() const {
1563 void View::GetHitTestMask(HitTestSource source, gfx::Path* mask) const {
1567 View::DragInfo* View::GetDragInfo() {
1568 return parent_ ? parent_->GetDragInfo() : NULL;
1571 // Focus -----------------------------------------------------------------------
1573 void View::OnFocus() {
1574 // TODO(beng): Investigate whether it's possible for us to move this to
1576 // By default, we clear the native focus. This ensures that no visible native
1577 // view as the focus and that we still receive keyboard inputs.
1578 FocusManager* focus_manager = GetFocusManager();
1580 focus_manager->ClearNativeFocus();
1582 // TODO(beng): Investigate whether it's possible for us to move this to
1584 // Notify assistive technologies of the focus change.
1585 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1588 void View::OnBlur() {
1591 void View::Focus() {
1599 // Tooltips --------------------------------------------------------------------
1601 void View::TooltipTextChanged() {
1602 Widget* widget = GetWidget();
1603 // TooltipManager may be null if there is a problem creating it.
1604 if (widget && widget->GetTooltipManager())
1605 widget->GetTooltipManager()->TooltipTextChanged(this);
1608 // Context menus ---------------------------------------------------------------
1610 gfx::Point View::GetKeyboardContextMenuLocation() {
1611 gfx::Rect vis_bounds = GetVisibleBounds();
1612 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1613 vis_bounds.y() + vis_bounds.height() / 2);
1614 ConvertPointToScreen(this, &screen_point);
1615 return screen_point;
1618 // Drag and drop ---------------------------------------------------------------
1620 int View::GetDragOperations(const gfx::Point& press_pt) {
1621 return drag_controller_ ?
1622 drag_controller_->GetDragOperationsForView(this, press_pt) :
1623 ui::DragDropTypes::DRAG_NONE;
1626 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1627 DCHECK(drag_controller_);
1628 drag_controller_->WriteDragDataForView(this, press_pt, data);
1631 bool View::InDrag() {
1632 Widget* widget = GetWidget();
1633 return widget ? widget->dragged_view() == this : false;
1636 int View::GetHorizontalDragThreshold() {
1637 // TODO(jennyz): This value may need to be adjusted for different platforms
1638 // and for different display density.
1639 return kDefaultHorizontalDragThreshold;
1642 int View::GetVerticalDragThreshold() {
1643 // TODO(jennyz): This value may need to be adjusted for different platforms
1644 // and for different display density.
1645 return kDefaultVerticalDragThreshold;
1648 // Debugging -------------------------------------------------------------------
1650 #if !defined(NDEBUG)
1652 std::string View::PrintViewGraph(bool first) {
1653 return DoPrintViewGraph(first, this);
1656 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1657 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1658 const size_t kMaxPointerStringLength = 19;
1663 result.append("digraph {\n");
1665 // Node characteristics.
1666 char p[kMaxPointerStringLength];
1668 const std::string class_name(GetClassName());
1669 size_t base_name_index = class_name.find_last_of('/');
1670 if (base_name_index == std::string::npos)
1671 base_name_index = 0;
1675 char bounds_buffer[512];
1677 // Information about current node.
1678 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1679 result.append(" N");
1680 result.append(p + 2);
1681 result.append(" [label=\"");
1683 result.append(class_name.substr(base_name_index).c_str());
1685 base::snprintf(bounds_buffer,
1686 arraysize(bounds_buffer),
1687 "\\n bounds: (%d, %d), (%dx%d)",
1692 result.append(bounds_buffer);
1694 gfx::DecomposedTransform decomp;
1695 if (!GetTransform().IsIdentity() &&
1696 gfx::DecomposeTransform(&decomp, GetTransform())) {
1697 base::snprintf(bounds_buffer,
1698 arraysize(bounds_buffer),
1699 "\\n translation: (%f, %f)",
1700 decomp.translate[0],
1701 decomp.translate[1]);
1702 result.append(bounds_buffer);
1704 base::snprintf(bounds_buffer,
1705 arraysize(bounds_buffer),
1706 "\\n rotation: %3.2f",
1707 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1708 result.append(bounds_buffer);
1710 base::snprintf(bounds_buffer,
1711 arraysize(bounds_buffer),
1712 "\\n scale: (%2.4f, %2.4f)",
1715 result.append(bounds_buffer);
1718 result.append("\"");
1720 result.append(", shape=box");
1722 if (layer()->has_external_content())
1723 result.append(", color=green");
1725 result.append(", color=red");
1727 if (layer()->fills_bounds_opaquely())
1728 result.append(", style=filled");
1730 result.append("]\n");
1734 char pp[kMaxPointerStringLength];
1736 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1737 result.append(" N");
1738 result.append(pp + 2);
1739 result.append(" -> N");
1740 result.append(p + 2);
1741 result.append("\n");
1745 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1746 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1749 result.append("}\n");
1756 ////////////////////////////////////////////////////////////////////////////////
1759 // DropInfo --------------------------------------------------------------------
1761 void View::DragInfo::Reset() {
1762 possible_drag = false;
1763 start_pt = gfx::Point();
1766 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1767 possible_drag = true;
1771 // Painting --------------------------------------------------------------------
1773 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1774 // If we have a layer and the View's size did not change, we do not need to
1775 // schedule any paints since the layer will be redrawn at its new location
1776 // during the next Draw() cycle in the compositor.
1777 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1778 // Otherwise, if the size changes or we don't have a layer then we need to
1779 // use SchedulePaint to invalidate the area occupied by the View.
1781 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1782 // The compositor doesn't Draw() until something on screen changes, so
1783 // if our position changes but nothing is being animated on screen, then
1784 // tell the compositor to redraw the scene. We know layer() exists due to
1785 // the above if clause.
1786 layer()->ScheduleDraw();
1790 void View::PaintCommon(gfx::Canvas* canvas) {
1795 // If the View we are about to paint requested the canvas to be flipped, we
1796 // should change the transform appropriately.
1797 // The canvas mirroring is undone once the View is done painting so that we
1798 // don't pass the canvas with the mirrored transform to Views that didn't
1799 // request the canvas to be flipped.
1800 gfx::ScopedCanvas scoped(canvas);
1801 if (FlipCanvasOnPaintForRTLUI()) {
1802 canvas->Translate(gfx::Vector2d(width(), 0));
1803 canvas->Scale(-1, 1);
1809 PaintChildren(canvas);
1812 // Tree operations -------------------------------------------------------------
1814 void View::DoRemoveChildView(View* view,
1815 bool update_focus_cycle,
1816 bool update_tool_tip,
1817 bool delete_removed_view,
1821 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1822 scoped_ptr<View> view_to_be_deleted;
1823 if (i != children_.end()) {
1824 if (update_focus_cycle) {
1825 // Let's remove the view from the focus traversal.
1826 View* next_focusable = view->next_focusable_view_;
1827 View* prev_focusable = view->previous_focusable_view_;
1829 prev_focusable->next_focusable_view_ = next_focusable;
1831 next_focusable->previous_focusable_view_ = prev_focusable;
1835 UnregisterChildrenForVisibleBoundsNotification(view);
1836 if (view->visible())
1837 view->SchedulePaint();
1838 GetWidget()->NotifyWillRemoveView(view);
1840 view->PropagateRemoveNotifications(this, new_parent);
1841 view->parent_ = NULL;
1842 view->UpdateLayerVisibility();
1844 if (delete_removed_view && !view->owned_by_client_)
1845 view_to_be_deleted.reset(view);
1850 if (update_tool_tip)
1853 if (layout_manager_.get())
1854 layout_manager_->ViewRemoved(this, view);
1857 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1858 for (int i = 0, count = child_count(); i < count; ++i)
1859 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1861 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1862 for (View* v = this; v; v = v->parent_)
1863 v->ViewHierarchyChangedImpl(true, details);
1866 void View::PropagateAddNotifications(
1867 const ViewHierarchyChangedDetails& details) {
1868 for (int i = 0, count = child_count(); i < count; ++i)
1869 child_at(i)->PropagateAddNotifications(details);
1870 ViewHierarchyChangedImpl(true, details);
1873 void View::PropagateNativeViewHierarchyChanged() {
1874 for (int i = 0, count = child_count(); i < count; ++i)
1875 child_at(i)->PropagateNativeViewHierarchyChanged();
1876 NativeViewHierarchyChanged();
1879 void View::ViewHierarchyChangedImpl(
1880 bool register_accelerators,
1881 const ViewHierarchyChangedDetails& details) {
1882 if (register_accelerators) {
1883 if (details.is_add) {
1884 // If you get this registration, you are part of a subtree that has been
1885 // added to the view hierarchy.
1886 if (GetFocusManager())
1887 RegisterPendingAccelerators();
1889 if (details.child == this)
1890 UnregisterAccelerators(true);
1894 if (details.is_add && layer() && !layer()->parent()) {
1895 UpdateParentLayer();
1896 Widget* widget = GetWidget();
1898 widget->UpdateRootLayers();
1899 } else if (!details.is_add && details.child == this) {
1900 // Make sure the layers belonging to the subtree rooted at |child| get
1901 // removed from layers that do not belong in the same subtree.
1903 Widget* widget = GetWidget();
1905 widget->UpdateRootLayers();
1908 ViewHierarchyChanged(details);
1909 details.parent->needs_layout_ = true;
1912 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1913 for (int i = 0, count = child_count(); i < count; ++i)
1914 child_at(i)->PropagateNativeThemeChanged(theme);
1915 OnNativeThemeChanged(theme);
1918 // Size and disposition --------------------------------------------------------
1920 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1921 for (int i = 0, count = child_count(); i < count; ++i)
1922 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1923 VisibilityChangedImpl(start, is_visible);
1926 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1927 VisibilityChanged(starting_from, is_visible);
1930 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1932 // Paint the new bounds.
1933 SchedulePaintBoundsChanged(
1934 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1935 SCHEDULE_PAINT_SIZE_CHANGED);
1940 SetLayerBounds(GetLocalBounds() +
1941 gfx::Vector2d(GetMirroredX(), y()) +
1942 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1944 SetLayerBounds(bounds_);
1947 // If our bounds have changed, then any descendant layer bounds may have
1948 // changed. Update them accordingly.
1949 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1952 OnBoundsChanged(previous_bounds);
1954 if (previous_bounds.size() != size()) {
1955 needs_layout_ = false;
1959 if (NeedsNotificationWhenVisibleBoundsChange())
1960 OnVisibleBoundsChanged();
1962 // Notify interested Views that visible bounds within the root view may have
1964 if (descendants_to_notify_.get()) {
1965 for (Views::iterator i(descendants_to_notify_->begin());
1966 i != descendants_to_notify_->end(); ++i) {
1967 (*i)->OnVisibleBoundsChanged();
1973 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1974 if (view->NeedsNotificationWhenVisibleBoundsChange())
1975 view->RegisterForVisibleBoundsNotification();
1976 for (int i = 0; i < view->child_count(); ++i)
1977 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1981 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1982 if (view->NeedsNotificationWhenVisibleBoundsChange())
1983 view->UnregisterForVisibleBoundsNotification();
1984 for (int i = 0; i < view->child_count(); ++i)
1985 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1988 void View::RegisterForVisibleBoundsNotification() {
1989 if (registered_for_visible_bounds_notification_)
1992 registered_for_visible_bounds_notification_ = true;
1993 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1994 ancestor->AddDescendantToNotify(this);
1997 void View::UnregisterForVisibleBoundsNotification() {
1998 if (!registered_for_visible_bounds_notification_)
2001 registered_for_visible_bounds_notification_ = false;
2002 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
2003 ancestor->RemoveDescendantToNotify(this);
2006 void View::AddDescendantToNotify(View* view) {
2008 if (!descendants_to_notify_.get())
2009 descendants_to_notify_.reset(new Views);
2010 descendants_to_notify_->push_back(view);
2013 void View::RemoveDescendantToNotify(View* view) {
2014 DCHECK(view && descendants_to_notify_.get());
2015 Views::iterator i(std::find(
2016 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
2017 DCHECK(i != descendants_to_notify_->end());
2018 descendants_to_notify_->erase(i);
2019 if (descendants_to_notify_->empty())
2020 descendants_to_notify_.reset();
2023 void View::SetLayerBounds(const gfx::Rect& bounds) {
2024 layer()->SetBounds(bounds);
2027 // Transformations -------------------------------------------------------------
2029 bool View::GetTransformRelativeTo(const View* ancestor,
2030 gfx::Transform* transform) const {
2031 const View* p = this;
2033 while (p && p != ancestor) {
2034 transform->ConcatTransform(p->GetTransform());
2035 gfx::Transform translation;
2036 translation.Translate(static_cast<float>(p->GetMirroredX()),
2037 static_cast<float>(p->y()));
2038 transform->ConcatTransform(translation);
2043 return p == ancestor;
2046 // Coordinate conversion -------------------------------------------------------
2048 bool View::ConvertPointForAncestor(const View* ancestor,
2049 gfx::Point* point) const {
2050 gfx::Transform trans;
2051 // TODO(sad): Have some way of caching the transformation results.
2052 bool result = GetTransformRelativeTo(ancestor, &trans);
2053 gfx::Point3F p(*point);
2054 trans.TransformPoint(&p);
2055 *point = gfx::ToFlooredPoint(p.AsPointF());
2059 bool View::ConvertPointFromAncestor(const View* ancestor,
2060 gfx::Point* point) const {
2061 gfx::Transform trans;
2062 bool result = GetTransformRelativeTo(ancestor, &trans);
2063 gfx::Point3F p(*point);
2064 trans.TransformPointReverse(&p);
2065 *point = gfx::ToFlooredPoint(p.AsPointF());
2069 bool View::ConvertRectForAncestor(const View* ancestor,
2070 gfx::RectF* rect) const {
2071 gfx::Transform trans;
2072 // TODO(sad): Have some way of caching the transformation results.
2073 bool result = GetTransformRelativeTo(ancestor, &trans);
2074 trans.TransformRect(rect);
2078 bool View::ConvertRectFromAncestor(const View* ancestor,
2079 gfx::RectF* rect) const {
2080 gfx::Transform trans;
2081 bool result = GetTransformRelativeTo(ancestor, &trans);
2082 trans.TransformRectReverse(rect);
2086 // Accelerated painting --------------------------------------------------------
2088 void View::CreateLayer() {
2089 // A new layer is being created for the view. So all the layers of the
2090 // sub-tree can inherit the visibility of the corresponding view.
2091 for (int i = 0, count = child_count(); i < count; ++i)
2092 child_at(i)->UpdateChildLayerVisibility(true);
2094 SetLayer(new ui::Layer());
2095 layer()->set_delegate(this);
2096 #if !defined(NDEBUG)
2097 layer()->set_name(GetClassName());
2100 UpdateParentLayers();
2101 UpdateLayerVisibility();
2103 // The new layer needs to be ordered in the layer tree according
2104 // to the view tree. Children of this layer were added in order
2105 // in UpdateParentLayers().
2107 parent()->ReorderLayers();
2109 Widget* widget = GetWidget();
2111 widget->UpdateRootLayers();
2114 void View::UpdateParentLayers() {
2115 // Attach all top-level un-parented layers.
2116 if (layer() && !layer()->parent()) {
2117 UpdateParentLayer();
2119 for (int i = 0, count = child_count(); i < count; ++i)
2120 child_at(i)->UpdateParentLayers();
2124 void View::OrphanLayers() {
2126 if (layer()->parent())
2127 layer()->parent()->Remove(layer());
2129 // The layer belonging to this View has already been orphaned. It is not
2130 // necessary to orphan the child layers.
2133 for (int i = 0, count = child_count(); i < count; ++i)
2134 child_at(i)->OrphanLayers();
2137 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2138 layer()->SetBounds(GetLocalBounds() + offset);
2139 DCHECK_NE(layer(), parent_layer);
2141 parent_layer->Add(layer());
2142 layer()->SchedulePaint(GetLocalBounds());
2143 MoveLayerToParent(layer(), gfx::Point());
2146 void View::DestroyLayer() {
2147 ui::Layer* new_parent = layer()->parent();
2148 std::vector<ui::Layer*> children = layer()->children();
2149 for (size_t i = 0; i < children.size(); ++i) {
2150 layer()->Remove(children[i]);
2152 new_parent->Add(children[i]);
2155 LayerOwner::DestroyLayer();
2160 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2164 Widget* widget = GetWidget();
2166 widget->UpdateRootLayers();
2169 // Input -----------------------------------------------------------------------
2171 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2172 int drag_operations =
2173 (enabled_ && event.IsOnlyLeftMouseButton() &&
2174 HitTestPoint(event.location())) ?
2175 GetDragOperations(event.location()) : 0;
2176 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2177 context_menu_controller_ : 0;
2178 View::DragInfo* drag_info = GetDragInfo();
2180 // TODO(sky): for debugging 360238.
2182 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2183 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2184 ViewStorage* view_storage = ViewStorage::GetInstance();
2185 storage_id = view_storage->CreateStorageID();
2186 view_storage->StoreView(storage_id, this);
2189 const bool enabled = enabled_;
2190 const bool result = OnMousePressed(event);
2195 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2196 kContextMenuOnMousePress) {
2197 // Assume that if there is a context menu controller we won't be deleted
2198 // from mouse pressed.
2199 gfx::Point location(event.location());
2200 if (HitTestPoint(location)) {
2201 if (storage_id != 0)
2202 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2203 ConvertPointToScreen(this, &location);
2204 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2209 // WARNING: we may have been deleted, don't use any View variables.
2210 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2211 drag_info->PossibleDrag(event.location());
2214 return !!context_menu_controller || result;
2217 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2218 // Copy the field, that way if we're deleted after drag and drop no harm is
2220 ContextMenuController* context_menu_controller = context_menu_controller_;
2221 const bool possible_drag = GetDragInfo()->possible_drag;
2222 if (possible_drag &&
2223 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2224 (!drag_controller_ ||
2225 drag_controller_->CanStartDragForView(
2226 this, GetDragInfo()->start_pt, event.location()))) {
2227 DoDrag(event, GetDragInfo()->start_pt,
2228 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2230 if (OnMouseDragged(event))
2232 // Fall through to return value based on context menu controller.
2234 // WARNING: we may have been deleted.
2235 return (context_menu_controller != NULL) || possible_drag;
2238 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2239 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2240 event.IsOnlyRightMouseButton()) {
2241 // Assume that if there is a context menu controller we won't be deleted
2242 // from mouse released.
2243 gfx::Point location(event.location());
2244 OnMouseReleased(event);
2245 if (HitTestPoint(location)) {
2246 ConvertPointToScreen(this, &location);
2247 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2250 OnMouseReleased(event);
2252 // WARNING: we may have been deleted.
2255 // Accelerators ----------------------------------------------------------------
2257 void View::RegisterPendingAccelerators() {
2258 if (!accelerators_.get() ||
2259 registered_accelerator_count_ == accelerators_->size()) {
2260 // No accelerators are waiting for registration.
2265 // The view is not yet attached to a widget, defer registration until then.
2269 accelerator_focus_manager_ = GetFocusManager();
2270 if (!accelerator_focus_manager_) {
2271 // Some crash reports seem to show that we may get cases where we have no
2272 // focus manager (see bug #1291225). This should never be the case, just
2273 // making sure we don't crash.
2277 for (std::vector<ui::Accelerator>::const_iterator i(
2278 accelerators_->begin() + registered_accelerator_count_);
2279 i != accelerators_->end(); ++i) {
2280 accelerator_focus_manager_->RegisterAccelerator(
2281 *i, ui::AcceleratorManager::kNormalPriority, this);
2283 registered_accelerator_count_ = accelerators_->size();
2286 void View::UnregisterAccelerators(bool leave_data_intact) {
2287 if (!accelerators_.get())
2291 if (accelerator_focus_manager_) {
2292 accelerator_focus_manager_->UnregisterAccelerators(this);
2293 accelerator_focus_manager_ = NULL;
2295 if (!leave_data_intact) {
2296 accelerators_->clear();
2297 accelerators_.reset();
2299 registered_accelerator_count_ = 0;
2303 // Focus -----------------------------------------------------------------------
2305 void View::InitFocusSiblings(View* v, int index) {
2306 int count = child_count();
2309 v->next_focusable_view_ = NULL;
2310 v->previous_focusable_view_ = NULL;
2312 if (index == count) {
2313 // We are inserting at the end, but the end of the child list may not be
2314 // the last focusable element. Let's try to find an element with no next
2315 // focusable element to link to.
2316 View* last_focusable_view = NULL;
2317 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2318 if (!(*i)->next_focusable_view_) {
2319 last_focusable_view = *i;
2323 if (last_focusable_view == NULL) {
2324 // Hum... there is a cycle in the focus list. Let's just insert ourself
2325 // after the last child.
2326 View* prev = children_[index - 1];
2327 v->previous_focusable_view_ = prev;
2328 v->next_focusable_view_ = prev->next_focusable_view_;
2329 prev->next_focusable_view_->previous_focusable_view_ = v;
2330 prev->next_focusable_view_ = v;
2332 last_focusable_view->next_focusable_view_ = v;
2333 v->next_focusable_view_ = NULL;
2334 v->previous_focusable_view_ = last_focusable_view;
2337 View* prev = children_[index]->GetPreviousFocusableView();
2338 v->previous_focusable_view_ = prev;
2339 v->next_focusable_view_ = children_[index];
2341 prev->next_focusable_view_ = v;
2342 children_[index]->previous_focusable_view_ = v;
2347 // System events ---------------------------------------------------------------
2349 void View::PropagateThemeChanged() {
2350 for (int i = child_count() - 1; i >= 0; --i)
2351 child_at(i)->PropagateThemeChanged();
2355 void View::PropagateLocaleChanged() {
2356 for (int i = child_count() - 1; i >= 0; --i)
2357 child_at(i)->PropagateLocaleChanged();
2361 // Tooltips --------------------------------------------------------------------
2363 void View::UpdateTooltip() {
2364 Widget* widget = GetWidget();
2365 // TODO(beng): The TooltipManager NULL check can be removed when we
2366 // consolidate Init() methods and make views_unittests Init() all
2367 // Widgets that it uses.
2368 if (widget && widget->GetTooltipManager())
2369 widget->GetTooltipManager()->UpdateTooltip();
2372 // Drag and drop ---------------------------------------------------------------
2374 bool View::DoDrag(const ui::LocatedEvent& event,
2375 const gfx::Point& press_pt,
2376 ui::DragDropTypes::DragEventSource source) {
2377 int drag_operations = GetDragOperations(press_pt);
2378 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2381 Widget* widget = GetWidget();
2382 // We should only start a drag from an event, implying we have a widget.
2385 // Don't attempt to start a drag while in the process of dragging. This is
2386 // especially important on X where we can get multiple mouse move events when
2387 // we start the drag.
2388 if (widget->dragged_view())
2391 OSExchangeData data;
2392 WriteDragData(press_pt, &data);
2394 // Message the RootView to do the drag and drop. That way if we're removed
2395 // the RootView can detect it and avoid calling us back.
2396 gfx::Point widget_location(event.location());
2397 ConvertPointToWidget(this, &widget_location);
2398 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2399 // WARNING: we may have been deleted.
2403 } // namespace views