Move views event targeting into ViewTargeterDelegate::TargetForRect()
[chromium-blink-merge.git] / ui / views / view.cc
blob290dfdafb8ae40e62332f425caeca4a5c6af9e02
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"
9 #include <algorithm>
10 #include <cmath>
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/compositor/compositor.h"
23 #include "ui/compositor/dip_util.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/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/focus/view_storage.h"
43 #include "ui/views/layout/layout_manager.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"
50 #if defined(OS_WIN)
51 #include "base/win/scoped_gdi_object.h"
52 #endif
54 namespace {
56 #if defined(OS_WIN)
57 const bool kContextMenuOnMousePress = false;
58 #else
59 const bool kContextMenuOnMousePress = true;
60 #endif
62 // Default horizontal drag threshold in pixels.
63 // Same as what gtk uses.
64 const int kDefaultHorizontalDragThreshold = 8;
66 // Default vertical drag threshold in pixels.
67 // Same as what gtk uses.
68 const int kDefaultVerticalDragThreshold = 8;
70 // Returns the top view in |view|'s hierarchy.
71 const views::View* GetHierarchyRoot(const views::View* view) {
72 const views::View* root = view;
73 while (root && root->parent())
74 root = root->parent();
75 return root;
78 } // namespace
80 namespace views {
82 namespace internal {
84 } // namespace internal
86 // static
87 ViewsDelegate* ViewsDelegate::views_delegate = NULL;
89 // static
90 const char View::kViewClassName[] = "View";
92 ////////////////////////////////////////////////////////////////////////////////
93 // View, public:
95 // Creation and lifetime -------------------------------------------------------
97 View::View()
98 : owned_by_client_(false),
99 id_(0),
100 group_(-1),
101 parent_(NULL),
102 visible_(true),
103 enabled_(true),
104 notify_enter_exit_on_child_(false),
105 registered_for_visible_bounds_notification_(false),
106 root_bounds_dirty_(true),
107 clip_insets_(0, 0, 0, 0),
108 needs_layout_(true),
109 snap_layer_to_pixel_boundary_(false),
110 flip_canvas_on_paint_for_rtl_ui_(false),
111 paint_to_layer_(false),
112 accelerator_focus_manager_(NULL),
113 registered_accelerator_count_(0),
114 next_focusable_view_(NULL),
115 previous_focusable_view_(NULL),
116 focusable_(false),
117 accessibility_focusable_(false),
118 context_menu_controller_(NULL),
119 drag_controller_(NULL),
120 native_view_accessibility_(NULL) {
123 View::~View() {
124 if (parent_)
125 parent_->RemoveChildView(this);
127 ViewStorage::GetInstance()->ViewRemoved(this);
129 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
130 (*i)->parent_ = NULL;
131 if (!(*i)->owned_by_client_)
132 delete *i;
135 // Release ownership of the native accessibility object, but it's
136 // reference-counted on some platforms, so it may not be deleted right away.
137 if (native_view_accessibility_)
138 native_view_accessibility_->Destroy();
141 // Tree operations -------------------------------------------------------------
143 const Widget* View::GetWidget() const {
144 // The root view holds a reference to this view hierarchy's Widget.
145 return parent_ ? parent_->GetWidget() : NULL;
148 Widget* View::GetWidget() {
149 return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
152 void View::AddChildView(View* view) {
153 if (view->parent_ == this)
154 return;
155 AddChildViewAt(view, child_count());
158 void View::AddChildViewAt(View* view, int index) {
159 CHECK_NE(view, this) << "You cannot add a view as its own child";
160 DCHECK_GE(index, 0);
161 DCHECK_LE(index, child_count());
163 // If |view| has a parent, remove it from its parent.
164 View* parent = view->parent_;
165 ui::NativeTheme* old_theme = NULL;
166 if (parent) {
167 old_theme = view->GetNativeTheme();
168 if (parent == this) {
169 ReorderChildView(view, index);
170 return;
172 parent->DoRemoveChildView(view, true, true, false, this);
175 // Sets the prev/next focus views.
176 InitFocusSiblings(view, index);
178 // Let's insert the view.
179 view->parent_ = this;
180 children_.insert(children_.begin() + index, view);
182 // Instruct the view to recompute its root bounds on next Paint().
183 view->SetRootBoundsDirty(true);
185 views::Widget* widget = GetWidget();
186 if (widget) {
187 const ui::NativeTheme* new_theme = view->GetNativeTheme();
188 if (new_theme != old_theme)
189 view->PropagateNativeThemeChanged(new_theme);
192 ViewHierarchyChangedDetails details(true, this, view, parent);
194 for (View* v = this; v; v = v->parent_)
195 v->ViewHierarchyChangedImpl(false, details);
197 view->PropagateAddNotifications(details);
198 UpdateTooltip();
199 if (widget) {
200 RegisterChildrenForVisibleBoundsNotification(view);
201 if (view->visible())
202 view->SchedulePaint();
205 if (layout_manager_.get())
206 layout_manager_->ViewAdded(this, view);
208 ReorderLayers();
210 // Make sure the visibility of the child layers are correct.
211 // If any of the parent View is hidden, then the layers of the subtree
212 // rooted at |this| should be hidden. Otherwise, all the child layers should
213 // inherit the visibility of the owner View.
214 UpdateLayerVisibility();
217 void View::ReorderChildView(View* view, int index) {
218 DCHECK_EQ(view->parent_, this);
219 if (index < 0)
220 index = child_count() - 1;
221 else if (index >= child_count())
222 return;
223 if (children_[index] == view)
224 return;
226 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
227 DCHECK(i != children_.end());
228 children_.erase(i);
230 // Unlink the view first
231 View* next_focusable = view->next_focusable_view_;
232 View* prev_focusable = view->previous_focusable_view_;
233 if (prev_focusable)
234 prev_focusable->next_focusable_view_ = next_focusable;
235 if (next_focusable)
236 next_focusable->previous_focusable_view_ = prev_focusable;
238 // Add it in the specified index now.
239 InitFocusSiblings(view, index);
240 children_.insert(children_.begin() + index, view);
242 ReorderLayers();
245 void View::RemoveChildView(View* view) {
246 DoRemoveChildView(view, true, true, false, NULL);
249 void View::RemoveAllChildViews(bool delete_children) {
250 while (!children_.empty())
251 DoRemoveChildView(children_.front(), false, false, delete_children, NULL);
252 UpdateTooltip();
255 bool View::Contains(const View* view) const {
256 for (const View* v = view; v; v = v->parent_) {
257 if (v == this)
258 return true;
260 return false;
263 int View::GetIndexOf(const View* view) const {
264 Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
265 return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
268 // Size and disposition --------------------------------------------------------
270 void View::SetBounds(int x, int y, int width, int height) {
271 SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
274 void View::SetBoundsRect(const gfx::Rect& bounds) {
275 if (bounds == bounds_) {
276 if (needs_layout_) {
277 needs_layout_ = false;
278 Layout();
280 return;
283 if (visible_) {
284 // Paint where the view is currently.
285 SchedulePaintBoundsChanged(
286 bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
287 SCHEDULE_PAINT_SIZE_CHANGED);
290 gfx::Rect prev = bounds_;
291 bounds_ = bounds;
292 BoundsChanged(prev);
295 void View::SetSize(const gfx::Size& size) {
296 SetBounds(x(), y(), size.width(), size.height());
299 void View::SetPosition(const gfx::Point& position) {
300 SetBounds(position.x(), position.y(), width(), height());
303 void View::SetX(int x) {
304 SetBounds(x, y(), width(), height());
307 void View::SetY(int y) {
308 SetBounds(x(), y, width(), height());
311 gfx::Rect View::GetContentsBounds() const {
312 gfx::Rect contents_bounds(GetLocalBounds());
313 if (border_.get())
314 contents_bounds.Inset(border_->GetInsets());
315 return contents_bounds;
318 gfx::Rect View::GetLocalBounds() const {
319 return gfx::Rect(size());
322 gfx::Rect View::GetLayerBoundsInPixel() const {
323 return layer()->GetTargetBounds();
326 gfx::Insets View::GetInsets() const {
327 return border_.get() ? border_->GetInsets() : gfx::Insets();
330 gfx::Rect View::GetVisibleBounds() const {
331 if (!IsDrawn())
332 return gfx::Rect();
333 gfx::Rect vis_bounds(GetLocalBounds());
334 gfx::Rect ancestor_bounds;
335 const View* view = this;
336 gfx::Transform transform;
338 while (view != NULL && !vis_bounds.IsEmpty()) {
339 transform.ConcatTransform(view->GetTransform());
340 gfx::Transform translation;
341 translation.Translate(static_cast<float>(view->GetMirroredX()),
342 static_cast<float>(view->y()));
343 transform.ConcatTransform(translation);
345 vis_bounds = view->ConvertRectToParent(vis_bounds);
346 const View* ancestor = view->parent_;
347 if (ancestor != NULL) {
348 ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
349 vis_bounds.Intersect(ancestor_bounds);
350 } else if (!view->GetWidget()) {
351 // If the view has no Widget, we're not visible. Return an empty rect.
352 return gfx::Rect();
354 view = ancestor;
356 if (vis_bounds.IsEmpty())
357 return vis_bounds;
358 // Convert back to this views coordinate system.
359 gfx::RectF views_vis_bounds(vis_bounds);
360 transform.TransformRectReverse(&views_vis_bounds);
361 // Partially visible pixels should be considered visible.
362 return gfx::ToEnclosingRect(views_vis_bounds);
365 gfx::Rect View::GetBoundsInScreen() const {
366 gfx::Point origin;
367 View::ConvertPointToScreen(this, &origin);
368 return gfx::Rect(origin, size());
371 gfx::Size View::GetPreferredSize() const {
372 if (layout_manager_.get())
373 return layout_manager_->GetPreferredSize(this);
374 return gfx::Size();
377 int View::GetBaseline() const {
378 return -1;
381 void View::SizeToPreferredSize() {
382 gfx::Size prefsize = GetPreferredSize();
383 if ((prefsize.width() != width()) || (prefsize.height() != height()))
384 SetBounds(x(), y(), prefsize.width(), prefsize.height());
387 gfx::Size View::GetMinimumSize() const {
388 return GetPreferredSize();
391 gfx::Size View::GetMaximumSize() const {
392 return gfx::Size();
395 int View::GetHeightForWidth(int w) const {
396 if (layout_manager_.get())
397 return layout_manager_->GetPreferredHeightForWidth(this, w);
398 return GetPreferredSize().height();
401 void View::SetVisible(bool visible) {
402 if (visible != visible_) {
403 // If the View is currently visible, schedule paint to refresh parent.
404 // TODO(beng): not sure we should be doing this if we have a layer.
405 if (visible_)
406 SchedulePaint();
408 visible_ = visible;
410 // Notify the parent.
411 if (parent_)
412 parent_->ChildVisibilityChanged(this);
414 // This notifies all sub-views recursively.
415 PropagateVisibilityNotifications(this, visible_);
416 UpdateLayerVisibility();
418 // If we are newly visible, schedule paint.
419 if (visible_)
420 SchedulePaint();
424 bool View::IsDrawn() const {
425 return visible_ && parent_ ? parent_->IsDrawn() : false;
428 void View::SetEnabled(bool enabled) {
429 if (enabled != enabled_) {
430 enabled_ = enabled;
431 OnEnabledChanged();
435 void View::OnEnabledChanged() {
436 SchedulePaint();
439 // Transformations -------------------------------------------------------------
441 gfx::Transform View::GetTransform() const {
442 return layer() ? layer()->transform() : gfx::Transform();
445 void View::SetTransform(const gfx::Transform& transform) {
446 if (transform.IsIdentity()) {
447 if (layer()) {
448 layer()->SetTransform(transform);
449 if (!paint_to_layer_)
450 DestroyLayer();
451 } else {
452 // Nothing.
454 } else {
455 if (!layer())
456 CreateLayer();
457 layer()->SetTransform(transform);
458 layer()->ScheduleDraw();
462 void View::SetPaintToLayer(bool paint_to_layer) {
463 if (paint_to_layer_ == paint_to_layer)
464 return;
466 // If this is a change in state we will also need to update bounds trees.
467 if (paint_to_layer) {
468 // Gaining a layer means becoming a paint root. We must remove ourselves
469 // from our old paint root, if we had one. Traverse up view tree to find old
470 // paint root.
471 View* old_paint_root = parent_;
472 while (old_paint_root && !old_paint_root->IsPaintRoot())
473 old_paint_root = old_paint_root->parent_;
475 // Remove our and our children's bounds from the old tree. This will also
476 // mark all of our bounds as dirty.
477 if (old_paint_root && old_paint_root->bounds_tree_)
478 RemoveRootBounds(old_paint_root->bounds_tree_.get());
480 } else {
481 // Losing a layer means we are no longer a paint root, so delete our
482 // bounds tree and mark ourselves as dirty for future insertion into our
483 // new paint root's bounds tree.
484 bounds_tree_.reset();
485 SetRootBoundsDirty(true);
488 paint_to_layer_ = paint_to_layer;
489 if (paint_to_layer_ && !layer()) {
490 CreateLayer();
491 } else if (!paint_to_layer_ && layer()) {
492 DestroyLayer();
496 // RTL positioning -------------------------------------------------------------
498 gfx::Rect View::GetMirroredBounds() const {
499 gfx::Rect bounds(bounds_);
500 bounds.set_x(GetMirroredX());
501 return bounds;
504 gfx::Point View::GetMirroredPosition() const {
505 return gfx::Point(GetMirroredX(), y());
508 int View::GetMirroredX() const {
509 return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
512 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
513 return base::i18n::IsRTL() ?
514 (width() - bounds.x() - bounds.width()) : bounds.x();
517 int View::GetMirroredXInView(int x) const {
518 return base::i18n::IsRTL() ? width() - x : x;
521 int View::GetMirroredXWithWidthInView(int x, int w) const {
522 return base::i18n::IsRTL() ? width() - x - w : x;
525 // Layout ----------------------------------------------------------------------
527 void View::Layout() {
528 needs_layout_ = false;
530 // If we have a layout manager, let it handle the layout for us.
531 if (layout_manager_.get())
532 layout_manager_->Layout(this);
534 // Make sure to propagate the Layout() call to any children that haven't
535 // received it yet through the layout manager and need to be laid out. This
536 // is needed for the case when the child requires a layout but its bounds
537 // weren't changed by the layout manager. If there is no layout manager, we
538 // just propagate the Layout() call down the hierarchy, so whoever receives
539 // the call can take appropriate action.
540 for (int i = 0, count = child_count(); i < count; ++i) {
541 View* child = child_at(i);
542 if (child->needs_layout_ || !layout_manager_.get()) {
543 child->needs_layout_ = false;
544 child->Layout();
549 void View::InvalidateLayout() {
550 // Always invalidate up. This is needed to handle the case of us already being
551 // valid, but not our parent.
552 needs_layout_ = true;
553 if (parent_)
554 parent_->InvalidateLayout();
557 LayoutManager* View::GetLayoutManager() const {
558 return layout_manager_.get();
561 void View::SetLayoutManager(LayoutManager* layout_manager) {
562 if (layout_manager_.get())
563 layout_manager_->Uninstalled(this);
565 layout_manager_.reset(layout_manager);
566 if (layout_manager_.get())
567 layout_manager_->Installed(this);
570 void View::SnapLayerToPixelBoundary() {
571 if (!layer())
572 return;
574 if (snap_layer_to_pixel_boundary_ && layer()->parent() &&
575 layer()->GetCompositor()) {
576 ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer());
577 } else {
578 // Reset the offset.
579 layer()->SetSubpixelPositionOffset(gfx::Vector2dF());
583 // Attributes ------------------------------------------------------------------
585 const char* View::GetClassName() const {
586 return kViewClassName;
589 const View* View::GetAncestorWithClassName(const std::string& name) const {
590 for (const View* view = this; view; view = view->parent_) {
591 if (!strcmp(view->GetClassName(), name.c_str()))
592 return view;
594 return NULL;
597 View* View::GetAncestorWithClassName(const std::string& name) {
598 return const_cast<View*>(const_cast<const View*>(this)->
599 GetAncestorWithClassName(name));
602 const View* View::GetViewByID(int id) const {
603 if (id == id_)
604 return const_cast<View*>(this);
606 for (int i = 0, count = child_count(); i < count; ++i) {
607 const View* view = child_at(i)->GetViewByID(id);
608 if (view)
609 return view;
611 return NULL;
614 View* View::GetViewByID(int id) {
615 return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
618 void View::SetGroup(int gid) {
619 // Don't change the group id once it's set.
620 DCHECK(group_ == -1 || group_ == gid);
621 group_ = gid;
624 int View::GetGroup() const {
625 return group_;
628 bool View::IsGroupFocusTraversable() const {
629 return true;
632 void View::GetViewsInGroup(int group, Views* views) {
633 if (group_ == group)
634 views->push_back(this);
636 for (int i = 0, count = child_count(); i < count; ++i)
637 child_at(i)->GetViewsInGroup(group, views);
640 View* View::GetSelectedViewForGroup(int group) {
641 Views views;
642 GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
643 return views.empty() ? NULL : views[0];
646 // Coordinate conversion -------------------------------------------------------
648 // static
649 void View::ConvertPointToTarget(const View* source,
650 const View* target,
651 gfx::Point* point) {
652 DCHECK(source);
653 DCHECK(target);
654 if (source == target)
655 return;
657 const View* root = GetHierarchyRoot(target);
658 CHECK_EQ(GetHierarchyRoot(source), root);
660 if (source != root)
661 source->ConvertPointForAncestor(root, point);
663 if (target != root)
664 target->ConvertPointFromAncestor(root, point);
667 // static
668 void View::ConvertRectToTarget(const View* source,
669 const View* target,
670 gfx::RectF* rect) {
671 DCHECK(source);
672 DCHECK(target);
673 if (source == target)
674 return;
676 const View* root = GetHierarchyRoot(target);
677 CHECK_EQ(GetHierarchyRoot(source), root);
679 if (source != root)
680 source->ConvertRectForAncestor(root, rect);
682 if (target != root)
683 target->ConvertRectFromAncestor(root, rect);
686 // static
687 void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
688 DCHECK(src);
689 DCHECK(p);
691 src->ConvertPointForAncestor(NULL, p);
694 // static
695 void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
696 DCHECK(dest);
697 DCHECK(p);
699 dest->ConvertPointFromAncestor(NULL, p);
702 // static
703 void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
704 DCHECK(src);
705 DCHECK(p);
707 // If the view is not connected to a tree, there's nothing we can do.
708 const Widget* widget = src->GetWidget();
709 if (widget) {
710 ConvertPointToWidget(src, p);
711 *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
715 // static
716 void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
717 DCHECK(dst);
718 DCHECK(p);
720 const views::Widget* widget = dst->GetWidget();
721 if (!widget)
722 return;
723 *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
724 views::View::ConvertPointFromWidget(dst, p);
727 gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
728 gfx::RectF x_rect = rect;
729 GetTransform().TransformRect(&x_rect);
730 x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
731 // Pixels we partially occupy in the parent should be included.
732 return gfx::ToEnclosingRect(x_rect);
735 gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
736 gfx::Rect x_rect = rect;
737 for (const View* v = this; v; v = v->parent_)
738 x_rect = v->ConvertRectToParent(x_rect);
739 return x_rect;
742 // Painting --------------------------------------------------------------------
744 void View::SchedulePaint() {
745 SchedulePaintInRect(GetLocalBounds());
748 void View::SchedulePaintInRect(const gfx::Rect& rect) {
749 if (!visible_)
750 return;
752 if (layer()) {
753 layer()->SchedulePaint(rect);
754 } else if (parent_) {
755 // Translate the requested paint rect to the parent's coordinate system
756 // then pass this notification up to the parent.
757 parent_->SchedulePaintInRect(ConvertRectToParent(rect));
761 void View::Paint(gfx::Canvas* canvas, const CullSet& cull_set) {
762 // The cull_set may allow us to skip painting without canvas construction or
763 // even canvas rect intersection.
764 if (cull_set.ShouldPaint(this)) {
765 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
767 gfx::ScopedCanvas scoped_canvas(canvas);
769 // Paint this View and its children, setting the clip rect to the bounds
770 // of this View and translating the origin to the local bounds' top left
771 // point.
773 // Note that the X (or left) position we pass to ClipRectInt takes into
774 // consideration whether or not the view uses a right-to-left layout so that
775 // we paint our view in its mirrored position if need be.
776 gfx::Rect clip_rect = bounds();
777 clip_rect.Inset(clip_insets_);
778 if (parent_)
779 clip_rect.set_x(parent_->GetMirroredXForRect(clip_rect));
780 canvas->ClipRect(clip_rect);
781 if (canvas->IsClipEmpty())
782 return;
784 // Non-empty clip, translate the graphics such that 0,0 corresponds to where
785 // this view is located (related to its parent).
786 canvas->Translate(GetMirroredPosition().OffsetFromOrigin());
787 canvas->Transform(GetTransform());
789 // If we are a paint root, we need to construct our own CullSet object for
790 // propagation to our children.
791 if (IsPaintRoot()) {
792 if (!bounds_tree_)
793 bounds_tree_.reset(new BoundsTree(2, 5));
795 // Recompute our bounds tree as needed.
796 UpdateRootBounds(bounds_tree_.get(), gfx::Vector2d());
798 // Grab the clip rect from the supplied canvas to use as the query rect.
799 gfx::Rect canvas_bounds;
800 if (!canvas->GetClipBounds(&canvas_bounds)) {
801 NOTREACHED() << "Failed to get clip bounds from the canvas!";
802 return;
805 // Now query our bounds_tree_ for a set of damaged views that intersect
806 // our canvas bounds.
807 scoped_ptr<base::hash_set<intptr_t> > damaged_views(
808 new base::hash_set<intptr_t>());
809 bounds_tree_->AppendIntersectingRecords(
810 canvas_bounds, damaged_views.get());
811 // Construct a CullSet to wrap the damaged views set, it will delete it
812 // for us on scope exit.
813 CullSet paint_root_cull_set(damaged_views.Pass());
814 // Paint all descendents using our new cull set.
815 PaintCommon(canvas, paint_root_cull_set);
816 } else {
817 // Not a paint root, so we can proceed as normal.
818 PaintCommon(canvas, cull_set);
823 void View::set_background(Background* b) {
824 background_.reset(b);
827 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
829 ui::ThemeProvider* View::GetThemeProvider() const {
830 const Widget* widget = GetWidget();
831 return widget ? widget->GetThemeProvider() : NULL;
834 const ui::NativeTheme* View::GetNativeTheme() const {
835 const Widget* widget = GetWidget();
836 return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
839 // Input -----------------------------------------------------------------------
841 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
842 return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
845 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
846 return GetEffectiveViewTargeter()->TargetForRect(this, rect);
849 bool View::CanProcessEventsWithinSubtree() const {
850 return true;
853 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
854 // TODO(tdanderson): Move this implementation into ViewTargetDelegate.
855 if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree())
856 return NULL;
858 // Walk the child Views recursively looking for the View that most
859 // tightly encloses the specified point.
860 for (int i = child_count() - 1; i >= 0; --i) {
861 View* child = child_at(i);
862 if (!child->visible())
863 continue;
865 gfx::Point point_in_child_coords(point);
866 ConvertPointToTarget(this, child, &point_in_child_coords);
867 View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
868 if (handler)
869 return handler;
871 return this;
874 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
875 #if defined(OS_WIN)
876 static ui::Cursor arrow;
877 if (!arrow.platform())
878 arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
879 return arrow;
880 #else
881 return gfx::kNullCursor;
882 #endif
885 bool View::HitTestPoint(const gfx::Point& point) const {
886 return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
889 bool View::HitTestRect(const gfx::Rect& rect) const {
890 return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect);
893 bool View::IsMouseHovered() {
894 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
895 // hovered.
896 if (!GetWidget())
897 return false;
899 // If mouse events are disabled, then the mouse cursor is invisible and
900 // is therefore not hovering over this button.
901 if (!GetWidget()->IsMouseEventsEnabled())
902 return false;
904 gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
905 GetWidget()->GetNativeView())->GetCursorScreenPoint());
906 ConvertPointFromScreen(this, &cursor_pos);
907 return HitTestPoint(cursor_pos);
910 bool View::OnMousePressed(const ui::MouseEvent& event) {
911 return false;
914 bool View::OnMouseDragged(const ui::MouseEvent& event) {
915 return false;
918 void View::OnMouseReleased(const ui::MouseEvent& event) {
921 void View::OnMouseCaptureLost() {
924 void View::OnMouseMoved(const ui::MouseEvent& event) {
927 void View::OnMouseEntered(const ui::MouseEvent& event) {
930 void View::OnMouseExited(const ui::MouseEvent& event) {
933 void View::SetMouseHandler(View* new_mouse_handler) {
934 // |new_mouse_handler| may be NULL.
935 if (parent_)
936 parent_->SetMouseHandler(new_mouse_handler);
939 bool View::OnKeyPressed(const ui::KeyEvent& event) {
940 return false;
943 bool View::OnKeyReleased(const ui::KeyEvent& event) {
944 return false;
947 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
948 return false;
951 void View::OnKeyEvent(ui::KeyEvent* event) {
952 bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
953 OnKeyReleased(*event);
954 if (consumed)
955 event->StopPropagation();
958 void View::OnMouseEvent(ui::MouseEvent* event) {
959 switch (event->type()) {
960 case ui::ET_MOUSE_PRESSED:
961 if (ProcessMousePressed(*event))
962 event->SetHandled();
963 return;
965 case ui::ET_MOUSE_MOVED:
966 if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
967 ui::EF_RIGHT_MOUSE_BUTTON |
968 ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
969 OnMouseMoved(*event);
970 return;
972 // FALL-THROUGH
973 case ui::ET_MOUSE_DRAGGED:
974 if (ProcessMouseDragged(*event))
975 event->SetHandled();
976 return;
978 case ui::ET_MOUSE_RELEASED:
979 ProcessMouseReleased(*event);
980 return;
982 case ui::ET_MOUSEWHEEL:
983 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
984 event->SetHandled();
985 break;
987 case ui::ET_MOUSE_ENTERED:
988 if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY)
989 NotifyAccessibilityEvent(ui::AX_EVENT_HOVER, true);
990 OnMouseEntered(*event);
991 break;
993 case ui::ET_MOUSE_EXITED:
994 OnMouseExited(*event);
995 break;
997 default:
998 return;
1002 void View::OnScrollEvent(ui::ScrollEvent* event) {
1005 void View::OnTouchEvent(ui::TouchEvent* event) {
1006 NOTREACHED() << "Views should not receive touch events.";
1009 void View::OnGestureEvent(ui::GestureEvent* event) {
1012 ui::TextInputClient* View::GetTextInputClient() {
1013 return NULL;
1016 InputMethod* View::GetInputMethod() {
1017 Widget* widget = GetWidget();
1018 return widget ? widget->GetInputMethod() : NULL;
1021 const InputMethod* View::GetInputMethod() const {
1022 const Widget* widget = GetWidget();
1023 return widget ? widget->GetInputMethod() : NULL;
1026 scoped_ptr<ViewTargeter>
1027 View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) {
1028 scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass();
1029 targeter_ = targeter.Pass();
1030 return old_targeter.Pass();
1033 bool View::CanAcceptEvent(const ui::Event& event) {
1034 return IsDrawn();
1037 ui::EventTarget* View::GetParentTarget() {
1038 return parent_;
1041 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1042 return scoped_ptr<ui::EventTargetIterator>(
1043 new ui::EventTargetIteratorImpl<View>(children_));
1046 ui::EventTargeter* View::GetEventTargeter() {
1047 return targeter_.get();
1050 void View::ConvertEventToTarget(ui::EventTarget* target,
1051 ui::LocatedEvent* event) {
1052 event->ConvertLocationToTarget(this, static_cast<View*>(target));
1055 // Accelerators ----------------------------------------------------------------
1057 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1058 if (!accelerators_.get())
1059 accelerators_.reset(new std::vector<ui::Accelerator>());
1061 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1062 accelerators_->end()) {
1063 accelerators_->push_back(accelerator);
1065 RegisterPendingAccelerators();
1068 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1069 if (!accelerators_.get()) {
1070 NOTREACHED() << "Removing non-existing accelerator";
1071 return;
1074 std::vector<ui::Accelerator>::iterator i(
1075 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1076 if (i == accelerators_->end()) {
1077 NOTREACHED() << "Removing non-existing accelerator";
1078 return;
1081 size_t index = i - accelerators_->begin();
1082 accelerators_->erase(i);
1083 if (index >= registered_accelerator_count_) {
1084 // The accelerator is not registered to FocusManager.
1085 return;
1087 --registered_accelerator_count_;
1089 // Providing we are attached to a Widget and registered with a focus manager,
1090 // we should de-register from that focus manager now.
1091 if (GetWidget() && accelerator_focus_manager_)
1092 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1095 void View::ResetAccelerators() {
1096 if (accelerators_.get())
1097 UnregisterAccelerators(false);
1100 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1101 return false;
1104 bool View::CanHandleAccelerators() const {
1105 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1108 // Focus -----------------------------------------------------------------------
1110 bool View::HasFocus() const {
1111 const FocusManager* focus_manager = GetFocusManager();
1112 return focus_manager && (focus_manager->GetFocusedView() == this);
1115 View* View::GetNextFocusableView() {
1116 return next_focusable_view_;
1119 const View* View::GetNextFocusableView() const {
1120 return next_focusable_view_;
1123 View* View::GetPreviousFocusableView() {
1124 return previous_focusable_view_;
1127 void View::SetNextFocusableView(View* view) {
1128 if (view)
1129 view->previous_focusable_view_ = this;
1130 next_focusable_view_ = view;
1133 void View::SetFocusable(bool focusable) {
1134 if (focusable_ == focusable)
1135 return;
1137 focusable_ = focusable;
1140 bool View::IsFocusable() const {
1141 return focusable_ && enabled_ && IsDrawn();
1144 bool View::IsAccessibilityFocusable() const {
1145 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1148 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1149 if (accessibility_focusable_ == accessibility_focusable)
1150 return;
1152 accessibility_focusable_ = accessibility_focusable;
1155 FocusManager* View::GetFocusManager() {
1156 Widget* widget = GetWidget();
1157 return widget ? widget->GetFocusManager() : NULL;
1160 const FocusManager* View::GetFocusManager() const {
1161 const Widget* widget = GetWidget();
1162 return widget ? widget->GetFocusManager() : NULL;
1165 void View::RequestFocus() {
1166 FocusManager* focus_manager = GetFocusManager();
1167 if (focus_manager && IsFocusable())
1168 focus_manager->SetFocusedView(this);
1171 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1172 return false;
1175 FocusTraversable* View::GetFocusTraversable() {
1176 return NULL;
1179 FocusTraversable* View::GetPaneFocusTraversable() {
1180 return NULL;
1183 // Tooltips --------------------------------------------------------------------
1185 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1186 return false;
1189 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1190 return false;
1193 // Context menus ---------------------------------------------------------------
1195 void View::ShowContextMenu(const gfx::Point& p,
1196 ui::MenuSourceType source_type) {
1197 if (!context_menu_controller_)
1198 return;
1200 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1203 // static
1204 bool View::ShouldShowContextMenuOnMousePress() {
1205 return kContextMenuOnMousePress;
1208 // Drag and drop ---------------------------------------------------------------
1210 bool View::GetDropFormats(
1211 int* formats,
1212 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1213 return false;
1216 bool View::AreDropTypesRequired() {
1217 return false;
1220 bool View::CanDrop(const OSExchangeData& data) {
1221 // TODO(sky): when I finish up migration, this should default to true.
1222 return false;
1225 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1228 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1229 return ui::DragDropTypes::DRAG_NONE;
1232 void View::OnDragExited() {
1235 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1236 return ui::DragDropTypes::DRAG_NONE;
1239 void View::OnDragDone() {
1242 // static
1243 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1244 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1245 abs(delta.y()) > GetVerticalDragThreshold());
1248 // Accessibility----------------------------------------------------------------
1250 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1251 if (!native_view_accessibility_)
1252 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1253 if (native_view_accessibility_)
1254 return native_view_accessibility_->GetNativeObject();
1255 return NULL;
1258 void View::NotifyAccessibilityEvent(
1259 ui::AXEvent event_type,
1260 bool send_native_event) {
1261 if (ViewsDelegate::views_delegate)
1262 ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1264 if (send_native_event && GetWidget()) {
1265 if (!native_view_accessibility_)
1266 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1267 if (native_view_accessibility_)
1268 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1272 // Scrolling -------------------------------------------------------------------
1274 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1275 // We must take RTL UI mirroring into account when adjusting the position of
1276 // the region.
1277 if (parent_) {
1278 gfx::Rect scroll_rect(rect);
1279 scroll_rect.Offset(GetMirroredX(), y());
1280 parent_->ScrollRectToVisible(scroll_rect);
1284 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1285 bool is_horizontal, bool is_positive) {
1286 return 0;
1289 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1290 bool is_horizontal, bool is_positive) {
1291 return 0;
1294 ////////////////////////////////////////////////////////////////////////////////
1295 // View, protected:
1297 // Size and disposition --------------------------------------------------------
1299 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1302 void View::PreferredSizeChanged() {
1303 InvalidateLayout();
1304 if (parent_)
1305 parent_->ChildPreferredSizeChanged(this);
1308 bool View::NeedsNotificationWhenVisibleBoundsChange() const {
1309 return false;
1312 void View::OnVisibleBoundsChanged() {
1315 // Tree operations -------------------------------------------------------------
1317 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1320 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1323 void View::NativeViewHierarchyChanged() {
1324 FocusManager* focus_manager = GetFocusManager();
1325 if (accelerator_focus_manager_ != focus_manager) {
1326 UnregisterAccelerators(true);
1328 if (focus_manager)
1329 RegisterPendingAccelerators();
1333 // Painting --------------------------------------------------------------------
1335 void View::PaintChildren(gfx::Canvas* canvas, const CullSet& cull_set) {
1336 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1337 for (int i = 0, count = child_count(); i < count; ++i)
1338 if (!child_at(i)->layer())
1339 child_at(i)->Paint(canvas, cull_set);
1342 void View::OnPaint(gfx::Canvas* canvas) {
1343 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1344 OnPaintBackground(canvas);
1345 OnPaintBorder(canvas);
1348 void View::OnPaintBackground(gfx::Canvas* canvas) {
1349 if (background_.get()) {
1350 TRACE_EVENT2("views", "View::OnPaintBackground",
1351 "width", canvas->sk_canvas()->getDevice()->width(),
1352 "height", canvas->sk_canvas()->getDevice()->height());
1353 background_->Paint(canvas, this);
1357 void View::OnPaintBorder(gfx::Canvas* canvas) {
1358 if (border_.get()) {
1359 TRACE_EVENT2("views", "View::OnPaintBorder",
1360 "width", canvas->sk_canvas()->getDevice()->width(),
1361 "height", canvas->sk_canvas()->getDevice()->height());
1362 border_->Paint(*this, canvas);
1366 bool View::IsPaintRoot() {
1367 return paint_to_layer_ || !parent_;
1370 // Accelerated Painting --------------------------------------------------------
1372 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1373 // This method should not have the side-effect of creating the layer.
1374 if (layer())
1375 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1378 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1379 ui::Layer** layer_parent) {
1380 if (layer()) {
1381 if (layer_parent)
1382 *layer_parent = layer();
1383 return gfx::Vector2d();
1385 if (!parent_)
1386 return gfx::Vector2d();
1388 return gfx::Vector2d(GetMirroredX(), y()) +
1389 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1392 void View::UpdateParentLayer() {
1393 if (!layer())
1394 return;
1396 ui::Layer* parent_layer = NULL;
1397 gfx::Vector2d offset(GetMirroredX(), y());
1399 if (parent_)
1400 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1402 ReparentLayer(offset, parent_layer);
1405 void View::MoveLayerToParent(ui::Layer* parent_layer,
1406 const gfx::Point& point) {
1407 gfx::Point local_point(point);
1408 if (parent_layer != layer())
1409 local_point.Offset(GetMirroredX(), y());
1410 if (layer() && parent_layer != layer()) {
1411 parent_layer->Add(layer());
1412 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1413 width(), height()));
1414 } else {
1415 for (int i = 0, count = child_count(); i < count; ++i)
1416 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1420 void View::UpdateLayerVisibility() {
1421 bool visible = visible_;
1422 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1423 visible = v->visible();
1425 UpdateChildLayerVisibility(visible);
1428 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1429 if (layer()) {
1430 layer()->SetVisible(ancestor_visible && visible_);
1431 } else {
1432 for (int i = 0, count = child_count(); i < count; ++i)
1433 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1437 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1438 if (layer()) {
1439 SetLayerBounds(GetLocalBounds() + offset);
1440 } else {
1441 for (int i = 0, count = child_count(); i < count; ++i) {
1442 View* child = child_at(i);
1443 child->UpdateChildLayerBounds(
1444 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1449 void View::OnPaintLayer(gfx::Canvas* canvas) {
1450 if (!layer() || !layer()->fills_bounds_opaquely())
1451 canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1452 PaintCommon(canvas, CullSet());
1455 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1456 snap_layer_to_pixel_boundary_ =
1457 (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1458 SnapLayerToPixelBoundary();
1459 // Repainting with new scale factor will paint the content at the right scale.
1462 base::Closure View::PrepareForLayerBoundsChange() {
1463 return base::Closure();
1466 void View::ReorderLayers() {
1467 View* v = this;
1468 while (v && !v->layer())
1469 v = v->parent();
1471 Widget* widget = GetWidget();
1472 if (!v) {
1473 if (widget) {
1474 ui::Layer* layer = widget->GetLayer();
1475 if (layer)
1476 widget->GetRootView()->ReorderChildLayers(layer);
1478 } else {
1479 v->ReorderChildLayers(v->layer());
1482 if (widget) {
1483 // Reorder the widget's child NativeViews in case a child NativeView is
1484 // associated with a view (eg via a NativeViewHost). Always do the
1485 // reordering because the associated NativeView's layer (if it has one)
1486 // is parented to the widget's layer regardless of whether the host view has
1487 // an ancestor with a layer.
1488 widget->ReorderNativeViews();
1492 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1493 if (layer() && layer() != parent_layer) {
1494 DCHECK_EQ(parent_layer, layer()->parent());
1495 parent_layer->StackAtBottom(layer());
1496 } else {
1497 // Iterate backwards through the children so that a child with a layer
1498 // which is further to the back is stacked above one which is further to
1499 // the front.
1500 for (Views::reverse_iterator it(children_.rbegin());
1501 it != children_.rend(); ++it) {
1502 (*it)->ReorderChildLayers(parent_layer);
1507 // Input -----------------------------------------------------------------------
1509 View::DragInfo* View::GetDragInfo() {
1510 return parent_ ? parent_->GetDragInfo() : NULL;
1513 // Focus -----------------------------------------------------------------------
1515 void View::OnFocus() {
1516 // TODO(beng): Investigate whether it's possible for us to move this to
1517 // Focus().
1518 // By default, we clear the native focus. This ensures that no visible native
1519 // view as the focus and that we still receive keyboard inputs.
1520 FocusManager* focus_manager = GetFocusManager();
1521 if (focus_manager)
1522 focus_manager->ClearNativeFocus();
1524 // TODO(beng): Investigate whether it's possible for us to move this to
1525 // Focus().
1526 // Notify assistive technologies of the focus change.
1527 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1530 void View::OnBlur() {
1533 void View::Focus() {
1534 OnFocus();
1537 void View::Blur() {
1538 OnBlur();
1541 // Tooltips --------------------------------------------------------------------
1543 void View::TooltipTextChanged() {
1544 Widget* widget = GetWidget();
1545 // TooltipManager may be null if there is a problem creating it.
1546 if (widget && widget->GetTooltipManager())
1547 widget->GetTooltipManager()->TooltipTextChanged(this);
1550 // Context menus ---------------------------------------------------------------
1552 gfx::Point View::GetKeyboardContextMenuLocation() {
1553 gfx::Rect vis_bounds = GetVisibleBounds();
1554 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1555 vis_bounds.y() + vis_bounds.height() / 2);
1556 ConvertPointToScreen(this, &screen_point);
1557 return screen_point;
1560 // Drag and drop ---------------------------------------------------------------
1562 int View::GetDragOperations(const gfx::Point& press_pt) {
1563 return drag_controller_ ?
1564 drag_controller_->GetDragOperationsForView(this, press_pt) :
1565 ui::DragDropTypes::DRAG_NONE;
1568 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1569 DCHECK(drag_controller_);
1570 drag_controller_->WriteDragDataForView(this, press_pt, data);
1573 bool View::InDrag() {
1574 Widget* widget = GetWidget();
1575 return widget ? widget->dragged_view() == this : false;
1578 int View::GetHorizontalDragThreshold() {
1579 // TODO(jennyz): This value may need to be adjusted for different platforms
1580 // and for different display density.
1581 return kDefaultHorizontalDragThreshold;
1584 int View::GetVerticalDragThreshold() {
1585 // TODO(jennyz): This value may need to be adjusted for different platforms
1586 // and for different display density.
1587 return kDefaultVerticalDragThreshold;
1590 // Debugging -------------------------------------------------------------------
1592 #if !defined(NDEBUG)
1594 std::string View::PrintViewGraph(bool first) {
1595 return DoPrintViewGraph(first, this);
1598 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1599 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1600 const size_t kMaxPointerStringLength = 19;
1602 std::string result;
1604 if (first)
1605 result.append("digraph {\n");
1607 // Node characteristics.
1608 char p[kMaxPointerStringLength];
1610 const std::string class_name(GetClassName());
1611 size_t base_name_index = class_name.find_last_of('/');
1612 if (base_name_index == std::string::npos)
1613 base_name_index = 0;
1614 else
1615 base_name_index++;
1617 char bounds_buffer[512];
1619 // Information about current node.
1620 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1621 result.append(" N");
1622 result.append(p + 2);
1623 result.append(" [label=\"");
1625 result.append(class_name.substr(base_name_index).c_str());
1627 base::snprintf(bounds_buffer,
1628 arraysize(bounds_buffer),
1629 "\\n bounds: (%d, %d), (%dx%d)",
1630 bounds().x(),
1631 bounds().y(),
1632 bounds().width(),
1633 bounds().height());
1634 result.append(bounds_buffer);
1636 gfx::DecomposedTransform decomp;
1637 if (!GetTransform().IsIdentity() &&
1638 gfx::DecomposeTransform(&decomp, GetTransform())) {
1639 base::snprintf(bounds_buffer,
1640 arraysize(bounds_buffer),
1641 "\\n translation: (%f, %f)",
1642 decomp.translate[0],
1643 decomp.translate[1]);
1644 result.append(bounds_buffer);
1646 base::snprintf(bounds_buffer,
1647 arraysize(bounds_buffer),
1648 "\\n rotation: %3.2f",
1649 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1650 result.append(bounds_buffer);
1652 base::snprintf(bounds_buffer,
1653 arraysize(bounds_buffer),
1654 "\\n scale: (%2.4f, %2.4f)",
1655 decomp.scale[0],
1656 decomp.scale[1]);
1657 result.append(bounds_buffer);
1660 result.append("\"");
1661 if (!parent_)
1662 result.append(", shape=box");
1663 if (layer()) {
1664 if (layer()->has_external_content())
1665 result.append(", color=green");
1666 else
1667 result.append(", color=red");
1669 if (layer()->fills_bounds_opaquely())
1670 result.append(", style=filled");
1672 result.append("]\n");
1674 // Link to parent.
1675 if (parent_) {
1676 char pp[kMaxPointerStringLength];
1678 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1679 result.append(" N");
1680 result.append(pp + 2);
1681 result.append(" -> N");
1682 result.append(p + 2);
1683 result.append("\n");
1686 // Children.
1687 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1688 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1690 if (first)
1691 result.append("}\n");
1693 return result;
1695 #endif
1697 ////////////////////////////////////////////////////////////////////////////////
1698 // View, private:
1700 // DropInfo --------------------------------------------------------------------
1702 void View::DragInfo::Reset() {
1703 possible_drag = false;
1704 start_pt = gfx::Point();
1707 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1708 possible_drag = true;
1709 start_pt = p;
1712 // Painting --------------------------------------------------------------------
1714 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1715 // If we have a layer and the View's size did not change, we do not need to
1716 // schedule any paints since the layer will be redrawn at its new location
1717 // during the next Draw() cycle in the compositor.
1718 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1719 // Otherwise, if the size changes or we don't have a layer then we need to
1720 // use SchedulePaint to invalidate the area occupied by the View.
1721 SchedulePaint();
1722 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1723 // The compositor doesn't Draw() until something on screen changes, so
1724 // if our position changes but nothing is being animated on screen, then
1725 // tell the compositor to redraw the scene. We know layer() exists due to
1726 // the above if clause.
1727 layer()->ScheduleDraw();
1731 void View::PaintCommon(gfx::Canvas* canvas, const CullSet& cull_set) {
1732 if (!visible_)
1733 return;
1736 // If the View we are about to paint requested the canvas to be flipped, we
1737 // should change the transform appropriately.
1738 // The canvas mirroring is undone once the View is done painting so that we
1739 // don't pass the canvas with the mirrored transform to Views that didn't
1740 // request the canvas to be flipped.
1741 gfx::ScopedCanvas scoped(canvas);
1742 if (FlipCanvasOnPaintForRTLUI()) {
1743 canvas->Translate(gfx::Vector2d(width(), 0));
1744 canvas->Scale(-1, 1);
1747 OnPaint(canvas);
1750 PaintChildren(canvas, cull_set);
1753 // Tree operations -------------------------------------------------------------
1755 void View::DoRemoveChildView(View* view,
1756 bool update_focus_cycle,
1757 bool update_tool_tip,
1758 bool delete_removed_view,
1759 View* new_parent) {
1760 DCHECK(view);
1762 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1763 scoped_ptr<View> view_to_be_deleted;
1764 if (i != children_.end()) {
1765 if (update_focus_cycle) {
1766 // Let's remove the view from the focus traversal.
1767 View* next_focusable = view->next_focusable_view_;
1768 View* prev_focusable = view->previous_focusable_view_;
1769 if (prev_focusable)
1770 prev_focusable->next_focusable_view_ = next_focusable;
1771 if (next_focusable)
1772 next_focusable->previous_focusable_view_ = prev_focusable;
1775 if (GetWidget()) {
1776 UnregisterChildrenForVisibleBoundsNotification(view);
1777 if (view->visible())
1778 view->SchedulePaint();
1779 GetWidget()->NotifyWillRemoveView(view);
1782 // Remove the bounds of this child and any of its descendants from our
1783 // paint root bounds tree.
1784 BoundsTree* bounds_tree = GetBoundsTreeFromPaintRoot();
1785 if (bounds_tree)
1786 view->RemoveRootBounds(bounds_tree);
1788 view->PropagateRemoveNotifications(this, new_parent);
1789 view->parent_ = NULL;
1790 view->UpdateLayerVisibility();
1792 if (delete_removed_view && !view->owned_by_client_)
1793 view_to_be_deleted.reset(view);
1795 children_.erase(i);
1798 if (update_tool_tip)
1799 UpdateTooltip();
1801 if (layout_manager_.get())
1802 layout_manager_->ViewRemoved(this, view);
1805 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1806 for (int i = 0, count = child_count(); i < count; ++i)
1807 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1809 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1810 for (View* v = this; v; v = v->parent_)
1811 v->ViewHierarchyChangedImpl(true, details);
1814 void View::PropagateAddNotifications(
1815 const ViewHierarchyChangedDetails& details) {
1816 for (int i = 0, count = child_count(); i < count; ++i)
1817 child_at(i)->PropagateAddNotifications(details);
1818 ViewHierarchyChangedImpl(true, details);
1821 void View::PropagateNativeViewHierarchyChanged() {
1822 for (int i = 0, count = child_count(); i < count; ++i)
1823 child_at(i)->PropagateNativeViewHierarchyChanged();
1824 NativeViewHierarchyChanged();
1827 void View::ViewHierarchyChangedImpl(
1828 bool register_accelerators,
1829 const ViewHierarchyChangedDetails& details) {
1830 if (register_accelerators) {
1831 if (details.is_add) {
1832 // If you get this registration, you are part of a subtree that has been
1833 // added to the view hierarchy.
1834 if (GetFocusManager())
1835 RegisterPendingAccelerators();
1836 } else {
1837 if (details.child == this)
1838 UnregisterAccelerators(true);
1842 if (details.is_add && layer() && !layer()->parent()) {
1843 UpdateParentLayer();
1844 Widget* widget = GetWidget();
1845 if (widget)
1846 widget->UpdateRootLayers();
1847 } else if (!details.is_add && details.child == this) {
1848 // Make sure the layers belonging to the subtree rooted at |child| get
1849 // removed from layers that do not belong in the same subtree.
1850 OrphanLayers();
1851 Widget* widget = GetWidget();
1852 if (widget)
1853 widget->UpdateRootLayers();
1856 ViewHierarchyChanged(details);
1857 details.parent->needs_layout_ = true;
1860 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1861 for (int i = 0, count = child_count(); i < count; ++i)
1862 child_at(i)->PropagateNativeThemeChanged(theme);
1863 OnNativeThemeChanged(theme);
1866 // Size and disposition --------------------------------------------------------
1868 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1869 for (int i = 0, count = child_count(); i < count; ++i)
1870 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1871 VisibilityChangedImpl(start, is_visible);
1874 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1875 VisibilityChanged(starting_from, is_visible);
1878 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1879 // Mark our bounds as dirty for the paint root, also see if we need to
1880 // recompute our children's bounds due to origin change.
1881 bool origin_changed =
1882 previous_bounds.OffsetFromOrigin() != bounds_.OffsetFromOrigin();
1883 SetRootBoundsDirty(origin_changed);
1885 if (visible_) {
1886 // Paint the new bounds.
1887 SchedulePaintBoundsChanged(
1888 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1889 SCHEDULE_PAINT_SIZE_CHANGED);
1892 if (layer()) {
1893 if (parent_) {
1894 SetLayerBounds(GetLocalBounds() +
1895 gfx::Vector2d(GetMirroredX(), y()) +
1896 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1897 } else {
1898 SetLayerBounds(bounds_);
1900 } else {
1901 // If our bounds have changed, then any descendant layer bounds may have
1902 // changed. Update them accordingly.
1903 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1906 OnBoundsChanged(previous_bounds);
1908 if (previous_bounds.size() != size()) {
1909 needs_layout_ = false;
1910 Layout();
1913 if (NeedsNotificationWhenVisibleBoundsChange())
1914 OnVisibleBoundsChanged();
1916 // Notify interested Views that visible bounds within the root view may have
1917 // changed.
1918 if (descendants_to_notify_.get()) {
1919 for (Views::iterator i(descendants_to_notify_->begin());
1920 i != descendants_to_notify_->end(); ++i) {
1921 (*i)->OnVisibleBoundsChanged();
1926 // static
1927 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1928 if (view->NeedsNotificationWhenVisibleBoundsChange())
1929 view->RegisterForVisibleBoundsNotification();
1930 for (int i = 0; i < view->child_count(); ++i)
1931 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1934 // static
1935 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1936 if (view->NeedsNotificationWhenVisibleBoundsChange())
1937 view->UnregisterForVisibleBoundsNotification();
1938 for (int i = 0; i < view->child_count(); ++i)
1939 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1942 void View::RegisterForVisibleBoundsNotification() {
1943 if (registered_for_visible_bounds_notification_)
1944 return;
1946 registered_for_visible_bounds_notification_ = true;
1947 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1948 ancestor->AddDescendantToNotify(this);
1951 void View::UnregisterForVisibleBoundsNotification() {
1952 if (!registered_for_visible_bounds_notification_)
1953 return;
1955 registered_for_visible_bounds_notification_ = false;
1956 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1957 ancestor->RemoveDescendantToNotify(this);
1960 void View::AddDescendantToNotify(View* view) {
1961 DCHECK(view);
1962 if (!descendants_to_notify_.get())
1963 descendants_to_notify_.reset(new Views);
1964 descendants_to_notify_->push_back(view);
1967 void View::RemoveDescendantToNotify(View* view) {
1968 DCHECK(view && descendants_to_notify_.get());
1969 Views::iterator i(std::find(
1970 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1971 DCHECK(i != descendants_to_notify_->end());
1972 descendants_to_notify_->erase(i);
1973 if (descendants_to_notify_->empty())
1974 descendants_to_notify_.reset();
1977 void View::SetLayerBounds(const gfx::Rect& bounds) {
1978 layer()->SetBounds(bounds);
1979 SnapLayerToPixelBoundary();
1982 void View::SetRootBoundsDirty(bool origin_changed) {
1983 root_bounds_dirty_ = true;
1985 if (origin_changed) {
1986 // Inform our children that their root bounds are dirty, as their relative
1987 // coordinates in paint root space have changed since ours have changed.
1988 for (Views::const_iterator i(children_.begin()); i != children_.end();
1989 ++i) {
1990 if (!(*i)->IsPaintRoot())
1991 (*i)->SetRootBoundsDirty(origin_changed);
1996 void View::UpdateRootBounds(BoundsTree* tree, const gfx::Vector2d& offset) {
1997 // No need to recompute bounds if we haven't flagged ours as dirty.
1998 TRACE_EVENT1("views", "View::UpdateRootBounds", "class", GetClassName());
2000 // Add our own offset to the provided offset, for our own bounds update and
2001 // for propagation to our children if needed.
2002 gfx::Vector2d view_offset = offset + GetMirroredBounds().OffsetFromOrigin();
2004 // If our bounds have changed we must re-insert our new bounds to the tree.
2005 if (root_bounds_dirty_) {
2006 root_bounds_dirty_ = false;
2007 gfx::Rect bounds(
2008 view_offset.x(), view_offset.y(), bounds_.width(), bounds_.height());
2009 tree->Insert(bounds, reinterpret_cast<intptr_t>(this));
2012 // Update our children's bounds if needed.
2013 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
2014 // We don't descend in to layer views for bounds recomputation, as they
2015 // manage their own RTree as paint roots.
2016 if (!(*i)->IsPaintRoot())
2017 (*i)->UpdateRootBounds(tree, view_offset);
2021 void View::RemoveRootBounds(BoundsTree* tree) {
2022 tree->Remove(reinterpret_cast<intptr_t>(this));
2024 root_bounds_dirty_ = true;
2026 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
2027 if (!(*i)->IsPaintRoot())
2028 (*i)->RemoveRootBounds(tree);
2032 View::BoundsTree* View::GetBoundsTreeFromPaintRoot() {
2033 BoundsTree* bounds_tree = bounds_tree_.get();
2034 View* paint_root = this;
2035 while (!bounds_tree && !paint_root->IsPaintRoot()) {
2036 // Assumption is that if IsPaintRoot() is false then parent_ is valid.
2037 DCHECK(paint_root);
2038 paint_root = paint_root->parent_;
2039 bounds_tree = paint_root->bounds_tree_.get();
2042 return bounds_tree;
2045 // Transformations -------------------------------------------------------------
2047 bool View::GetTransformRelativeTo(const View* ancestor,
2048 gfx::Transform* transform) const {
2049 const View* p = this;
2051 while (p && p != ancestor) {
2052 transform->ConcatTransform(p->GetTransform());
2053 gfx::Transform translation;
2054 translation.Translate(static_cast<float>(p->GetMirroredX()),
2055 static_cast<float>(p->y()));
2056 transform->ConcatTransform(translation);
2058 p = p->parent_;
2061 return p == ancestor;
2064 // Coordinate conversion -------------------------------------------------------
2066 bool View::ConvertPointForAncestor(const View* ancestor,
2067 gfx::Point* point) const {
2068 gfx::Transform trans;
2069 // TODO(sad): Have some way of caching the transformation results.
2070 bool result = GetTransformRelativeTo(ancestor, &trans);
2071 gfx::Point3F p(*point);
2072 trans.TransformPoint(&p);
2073 *point = gfx::ToFlooredPoint(p.AsPointF());
2074 return result;
2077 bool View::ConvertPointFromAncestor(const View* ancestor,
2078 gfx::Point* point) const {
2079 gfx::Transform trans;
2080 bool result = GetTransformRelativeTo(ancestor, &trans);
2081 gfx::Point3F p(*point);
2082 trans.TransformPointReverse(&p);
2083 *point = gfx::ToFlooredPoint(p.AsPointF());
2084 return result;
2087 bool View::ConvertRectForAncestor(const View* ancestor,
2088 gfx::RectF* rect) const {
2089 gfx::Transform trans;
2090 // TODO(sad): Have some way of caching the transformation results.
2091 bool result = GetTransformRelativeTo(ancestor, &trans);
2092 trans.TransformRect(rect);
2093 return result;
2096 bool View::ConvertRectFromAncestor(const View* ancestor,
2097 gfx::RectF* rect) const {
2098 gfx::Transform trans;
2099 bool result = GetTransformRelativeTo(ancestor, &trans);
2100 trans.TransformRectReverse(rect);
2101 return result;
2104 // Accelerated painting --------------------------------------------------------
2106 void View::CreateLayer() {
2107 // A new layer is being created for the view. So all the layers of the
2108 // sub-tree can inherit the visibility of the corresponding view.
2109 for (int i = 0, count = child_count(); i < count; ++i)
2110 child_at(i)->UpdateChildLayerVisibility(true);
2112 SetLayer(new ui::Layer());
2113 layer()->set_delegate(this);
2114 #if !defined(NDEBUG)
2115 layer()->set_name(GetClassName());
2116 #endif
2118 UpdateParentLayers();
2119 UpdateLayerVisibility();
2121 // The new layer needs to be ordered in the layer tree according
2122 // to the view tree. Children of this layer were added in order
2123 // in UpdateParentLayers().
2124 if (parent())
2125 parent()->ReorderLayers();
2127 Widget* widget = GetWidget();
2128 if (widget)
2129 widget->UpdateRootLayers();
2132 void View::UpdateParentLayers() {
2133 // Attach all top-level un-parented layers.
2134 if (layer() && !layer()->parent()) {
2135 UpdateParentLayer();
2136 } else {
2137 for (int i = 0, count = child_count(); i < count; ++i)
2138 child_at(i)->UpdateParentLayers();
2142 void View::OrphanLayers() {
2143 if (layer()) {
2144 if (layer()->parent())
2145 layer()->parent()->Remove(layer());
2147 // The layer belonging to this View has already been orphaned. It is not
2148 // necessary to orphan the child layers.
2149 return;
2151 for (int i = 0, count = child_count(); i < count; ++i)
2152 child_at(i)->OrphanLayers();
2155 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2156 layer()->SetBounds(GetLocalBounds() + offset);
2157 DCHECK_NE(layer(), parent_layer);
2158 if (parent_layer)
2159 parent_layer->Add(layer());
2160 layer()->SchedulePaint(GetLocalBounds());
2161 MoveLayerToParent(layer(), gfx::Point());
2164 void View::DestroyLayer() {
2165 ui::Layer* new_parent = layer()->parent();
2166 std::vector<ui::Layer*> children = layer()->children();
2167 for (size_t i = 0; i < children.size(); ++i) {
2168 layer()->Remove(children[i]);
2169 if (new_parent)
2170 new_parent->Add(children[i]);
2173 LayerOwner::DestroyLayer();
2175 if (new_parent)
2176 ReorderLayers();
2178 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2180 SchedulePaint();
2182 Widget* widget = GetWidget();
2183 if (widget)
2184 widget->UpdateRootLayers();
2187 // Input -----------------------------------------------------------------------
2189 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2190 int drag_operations =
2191 (enabled_ && event.IsOnlyLeftMouseButton() &&
2192 HitTestPoint(event.location())) ?
2193 GetDragOperations(event.location()) : 0;
2194 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2195 context_menu_controller_ : 0;
2196 View::DragInfo* drag_info = GetDragInfo();
2198 // TODO(sky): for debugging 360238.
2199 int storage_id = 0;
2200 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2201 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2202 ViewStorage* view_storage = ViewStorage::GetInstance();
2203 storage_id = view_storage->CreateStorageID();
2204 view_storage->StoreView(storage_id, this);
2207 const bool enabled = enabled_;
2208 const bool result = OnMousePressed(event);
2210 if (!enabled)
2211 return result;
2213 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2214 kContextMenuOnMousePress) {
2215 // Assume that if there is a context menu controller we won't be deleted
2216 // from mouse pressed.
2217 gfx::Point location(event.location());
2218 if (HitTestPoint(location)) {
2219 if (storage_id != 0)
2220 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2221 ConvertPointToScreen(this, &location);
2222 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2223 return true;
2227 // WARNING: we may have been deleted, don't use any View variables.
2228 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2229 drag_info->PossibleDrag(event.location());
2230 return true;
2232 return !!context_menu_controller || result;
2235 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2236 // Copy the field, that way if we're deleted after drag and drop no harm is
2237 // done.
2238 ContextMenuController* context_menu_controller = context_menu_controller_;
2239 const bool possible_drag = GetDragInfo()->possible_drag;
2240 if (possible_drag &&
2241 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2242 (!drag_controller_ ||
2243 drag_controller_->CanStartDragForView(
2244 this, GetDragInfo()->start_pt, event.location()))) {
2245 DoDrag(event, GetDragInfo()->start_pt,
2246 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2247 } else {
2248 if (OnMouseDragged(event))
2249 return true;
2250 // Fall through to return value based on context menu controller.
2252 // WARNING: we may have been deleted.
2253 return (context_menu_controller != NULL) || possible_drag;
2256 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2257 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2258 event.IsOnlyRightMouseButton()) {
2259 // Assume that if there is a context menu controller we won't be deleted
2260 // from mouse released.
2261 gfx::Point location(event.location());
2262 OnMouseReleased(event);
2263 if (HitTestPoint(location)) {
2264 ConvertPointToScreen(this, &location);
2265 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2267 } else {
2268 OnMouseReleased(event);
2270 // WARNING: we may have been deleted.
2273 ViewTargeter* View::GetEffectiveViewTargeter() const {
2274 ViewTargeter* view_targeter = targeter();
2275 if (!view_targeter)
2276 view_targeter = GetWidget()->GetRootView()->targeter();
2277 CHECK(view_targeter);
2278 return view_targeter;
2281 // Accelerators ----------------------------------------------------------------
2283 void View::RegisterPendingAccelerators() {
2284 if (!accelerators_.get() ||
2285 registered_accelerator_count_ == accelerators_->size()) {
2286 // No accelerators are waiting for registration.
2287 return;
2290 if (!GetWidget()) {
2291 // The view is not yet attached to a widget, defer registration until then.
2292 return;
2295 accelerator_focus_manager_ = GetFocusManager();
2296 if (!accelerator_focus_manager_) {
2297 // Some crash reports seem to show that we may get cases where we have no
2298 // focus manager (see bug #1291225). This should never be the case, just
2299 // making sure we don't crash.
2300 NOTREACHED();
2301 return;
2303 for (std::vector<ui::Accelerator>::const_iterator i(
2304 accelerators_->begin() + registered_accelerator_count_);
2305 i != accelerators_->end(); ++i) {
2306 accelerator_focus_manager_->RegisterAccelerator(
2307 *i, ui::AcceleratorManager::kNormalPriority, this);
2309 registered_accelerator_count_ = accelerators_->size();
2312 void View::UnregisterAccelerators(bool leave_data_intact) {
2313 if (!accelerators_.get())
2314 return;
2316 if (GetWidget()) {
2317 if (accelerator_focus_manager_) {
2318 accelerator_focus_manager_->UnregisterAccelerators(this);
2319 accelerator_focus_manager_ = NULL;
2321 if (!leave_data_intact) {
2322 accelerators_->clear();
2323 accelerators_.reset();
2325 registered_accelerator_count_ = 0;
2329 // Focus -----------------------------------------------------------------------
2331 void View::InitFocusSiblings(View* v, int index) {
2332 int count = child_count();
2334 if (count == 0) {
2335 v->next_focusable_view_ = NULL;
2336 v->previous_focusable_view_ = NULL;
2337 } else {
2338 if (index == count) {
2339 // We are inserting at the end, but the end of the child list may not be
2340 // the last focusable element. Let's try to find an element with no next
2341 // focusable element to link to.
2342 View* last_focusable_view = NULL;
2343 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2344 if (!(*i)->next_focusable_view_) {
2345 last_focusable_view = *i;
2346 break;
2349 if (last_focusable_view == NULL) {
2350 // Hum... there is a cycle in the focus list. Let's just insert ourself
2351 // after the last child.
2352 View* prev = children_[index - 1];
2353 v->previous_focusable_view_ = prev;
2354 v->next_focusable_view_ = prev->next_focusable_view_;
2355 prev->next_focusable_view_->previous_focusable_view_ = v;
2356 prev->next_focusable_view_ = v;
2357 } else {
2358 last_focusable_view->next_focusable_view_ = v;
2359 v->next_focusable_view_ = NULL;
2360 v->previous_focusable_view_ = last_focusable_view;
2362 } else {
2363 View* prev = children_[index]->GetPreviousFocusableView();
2364 v->previous_focusable_view_ = prev;
2365 v->next_focusable_view_ = children_[index];
2366 if (prev)
2367 prev->next_focusable_view_ = v;
2368 children_[index]->previous_focusable_view_ = v;
2373 // System events ---------------------------------------------------------------
2375 void View::PropagateThemeChanged() {
2376 for (int i = child_count() - 1; i >= 0; --i)
2377 child_at(i)->PropagateThemeChanged();
2378 OnThemeChanged();
2381 void View::PropagateLocaleChanged() {
2382 for (int i = child_count() - 1; i >= 0; --i)
2383 child_at(i)->PropagateLocaleChanged();
2384 OnLocaleChanged();
2387 // Tooltips --------------------------------------------------------------------
2389 void View::UpdateTooltip() {
2390 Widget* widget = GetWidget();
2391 // TODO(beng): The TooltipManager NULL check can be removed when we
2392 // consolidate Init() methods and make views_unittests Init() all
2393 // Widgets that it uses.
2394 if (widget && widget->GetTooltipManager())
2395 widget->GetTooltipManager()->UpdateTooltip();
2398 // Drag and drop ---------------------------------------------------------------
2400 bool View::DoDrag(const ui::LocatedEvent& event,
2401 const gfx::Point& press_pt,
2402 ui::DragDropTypes::DragEventSource source) {
2403 int drag_operations = GetDragOperations(press_pt);
2404 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2405 return false;
2407 Widget* widget = GetWidget();
2408 // We should only start a drag from an event, implying we have a widget.
2409 DCHECK(widget);
2411 // Don't attempt to start a drag while in the process of dragging. This is
2412 // especially important on X where we can get multiple mouse move events when
2413 // we start the drag.
2414 if (widget->dragged_view())
2415 return false;
2417 OSExchangeData data;
2418 WriteDragData(press_pt, &data);
2420 // Message the RootView to do the drag and drop. That way if we're removed
2421 // the RootView can detect it and avoid calling us back.
2422 gfx::Point widget_location(event.location());
2423 ConvertPointToWidget(this, &widget_location);
2424 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2425 // WARNING: we may have been deleted.
2426 return true;
2429 } // namespace views