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/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/events/event_target_iterator.h"
26 #include "ui/gfx/canvas.h"
27 #include "ui/gfx/interpolated_transform.h"
28 #include "ui/gfx/path.h"
29 #include "ui/gfx/point3_f.h"
30 #include "ui/gfx/point_conversions.h"
31 #include "ui/gfx/rect_conversions.h"
32 #include "ui/gfx/scoped_canvas.h"
33 #include "ui/gfx/screen.h"
34 #include "ui/gfx/skia_util.h"
35 #include "ui/gfx/transform.h"
36 #include "ui/native_theme/native_theme.h"
37 #include "ui/views/accessibility/native_view_accessibility.h"
38 #include "ui/views/background.h"
39 #include "ui/views/border.h"
40 #include "ui/views/context_menu_controller.h"
41 #include "ui/views/drag_controller.h"
42 #include "ui/views/layout/layout_manager.h"
43 #include "ui/views/rect_based_targeting_utils.h"
44 #include "ui/views/views_delegate.h"
45 #include "ui/views/widget/native_widget_private.h"
46 #include "ui/views/widget/root_view.h"
47 #include "ui/views/widget/tooltip_manager.h"
48 #include "ui/views/widget/widget.h"
51 #include "ui/base/cursor/cursor.h"
55 #include "base/win/scoped_gdi_object.h"
60 // Whether to use accelerated compositing when necessary (e.g. when a view has a
63 bool use_acceleration_when_possible = true;
65 bool use_acceleration_when_possible = false;
69 const bool kContextMenuOnMousePress = false;
71 const bool kContextMenuOnMousePress = true;
74 // The minimum percentage of a view's area that needs to be covered by a rect
75 // representing a touch region in order for that view to be considered by the
76 // rect-based targeting algorithm.
77 static const float kRectTargetOverlap = 0.6f;
79 // Returns the top view in |view|'s hierarchy.
80 const views::View* GetHierarchyRoot(const views::View* view) {
81 const views::View* root = view;
82 while (root && root->parent())
83 root = root->parent();
93 // This event handler receives events in the post-target phase and takes care of
95 // - Generates context menu, or initiates drag-and-drop, from gesture events.
96 class PostEventDispatchHandler : public ui::EventHandler {
98 explicit PostEventDispatchHandler(View* owner)
100 touch_dnd_enabled_(switches::IsTouchDragDropEnabled()) {
102 virtual ~PostEventDispatchHandler() {}
105 // Overridden from ui::EventHandler:
106 virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
107 DCHECK_EQ(ui::EP_POSTTARGET, event->phase());
108 if (event->handled())
111 if (touch_dnd_enabled_) {
112 if (event->type() == ui::ET_GESTURE_LONG_PRESS &&
113 (!owner_->drag_controller() ||
114 owner_->drag_controller()->CanStartDragForView(
115 owner_, event->location(), event->location()))) {
116 if (owner_->DoDrag(*event, event->location(),
117 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH)) {
118 event->StopPropagation();
124 if (owner_->context_menu_controller() &&
125 (event->type() == ui::ET_GESTURE_LONG_PRESS ||
126 event->type() == ui::ET_GESTURE_LONG_TAP ||
127 event->type() == ui::ET_GESTURE_TWO_FINGER_TAP)) {
128 gfx::Point location(event->location());
129 View::ConvertPointToScreen(owner_, &location);
130 owner_->ShowContextMenu(location, ui::MENU_SOURCE_TOUCH);
131 event->StopPropagation();
136 bool touch_dnd_enabled_;
138 DISALLOW_COPY_AND_ASSIGN(PostEventDispatchHandler);
141 } // namespace internal
144 ViewsDelegate* ViewsDelegate::views_delegate = NULL;
147 const char View::kViewClassName[] = "View";
149 ////////////////////////////////////////////////////////////////////////////////
152 // Creation and lifetime -------------------------------------------------------
155 : owned_by_client_(false),
161 notify_enter_exit_on_child_(false),
162 registered_for_visible_bounds_notification_(false),
163 clip_insets_(0, 0, 0, 0),
165 flip_canvas_on_paint_for_rtl_ui_(false),
166 paint_to_layer_(false),
167 accelerator_focus_manager_(NULL),
168 registered_accelerator_count_(0),
169 next_focusable_view_(NULL),
170 previous_focusable_view_(NULL),
172 accessibility_focusable_(false),
173 context_menu_controller_(NULL),
174 drag_controller_(NULL),
175 post_dispatch_handler_(new internal::PostEventDispatchHandler(this)),
176 native_view_accessibility_(NULL) {
177 AddPostTargetHandler(post_dispatch_handler_.get());
182 parent_->RemoveChildView(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 const ui::NativeTheme* old_theme = view->GetNativeTheme();
222 if (parent == this) {
223 ReorderChildView(view, index);
226 parent->DoRemoveChildView(view, true, true, false, this);
229 // Sets the prev/next focus views.
230 InitFocusSiblings(view, index);
232 // Let's insert the view.
233 view->parent_ = this;
234 children_.insert(children_.begin() + index, view);
236 ViewHierarchyChangedDetails details(true, this, view, parent);
238 for (View* v = this; v; v = v->parent_)
239 v->ViewHierarchyChangedImpl(false, details);
241 view->PropagateAddNotifications(details);
243 views::Widget* widget = GetWidget();
245 RegisterChildrenForVisibleBoundsNotification(view);
246 const ui::NativeTheme* new_theme = widget->GetNativeTheme();
247 if (new_theme != old_theme)
248 PropagateNativeThemeChanged(new_theme);
250 view->SchedulePaint();
253 if (layout_manager_.get())
254 layout_manager_->ViewAdded(this, view);
256 if (use_acceleration_when_possible)
259 // Make sure the visibility of the child layers are correct.
260 // If any of the parent View is hidden, then the layers of the subtree
261 // rooted at |this| should be hidden. Otherwise, all the child layers should
262 // inherit the visibility of the owner View.
263 UpdateLayerVisibility();
266 void View::ReorderChildView(View* view, int index) {
267 DCHECK_EQ(view->parent_, this);
269 index = child_count() - 1;
270 else if (index >= child_count())
272 if (children_[index] == view)
275 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
276 DCHECK(i != children_.end());
279 // Unlink the view first
280 View* next_focusable = view->next_focusable_view_;
281 View* prev_focusable = view->previous_focusable_view_;
283 prev_focusable->next_focusable_view_ = next_focusable;
285 next_focusable->previous_focusable_view_ = prev_focusable;
287 // Add it in the specified index now.
288 InitFocusSiblings(view, index);
289 children_.insert(children_.begin() + index, view);
291 if (use_acceleration_when_possible)
295 void View::RemoveChildView(View* view) {
296 DoRemoveChildView(view, true, true, false, NULL);
299 void View::RemoveAllChildViews(bool delete_children) {
300 while (!children_.empty())
301 DoRemoveChildView(children_.front(), false, false, delete_children, NULL);
305 bool View::Contains(const View* view) const {
306 for (const View* v = view; v; v = v->parent_) {
313 int View::GetIndexOf(const View* view) const {
314 Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
315 return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
318 // Size and disposition --------------------------------------------------------
320 void View::SetBounds(int x, int y, int width, int height) {
321 SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
324 void View::SetBoundsRect(const gfx::Rect& bounds) {
325 if (bounds == bounds_) {
327 needs_layout_ = false;
334 // Paint where the view is currently.
335 SchedulePaintBoundsChanged(
336 bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
337 SCHEDULE_PAINT_SIZE_CHANGED);
340 gfx::Rect prev = bounds_;
345 void View::SetSize(const gfx::Size& size) {
346 SetBounds(x(), y(), size.width(), size.height());
349 void View::SetPosition(const gfx::Point& position) {
350 SetBounds(position.x(), position.y(), width(), height());
353 void View::SetX(int x) {
354 SetBounds(x, y(), width(), height());
357 void View::SetY(int y) {
358 SetBounds(x(), y, width(), height());
361 gfx::Rect View::GetContentsBounds() const {
362 gfx::Rect contents_bounds(GetLocalBounds());
364 contents_bounds.Inset(border_->GetInsets());
365 return contents_bounds;
368 gfx::Rect View::GetLocalBounds() const {
369 return gfx::Rect(size());
372 gfx::Rect View::GetLayerBoundsInPixel() const {
373 return layer()->GetTargetBounds();
376 gfx::Insets View::GetInsets() const {
377 return border_.get() ? border_->GetInsets() : gfx::Insets();
380 gfx::Rect View::GetVisibleBounds() const {
383 gfx::Rect vis_bounds(GetLocalBounds());
384 gfx::Rect ancestor_bounds;
385 const View* view = this;
386 gfx::Transform transform;
388 while (view != NULL && !vis_bounds.IsEmpty()) {
389 transform.ConcatTransform(view->GetTransform());
390 gfx::Transform translation;
391 translation.Translate(static_cast<float>(view->GetMirroredX()),
392 static_cast<float>(view->y()));
393 transform.ConcatTransform(translation);
395 vis_bounds = view->ConvertRectToParent(vis_bounds);
396 const View* ancestor = view->parent_;
397 if (ancestor != NULL) {
398 ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
399 vis_bounds.Intersect(ancestor_bounds);
400 } else if (!view->GetWidget()) {
401 // If the view has no Widget, we're not visible. Return an empty rect.
406 if (vis_bounds.IsEmpty())
408 // Convert back to this views coordinate system.
409 gfx::RectF views_vis_bounds(vis_bounds);
410 transform.TransformRectReverse(&views_vis_bounds);
411 // Partially visible pixels should be considered visible.
412 return gfx::ToEnclosingRect(views_vis_bounds);
415 gfx::Rect View::GetBoundsInScreen() const {
417 View::ConvertPointToScreen(this, &origin);
418 return gfx::Rect(origin, size());
421 gfx::Size View::GetPreferredSize() {
422 if (layout_manager_.get())
423 return layout_manager_->GetPreferredSize(this);
427 int View::GetBaseline() const {
431 void View::SizeToPreferredSize() {
432 gfx::Size prefsize = GetPreferredSize();
433 if ((prefsize.width() != width()) || (prefsize.height() != height()))
434 SetBounds(x(), y(), prefsize.width(), prefsize.height());
437 gfx::Size View::GetMinimumSize() {
438 return GetPreferredSize();
441 gfx::Size View::GetMaximumSize() {
445 int View::GetHeightForWidth(int w) {
446 if (layout_manager_.get())
447 return layout_manager_->GetPreferredHeightForWidth(this, w);
448 return GetPreferredSize().height();
451 void View::SetVisible(bool visible) {
452 if (visible != visible_) {
453 // If the View is currently visible, schedule paint to refresh parent.
454 // TODO(beng): not sure we should be doing this if we have a layer.
460 // Notify the parent.
462 parent_->ChildVisibilityChanged(this);
464 // This notifies all sub-views recursively.
465 PropagateVisibilityNotifications(this, visible_);
466 UpdateLayerVisibility();
468 // If we are newly visible, schedule paint.
474 bool View::IsDrawn() const {
475 return visible_ && parent_ ? parent_->IsDrawn() : false;
478 void View::SetEnabled(bool enabled) {
479 if (enabled != enabled_) {
485 void View::OnEnabledChanged() {
489 // Transformations -------------------------------------------------------------
491 gfx::Transform View::GetTransform() const {
492 return layer() ? layer()->transform() : gfx::Transform();
495 void View::SetTransform(const gfx::Transform& transform) {
496 if (transform.IsIdentity()) {
498 layer()->SetTransform(transform);
499 if (!paint_to_layer_)
507 layer()->SetTransform(transform);
508 layer()->ScheduleDraw();
512 void View::SetPaintToLayer(bool paint_to_layer) {
513 paint_to_layer_ = paint_to_layer;
514 if (paint_to_layer_ && !layer()) {
516 } else if (!paint_to_layer_ && layer()) {
521 ui::Layer* View::RecreateLayer() {
522 ui::Layer* layer = AcquireLayer();
527 layer_->set_scale_content(layer->scale_content());
531 // RTL positioning -------------------------------------------------------------
533 gfx::Rect View::GetMirroredBounds() const {
534 gfx::Rect bounds(bounds_);
535 bounds.set_x(GetMirroredX());
539 gfx::Point View::GetMirroredPosition() const {
540 return gfx::Point(GetMirroredX(), y());
543 int View::GetMirroredX() const {
544 return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
547 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
548 return base::i18n::IsRTL() ?
549 (width() - bounds.x() - bounds.width()) : bounds.x();
552 int View::GetMirroredXInView(int x) const {
553 return base::i18n::IsRTL() ? width() - x : x;
556 int View::GetMirroredXWithWidthInView(int x, int w) const {
557 return base::i18n::IsRTL() ? width() - x - w : x;
560 // Layout ----------------------------------------------------------------------
562 void View::Layout() {
563 needs_layout_ = false;
565 // If we have a layout manager, let it handle the layout for us.
566 if (layout_manager_.get())
567 layout_manager_->Layout(this);
569 // Make sure to propagate the Layout() call to any children that haven't
570 // received it yet through the layout manager and need to be laid out. This
571 // is needed for the case when the child requires a layout but its bounds
572 // weren't changed by the layout manager. If there is no layout manager, we
573 // just propagate the Layout() call down the hierarchy, so whoever receives
574 // the call can take appropriate action.
575 for (int i = 0, count = child_count(); i < count; ++i) {
576 View* child = child_at(i);
577 if (child->needs_layout_ || !layout_manager_.get()) {
578 child->needs_layout_ = false;
584 void View::InvalidateLayout() {
585 // Always invalidate up. This is needed to handle the case of us already being
586 // valid, but not our parent.
587 needs_layout_ = true;
589 parent_->InvalidateLayout();
592 LayoutManager* View::GetLayoutManager() const {
593 return layout_manager_.get();
596 void View::SetLayoutManager(LayoutManager* layout_manager) {
597 if (layout_manager_.get())
598 layout_manager_->Uninstalled(this);
600 layout_manager_.reset(layout_manager);
601 if (layout_manager_.get())
602 layout_manager_->Installed(this);
605 // Attributes ------------------------------------------------------------------
607 const char* View::GetClassName() const {
608 return kViewClassName;
611 View* View::GetAncestorWithClassName(const std::string& name) {
612 for (View* view = this; view; view = view->parent_) {
613 if (!strcmp(view->GetClassName(), name.c_str()))
619 const View* View::GetViewByID(int id) const {
621 return const_cast<View*>(this);
623 for (int i = 0, count = child_count(); i < count; ++i) {
624 const View* view = child_at(i)->GetViewByID(id);
631 View* View::GetViewByID(int id) {
632 return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
635 void View::SetGroup(int gid) {
636 // Don't change the group id once it's set.
637 DCHECK(group_ == -1 || group_ == gid);
641 int View::GetGroup() const {
645 bool View::IsGroupFocusTraversable() const {
649 void View::GetViewsInGroup(int group, Views* views) {
651 views->push_back(this);
653 for (int i = 0, count = child_count(); i < count; ++i)
654 child_at(i)->GetViewsInGroup(group, views);
657 View* View::GetSelectedViewForGroup(int group) {
659 GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
660 return views.empty() ? NULL : views[0];
663 // Coordinate conversion -------------------------------------------------------
666 void View::ConvertPointToTarget(const View* source,
671 if (source == target)
674 const View* root = GetHierarchyRoot(target);
675 CHECK_EQ(GetHierarchyRoot(source), root);
678 source->ConvertPointForAncestor(root, point);
681 target->ConvertPointFromAncestor(root, point);
685 void View::ConvertRectToTarget(const View* source,
690 if (source == target)
693 const View* root = GetHierarchyRoot(target);
694 CHECK_EQ(GetHierarchyRoot(source), root);
697 source->ConvertRectForAncestor(root, rect);
700 target->ConvertRectFromAncestor(root, rect);
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 gfx::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 void View::set_background(Background* b) {
806 background_.reset(b);
809 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
811 ui::ThemeProvider* View::GetThemeProvider() const {
812 const Widget* widget = GetWidget();
813 return widget ? widget->GetThemeProvider() : NULL;
816 const ui::NativeTheme* View::GetNativeTheme() const {
817 const Widget* widget = GetWidget();
818 return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
821 // Accelerated Painting --------------------------------------------------------
824 void View::set_use_acceleration_when_possible(bool use) {
825 use_acceleration_when_possible = use;
829 bool View::get_use_acceleration_when_possible() {
830 return use_acceleration_when_possible;
833 // Input -----------------------------------------------------------------------
835 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
836 return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
839 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
840 // |rect_view| represents the current best candidate to return
841 // if rect-based targeting (i.e., fuzzing) is used.
842 // |rect_view_distance| is used to keep track of the distance
843 // between the center point of |rect_view| and the center
845 View* rect_view = NULL;
846 int rect_view_distance = INT_MAX;
848 // |point_view| represents the view that would have been returned
849 // from this function call if point-based targeting were used.
850 View* point_view = NULL;
852 for (int i = child_count() - 1; i >= 0; --i) {
853 View* child = child_at(i);
855 // Ignore any children which are invisible or do not intersect |rect|.
856 if (!child->visible())
858 gfx::RectF rect_in_child_coords_f(rect);
859 ConvertRectToTarget(this, child, &rect_in_child_coords_f);
860 gfx::Rect rect_in_child_coords = gfx::ToEnclosingRect(
861 rect_in_child_coords_f);
862 if (!child->HitTestRect(rect_in_child_coords))
865 View* cur_view = child->GetEventHandlerForRect(rect_in_child_coords);
867 if (views::UsePointBasedTargeting(rect))
870 gfx::RectF cur_view_bounds_f(cur_view->GetLocalBounds());
871 ConvertRectToTarget(cur_view, this, &cur_view_bounds_f);
872 gfx::Rect cur_view_bounds = gfx::ToEnclosingRect(
874 if (views::PercentCoveredBy(cur_view_bounds, rect) >= kRectTargetOverlap) {
875 // |cur_view| is a suitable candidate for rect-based targeting.
876 // Check to see if it is the closest suitable candidate so far.
877 gfx::Point touch_center(rect.CenterPoint());
878 int cur_dist = views::DistanceSquaredFromCenterToPoint(touch_center,
880 if (!rect_view || cur_dist < rect_view_distance) {
881 rect_view = cur_view;
882 rect_view_distance = cur_dist;
884 } else if (!rect_view && !point_view) {
885 // Rect-based targeting has not yielded any candidates so far. Check
886 // if point-based targeting would have selected |cur_view|.
887 gfx::Point point_in_child_coords(rect_in_child_coords.CenterPoint());
888 if (child->HitTestPoint(point_in_child_coords))
889 point_view = child->GetEventHandlerForPoint(point_in_child_coords);
893 if (views::UsePointBasedTargeting(rect) || (!rect_view && !point_view))
896 // If |this| is a suitable candidate for rect-based targeting, check to
897 // see if it is closer than the current best suitable candidate so far.
898 gfx::Rect local_bounds(GetLocalBounds());
899 if (views::PercentCoveredBy(local_bounds, rect) >= kRectTargetOverlap) {
900 gfx::Point touch_center(rect.CenterPoint());
901 int cur_dist = views::DistanceSquaredFromCenterToPoint(touch_center,
903 if (!rect_view || cur_dist < rect_view_distance)
907 return rect_view ? rect_view : point_view;
910 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
911 if (!HitTestPoint(point))
914 // Walk the child Views recursively looking for the View that most
915 // tightly encloses the specified point.
916 for (int i = child_count() - 1; i >= 0; --i) {
917 View* child = child_at(i);
918 if (!child->visible())
921 gfx::Point point_in_child_coords(point);
922 ConvertPointToTarget(this, child, &point_in_child_coords);
923 View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
930 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
932 #if defined(USE_AURA)
933 static ui::Cursor arrow;
934 if (!arrow.platform())
935 arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
938 static HCURSOR arrow = LoadCursor(NULL, IDC_ARROW);
942 return gfx::kNullCursor;
946 bool View::HitTestPoint(const gfx::Point& point) const {
947 return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
950 bool View::HitTestRect(const gfx::Rect& rect) const {
951 if (GetLocalBounds().Intersects(rect)) {
952 if (HasHitTestMask()) {
954 HitTestSource source = HIT_TEST_SOURCE_MOUSE;
955 if (!views::UsePointBasedTargeting(rect))
956 source = HIT_TEST_SOURCE_TOUCH;
957 GetHitTestMask(source, &mask);
958 #if defined(USE_AURA)
959 // TODO: should we use this every where?
960 SkRegion clip_region;
961 clip_region.setRect(0, 0, width(), height());
962 SkRegion mask_region;
963 return mask_region.setPath(mask, clip_region) &&
964 mask_region.intersects(RectToSkIRect(rect));
965 #elif defined(OS_WIN)
966 base::win::ScopedRegion rgn(mask.CreateNativeRegion());
967 const RECT r(rect.ToRECT());
968 return RectInRegion(rgn, &r) != 0;
971 // No mask, but inside our bounds.
974 // Outside our bounds.
978 bool View::IsMouseHovered() {
979 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
984 // If mouse events are disabled, then the mouse cursor is invisible and
985 // is therefore not hovering over this button.
986 if (!GetWidget()->IsMouseEventsEnabled())
989 gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
990 GetWidget()->GetNativeView())->GetCursorScreenPoint());
991 ConvertPointFromScreen(this, &cursor_pos);
992 return HitTestPoint(cursor_pos);
995 bool View::OnMousePressed(const ui::MouseEvent& event) {
999 bool View::OnMouseDragged(const ui::MouseEvent& event) {
1003 void View::OnMouseReleased(const ui::MouseEvent& event) {
1006 void View::OnMouseCaptureLost() {
1009 void View::OnMouseMoved(const ui::MouseEvent& event) {
1012 void View::OnMouseEntered(const ui::MouseEvent& event) {
1015 void View::OnMouseExited(const ui::MouseEvent& event) {
1018 void View::SetMouseHandler(View* new_mouse_handler) {
1019 // |new_mouse_handler| may be NULL.
1021 parent_->SetMouseHandler(new_mouse_handler);
1024 bool View::OnKeyPressed(const ui::KeyEvent& event) {
1028 bool View::OnKeyReleased(const ui::KeyEvent& event) {
1032 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
1036 void View::OnKeyEvent(ui::KeyEvent* event) {
1037 bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
1038 OnKeyReleased(*event);
1040 event->StopPropagation();
1043 void View::OnMouseEvent(ui::MouseEvent* event) {
1044 switch (event->type()) {
1045 case ui::ET_MOUSE_PRESSED:
1046 if (ProcessMousePressed(*event))
1047 event->SetHandled();
1050 case ui::ET_MOUSE_MOVED:
1051 if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
1052 ui::EF_RIGHT_MOUSE_BUTTON |
1053 ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
1054 OnMouseMoved(*event);
1058 case ui::ET_MOUSE_DRAGGED:
1059 if (ProcessMouseDragged(*event))
1060 event->SetHandled();
1063 case ui::ET_MOUSE_RELEASED:
1064 ProcessMouseReleased(*event);
1067 case ui::ET_MOUSEWHEEL:
1068 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
1069 event->SetHandled();
1072 case ui::ET_MOUSE_ENTERED:
1073 OnMouseEntered(*event);
1076 case ui::ET_MOUSE_EXITED:
1077 OnMouseExited(*event);
1085 void View::OnScrollEvent(ui::ScrollEvent* event) {
1088 void View::OnTouchEvent(ui::TouchEvent* event) {
1091 void View::OnGestureEvent(ui::GestureEvent* event) {
1094 ui::TextInputClient* View::GetTextInputClient() {
1098 InputMethod* View::GetInputMethod() {
1099 Widget* widget = GetWidget();
1100 return widget ? widget->GetInputMethod() : NULL;
1103 const InputMethod* View::GetInputMethod() const {
1104 const Widget* widget = GetWidget();
1105 return widget ? widget->GetInputMethod() : NULL;
1108 bool View::CanAcceptEvent(const ui::Event& event) {
1112 ui::EventTarget* View::GetParentTarget() {
1116 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1117 return scoped_ptr<ui::EventTargetIterator>(
1118 new ui::EventTargetIteratorImpl<View>(children_));
1121 ui::EventTargeter* View::GetEventTargeter() {
1125 // Accelerators ----------------------------------------------------------------
1127 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1128 if (!accelerators_.get())
1129 accelerators_.reset(new std::vector<ui::Accelerator>());
1131 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1132 accelerators_->end()) {
1133 accelerators_->push_back(accelerator);
1135 RegisterPendingAccelerators();
1138 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1139 if (!accelerators_.get()) {
1140 NOTREACHED() << "Removing non-existing accelerator";
1144 std::vector<ui::Accelerator>::iterator i(
1145 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1146 if (i == accelerators_->end()) {
1147 NOTREACHED() << "Removing non-existing accelerator";
1151 size_t index = i - accelerators_->begin();
1152 accelerators_->erase(i);
1153 if (index >= registered_accelerator_count_) {
1154 // The accelerator is not registered to FocusManager.
1157 --registered_accelerator_count_;
1159 // Providing we are attached to a Widget and registered with a focus manager,
1160 // we should de-register from that focus manager now.
1161 if (GetWidget() && accelerator_focus_manager_)
1162 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1165 void View::ResetAccelerators() {
1166 if (accelerators_.get())
1167 UnregisterAccelerators(false);
1170 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1174 bool View::CanHandleAccelerators() const {
1175 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1178 // Focus -----------------------------------------------------------------------
1180 bool View::HasFocus() const {
1181 const FocusManager* focus_manager = GetFocusManager();
1182 return focus_manager && (focus_manager->GetFocusedView() == this);
1185 View* View::GetNextFocusableView() {
1186 return next_focusable_view_;
1189 const View* View::GetNextFocusableView() const {
1190 return next_focusable_view_;
1193 View* View::GetPreviousFocusableView() {
1194 return previous_focusable_view_;
1197 void View::SetNextFocusableView(View* view) {
1199 view->previous_focusable_view_ = this;
1200 next_focusable_view_ = view;
1203 void View::SetFocusable(bool focusable) {
1204 if (focusable_ == focusable)
1207 focusable_ = focusable;
1210 bool View::IsFocusable() const {
1211 return focusable_ && enabled_ && IsDrawn();
1214 bool View::IsAccessibilityFocusable() const {
1215 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1218 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1219 if (accessibility_focusable_ == accessibility_focusable)
1222 accessibility_focusable_ = accessibility_focusable;
1225 FocusManager* View::GetFocusManager() {
1226 Widget* widget = GetWidget();
1227 return widget ? widget->GetFocusManager() : NULL;
1230 const FocusManager* View::GetFocusManager() const {
1231 const Widget* widget = GetWidget();
1232 return widget ? widget->GetFocusManager() : NULL;
1235 void View::RequestFocus() {
1236 FocusManager* focus_manager = GetFocusManager();
1237 if (focus_manager && IsFocusable())
1238 focus_manager->SetFocusedView(this);
1241 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1245 FocusTraversable* View::GetFocusTraversable() {
1249 FocusTraversable* View::GetPaneFocusTraversable() {
1253 // Tooltips --------------------------------------------------------------------
1255 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1259 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1263 // Context menus ---------------------------------------------------------------
1265 void View::ShowContextMenu(const gfx::Point& p,
1266 ui::MenuSourceType source_type) {
1267 if (!context_menu_controller_)
1270 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1274 bool View::ShouldShowContextMenuOnMousePress() {
1275 return kContextMenuOnMousePress;
1278 // Drag and drop ---------------------------------------------------------------
1280 bool View::GetDropFormats(
1282 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1286 bool View::AreDropTypesRequired() {
1290 bool View::CanDrop(const OSExchangeData& data) {
1291 // TODO(sky): when I finish up migration, this should default to true.
1295 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1298 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1299 return ui::DragDropTypes::DRAG_NONE;
1302 void View::OnDragExited() {
1305 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1306 return ui::DragDropTypes::DRAG_NONE;
1309 void View::OnDragDone() {
1313 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1314 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1315 abs(delta.y()) > GetVerticalDragThreshold());
1318 // Accessibility----------------------------------------------------------------
1320 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1321 if (!native_view_accessibility_)
1322 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1323 if (native_view_accessibility_)
1324 return native_view_accessibility_->GetNativeObject();
1328 void View::NotifyAccessibilityEvent(
1329 ui::AccessibilityTypes::Event event_type,
1330 bool send_native_event) {
1331 if (ViewsDelegate::views_delegate)
1332 ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1334 if (send_native_event && GetWidget()) {
1335 if (!native_view_accessibility_)
1336 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1337 if (native_view_accessibility_)
1338 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1342 // Scrolling -------------------------------------------------------------------
1344 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1345 // We must take RTL UI mirroring into account when adjusting the position of
1348 gfx::Rect scroll_rect(rect);
1349 scroll_rect.Offset(GetMirroredX(), y());
1350 parent_->ScrollRectToVisible(scroll_rect);
1354 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1355 bool is_horizontal, bool is_positive) {
1359 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1360 bool is_horizontal, bool is_positive) {
1364 ////////////////////////////////////////////////////////////////////////////////
1367 // Size and disposition --------------------------------------------------------
1369 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1372 void View::PreferredSizeChanged() {
1375 parent_->ChildPreferredSizeChanged(this);
1378 bool View::NeedsNotificationWhenVisibleBoundsChange() const {
1382 void View::OnVisibleBoundsChanged() {
1385 // Tree operations -------------------------------------------------------------
1387 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1390 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1393 void View::NativeViewHierarchyChanged() {
1394 FocusManager* focus_manager = GetFocusManager();
1395 if (accelerator_focus_manager_ != focus_manager) {
1396 UnregisterAccelerators(true);
1399 RegisterPendingAccelerators();
1403 // Painting --------------------------------------------------------------------
1405 void View::PaintChildren(gfx::Canvas* canvas) {
1406 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1407 for (int i = 0, count = child_count(); i < count; ++i)
1408 if (!child_at(i)->layer())
1409 child_at(i)->Paint(canvas);
1412 void View::OnPaint(gfx::Canvas* canvas) {
1413 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1414 OnPaintBackground(canvas);
1415 OnPaintBorder(canvas);
1418 void View::OnPaintBackground(gfx::Canvas* canvas) {
1419 if (background_.get()) {
1420 TRACE_EVENT2("views", "View::OnPaintBackground",
1421 "width", canvas->sk_canvas()->getDevice()->width(),
1422 "height", canvas->sk_canvas()->getDevice()->height());
1423 background_->Paint(canvas, this);
1427 void View::OnPaintBorder(gfx::Canvas* canvas) {
1428 if (border_.get()) {
1429 TRACE_EVENT2("views", "View::OnPaintBorder",
1430 "width", canvas->sk_canvas()->getDevice()->width(),
1431 "height", canvas->sk_canvas()->getDevice()->height());
1432 border_->Paint(*this, canvas);
1436 // Accelerated Painting --------------------------------------------------------
1438 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1439 // This method should not have the side-effect of creating the layer.
1441 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1444 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1445 ui::Layer** layer_parent) {
1448 *layer_parent = layer();
1449 return gfx::Vector2d();
1452 return gfx::Vector2d();
1454 return gfx::Vector2d(GetMirroredX(), y()) +
1455 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1458 void View::UpdateParentLayer() {
1462 ui::Layer* parent_layer = NULL;
1463 gfx::Vector2d offset(GetMirroredX(), y());
1466 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1468 ReparentLayer(offset, parent_layer);
1471 void View::MoveLayerToParent(ui::Layer* parent_layer,
1472 const gfx::Point& point) {
1473 gfx::Point local_point(point);
1474 if (parent_layer != layer())
1475 local_point.Offset(GetMirroredX(), y());
1476 if (layer() && parent_layer != layer()) {
1477 parent_layer->Add(layer());
1478 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1479 width(), height()));
1481 for (int i = 0, count = child_count(); i < count; ++i)
1482 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1486 void View::UpdateLayerVisibility() {
1487 if (!use_acceleration_when_possible)
1489 bool visible = visible_;
1490 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1491 visible = v->visible();
1493 UpdateChildLayerVisibility(visible);
1496 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1498 layer()->SetVisible(ancestor_visible && visible_);
1500 for (int i = 0, count = child_count(); i < count; ++i)
1501 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1505 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1507 SetLayerBounds(GetLocalBounds() + offset);
1509 for (int i = 0, count = child_count(); i < count; ++i) {
1510 View* child = child_at(i);
1511 child->UpdateChildLayerBounds(
1512 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1517 void View::OnPaintLayer(gfx::Canvas* canvas) {
1518 if (!layer() || !layer()->fills_bounds_opaquely())
1519 canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1520 PaintCommon(canvas);
1523 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1524 // Repainting with new scale factor will paint the content at the right scale.
1527 base::Closure View::PrepareForLayerBoundsChange() {
1528 return base::Closure();
1531 void View::ReorderLayers() {
1533 while (v && !v->layer())
1536 Widget* widget = GetWidget();
1539 ui::Layer* layer = widget->GetLayer();
1541 widget->GetRootView()->ReorderChildLayers(layer);
1544 v->ReorderChildLayers(v->layer());
1548 // Reorder the widget's child NativeViews in case a child NativeView is
1549 // associated with a view (eg via a NativeViewHost). Always do the
1550 // reordering because the associated NativeView's layer (if it has one)
1551 // is parented to the widget's layer regardless of whether the host view has
1552 // an ancestor with a layer.
1553 widget->ReorderNativeViews();
1557 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1558 if (layer() && layer() != parent_layer) {
1559 DCHECK_EQ(parent_layer, layer()->parent());
1560 parent_layer->StackAtBottom(layer());
1562 // Iterate backwards through the children so that a child with a layer
1563 // which is further to the back is stacked above one which is further to
1565 for (Views::reverse_iterator it(children_.rbegin());
1566 it != children_.rend(); ++it) {
1567 (*it)->ReorderChildLayers(parent_layer);
1572 // Input -----------------------------------------------------------------------
1574 bool View::HasHitTestMask() const {
1578 void View::GetHitTestMask(HitTestSource source, gfx::Path* mask) const {
1582 View::DragInfo* View::GetDragInfo() {
1583 return parent_ ? parent_->GetDragInfo() : NULL;
1586 // Focus -----------------------------------------------------------------------
1588 void View::OnFocus() {
1589 // TODO(beng): Investigate whether it's possible for us to move this to
1591 // By default, we clear the native focus. This ensures that no visible native
1592 // view as the focus and that we still receive keyboard inputs.
1593 FocusManager* focus_manager = GetFocusManager();
1595 focus_manager->ClearNativeFocus();
1597 // TODO(beng): Investigate whether it's possible for us to move this to
1599 // Notify assistive technologies of the focus change.
1600 NotifyAccessibilityEvent(ui::AccessibilityTypes::EVENT_FOCUS, true);
1603 void View::OnBlur() {
1606 void View::Focus() {
1614 // Tooltips --------------------------------------------------------------------
1616 void View::TooltipTextChanged() {
1617 Widget* widget = GetWidget();
1618 // TooltipManager may be null if there is a problem creating it.
1619 if (widget && widget->GetTooltipManager())
1620 widget->GetTooltipManager()->TooltipTextChanged(this);
1623 // Context menus ---------------------------------------------------------------
1625 gfx::Point View::GetKeyboardContextMenuLocation() {
1626 gfx::Rect vis_bounds = GetVisibleBounds();
1627 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1628 vis_bounds.y() + vis_bounds.height() / 2);
1629 ConvertPointToScreen(this, &screen_point);
1630 return screen_point;
1633 // Drag and drop ---------------------------------------------------------------
1635 int View::GetDragOperations(const gfx::Point& press_pt) {
1636 return drag_controller_ ?
1637 drag_controller_->GetDragOperationsForView(this, press_pt) :
1638 ui::DragDropTypes::DRAG_NONE;
1641 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1642 DCHECK(drag_controller_);
1643 drag_controller_->WriteDragDataForView(this, press_pt, data);
1646 bool View::InDrag() {
1647 Widget* widget = GetWidget();
1648 return widget ? widget->dragged_view() == this : false;
1651 // Debugging -------------------------------------------------------------------
1653 #if !defined(NDEBUG)
1655 std::string View::PrintViewGraph(bool first) {
1656 return DoPrintViewGraph(first, this);
1659 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1660 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1661 const size_t kMaxPointerStringLength = 19;
1666 result.append("digraph {\n");
1668 // Node characteristics.
1669 char p[kMaxPointerStringLength];
1671 const std::string class_name(GetClassName());
1672 size_t base_name_index = class_name.find_last_of('/');
1673 if (base_name_index == std::string::npos)
1674 base_name_index = 0;
1678 char bounds_buffer[512];
1680 // Information about current node.
1681 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1682 result.append(" N");
1683 result.append(p + 2);
1684 result.append(" [label=\"");
1686 result.append(class_name.substr(base_name_index).c_str());
1688 base::snprintf(bounds_buffer,
1689 arraysize(bounds_buffer),
1690 "\\n bounds: (%d, %d), (%dx%d)",
1695 result.append(bounds_buffer);
1697 gfx::DecomposedTransform decomp;
1698 if (!GetTransform().IsIdentity() &&
1699 gfx::DecomposeTransform(&decomp, GetTransform())) {
1700 base::snprintf(bounds_buffer,
1701 arraysize(bounds_buffer),
1702 "\\n translation: (%f, %f)",
1703 decomp.translate[0],
1704 decomp.translate[1]);
1705 result.append(bounds_buffer);
1707 base::snprintf(bounds_buffer,
1708 arraysize(bounds_buffer),
1709 "\\n rotation: %3.2f",
1710 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1711 result.append(bounds_buffer);
1713 base::snprintf(bounds_buffer,
1714 arraysize(bounds_buffer),
1715 "\\n scale: (%2.4f, %2.4f)",
1718 result.append(bounds_buffer);
1721 result.append("\"");
1723 result.append(", shape=box");
1725 if (layer()->texture())
1726 result.append(", color=green");
1728 result.append(", color=red");
1730 if (layer()->fills_bounds_opaquely())
1731 result.append(", style=filled");
1733 result.append("]\n");
1737 char pp[kMaxPointerStringLength];
1739 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1740 result.append(" N");
1741 result.append(pp + 2);
1742 result.append(" -> N");
1743 result.append(p + 2);
1744 result.append("\n");
1748 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1749 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1752 result.append("}\n");
1759 ////////////////////////////////////////////////////////////////////////////////
1762 // DropInfo --------------------------------------------------------------------
1764 void View::DragInfo::Reset() {
1765 possible_drag = false;
1766 start_pt = gfx::Point();
1769 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1770 possible_drag = true;
1774 // Painting --------------------------------------------------------------------
1776 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1777 // If we have a layer and the View's size did not change, we do not need to
1778 // schedule any paints since the layer will be redrawn at its new location
1779 // during the next Draw() cycle in the compositor.
1780 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1781 // Otherwise, if the size changes or we don't have a layer then we need to
1782 // use SchedulePaint to invalidate the area occupied by the View.
1784 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1785 // The compositor doesn't Draw() until something on screen changes, so
1786 // if our position changes but nothing is being animated on screen, then
1787 // tell the compositor to redraw the scene. We know layer() exists due to
1788 // the above if clause.
1789 layer()->ScheduleDraw();
1793 void View::PaintCommon(gfx::Canvas* canvas) {
1798 // If the View we are about to paint requested the canvas to be flipped, we
1799 // should change the transform appropriately.
1800 // The canvas mirroring is undone once the View is done painting so that we
1801 // don't pass the canvas with the mirrored transform to Views that didn't
1802 // request the canvas to be flipped.
1803 gfx::ScopedCanvas scoped(canvas);
1804 if (FlipCanvasOnPaintForRTLUI()) {
1805 canvas->Translate(gfx::Vector2d(width(), 0));
1806 canvas->Scale(-1, 1);
1812 PaintChildren(canvas);
1815 // Tree operations -------------------------------------------------------------
1817 void View::DoRemoveChildView(View* view,
1818 bool update_focus_cycle,
1819 bool update_tool_tip,
1820 bool delete_removed_view,
1824 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1825 scoped_ptr<View> view_to_be_deleted;
1826 if (i != children_.end()) {
1827 if (update_focus_cycle) {
1828 // Let's remove the view from the focus traversal.
1829 View* next_focusable = view->next_focusable_view_;
1830 View* prev_focusable = view->previous_focusable_view_;
1832 prev_focusable->next_focusable_view_ = next_focusable;
1834 next_focusable->previous_focusable_view_ = prev_focusable;
1838 UnregisterChildrenForVisibleBoundsNotification(view);
1839 if (view->visible())
1840 view->SchedulePaint();
1842 view->PropagateRemoveNotifications(this, new_parent);
1843 view->parent_ = NULL;
1844 view->UpdateLayerVisibility();
1846 if (delete_removed_view && !view->owned_by_client_)
1847 view_to_be_deleted.reset(view);
1852 if (update_tool_tip)
1855 if (layout_manager_.get())
1856 layout_manager_->ViewRemoved(this, view);
1859 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1860 for (int i = 0, count = child_count(); i < count; ++i)
1861 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1863 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1864 for (View* v = this; v; v = v->parent_)
1865 v->ViewHierarchyChangedImpl(true, details);
1868 void View::PropagateAddNotifications(
1869 const ViewHierarchyChangedDetails& details) {
1870 for (int i = 0, count = child_count(); i < count; ++i)
1871 child_at(i)->PropagateAddNotifications(details);
1872 ViewHierarchyChangedImpl(true, details);
1875 void View::PropagateNativeViewHierarchyChanged() {
1876 for (int i = 0, count = child_count(); i < count; ++i)
1877 child_at(i)->PropagateNativeViewHierarchyChanged();
1878 NativeViewHierarchyChanged();
1881 void View::ViewHierarchyChangedImpl(
1882 bool register_accelerators,
1883 const ViewHierarchyChangedDetails& details) {
1884 if (register_accelerators) {
1885 if (details.is_add) {
1886 // If you get this registration, you are part of a subtree that has been
1887 // added to the view hierarchy.
1888 if (GetFocusManager())
1889 RegisterPendingAccelerators();
1891 if (details.child == this)
1892 UnregisterAccelerators(true);
1896 if (details.is_add && layer() && !layer()->parent()) {
1897 UpdateParentLayer();
1898 Widget* widget = GetWidget();
1900 widget->UpdateRootLayers();
1901 } else if (!details.is_add && details.child == this) {
1902 // Make sure the layers belonging to the subtree rooted at |child| get
1903 // removed from layers that do not belong in the same subtree.
1905 if (use_acceleration_when_possible) {
1906 Widget* widget = GetWidget();
1908 widget->UpdateRootLayers();
1912 ViewHierarchyChanged(details);
1913 details.parent->needs_layout_ = true;
1916 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1917 for (int i = 0, count = child_count(); i < count; ++i)
1918 child_at(i)->PropagateNativeThemeChanged(theme);
1919 OnNativeThemeChanged(theme);
1922 // Size and disposition --------------------------------------------------------
1924 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1925 for (int i = 0, count = child_count(); i < count; ++i)
1926 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1927 VisibilityChangedImpl(start, is_visible);
1930 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1931 VisibilityChanged(starting_from, is_visible);
1934 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1936 // Paint the new bounds.
1937 SchedulePaintBoundsChanged(
1938 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1939 SCHEDULE_PAINT_SIZE_CHANGED);
1942 if (use_acceleration_when_possible) {
1945 SetLayerBounds(GetLocalBounds() +
1946 gfx::Vector2d(GetMirroredX(), y()) +
1947 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1949 SetLayerBounds(bounds_);
1952 // If our bounds have changed, then any descendant layer bounds may
1953 // have changed. Update them accordingly.
1954 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1958 OnBoundsChanged(previous_bounds);
1960 if (previous_bounds.size() != size()) {
1961 needs_layout_ = false;
1965 if (NeedsNotificationWhenVisibleBoundsChange())
1966 OnVisibleBoundsChanged();
1968 // Notify interested Views that visible bounds within the root view may have
1970 if (descendants_to_notify_.get()) {
1971 for (Views::iterator i(descendants_to_notify_->begin());
1972 i != descendants_to_notify_->end(); ++i) {
1973 (*i)->OnVisibleBoundsChanged();
1979 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1980 if (view->NeedsNotificationWhenVisibleBoundsChange())
1981 view->RegisterForVisibleBoundsNotification();
1982 for (int i = 0; i < view->child_count(); ++i)
1983 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1987 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1988 if (view->NeedsNotificationWhenVisibleBoundsChange())
1989 view->UnregisterForVisibleBoundsNotification();
1990 for (int i = 0; i < view->child_count(); ++i)
1991 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1994 void View::RegisterForVisibleBoundsNotification() {
1995 if (registered_for_visible_bounds_notification_)
1998 registered_for_visible_bounds_notification_ = true;
1999 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
2000 ancestor->AddDescendantToNotify(this);
2003 void View::UnregisterForVisibleBoundsNotification() {
2004 if (!registered_for_visible_bounds_notification_)
2007 registered_for_visible_bounds_notification_ = false;
2008 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
2009 ancestor->RemoveDescendantToNotify(this);
2012 void View::AddDescendantToNotify(View* view) {
2014 if (!descendants_to_notify_.get())
2015 descendants_to_notify_.reset(new Views);
2016 descendants_to_notify_->push_back(view);
2019 void View::RemoveDescendantToNotify(View* view) {
2020 DCHECK(view && descendants_to_notify_.get());
2021 Views::iterator i(std::find(
2022 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
2023 DCHECK(i != descendants_to_notify_->end());
2024 descendants_to_notify_->erase(i);
2025 if (descendants_to_notify_->empty())
2026 descendants_to_notify_.reset();
2029 void View::SetLayerBounds(const gfx::Rect& bounds) {
2030 layer()->SetBounds(bounds);
2033 // Transformations -------------------------------------------------------------
2035 bool View::GetTransformRelativeTo(const View* ancestor,
2036 gfx::Transform* transform) const {
2037 const View* p = this;
2039 while (p && p != ancestor) {
2040 transform->ConcatTransform(p->GetTransform());
2041 gfx::Transform translation;
2042 translation.Translate(static_cast<float>(p->GetMirroredX()),
2043 static_cast<float>(p->y()));
2044 transform->ConcatTransform(translation);
2049 return p == ancestor;
2052 // Coordinate conversion -------------------------------------------------------
2054 bool View::ConvertPointForAncestor(const View* ancestor,
2055 gfx::Point* point) const {
2056 gfx::Transform trans;
2057 // TODO(sad): Have some way of caching the transformation results.
2058 bool result = GetTransformRelativeTo(ancestor, &trans);
2059 gfx::Point3F p(*point);
2060 trans.TransformPoint(&p);
2061 *point = gfx::ToFlooredPoint(p.AsPointF());
2065 bool View::ConvertPointFromAncestor(const View* ancestor,
2066 gfx::Point* point) const {
2067 gfx::Transform trans;
2068 bool result = GetTransformRelativeTo(ancestor, &trans);
2069 gfx::Point3F p(*point);
2070 trans.TransformPointReverse(&p);
2071 *point = gfx::ToFlooredPoint(p.AsPointF());
2075 bool View::ConvertRectForAncestor(const View* ancestor,
2076 gfx::RectF* rect) const {
2077 gfx::Transform trans;
2078 // TODO(sad): Have some way of caching the transformation results.
2079 bool result = GetTransformRelativeTo(ancestor, &trans);
2080 trans.TransformRect(rect);
2084 bool View::ConvertRectFromAncestor(const View* ancestor,
2085 gfx::RectF* rect) const {
2086 gfx::Transform trans;
2087 bool result = GetTransformRelativeTo(ancestor, &trans);
2088 trans.TransformRectReverse(rect);
2092 // Accelerated painting --------------------------------------------------------
2094 void View::CreateLayer() {
2095 // A new layer is being created for the view. So all the layers of the
2096 // sub-tree can inherit the visibility of the corresponding view.
2097 for (int i = 0, count = child_count(); i < count; ++i)
2098 child_at(i)->UpdateChildLayerVisibility(true);
2100 layer_ = new ui::Layer();
2101 layer_owner_.reset(layer_);
2102 layer_->set_delegate(this);
2103 #if !defined(NDEBUG)
2104 layer_->set_name(GetClassName());
2107 UpdateParentLayers();
2108 UpdateLayerVisibility();
2110 // The new layer needs to be ordered in the layer tree according
2111 // to the view tree. Children of this layer were added in order
2112 // in UpdateParentLayers().
2114 parent()->ReorderLayers();
2116 Widget* widget = GetWidget();
2118 widget->UpdateRootLayers();
2121 void View::UpdateParentLayers() {
2122 // Attach all top-level un-parented layers.
2123 if (layer() && !layer()->parent()) {
2124 UpdateParentLayer();
2126 for (int i = 0, count = child_count(); i < count; ++i)
2127 child_at(i)->UpdateParentLayers();
2131 void View::OrphanLayers() {
2133 if (layer()->parent())
2134 layer()->parent()->Remove(layer());
2136 // The layer belonging to this View has already been orphaned. It is not
2137 // necessary to orphan the child layers.
2140 for (int i = 0, count = child_count(); i < count; ++i)
2141 child_at(i)->OrphanLayers();
2144 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2145 layer_->SetBounds(GetLocalBounds() + offset);
2146 DCHECK_NE(layer(), parent_layer);
2148 parent_layer->Add(layer());
2149 layer_->SchedulePaint(GetLocalBounds());
2150 MoveLayerToParent(layer(), gfx::Point());
2153 void View::DestroyLayer() {
2154 ui::Layer* new_parent = layer()->parent();
2155 std::vector<ui::Layer*> children = layer()->children();
2156 for (size_t i = 0; i < children.size(); ++i) {
2157 layer()->Remove(children[i]);
2159 new_parent->Add(children[i]);
2163 layer_owner_.reset();
2168 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2172 Widget* widget = GetWidget();
2174 widget->UpdateRootLayers();
2177 // Input -----------------------------------------------------------------------
2179 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2180 int drag_operations =
2181 (enabled_ && event.IsOnlyLeftMouseButton() &&
2182 HitTestPoint(event.location())) ?
2183 GetDragOperations(event.location()) : 0;
2184 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2185 context_menu_controller_ : 0;
2186 View::DragInfo* drag_info = GetDragInfo();
2188 const bool enabled = enabled_;
2189 const bool result = OnMousePressed(event);
2194 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2195 kContextMenuOnMousePress) {
2196 // Assume that if there is a context menu controller we won't be deleted
2197 // from mouse pressed.
2198 gfx::Point location(event.location());
2199 if (HitTestPoint(location)) {
2200 ConvertPointToScreen(this, &location);
2201 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2206 // WARNING: we may have been deleted, don't use any View variables.
2207 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2208 drag_info->PossibleDrag(event.location());
2211 return !!context_menu_controller || result;
2214 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2215 // Copy the field, that way if we're deleted after drag and drop no harm is
2217 ContextMenuController* context_menu_controller = context_menu_controller_;
2218 const bool possible_drag = GetDragInfo()->possible_drag;
2219 if (possible_drag &&
2220 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2221 (!drag_controller_ ||
2222 drag_controller_->CanStartDragForView(
2223 this, GetDragInfo()->start_pt, event.location()))) {
2224 DoDrag(event, GetDragInfo()->start_pt,
2225 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2227 if (OnMouseDragged(event))
2229 // Fall through to return value based on context menu controller.
2231 // WARNING: we may have been deleted.
2232 return (context_menu_controller != NULL) || possible_drag;
2235 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2236 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2237 event.IsOnlyRightMouseButton()) {
2238 // Assume that if there is a context menu controller we won't be deleted
2239 // from mouse released.
2240 gfx::Point location(event.location());
2241 OnMouseReleased(event);
2242 if (HitTestPoint(location)) {
2243 ConvertPointToScreen(this, &location);
2244 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2247 OnMouseReleased(event);
2249 // WARNING: we may have been deleted.
2252 // Accelerators ----------------------------------------------------------------
2254 void View::RegisterPendingAccelerators() {
2255 if (!accelerators_.get() ||
2256 registered_accelerator_count_ == accelerators_->size()) {
2257 // No accelerators are waiting for registration.
2262 // The view is not yet attached to a widget, defer registration until then.
2266 accelerator_focus_manager_ = GetFocusManager();
2267 if (!accelerator_focus_manager_) {
2268 // Some crash reports seem to show that we may get cases where we have no
2269 // focus manager (see bug #1291225). This should never be the case, just
2270 // making sure we don't crash.
2274 for (std::vector<ui::Accelerator>::const_iterator i(
2275 accelerators_->begin() + registered_accelerator_count_);
2276 i != accelerators_->end(); ++i) {
2277 accelerator_focus_manager_->RegisterAccelerator(
2278 *i, ui::AcceleratorManager::kNormalPriority, this);
2280 registered_accelerator_count_ = accelerators_->size();
2283 void View::UnregisterAccelerators(bool leave_data_intact) {
2284 if (!accelerators_.get())
2288 if (accelerator_focus_manager_) {
2289 accelerator_focus_manager_->UnregisterAccelerators(this);
2290 accelerator_focus_manager_ = NULL;
2292 if (!leave_data_intact) {
2293 accelerators_->clear();
2294 accelerators_.reset();
2296 registered_accelerator_count_ = 0;
2300 // Focus -----------------------------------------------------------------------
2302 void View::InitFocusSiblings(View* v, int index) {
2303 int count = child_count();
2306 v->next_focusable_view_ = NULL;
2307 v->previous_focusable_view_ = NULL;
2309 if (index == count) {
2310 // We are inserting at the end, but the end of the child list may not be
2311 // the last focusable element. Let's try to find an element with no next
2312 // focusable element to link to.
2313 View* last_focusable_view = NULL;
2314 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2315 if (!(*i)->next_focusable_view_) {
2316 last_focusable_view = *i;
2320 if (last_focusable_view == NULL) {
2321 // Hum... there is a cycle in the focus list. Let's just insert ourself
2322 // after the last child.
2323 View* prev = children_[index - 1];
2324 v->previous_focusable_view_ = prev;
2325 v->next_focusable_view_ = prev->next_focusable_view_;
2326 prev->next_focusable_view_->previous_focusable_view_ = v;
2327 prev->next_focusable_view_ = v;
2329 last_focusable_view->next_focusable_view_ = v;
2330 v->next_focusable_view_ = NULL;
2331 v->previous_focusable_view_ = last_focusable_view;
2334 View* prev = children_[index]->GetPreviousFocusableView();
2335 v->previous_focusable_view_ = prev;
2336 v->next_focusable_view_ = children_[index];
2338 prev->next_focusable_view_ = v;
2339 children_[index]->previous_focusable_view_ = v;
2344 // System events ---------------------------------------------------------------
2346 void View::PropagateThemeChanged() {
2347 for (int i = child_count() - 1; i >= 0; --i)
2348 child_at(i)->PropagateThemeChanged();
2352 void View::PropagateLocaleChanged() {
2353 for (int i = child_count() - 1; i >= 0; --i)
2354 child_at(i)->PropagateLocaleChanged();
2358 // Tooltips --------------------------------------------------------------------
2360 void View::UpdateTooltip() {
2361 Widget* widget = GetWidget();
2362 // TODO(beng): The TooltipManager NULL check can be removed when we
2363 // consolidate Init() methods and make views_unittests Init() all
2364 // Widgets that it uses.
2365 if (widget && widget->GetTooltipManager())
2366 widget->GetTooltipManager()->UpdateTooltip();
2369 // Drag and drop ---------------------------------------------------------------
2371 bool View::DoDrag(const ui::LocatedEvent& event,
2372 const gfx::Point& press_pt,
2373 ui::DragDropTypes::DragEventSource source) {
2374 int drag_operations = GetDragOperations(press_pt);
2375 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2378 Widget* widget = GetWidget();
2379 // We should only start a drag from an event, implying we have a widget.
2382 // Don't attempt to start a drag while in the process of dragging. This is
2383 // especially important on X where we can get multiple mouse move events when
2384 // we start the drag.
2385 if (widget->dragged_view())
2388 OSExchangeData data;
2389 WriteDragData(press_pt, &data);
2391 // Message the RootView to do the drag and drop. That way if we're removed
2392 // the RootView can detect it and avoid calling us back.
2393 gfx::Point widget_location(event.location());
2394 ConvertPointToWidget(this, &widget_location);
2395 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2396 // WARNING: we may have been deleted.
2400 } // namespace views