Move content_settings_pattern and content_settings_pattern_parser to the content_sett...
[chromium-blink-merge.git] / ui / views / view.cc
blob8b79faa37d5d25db90f0eca216514acce879b65d
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;
409 AdvanceFocusIfNecessary();
411 // Notify the parent.
412 if (parent_)
413 parent_->ChildVisibilityChanged(this);
415 // This notifies all sub-views recursively.
416 PropagateVisibilityNotifications(this, visible_);
417 UpdateLayerVisibility();
419 // If we are newly visible, schedule paint.
420 if (visible_)
421 SchedulePaint();
425 bool View::IsDrawn() const {
426 return visible_ && parent_ ? parent_->IsDrawn() : false;
429 void View::SetEnabled(bool enabled) {
430 if (enabled != enabled_) {
431 enabled_ = enabled;
432 AdvanceFocusIfNecessary();
433 OnEnabledChanged();
437 void View::OnEnabledChanged() {
438 SchedulePaint();
441 // Transformations -------------------------------------------------------------
443 gfx::Transform View::GetTransform() const {
444 return layer() ? layer()->transform() : gfx::Transform();
447 void View::SetTransform(const gfx::Transform& transform) {
448 if (transform.IsIdentity()) {
449 if (layer()) {
450 layer()->SetTransform(transform);
451 if (!paint_to_layer_)
452 DestroyLayer();
453 } else {
454 // Nothing.
456 } else {
457 if (!layer())
458 CreateLayer();
459 layer()->SetTransform(transform);
460 layer()->ScheduleDraw();
464 void View::SetPaintToLayer(bool paint_to_layer) {
465 if (paint_to_layer_ == paint_to_layer)
466 return;
468 // If this is a change in state we will also need to update bounds trees.
469 if (paint_to_layer) {
470 // Gaining a layer means becoming a paint root. We must remove ourselves
471 // from our old paint root, if we had one. Traverse up view tree to find old
472 // paint root.
473 View* old_paint_root = parent_;
474 while (old_paint_root && !old_paint_root->IsPaintRoot())
475 old_paint_root = old_paint_root->parent_;
477 // Remove our and our children's bounds from the old tree. This will also
478 // mark all of our bounds as dirty.
479 if (old_paint_root && old_paint_root->bounds_tree_)
480 RemoveRootBounds(old_paint_root->bounds_tree_.get());
482 } else {
483 // Losing a layer means we are no longer a paint root, so delete our
484 // bounds tree and mark ourselves as dirty for future insertion into our
485 // new paint root's bounds tree.
486 bounds_tree_.reset();
487 SetRootBoundsDirty(true);
490 paint_to_layer_ = paint_to_layer;
491 if (paint_to_layer_ && !layer()) {
492 CreateLayer();
493 } else if (!paint_to_layer_ && layer()) {
494 DestroyLayer();
498 // RTL positioning -------------------------------------------------------------
500 gfx::Rect View::GetMirroredBounds() const {
501 gfx::Rect bounds(bounds_);
502 bounds.set_x(GetMirroredX());
503 return bounds;
506 gfx::Point View::GetMirroredPosition() const {
507 return gfx::Point(GetMirroredX(), y());
510 int View::GetMirroredX() const {
511 return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
514 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
515 return base::i18n::IsRTL() ?
516 (width() - bounds.x() - bounds.width()) : bounds.x();
519 int View::GetMirroredXInView(int x) const {
520 return base::i18n::IsRTL() ? width() - x : x;
523 int View::GetMirroredXWithWidthInView(int x, int w) const {
524 return base::i18n::IsRTL() ? width() - x - w : x;
527 // Layout ----------------------------------------------------------------------
529 void View::Layout() {
530 needs_layout_ = false;
532 // If we have a layout manager, let it handle the layout for us.
533 if (layout_manager_.get())
534 layout_manager_->Layout(this);
536 // Make sure to propagate the Layout() call to any children that haven't
537 // received it yet through the layout manager and need to be laid out. This
538 // is needed for the case when the child requires a layout but its bounds
539 // weren't changed by the layout manager. If there is no layout manager, we
540 // just propagate the Layout() call down the hierarchy, so whoever receives
541 // the call can take appropriate action.
542 for (int i = 0, count = child_count(); i < count; ++i) {
543 View* child = child_at(i);
544 if (child->needs_layout_ || !layout_manager_.get()) {
545 child->needs_layout_ = false;
546 child->Layout();
551 void View::InvalidateLayout() {
552 // Always invalidate up. This is needed to handle the case of us already being
553 // valid, but not our parent.
554 needs_layout_ = true;
555 if (parent_)
556 parent_->InvalidateLayout();
559 LayoutManager* View::GetLayoutManager() const {
560 return layout_manager_.get();
563 void View::SetLayoutManager(LayoutManager* layout_manager) {
564 if (layout_manager_.get())
565 layout_manager_->Uninstalled(this);
567 layout_manager_.reset(layout_manager);
568 if (layout_manager_.get())
569 layout_manager_->Installed(this);
572 void View::SnapLayerToPixelBoundary() {
573 if (!layer())
574 return;
576 if (snap_layer_to_pixel_boundary_ && layer()->parent() &&
577 layer()->GetCompositor()) {
578 ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer());
579 } else {
580 // Reset the offset.
581 layer()->SetSubpixelPositionOffset(gfx::Vector2dF());
585 // Attributes ------------------------------------------------------------------
587 const char* View::GetClassName() const {
588 return kViewClassName;
591 const View* View::GetAncestorWithClassName(const std::string& name) const {
592 for (const View* view = this; view; view = view->parent_) {
593 if (!strcmp(view->GetClassName(), name.c_str()))
594 return view;
596 return NULL;
599 View* View::GetAncestorWithClassName(const std::string& name) {
600 return const_cast<View*>(const_cast<const View*>(this)->
601 GetAncestorWithClassName(name));
604 const View* View::GetViewByID(int id) const {
605 if (id == id_)
606 return const_cast<View*>(this);
608 for (int i = 0, count = child_count(); i < count; ++i) {
609 const View* view = child_at(i)->GetViewByID(id);
610 if (view)
611 return view;
613 return NULL;
616 View* View::GetViewByID(int id) {
617 return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
620 void View::SetGroup(int gid) {
621 // Don't change the group id once it's set.
622 DCHECK(group_ == -1 || group_ == gid);
623 group_ = gid;
626 int View::GetGroup() const {
627 return group_;
630 bool View::IsGroupFocusTraversable() const {
631 return true;
634 void View::GetViewsInGroup(int group, Views* views) {
635 if (group_ == group)
636 views->push_back(this);
638 for (int i = 0, count = child_count(); i < count; ++i)
639 child_at(i)->GetViewsInGroup(group, views);
642 View* View::GetSelectedViewForGroup(int group) {
643 Views views;
644 GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
645 return views.empty() ? NULL : views[0];
648 // Coordinate conversion -------------------------------------------------------
650 // static
651 void View::ConvertPointToTarget(const View* source,
652 const View* target,
653 gfx::Point* point) {
654 DCHECK(source);
655 DCHECK(target);
656 if (source == target)
657 return;
659 const View* root = GetHierarchyRoot(target);
660 CHECK_EQ(GetHierarchyRoot(source), root);
662 if (source != root)
663 source->ConvertPointForAncestor(root, point);
665 if (target != root)
666 target->ConvertPointFromAncestor(root, point);
669 // static
670 void View::ConvertRectToTarget(const View* source,
671 const View* target,
672 gfx::RectF* rect) {
673 DCHECK(source);
674 DCHECK(target);
675 if (source == target)
676 return;
678 const View* root = GetHierarchyRoot(target);
679 CHECK_EQ(GetHierarchyRoot(source), root);
681 if (source != root)
682 source->ConvertRectForAncestor(root, rect);
684 if (target != root)
685 target->ConvertRectFromAncestor(root, rect);
688 // static
689 void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
690 DCHECK(src);
691 DCHECK(p);
693 src->ConvertPointForAncestor(NULL, p);
696 // static
697 void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
698 DCHECK(dest);
699 DCHECK(p);
701 dest->ConvertPointFromAncestor(NULL, p);
704 // static
705 void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
706 DCHECK(src);
707 DCHECK(p);
709 // If the view is not connected to a tree, there's nothing we can do.
710 const Widget* widget = src->GetWidget();
711 if (widget) {
712 ConvertPointToWidget(src, p);
713 *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
717 // static
718 void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
719 DCHECK(dst);
720 DCHECK(p);
722 const views::Widget* widget = dst->GetWidget();
723 if (!widget)
724 return;
725 *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
726 views::View::ConvertPointFromWidget(dst, p);
729 gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
730 gfx::RectF x_rect = rect;
731 GetTransform().TransformRect(&x_rect);
732 x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
733 // Pixels we partially occupy in the parent should be included.
734 return gfx::ToEnclosingRect(x_rect);
737 gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
738 gfx::Rect x_rect = rect;
739 for (const View* v = this; v; v = v->parent_)
740 x_rect = v->ConvertRectToParent(x_rect);
741 return x_rect;
744 // Painting --------------------------------------------------------------------
746 void View::SchedulePaint() {
747 SchedulePaintInRect(GetLocalBounds());
750 void View::SchedulePaintInRect(const gfx::Rect& rect) {
751 if (!visible_)
752 return;
754 if (layer()) {
755 layer()->SchedulePaint(rect);
756 } else if (parent_) {
757 // Translate the requested paint rect to the parent's coordinate system
758 // then pass this notification up to the parent.
759 parent_->SchedulePaintInRect(ConvertRectToParent(rect));
763 void View::Paint(gfx::Canvas* canvas, const CullSet& cull_set) {
764 // The cull_set may allow us to skip painting without canvas construction or
765 // even canvas rect intersection.
766 if (cull_set.ShouldPaint(this)) {
767 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
769 gfx::ScopedCanvas scoped_canvas(canvas);
771 // Paint this View and its children, setting the clip rect to the bounds
772 // of this View and translating the origin to the local bounds' top left
773 // point.
775 // Note that the X (or left) position we pass to ClipRectInt takes into
776 // consideration whether or not the view uses a right-to-left layout so that
777 // we paint our view in its mirrored position if need be.
778 gfx::Rect clip_rect = bounds();
779 clip_rect.Inset(clip_insets_);
780 if (parent_)
781 clip_rect.set_x(parent_->GetMirroredXForRect(clip_rect));
782 canvas->ClipRect(clip_rect);
783 if (canvas->IsClipEmpty())
784 return;
786 // Non-empty clip, translate the graphics such that 0,0 corresponds to where
787 // this view is located (related to its parent).
788 canvas->Translate(GetMirroredPosition().OffsetFromOrigin());
789 canvas->Transform(GetTransform());
791 // If we are a paint root, we need to construct our own CullSet object for
792 // propagation to our children.
793 if (IsPaintRoot()) {
794 if (!bounds_tree_)
795 bounds_tree_.reset(new BoundsTree(2, 5));
797 // Recompute our bounds tree as needed.
798 UpdateRootBounds(bounds_tree_.get(), gfx::Vector2d());
800 // Grab the clip rect from the supplied canvas to use as the query rect.
801 gfx::Rect canvas_bounds;
802 if (!canvas->GetClipBounds(&canvas_bounds)) {
803 NOTREACHED() << "Failed to get clip bounds from the canvas!";
804 return;
807 // Now query our bounds_tree_ for a set of damaged views that intersect
808 // our canvas bounds.
809 scoped_ptr<base::hash_set<intptr_t> > damaged_views(
810 new base::hash_set<intptr_t>());
811 bounds_tree_->AppendIntersectingRecords(
812 canvas_bounds, damaged_views.get());
813 // Construct a CullSet to wrap the damaged views set, it will delete it
814 // for us on scope exit.
815 CullSet paint_root_cull_set(damaged_views.Pass());
816 // Paint all descendents using our new cull set.
817 PaintCommon(canvas, paint_root_cull_set);
818 } else {
819 // Not a paint root, so we can proceed as normal.
820 PaintCommon(canvas, cull_set);
825 void View::set_background(Background* b) {
826 background_.reset(b);
829 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
831 ui::ThemeProvider* View::GetThemeProvider() const {
832 const Widget* widget = GetWidget();
833 return widget ? widget->GetThemeProvider() : NULL;
836 const ui::NativeTheme* View::GetNativeTheme() const {
837 const Widget* widget = GetWidget();
838 return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
841 // Input -----------------------------------------------------------------------
843 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
844 return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
847 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
848 return GetEffectiveViewTargeter()->TargetForRect(this, rect);
851 bool View::CanProcessEventsWithinSubtree() const {
852 return true;
855 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
856 // TODO(tdanderson): Move this implementation into ViewTargetDelegate.
857 if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree())
858 return NULL;
860 // Walk the child Views recursively looking for the View that most
861 // tightly encloses the specified point.
862 for (int i = child_count() - 1; i >= 0; --i) {
863 View* child = child_at(i);
864 if (!child->visible())
865 continue;
867 gfx::Point point_in_child_coords(point);
868 ConvertPointToTarget(this, child, &point_in_child_coords);
869 View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
870 if (handler)
871 return handler;
873 return this;
876 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
877 #if defined(OS_WIN)
878 static ui::Cursor arrow;
879 if (!arrow.platform())
880 arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
881 return arrow;
882 #else
883 return gfx::kNullCursor;
884 #endif
887 bool View::HitTestPoint(const gfx::Point& point) const {
888 return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
891 bool View::HitTestRect(const gfx::Rect& rect) const {
892 return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect);
895 bool View::IsMouseHovered() {
896 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
897 // hovered.
898 if (!GetWidget())
899 return false;
901 // If mouse events are disabled, then the mouse cursor is invisible and
902 // is therefore not hovering over this button.
903 if (!GetWidget()->IsMouseEventsEnabled())
904 return false;
906 gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
907 GetWidget()->GetNativeView())->GetCursorScreenPoint());
908 ConvertPointFromScreen(this, &cursor_pos);
909 return HitTestPoint(cursor_pos);
912 bool View::OnMousePressed(const ui::MouseEvent& event) {
913 return false;
916 bool View::OnMouseDragged(const ui::MouseEvent& event) {
917 return false;
920 void View::OnMouseReleased(const ui::MouseEvent& event) {
923 void View::OnMouseCaptureLost() {
926 void View::OnMouseMoved(const ui::MouseEvent& event) {
929 void View::OnMouseEntered(const ui::MouseEvent& event) {
932 void View::OnMouseExited(const ui::MouseEvent& event) {
935 void View::SetMouseHandler(View* new_mouse_handler) {
936 // |new_mouse_handler| may be NULL.
937 if (parent_)
938 parent_->SetMouseHandler(new_mouse_handler);
941 bool View::OnKeyPressed(const ui::KeyEvent& event) {
942 return false;
945 bool View::OnKeyReleased(const ui::KeyEvent& event) {
946 return false;
949 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
950 return false;
953 void View::OnKeyEvent(ui::KeyEvent* event) {
954 bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
955 OnKeyReleased(*event);
956 if (consumed)
957 event->StopPropagation();
960 void View::OnMouseEvent(ui::MouseEvent* event) {
961 switch (event->type()) {
962 case ui::ET_MOUSE_PRESSED:
963 if (ProcessMousePressed(*event))
964 event->SetHandled();
965 return;
967 case ui::ET_MOUSE_MOVED:
968 if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
969 ui::EF_RIGHT_MOUSE_BUTTON |
970 ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
971 OnMouseMoved(*event);
972 return;
974 // FALL-THROUGH
975 case ui::ET_MOUSE_DRAGGED:
976 if (ProcessMouseDragged(*event))
977 event->SetHandled();
978 return;
980 case ui::ET_MOUSE_RELEASED:
981 ProcessMouseReleased(*event);
982 return;
984 case ui::ET_MOUSEWHEEL:
985 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
986 event->SetHandled();
987 break;
989 case ui::ET_MOUSE_ENTERED:
990 if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY)
991 NotifyAccessibilityEvent(ui::AX_EVENT_HOVER, true);
992 OnMouseEntered(*event);
993 break;
995 case ui::ET_MOUSE_EXITED:
996 OnMouseExited(*event);
997 break;
999 default:
1000 return;
1004 void View::OnScrollEvent(ui::ScrollEvent* event) {
1007 void View::OnTouchEvent(ui::TouchEvent* event) {
1008 NOTREACHED() << "Views should not receive touch events.";
1011 void View::OnGestureEvent(ui::GestureEvent* event) {
1014 ui::TextInputClient* View::GetTextInputClient() {
1015 return NULL;
1018 InputMethod* View::GetInputMethod() {
1019 Widget* widget = GetWidget();
1020 return widget ? widget->GetInputMethod() : NULL;
1023 const InputMethod* View::GetInputMethod() const {
1024 const Widget* widget = GetWidget();
1025 return widget ? widget->GetInputMethod() : NULL;
1028 scoped_ptr<ViewTargeter>
1029 View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) {
1030 scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass();
1031 targeter_ = targeter.Pass();
1032 return old_targeter.Pass();
1035 ViewTargeter* View::GetEffectiveViewTargeter() const {
1036 DCHECK(GetWidget());
1037 ViewTargeter* view_targeter = targeter();
1038 if (!view_targeter)
1039 view_targeter = GetWidget()->GetRootView()->targeter();
1040 CHECK(view_targeter);
1041 return view_targeter;
1044 bool View::CanAcceptEvent(const ui::Event& event) {
1045 return IsDrawn();
1048 ui::EventTarget* View::GetParentTarget() {
1049 return parent_;
1052 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1053 return scoped_ptr<ui::EventTargetIterator>(
1054 new ui::EventTargetIteratorImpl<View>(children_));
1057 ui::EventTargeter* View::GetEventTargeter() {
1058 return targeter_.get();
1061 void View::ConvertEventToTarget(ui::EventTarget* target,
1062 ui::LocatedEvent* event) {
1063 event->ConvertLocationToTarget(this, static_cast<View*>(target));
1066 // Accelerators ----------------------------------------------------------------
1068 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1069 if (!accelerators_.get())
1070 accelerators_.reset(new std::vector<ui::Accelerator>());
1072 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1073 accelerators_->end()) {
1074 accelerators_->push_back(accelerator);
1076 RegisterPendingAccelerators();
1079 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1080 if (!accelerators_.get()) {
1081 NOTREACHED() << "Removing non-existing accelerator";
1082 return;
1085 std::vector<ui::Accelerator>::iterator i(
1086 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1087 if (i == accelerators_->end()) {
1088 NOTREACHED() << "Removing non-existing accelerator";
1089 return;
1092 size_t index = i - accelerators_->begin();
1093 accelerators_->erase(i);
1094 if (index >= registered_accelerator_count_) {
1095 // The accelerator is not registered to FocusManager.
1096 return;
1098 --registered_accelerator_count_;
1100 // Providing we are attached to a Widget and registered with a focus manager,
1101 // we should de-register from that focus manager now.
1102 if (GetWidget() && accelerator_focus_manager_)
1103 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1106 void View::ResetAccelerators() {
1107 if (accelerators_.get())
1108 UnregisterAccelerators(false);
1111 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1112 return false;
1115 bool View::CanHandleAccelerators() const {
1116 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1119 // Focus -----------------------------------------------------------------------
1121 bool View::HasFocus() const {
1122 const FocusManager* focus_manager = GetFocusManager();
1123 return focus_manager && (focus_manager->GetFocusedView() == this);
1126 View* View::GetNextFocusableView() {
1127 return next_focusable_view_;
1130 const View* View::GetNextFocusableView() const {
1131 return next_focusable_view_;
1134 View* View::GetPreviousFocusableView() {
1135 return previous_focusable_view_;
1138 void View::SetNextFocusableView(View* view) {
1139 if (view)
1140 view->previous_focusable_view_ = this;
1141 next_focusable_view_ = view;
1144 void View::SetFocusable(bool focusable) {
1145 if (focusable_ == focusable)
1146 return;
1148 focusable_ = focusable;
1149 AdvanceFocusIfNecessary();
1152 bool View::IsFocusable() const {
1153 return focusable_ && enabled_ && IsDrawn();
1156 bool View::IsAccessibilityFocusable() const {
1157 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1160 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1161 if (accessibility_focusable_ == accessibility_focusable)
1162 return;
1164 accessibility_focusable_ = accessibility_focusable;
1165 AdvanceFocusIfNecessary();
1168 FocusManager* View::GetFocusManager() {
1169 Widget* widget = GetWidget();
1170 return widget ? widget->GetFocusManager() : NULL;
1173 const FocusManager* View::GetFocusManager() const {
1174 const Widget* widget = GetWidget();
1175 return widget ? widget->GetFocusManager() : NULL;
1178 void View::RequestFocus() {
1179 FocusManager* focus_manager = GetFocusManager();
1180 if (focus_manager && IsFocusable())
1181 focus_manager->SetFocusedView(this);
1184 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1185 return false;
1188 FocusTraversable* View::GetFocusTraversable() {
1189 return NULL;
1192 FocusTraversable* View::GetPaneFocusTraversable() {
1193 return NULL;
1196 // Tooltips --------------------------------------------------------------------
1198 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1199 return false;
1202 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1203 return false;
1206 // Context menus ---------------------------------------------------------------
1208 void View::ShowContextMenu(const gfx::Point& p,
1209 ui::MenuSourceType source_type) {
1210 if (!context_menu_controller_)
1211 return;
1213 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1216 // static
1217 bool View::ShouldShowContextMenuOnMousePress() {
1218 return kContextMenuOnMousePress;
1221 // Drag and drop ---------------------------------------------------------------
1223 bool View::GetDropFormats(
1224 int* formats,
1225 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1226 return false;
1229 bool View::AreDropTypesRequired() {
1230 return false;
1233 bool View::CanDrop(const OSExchangeData& data) {
1234 // TODO(sky): when I finish up migration, this should default to true.
1235 return false;
1238 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1241 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1242 return ui::DragDropTypes::DRAG_NONE;
1245 void View::OnDragExited() {
1248 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1249 return ui::DragDropTypes::DRAG_NONE;
1252 void View::OnDragDone() {
1255 // static
1256 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1257 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1258 abs(delta.y()) > GetVerticalDragThreshold());
1261 // Accessibility----------------------------------------------------------------
1263 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1264 if (!native_view_accessibility_)
1265 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1266 if (native_view_accessibility_)
1267 return native_view_accessibility_->GetNativeObject();
1268 return NULL;
1271 void View::NotifyAccessibilityEvent(
1272 ui::AXEvent event_type,
1273 bool send_native_event) {
1274 if (ViewsDelegate::views_delegate)
1275 ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1277 if (send_native_event && GetWidget()) {
1278 if (!native_view_accessibility_)
1279 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1280 if (native_view_accessibility_)
1281 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1285 // Scrolling -------------------------------------------------------------------
1287 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1288 // We must take RTL UI mirroring into account when adjusting the position of
1289 // the region.
1290 if (parent_) {
1291 gfx::Rect scroll_rect(rect);
1292 scroll_rect.Offset(GetMirroredX(), y());
1293 parent_->ScrollRectToVisible(scroll_rect);
1297 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1298 bool is_horizontal, bool is_positive) {
1299 return 0;
1302 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1303 bool is_horizontal, bool is_positive) {
1304 return 0;
1307 ////////////////////////////////////////////////////////////////////////////////
1308 // View, protected:
1310 // Size and disposition --------------------------------------------------------
1312 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1315 void View::PreferredSizeChanged() {
1316 InvalidateLayout();
1317 if (parent_)
1318 parent_->ChildPreferredSizeChanged(this);
1321 bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
1322 return false;
1325 void View::OnVisibleBoundsChanged() {
1328 // Tree operations -------------------------------------------------------------
1330 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1333 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1336 void View::NativeViewHierarchyChanged() {
1337 FocusManager* focus_manager = GetFocusManager();
1338 if (accelerator_focus_manager_ != focus_manager) {
1339 UnregisterAccelerators(true);
1341 if (focus_manager)
1342 RegisterPendingAccelerators();
1346 // Painting --------------------------------------------------------------------
1348 void View::PaintChildren(gfx::Canvas* canvas, const CullSet& cull_set) {
1349 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1350 for (int i = 0, count = child_count(); i < count; ++i)
1351 if (!child_at(i)->layer())
1352 child_at(i)->Paint(canvas, cull_set);
1355 void View::OnPaint(gfx::Canvas* canvas) {
1356 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1357 OnPaintBackground(canvas);
1358 OnPaintBorder(canvas);
1361 void View::OnPaintBackground(gfx::Canvas* canvas) {
1362 if (background_.get()) {
1363 TRACE_EVENT2("views", "View::OnPaintBackground",
1364 "width", canvas->sk_canvas()->getDevice()->width(),
1365 "height", canvas->sk_canvas()->getDevice()->height());
1366 background_->Paint(canvas, this);
1370 void View::OnPaintBorder(gfx::Canvas* canvas) {
1371 if (border_.get()) {
1372 TRACE_EVENT2("views", "View::OnPaintBorder",
1373 "width", canvas->sk_canvas()->getDevice()->width(),
1374 "height", canvas->sk_canvas()->getDevice()->height());
1375 border_->Paint(*this, canvas);
1379 bool View::IsPaintRoot() {
1380 return paint_to_layer_ || !parent_;
1383 // Accelerated Painting --------------------------------------------------------
1385 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1386 // This method should not have the side-effect of creating the layer.
1387 if (layer())
1388 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1391 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1392 ui::Layer** layer_parent) {
1393 if (layer()) {
1394 if (layer_parent)
1395 *layer_parent = layer();
1396 return gfx::Vector2d();
1398 if (!parent_)
1399 return gfx::Vector2d();
1401 return gfx::Vector2d(GetMirroredX(), y()) +
1402 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1405 void View::UpdateParentLayer() {
1406 if (!layer())
1407 return;
1409 ui::Layer* parent_layer = NULL;
1410 gfx::Vector2d offset(GetMirroredX(), y());
1412 if (parent_)
1413 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1415 ReparentLayer(offset, parent_layer);
1418 void View::MoveLayerToParent(ui::Layer* parent_layer,
1419 const gfx::Point& point) {
1420 gfx::Point local_point(point);
1421 if (parent_layer != layer())
1422 local_point.Offset(GetMirroredX(), y());
1423 if (layer() && parent_layer != layer()) {
1424 parent_layer->Add(layer());
1425 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1426 width(), height()));
1427 } else {
1428 for (int i = 0, count = child_count(); i < count; ++i)
1429 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1433 void View::UpdateLayerVisibility() {
1434 bool visible = visible_;
1435 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1436 visible = v->visible();
1438 UpdateChildLayerVisibility(visible);
1441 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1442 if (layer()) {
1443 layer()->SetVisible(ancestor_visible && visible_);
1444 } else {
1445 for (int i = 0, count = child_count(); i < count; ++i)
1446 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1450 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1451 if (layer()) {
1452 SetLayerBounds(GetLocalBounds() + offset);
1453 } else {
1454 for (int i = 0, count = child_count(); i < count; ++i) {
1455 View* child = child_at(i);
1456 child->UpdateChildLayerBounds(
1457 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1462 void View::OnPaintLayer(gfx::Canvas* canvas) {
1463 if (!layer() || !layer()->fills_bounds_opaquely())
1464 canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1465 PaintCommon(canvas, CullSet());
1468 void View::OnDelegatedFrameDamage(
1469 const gfx::Rect& damage_rect_in_dip) {
1472 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1473 snap_layer_to_pixel_boundary_ =
1474 (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1475 SnapLayerToPixelBoundary();
1476 // Repainting with new scale factor will paint the content at the right scale.
1479 base::Closure View::PrepareForLayerBoundsChange() {
1480 return base::Closure();
1483 void View::ReorderLayers() {
1484 View* v = this;
1485 while (v && !v->layer())
1486 v = v->parent();
1488 Widget* widget = GetWidget();
1489 if (!v) {
1490 if (widget) {
1491 ui::Layer* layer = widget->GetLayer();
1492 if (layer)
1493 widget->GetRootView()->ReorderChildLayers(layer);
1495 } else {
1496 v->ReorderChildLayers(v->layer());
1499 if (widget) {
1500 // Reorder the widget's child NativeViews in case a child NativeView is
1501 // associated with a view (eg via a NativeViewHost). Always do the
1502 // reordering because the associated NativeView's layer (if it has one)
1503 // is parented to the widget's layer regardless of whether the host view has
1504 // an ancestor with a layer.
1505 widget->ReorderNativeViews();
1509 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1510 if (layer() && layer() != parent_layer) {
1511 DCHECK_EQ(parent_layer, layer()->parent());
1512 parent_layer->StackAtBottom(layer());
1513 } else {
1514 // Iterate backwards through the children so that a child with a layer
1515 // which is further to the back is stacked above one which is further to
1516 // the front.
1517 for (Views::reverse_iterator it(children_.rbegin());
1518 it != children_.rend(); ++it) {
1519 (*it)->ReorderChildLayers(parent_layer);
1524 // Input -----------------------------------------------------------------------
1526 View::DragInfo* View::GetDragInfo() {
1527 return parent_ ? parent_->GetDragInfo() : NULL;
1530 // Focus -----------------------------------------------------------------------
1532 void View::OnFocus() {
1533 // TODO(beng): Investigate whether it's possible for us to move this to
1534 // Focus().
1535 // By default, we clear the native focus. This ensures that no visible native
1536 // view as the focus and that we still receive keyboard inputs.
1537 FocusManager* focus_manager = GetFocusManager();
1538 if (focus_manager)
1539 focus_manager->ClearNativeFocus();
1541 // TODO(beng): Investigate whether it's possible for us to move this to
1542 // Focus().
1543 // Notify assistive technologies of the focus change.
1544 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1547 void View::OnBlur() {
1550 void View::Focus() {
1551 OnFocus();
1554 void View::Blur() {
1555 OnBlur();
1558 // Tooltips --------------------------------------------------------------------
1560 void View::TooltipTextChanged() {
1561 Widget* widget = GetWidget();
1562 // TooltipManager may be null if there is a problem creating it.
1563 if (widget && widget->GetTooltipManager())
1564 widget->GetTooltipManager()->TooltipTextChanged(this);
1567 // Context menus ---------------------------------------------------------------
1569 gfx::Point View::GetKeyboardContextMenuLocation() {
1570 gfx::Rect vis_bounds = GetVisibleBounds();
1571 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1572 vis_bounds.y() + vis_bounds.height() / 2);
1573 ConvertPointToScreen(this, &screen_point);
1574 return screen_point;
1577 // Drag and drop ---------------------------------------------------------------
1579 int View::GetDragOperations(const gfx::Point& press_pt) {
1580 return drag_controller_ ?
1581 drag_controller_->GetDragOperationsForView(this, press_pt) :
1582 ui::DragDropTypes::DRAG_NONE;
1585 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1586 DCHECK(drag_controller_);
1587 drag_controller_->WriteDragDataForView(this, press_pt, data);
1590 bool View::InDrag() {
1591 Widget* widget = GetWidget();
1592 return widget ? widget->dragged_view() == this : false;
1595 int View::GetHorizontalDragThreshold() {
1596 // TODO(jennyz): This value may need to be adjusted for different platforms
1597 // and for different display density.
1598 return kDefaultHorizontalDragThreshold;
1601 int View::GetVerticalDragThreshold() {
1602 // TODO(jennyz): This value may need to be adjusted for different platforms
1603 // and for different display density.
1604 return kDefaultVerticalDragThreshold;
1607 // Debugging -------------------------------------------------------------------
1609 #if !defined(NDEBUG)
1611 std::string View::PrintViewGraph(bool first) {
1612 return DoPrintViewGraph(first, this);
1615 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1616 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1617 const size_t kMaxPointerStringLength = 19;
1619 std::string result;
1621 if (first)
1622 result.append("digraph {\n");
1624 // Node characteristics.
1625 char p[kMaxPointerStringLength];
1627 const std::string class_name(GetClassName());
1628 size_t base_name_index = class_name.find_last_of('/');
1629 if (base_name_index == std::string::npos)
1630 base_name_index = 0;
1631 else
1632 base_name_index++;
1634 char bounds_buffer[512];
1636 // Information about current node.
1637 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1638 result.append(" N");
1639 result.append(p + 2);
1640 result.append(" [label=\"");
1642 result.append(class_name.substr(base_name_index).c_str());
1644 base::snprintf(bounds_buffer,
1645 arraysize(bounds_buffer),
1646 "\\n bounds: (%d, %d), (%dx%d)",
1647 bounds().x(),
1648 bounds().y(),
1649 bounds().width(),
1650 bounds().height());
1651 result.append(bounds_buffer);
1653 gfx::DecomposedTransform decomp;
1654 if (!GetTransform().IsIdentity() &&
1655 gfx::DecomposeTransform(&decomp, GetTransform())) {
1656 base::snprintf(bounds_buffer,
1657 arraysize(bounds_buffer),
1658 "\\n translation: (%f, %f)",
1659 decomp.translate[0],
1660 decomp.translate[1]);
1661 result.append(bounds_buffer);
1663 base::snprintf(bounds_buffer,
1664 arraysize(bounds_buffer),
1665 "\\n rotation: %3.2f",
1666 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1667 result.append(bounds_buffer);
1669 base::snprintf(bounds_buffer,
1670 arraysize(bounds_buffer),
1671 "\\n scale: (%2.4f, %2.4f)",
1672 decomp.scale[0],
1673 decomp.scale[1]);
1674 result.append(bounds_buffer);
1677 result.append("\"");
1678 if (!parent_)
1679 result.append(", shape=box");
1680 if (layer()) {
1681 if (layer()->has_external_content())
1682 result.append(", color=green");
1683 else
1684 result.append(", color=red");
1686 if (layer()->fills_bounds_opaquely())
1687 result.append(", style=filled");
1689 result.append("]\n");
1691 // Link to parent.
1692 if (parent_) {
1693 char pp[kMaxPointerStringLength];
1695 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1696 result.append(" N");
1697 result.append(pp + 2);
1698 result.append(" -> N");
1699 result.append(p + 2);
1700 result.append("\n");
1703 // Children.
1704 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1705 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1707 if (first)
1708 result.append("}\n");
1710 return result;
1712 #endif
1714 ////////////////////////////////////////////////////////////////////////////////
1715 // View, private:
1717 // DropInfo --------------------------------------------------------------------
1719 void View::DragInfo::Reset() {
1720 possible_drag = false;
1721 start_pt = gfx::Point();
1724 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1725 possible_drag = true;
1726 start_pt = p;
1729 // Painting --------------------------------------------------------------------
1731 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1732 // If we have a layer and the View's size did not change, we do not need to
1733 // schedule any paints since the layer will be redrawn at its new location
1734 // during the next Draw() cycle in the compositor.
1735 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1736 // Otherwise, if the size changes or we don't have a layer then we need to
1737 // use SchedulePaint to invalidate the area occupied by the View.
1738 SchedulePaint();
1739 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1740 // The compositor doesn't Draw() until something on screen changes, so
1741 // if our position changes but nothing is being animated on screen, then
1742 // tell the compositor to redraw the scene. We know layer() exists due to
1743 // the above if clause.
1744 layer()->ScheduleDraw();
1748 void View::PaintCommon(gfx::Canvas* canvas, const CullSet& cull_set) {
1749 if (!visible_)
1750 return;
1753 // If the View we are about to paint requested the canvas to be flipped, we
1754 // should change the transform appropriately.
1755 // The canvas mirroring is undone once the View is done painting so that we
1756 // don't pass the canvas with the mirrored transform to Views that didn't
1757 // request the canvas to be flipped.
1758 gfx::ScopedCanvas scoped(canvas);
1759 if (FlipCanvasOnPaintForRTLUI()) {
1760 canvas->Translate(gfx::Vector2d(width(), 0));
1761 canvas->Scale(-1, 1);
1764 OnPaint(canvas);
1767 PaintChildren(canvas, cull_set);
1770 // Tree operations -------------------------------------------------------------
1772 void View::DoRemoveChildView(View* view,
1773 bool update_focus_cycle,
1774 bool update_tool_tip,
1775 bool delete_removed_view,
1776 View* new_parent) {
1777 DCHECK(view);
1779 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1780 scoped_ptr<View> view_to_be_deleted;
1781 if (i != children_.end()) {
1782 if (update_focus_cycle) {
1783 // Let's remove the view from the focus traversal.
1784 View* next_focusable = view->next_focusable_view_;
1785 View* prev_focusable = view->previous_focusable_view_;
1786 if (prev_focusable)
1787 prev_focusable->next_focusable_view_ = next_focusable;
1788 if (next_focusable)
1789 next_focusable->previous_focusable_view_ = prev_focusable;
1792 if (GetWidget()) {
1793 UnregisterChildrenForVisibleBoundsNotification(view);
1794 if (view->visible())
1795 view->SchedulePaint();
1796 GetWidget()->NotifyWillRemoveView(view);
1799 // Remove the bounds of this child and any of its descendants from our
1800 // paint root bounds tree.
1801 BoundsTree* bounds_tree = GetBoundsTreeFromPaintRoot();
1802 if (bounds_tree)
1803 view->RemoveRootBounds(bounds_tree);
1805 view->PropagateRemoveNotifications(this, new_parent);
1806 view->parent_ = NULL;
1807 view->UpdateLayerVisibility();
1809 if (delete_removed_view && !view->owned_by_client_)
1810 view_to_be_deleted.reset(view);
1812 children_.erase(i);
1815 if (update_tool_tip)
1816 UpdateTooltip();
1818 if (layout_manager_.get())
1819 layout_manager_->ViewRemoved(this, view);
1822 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1823 for (int i = 0, count = child_count(); i < count; ++i)
1824 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1826 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1827 for (View* v = this; v; v = v->parent_)
1828 v->ViewHierarchyChangedImpl(true, details);
1831 void View::PropagateAddNotifications(
1832 const ViewHierarchyChangedDetails& details) {
1833 for (int i = 0, count = child_count(); i < count; ++i)
1834 child_at(i)->PropagateAddNotifications(details);
1835 ViewHierarchyChangedImpl(true, details);
1838 void View::PropagateNativeViewHierarchyChanged() {
1839 for (int i = 0, count = child_count(); i < count; ++i)
1840 child_at(i)->PropagateNativeViewHierarchyChanged();
1841 NativeViewHierarchyChanged();
1844 void View::ViewHierarchyChangedImpl(
1845 bool register_accelerators,
1846 const ViewHierarchyChangedDetails& details) {
1847 if (register_accelerators) {
1848 if (details.is_add) {
1849 // If you get this registration, you are part of a subtree that has been
1850 // added to the view hierarchy.
1851 if (GetFocusManager())
1852 RegisterPendingAccelerators();
1853 } else {
1854 if (details.child == this)
1855 UnregisterAccelerators(true);
1859 if (details.is_add && layer() && !layer()->parent()) {
1860 UpdateParentLayer();
1861 Widget* widget = GetWidget();
1862 if (widget)
1863 widget->UpdateRootLayers();
1864 } else if (!details.is_add && details.child == this) {
1865 // Make sure the layers belonging to the subtree rooted at |child| get
1866 // removed from layers that do not belong in the same subtree.
1867 OrphanLayers();
1868 Widget* widget = GetWidget();
1869 if (widget)
1870 widget->UpdateRootLayers();
1873 ViewHierarchyChanged(details);
1874 details.parent->needs_layout_ = true;
1877 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1878 for (int i = 0, count = child_count(); i < count; ++i)
1879 child_at(i)->PropagateNativeThemeChanged(theme);
1880 OnNativeThemeChanged(theme);
1883 // Size and disposition --------------------------------------------------------
1885 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1886 for (int i = 0, count = child_count(); i < count; ++i)
1887 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1888 VisibilityChangedImpl(start, is_visible);
1891 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1892 VisibilityChanged(starting_from, is_visible);
1895 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1896 // Mark our bounds as dirty for the paint root, also see if we need to
1897 // recompute our children's bounds due to origin change.
1898 bool origin_changed =
1899 previous_bounds.OffsetFromOrigin() != bounds_.OffsetFromOrigin();
1900 SetRootBoundsDirty(origin_changed);
1902 if (visible_) {
1903 // Paint the new bounds.
1904 SchedulePaintBoundsChanged(
1905 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1906 SCHEDULE_PAINT_SIZE_CHANGED);
1909 if (layer()) {
1910 if (parent_) {
1911 SetLayerBounds(GetLocalBounds() +
1912 gfx::Vector2d(GetMirroredX(), y()) +
1913 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1914 } else {
1915 SetLayerBounds(bounds_);
1917 } else {
1918 // If our bounds have changed, then any descendant layer bounds may have
1919 // changed. Update them accordingly.
1920 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1923 OnBoundsChanged(previous_bounds);
1925 if (previous_bounds.size() != size()) {
1926 needs_layout_ = false;
1927 Layout();
1930 if (GetNeedsNotificationWhenVisibleBoundsChange())
1931 OnVisibleBoundsChanged();
1933 // Notify interested Views that visible bounds within the root view may have
1934 // changed.
1935 if (descendants_to_notify_.get()) {
1936 for (Views::iterator i(descendants_to_notify_->begin());
1937 i != descendants_to_notify_->end(); ++i) {
1938 (*i)->OnVisibleBoundsChanged();
1943 // static
1944 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1945 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1946 view->RegisterForVisibleBoundsNotification();
1947 for (int i = 0; i < view->child_count(); ++i)
1948 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1951 // static
1952 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1953 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1954 view->UnregisterForVisibleBoundsNotification();
1955 for (int i = 0; i < view->child_count(); ++i)
1956 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1959 void View::RegisterForVisibleBoundsNotification() {
1960 if (registered_for_visible_bounds_notification_)
1961 return;
1963 registered_for_visible_bounds_notification_ = true;
1964 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1965 ancestor->AddDescendantToNotify(this);
1968 void View::UnregisterForVisibleBoundsNotification() {
1969 if (!registered_for_visible_bounds_notification_)
1970 return;
1972 registered_for_visible_bounds_notification_ = false;
1973 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1974 ancestor->RemoveDescendantToNotify(this);
1977 void View::AddDescendantToNotify(View* view) {
1978 DCHECK(view);
1979 if (!descendants_to_notify_.get())
1980 descendants_to_notify_.reset(new Views);
1981 descendants_to_notify_->push_back(view);
1984 void View::RemoveDescendantToNotify(View* view) {
1985 DCHECK(view && descendants_to_notify_.get());
1986 Views::iterator i(std::find(
1987 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1988 DCHECK(i != descendants_to_notify_->end());
1989 descendants_to_notify_->erase(i);
1990 if (descendants_to_notify_->empty())
1991 descendants_to_notify_.reset();
1994 void View::SetLayerBounds(const gfx::Rect& bounds) {
1995 layer()->SetBounds(bounds);
1996 SnapLayerToPixelBoundary();
1999 void View::SetRootBoundsDirty(bool origin_changed) {
2000 root_bounds_dirty_ = true;
2002 if (origin_changed) {
2003 // Inform our children that their root bounds are dirty, as their relative
2004 // coordinates in paint root space have changed since ours have changed.
2005 for (Views::const_iterator i(children_.begin()); i != children_.end();
2006 ++i) {
2007 if (!(*i)->IsPaintRoot())
2008 (*i)->SetRootBoundsDirty(origin_changed);
2013 void View::UpdateRootBounds(BoundsTree* tree, const gfx::Vector2d& offset) {
2014 // No need to recompute bounds if we haven't flagged ours as dirty.
2015 TRACE_EVENT1("views", "View::UpdateRootBounds", "class", GetClassName());
2017 // Add our own offset to the provided offset, for our own bounds update and
2018 // for propagation to our children if needed.
2019 gfx::Vector2d view_offset = offset + GetMirroredBounds().OffsetFromOrigin();
2021 // If our bounds have changed we must re-insert our new bounds to the tree.
2022 if (root_bounds_dirty_) {
2023 root_bounds_dirty_ = false;
2024 gfx::Rect bounds(
2025 view_offset.x(), view_offset.y(), bounds_.width(), bounds_.height());
2026 tree->Insert(bounds, reinterpret_cast<intptr_t>(this));
2029 // Update our children's bounds if needed.
2030 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
2031 // We don't descend in to layer views for bounds recomputation, as they
2032 // manage their own RTree as paint roots.
2033 if (!(*i)->IsPaintRoot())
2034 (*i)->UpdateRootBounds(tree, view_offset);
2038 void View::RemoveRootBounds(BoundsTree* tree) {
2039 tree->Remove(reinterpret_cast<intptr_t>(this));
2041 root_bounds_dirty_ = true;
2043 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
2044 if (!(*i)->IsPaintRoot())
2045 (*i)->RemoveRootBounds(tree);
2049 View::BoundsTree* View::GetBoundsTreeFromPaintRoot() {
2050 BoundsTree* bounds_tree = bounds_tree_.get();
2051 View* paint_root = this;
2052 while (!bounds_tree && !paint_root->IsPaintRoot()) {
2053 // Assumption is that if IsPaintRoot() is false then parent_ is valid.
2054 DCHECK(paint_root);
2055 paint_root = paint_root->parent_;
2056 bounds_tree = paint_root->bounds_tree_.get();
2059 return bounds_tree;
2062 // Transformations -------------------------------------------------------------
2064 bool View::GetTransformRelativeTo(const View* ancestor,
2065 gfx::Transform* transform) const {
2066 const View* p = this;
2068 while (p && p != ancestor) {
2069 transform->ConcatTransform(p->GetTransform());
2070 gfx::Transform translation;
2071 translation.Translate(static_cast<float>(p->GetMirroredX()),
2072 static_cast<float>(p->y()));
2073 transform->ConcatTransform(translation);
2075 p = p->parent_;
2078 return p == ancestor;
2081 // Coordinate conversion -------------------------------------------------------
2083 bool View::ConvertPointForAncestor(const View* ancestor,
2084 gfx::Point* point) const {
2085 gfx::Transform trans;
2086 // TODO(sad): Have some way of caching the transformation results.
2087 bool result = GetTransformRelativeTo(ancestor, &trans);
2088 gfx::Point3F p(*point);
2089 trans.TransformPoint(&p);
2090 *point = gfx::ToFlooredPoint(p.AsPointF());
2091 return result;
2094 bool View::ConvertPointFromAncestor(const View* ancestor,
2095 gfx::Point* point) const {
2096 gfx::Transform trans;
2097 bool result = GetTransformRelativeTo(ancestor, &trans);
2098 gfx::Point3F p(*point);
2099 trans.TransformPointReverse(&p);
2100 *point = gfx::ToFlooredPoint(p.AsPointF());
2101 return result;
2104 bool View::ConvertRectForAncestor(const View* ancestor,
2105 gfx::RectF* rect) const {
2106 gfx::Transform trans;
2107 // TODO(sad): Have some way of caching the transformation results.
2108 bool result = GetTransformRelativeTo(ancestor, &trans);
2109 trans.TransformRect(rect);
2110 return result;
2113 bool View::ConvertRectFromAncestor(const View* ancestor,
2114 gfx::RectF* rect) const {
2115 gfx::Transform trans;
2116 bool result = GetTransformRelativeTo(ancestor, &trans);
2117 trans.TransformRectReverse(rect);
2118 return result;
2121 // Accelerated painting --------------------------------------------------------
2123 void View::CreateLayer() {
2124 // A new layer is being created for the view. So all the layers of the
2125 // sub-tree can inherit the visibility of the corresponding view.
2126 for (int i = 0, count = child_count(); i < count; ++i)
2127 child_at(i)->UpdateChildLayerVisibility(true);
2129 SetLayer(new ui::Layer());
2130 layer()->set_delegate(this);
2131 #if !defined(NDEBUG)
2132 layer()->set_name(GetClassName());
2133 #endif
2135 UpdateParentLayers();
2136 UpdateLayerVisibility();
2138 // The new layer needs to be ordered in the layer tree according
2139 // to the view tree. Children of this layer were added in order
2140 // in UpdateParentLayers().
2141 if (parent())
2142 parent()->ReorderLayers();
2144 Widget* widget = GetWidget();
2145 if (widget)
2146 widget->UpdateRootLayers();
2149 void View::UpdateParentLayers() {
2150 // Attach all top-level un-parented layers.
2151 if (layer() && !layer()->parent()) {
2152 UpdateParentLayer();
2153 } else {
2154 for (int i = 0, count = child_count(); i < count; ++i)
2155 child_at(i)->UpdateParentLayers();
2159 void View::OrphanLayers() {
2160 if (layer()) {
2161 if (layer()->parent())
2162 layer()->parent()->Remove(layer());
2164 // The layer belonging to this View has already been orphaned. It is not
2165 // necessary to orphan the child layers.
2166 return;
2168 for (int i = 0, count = child_count(); i < count; ++i)
2169 child_at(i)->OrphanLayers();
2172 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2173 layer()->SetBounds(GetLocalBounds() + offset);
2174 DCHECK_NE(layer(), parent_layer);
2175 if (parent_layer)
2176 parent_layer->Add(layer());
2177 layer()->SchedulePaint(GetLocalBounds());
2178 MoveLayerToParent(layer(), gfx::Point());
2181 void View::DestroyLayer() {
2182 ui::Layer* new_parent = layer()->parent();
2183 std::vector<ui::Layer*> children = layer()->children();
2184 for (size_t i = 0; i < children.size(); ++i) {
2185 layer()->Remove(children[i]);
2186 if (new_parent)
2187 new_parent->Add(children[i]);
2190 LayerOwner::DestroyLayer();
2192 if (new_parent)
2193 ReorderLayers();
2195 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2197 SchedulePaint();
2199 Widget* widget = GetWidget();
2200 if (widget)
2201 widget->UpdateRootLayers();
2204 // Input -----------------------------------------------------------------------
2206 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2207 int drag_operations =
2208 (enabled_ && event.IsOnlyLeftMouseButton() &&
2209 HitTestPoint(event.location())) ?
2210 GetDragOperations(event.location()) : 0;
2211 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2212 context_menu_controller_ : 0;
2213 View::DragInfo* drag_info = GetDragInfo();
2215 // TODO(sky): for debugging 360238.
2216 int storage_id = 0;
2217 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2218 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2219 ViewStorage* view_storage = ViewStorage::GetInstance();
2220 storage_id = view_storage->CreateStorageID();
2221 view_storage->StoreView(storage_id, this);
2224 const bool enabled = enabled_;
2225 const bool result = OnMousePressed(event);
2227 if (!enabled)
2228 return result;
2230 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2231 kContextMenuOnMousePress) {
2232 // Assume that if there is a context menu controller we won't be deleted
2233 // from mouse pressed.
2234 gfx::Point location(event.location());
2235 if (HitTestPoint(location)) {
2236 if (storage_id != 0)
2237 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2238 ConvertPointToScreen(this, &location);
2239 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2240 return true;
2244 // WARNING: we may have been deleted, don't use any View variables.
2245 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2246 drag_info->PossibleDrag(event.location());
2247 return true;
2249 return !!context_menu_controller || result;
2252 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2253 // Copy the field, that way if we're deleted after drag and drop no harm is
2254 // done.
2255 ContextMenuController* context_menu_controller = context_menu_controller_;
2256 const bool possible_drag = GetDragInfo()->possible_drag;
2257 if (possible_drag &&
2258 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2259 (!drag_controller_ ||
2260 drag_controller_->CanStartDragForView(
2261 this, GetDragInfo()->start_pt, event.location()))) {
2262 DoDrag(event, GetDragInfo()->start_pt,
2263 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2264 } else {
2265 if (OnMouseDragged(event))
2266 return true;
2267 // Fall through to return value based on context menu controller.
2269 // WARNING: we may have been deleted.
2270 return (context_menu_controller != NULL) || possible_drag;
2273 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2274 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2275 event.IsOnlyRightMouseButton()) {
2276 // Assume that if there is a context menu controller we won't be deleted
2277 // from mouse released.
2278 gfx::Point location(event.location());
2279 OnMouseReleased(event);
2280 if (HitTestPoint(location)) {
2281 ConvertPointToScreen(this, &location);
2282 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2284 } else {
2285 OnMouseReleased(event);
2287 // WARNING: we may have been deleted.
2290 // Accelerators ----------------------------------------------------------------
2292 void View::RegisterPendingAccelerators() {
2293 if (!accelerators_.get() ||
2294 registered_accelerator_count_ == accelerators_->size()) {
2295 // No accelerators are waiting for registration.
2296 return;
2299 if (!GetWidget()) {
2300 // The view is not yet attached to a widget, defer registration until then.
2301 return;
2304 accelerator_focus_manager_ = GetFocusManager();
2305 if (!accelerator_focus_manager_) {
2306 // Some crash reports seem to show that we may get cases where we have no
2307 // focus manager (see bug #1291225). This should never be the case, just
2308 // making sure we don't crash.
2309 NOTREACHED();
2310 return;
2312 for (std::vector<ui::Accelerator>::const_iterator i(
2313 accelerators_->begin() + registered_accelerator_count_);
2314 i != accelerators_->end(); ++i) {
2315 accelerator_focus_manager_->RegisterAccelerator(
2316 *i, ui::AcceleratorManager::kNormalPriority, this);
2318 registered_accelerator_count_ = accelerators_->size();
2321 void View::UnregisterAccelerators(bool leave_data_intact) {
2322 if (!accelerators_.get())
2323 return;
2325 if (GetWidget()) {
2326 if (accelerator_focus_manager_) {
2327 accelerator_focus_manager_->UnregisterAccelerators(this);
2328 accelerator_focus_manager_ = NULL;
2330 if (!leave_data_intact) {
2331 accelerators_->clear();
2332 accelerators_.reset();
2334 registered_accelerator_count_ = 0;
2338 // Focus -----------------------------------------------------------------------
2340 void View::InitFocusSiblings(View* v, int index) {
2341 int count = child_count();
2343 if (count == 0) {
2344 v->next_focusable_view_ = NULL;
2345 v->previous_focusable_view_ = NULL;
2346 } else {
2347 if (index == count) {
2348 // We are inserting at the end, but the end of the child list may not be
2349 // the last focusable element. Let's try to find an element with no next
2350 // focusable element to link to.
2351 View* last_focusable_view = NULL;
2352 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2353 if (!(*i)->next_focusable_view_) {
2354 last_focusable_view = *i;
2355 break;
2358 if (last_focusable_view == NULL) {
2359 // Hum... there is a cycle in the focus list. Let's just insert ourself
2360 // after the last child.
2361 View* prev = children_[index - 1];
2362 v->previous_focusable_view_ = prev;
2363 v->next_focusable_view_ = prev->next_focusable_view_;
2364 prev->next_focusable_view_->previous_focusable_view_ = v;
2365 prev->next_focusable_view_ = v;
2366 } else {
2367 last_focusable_view->next_focusable_view_ = v;
2368 v->next_focusable_view_ = NULL;
2369 v->previous_focusable_view_ = last_focusable_view;
2371 } else {
2372 View* prev = children_[index]->GetPreviousFocusableView();
2373 v->previous_focusable_view_ = prev;
2374 v->next_focusable_view_ = children_[index];
2375 if (prev)
2376 prev->next_focusable_view_ = v;
2377 children_[index]->previous_focusable_view_ = v;
2382 void View::AdvanceFocusIfNecessary() {
2383 // Focus should only be advanced if this is the focused view and has become
2384 // unfocusable. If the view is still focusable or is not focused, we can
2385 // return early avoiding furthur unnecessary checks. Focusability check is
2386 // performed first as it tends to be faster.
2387 if (IsAccessibilityFocusable() || !HasFocus())
2388 return;
2390 FocusManager* focus_manager = GetFocusManager();
2391 if (focus_manager)
2392 focus_manager->AdvanceFocusIfNecessary();
2395 // System events ---------------------------------------------------------------
2397 void View::PropagateThemeChanged() {
2398 for (int i = child_count() - 1; i >= 0; --i)
2399 child_at(i)->PropagateThemeChanged();
2400 OnThemeChanged();
2403 void View::PropagateLocaleChanged() {
2404 for (int i = child_count() - 1; i >= 0; --i)
2405 child_at(i)->PropagateLocaleChanged();
2406 OnLocaleChanged();
2409 // Tooltips --------------------------------------------------------------------
2411 void View::UpdateTooltip() {
2412 Widget* widget = GetWidget();
2413 // TODO(beng): The TooltipManager NULL check can be removed when we
2414 // consolidate Init() methods and make views_unittests Init() all
2415 // Widgets that it uses.
2416 if (widget && widget->GetTooltipManager())
2417 widget->GetTooltipManager()->UpdateTooltip();
2420 // Drag and drop ---------------------------------------------------------------
2422 bool View::DoDrag(const ui::LocatedEvent& event,
2423 const gfx::Point& press_pt,
2424 ui::DragDropTypes::DragEventSource source) {
2425 int drag_operations = GetDragOperations(press_pt);
2426 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2427 return false;
2429 Widget* widget = GetWidget();
2430 // We should only start a drag from an event, implying we have a widget.
2431 DCHECK(widget);
2433 // Don't attempt to start a drag while in the process of dragging. This is
2434 // especially important on X where we can get multiple mouse move events when
2435 // we start the drag.
2436 if (widget->dragged_view())
2437 return false;
2439 OSExchangeData data;
2440 WriteDragData(press_pt, &data);
2442 // Message the RootView to do the drag and drop. That way if we're removed
2443 // the RootView can detect it and avoid calling us back.
2444 gfx::Point widget_location(event.location());
2445 ConvertPointToWidget(this, &widget_location);
2446 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2447 // WARNING: we may have been deleted.
2448 return true;
2451 } // namespace views