[chromedriver] Disable ChromeDriverTest.testShouldHandleNewWindowLoadingProperly.
[chromium-blink-merge.git] / ui / views / view.cc
blob3c2aed7dbab63c64d06b4554d32574d33b66d92f
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/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/trace_event/trace_event.h"
18 #include "third_party/skia/include/core/SkRect.h"
19 #include "ui/accessibility/ax_enums.h"
20 #include "ui/base/cursor/cursor.h"
21 #include "ui/base/dragdrop/drag_drop_types.h"
22 #include "ui/base/ime/input_method.h"
23 #include "ui/compositor/clip_transform_recorder.h"
24 #include "ui/compositor/compositor.h"
25 #include "ui/compositor/dip_util.h"
26 #include "ui/compositor/layer.h"
27 #include "ui/compositor/layer_animator.h"
28 #include "ui/compositor/paint_context.h"
29 #include "ui/compositor/paint_recorder.h"
30 #include "ui/events/event_target_iterator.h"
31 #include "ui/gfx/canvas.h"
32 #include "ui/gfx/geometry/point3_f.h"
33 #include "ui/gfx/geometry/point_conversions.h"
34 #include "ui/gfx/interpolated_transform.h"
35 #include "ui/gfx/path.h"
36 #include "ui/gfx/scoped_canvas.h"
37 #include "ui/gfx/screen.h"
38 #include "ui/gfx/skia_util.h"
39 #include "ui/gfx/transform.h"
40 #include "ui/native_theme/native_theme.h"
41 #include "ui/views/accessibility/native_view_accessibility.h"
42 #include "ui/views/background.h"
43 #include "ui/views/border.h"
44 #include "ui/views/context_menu_controller.h"
45 #include "ui/views/drag_controller.h"
46 #include "ui/views/focus/view_storage.h"
47 #include "ui/views/layout/layout_manager.h"
48 #include "ui/views/views_delegate.h"
49 #include "ui/views/widget/native_widget_private.h"
50 #include "ui/views/widget/root_view.h"
51 #include "ui/views/widget/tooltip_manager.h"
52 #include "ui/views/widget/widget.h"
54 #if defined(OS_WIN)
55 #include "base/win/scoped_gdi_object.h"
56 #endif
58 namespace views {
60 namespace {
62 #if defined(OS_WIN)
63 const bool kContextMenuOnMousePress = false;
64 #else
65 const bool kContextMenuOnMousePress = true;
66 #endif
68 // Default horizontal drag threshold in pixels.
69 // Same as what gtk uses.
70 const int kDefaultHorizontalDragThreshold = 8;
72 // Default vertical drag threshold in pixels.
73 // Same as what gtk uses.
74 const int kDefaultVerticalDragThreshold = 8;
76 // Returns the top view in |view|'s hierarchy.
77 const View* GetHierarchyRoot(const View* view) {
78 const View* root = view;
79 while (root && root->parent())
80 root = root->parent();
81 return root;
84 } // namespace
86 // static
87 const char View::kViewClassName[] = "View";
89 ////////////////////////////////////////////////////////////////////////////////
90 // View, public:
92 // Creation and lifetime -------------------------------------------------------
94 View::View()
95 : owned_by_client_(false),
96 id_(0),
97 group_(-1),
98 parent_(NULL),
99 visible_(true),
100 enabled_(true),
101 notify_enter_exit_on_child_(false),
102 registered_for_visible_bounds_notification_(false),
103 clip_insets_(0, 0, 0, 0),
104 needs_layout_(true),
105 snap_layer_to_pixel_boundary_(false),
106 flip_canvas_on_paint_for_rtl_ui_(false),
107 paint_to_layer_(false),
108 accelerator_focus_manager_(NULL),
109 registered_accelerator_count_(0),
110 next_focusable_view_(NULL),
111 previous_focusable_view_(NULL),
112 focusable_(false),
113 accessibility_focusable_(false),
114 context_menu_controller_(NULL),
115 drag_controller_(NULL),
116 native_view_accessibility_(NULL) {
119 View::~View() {
120 if (parent_)
121 parent_->RemoveChildView(this);
123 ViewStorage::GetInstance()->ViewRemoved(this);
125 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
126 (*i)->parent_ = NULL;
127 if (!(*i)->owned_by_client_)
128 delete *i;
131 // Release ownership of the native accessibility object, but it's
132 // reference-counted on some platforms, so it may not be deleted right away.
133 if (native_view_accessibility_)
134 native_view_accessibility_->Destroy();
137 // Tree operations -------------------------------------------------------------
139 const Widget* View::GetWidget() const {
140 // The root view holds a reference to this view hierarchy's Widget.
141 return parent_ ? parent_->GetWidget() : NULL;
144 Widget* View::GetWidget() {
145 return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
148 void View::AddChildView(View* view) {
149 if (view->parent_ == this)
150 return;
151 AddChildViewAt(view, child_count());
154 void View::AddChildViewAt(View* view, int index) {
155 CHECK_NE(view, this) << "You cannot add a view as its own child";
156 DCHECK_GE(index, 0);
157 DCHECK_LE(index, child_count());
159 // If |view| has a parent, remove it from its parent.
160 View* parent = view->parent_;
161 ui::NativeTheme* old_theme = NULL;
162 if (parent) {
163 old_theme = view->GetNativeTheme();
164 if (parent == this) {
165 ReorderChildView(view, index);
166 return;
168 parent->DoRemoveChildView(view, true, true, false, this);
171 // Sets the prev/next focus views.
172 InitFocusSiblings(view, index);
174 // Let's insert the view.
175 view->parent_ = this;
176 children_.insert(children_.begin() + index, view);
178 views::Widget* widget = GetWidget();
179 if (widget) {
180 const ui::NativeTheme* new_theme = view->GetNativeTheme();
181 if (new_theme != old_theme)
182 view->PropagateNativeThemeChanged(new_theme);
185 ViewHierarchyChangedDetails details(true, this, view, parent);
187 for (View* v = this; v; v = v->parent_)
188 v->ViewHierarchyChangedImpl(false, details);
190 view->PropagateAddNotifications(details);
191 UpdateTooltip();
192 if (widget) {
193 RegisterChildrenForVisibleBoundsNotification(view);
194 if (view->visible())
195 view->SchedulePaint();
198 if (layout_manager_.get())
199 layout_manager_->ViewAdded(this, view);
201 ReorderLayers();
203 // Make sure the visibility of the child layers are correct.
204 // If any of the parent View is hidden, then the layers of the subtree
205 // rooted at |this| should be hidden. Otherwise, all the child layers should
206 // inherit the visibility of the owner View.
207 UpdateLayerVisibility();
210 void View::ReorderChildView(View* view, int index) {
211 DCHECK_EQ(view->parent_, this);
212 if (index < 0)
213 index = child_count() - 1;
214 else if (index >= child_count())
215 return;
216 if (children_[index] == view)
217 return;
219 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
220 DCHECK(i != children_.end());
221 children_.erase(i);
223 // Unlink the view first
224 View* next_focusable = view->next_focusable_view_;
225 View* prev_focusable = view->previous_focusable_view_;
226 if (prev_focusable)
227 prev_focusable->next_focusable_view_ = next_focusable;
228 if (next_focusable)
229 next_focusable->previous_focusable_view_ = prev_focusable;
231 // Add it in the specified index now.
232 InitFocusSiblings(view, index);
233 children_.insert(children_.begin() + index, view);
235 ReorderLayers();
238 void View::RemoveChildView(View* view) {
239 DoRemoveChildView(view, true, true, false, NULL);
242 void View::RemoveAllChildViews(bool delete_children) {
243 while (!children_.empty())
244 DoRemoveChildView(children_.front(), false, false, delete_children, NULL);
245 UpdateTooltip();
248 bool View::Contains(const View* view) const {
249 for (const View* v = view; v; v = v->parent_) {
250 if (v == this)
251 return true;
253 return false;
256 int View::GetIndexOf(const View* view) const {
257 Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
258 return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
261 // Size and disposition --------------------------------------------------------
263 void View::SetBounds(int x, int y, int width, int height) {
264 SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
267 void View::SetBoundsRect(const gfx::Rect& bounds) {
268 if (bounds == bounds_) {
269 if (needs_layout_) {
270 needs_layout_ = false;
271 Layout();
273 return;
276 if (visible_) {
277 // Paint where the view is currently.
278 SchedulePaintBoundsChanged(
279 bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
280 SCHEDULE_PAINT_SIZE_CHANGED);
283 gfx::Rect prev = bounds_;
284 bounds_ = bounds;
285 BoundsChanged(prev);
288 void View::SetSize(const gfx::Size& size) {
289 SetBounds(x(), y(), size.width(), size.height());
292 void View::SetPosition(const gfx::Point& position) {
293 SetBounds(position.x(), position.y(), width(), height());
296 void View::SetX(int x) {
297 SetBounds(x, y(), width(), height());
300 void View::SetY(int y) {
301 SetBounds(x(), y, width(), height());
304 gfx::Rect View::GetContentsBounds() const {
305 gfx::Rect contents_bounds(GetLocalBounds());
306 if (border_.get())
307 contents_bounds.Inset(border_->GetInsets());
308 return contents_bounds;
311 gfx::Rect View::GetLocalBounds() const {
312 return gfx::Rect(size());
315 gfx::Rect View::GetLayerBoundsInPixel() const {
316 return layer()->GetTargetBounds();
319 gfx::Insets View::GetInsets() const {
320 return border_.get() ? border_->GetInsets() : gfx::Insets();
323 gfx::Rect View::GetVisibleBounds() const {
324 if (!IsDrawn())
325 return gfx::Rect();
326 gfx::Rect vis_bounds(GetLocalBounds());
327 gfx::Rect ancestor_bounds;
328 const View* view = this;
329 gfx::Transform transform;
331 while (view != NULL && !vis_bounds.IsEmpty()) {
332 transform.ConcatTransform(view->GetTransform());
333 gfx::Transform translation;
334 translation.Translate(static_cast<float>(view->GetMirroredX()),
335 static_cast<float>(view->y()));
336 transform.ConcatTransform(translation);
338 vis_bounds = view->ConvertRectToParent(vis_bounds);
339 const View* ancestor = view->parent_;
340 if (ancestor != NULL) {
341 ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
342 vis_bounds.Intersect(ancestor_bounds);
343 } else if (!view->GetWidget()) {
344 // If the view has no Widget, we're not visible. Return an empty rect.
345 return gfx::Rect();
347 view = ancestor;
349 if (vis_bounds.IsEmpty())
350 return vis_bounds;
351 // Convert back to this views coordinate system.
352 gfx::RectF views_vis_bounds(vis_bounds);
353 transform.TransformRectReverse(&views_vis_bounds);
354 // Partially visible pixels should be considered visible.
355 return gfx::ToEnclosingRect(views_vis_bounds);
358 gfx::Rect View::GetBoundsInScreen() const {
359 gfx::Point origin;
360 View::ConvertPointToScreen(this, &origin);
361 return gfx::Rect(origin, size());
364 gfx::Size View::GetPreferredSize() const {
365 if (layout_manager_.get())
366 return layout_manager_->GetPreferredSize(this);
367 return gfx::Size();
370 int View::GetBaseline() const {
371 return -1;
374 void View::SizeToPreferredSize() {
375 gfx::Size prefsize = GetPreferredSize();
376 if ((prefsize.width() != width()) || (prefsize.height() != height()))
377 SetBounds(x(), y(), prefsize.width(), prefsize.height());
380 gfx::Size View::GetMinimumSize() const {
381 return GetPreferredSize();
384 gfx::Size View::GetMaximumSize() const {
385 return gfx::Size();
388 int View::GetHeightForWidth(int w) const {
389 if (layout_manager_.get())
390 return layout_manager_->GetPreferredHeightForWidth(this, w);
391 return GetPreferredSize().height();
394 void View::SetVisible(bool visible) {
395 if (visible != visible_) {
396 // If the View is currently visible, schedule paint to refresh parent.
397 // TODO(beng): not sure we should be doing this if we have a layer.
398 if (visible_)
399 SchedulePaint();
401 visible_ = visible;
402 AdvanceFocusIfNecessary();
404 // Notify the parent.
405 if (parent_)
406 parent_->ChildVisibilityChanged(this);
408 // This notifies all sub-views recursively.
409 PropagateVisibilityNotifications(this, visible_);
410 UpdateLayerVisibility();
412 // If we are newly visible, schedule paint.
413 if (visible_)
414 SchedulePaint();
418 bool View::IsDrawn() const {
419 return visible_ && parent_ ? parent_->IsDrawn() : false;
422 void View::SetEnabled(bool enabled) {
423 if (enabled != enabled_) {
424 enabled_ = enabled;
425 AdvanceFocusIfNecessary();
426 OnEnabledChanged();
430 void View::OnEnabledChanged() {
431 SchedulePaint();
434 // Transformations -------------------------------------------------------------
436 gfx::Transform View::GetTransform() const {
437 return layer() ? layer()->transform() : gfx::Transform();
440 void View::SetTransform(const gfx::Transform& transform) {
441 if (transform.IsIdentity()) {
442 if (layer()) {
443 layer()->SetTransform(transform);
444 if (!paint_to_layer_)
445 DestroyLayer();
446 } else {
447 // Nothing.
449 } else {
450 if (!layer())
451 CreateLayer();
452 layer()->SetTransform(transform);
453 layer()->ScheduleDraw();
457 void View::SetPaintToLayer(bool paint_to_layer) {
458 if (paint_to_layer_ == paint_to_layer)
459 return;
461 paint_to_layer_ = paint_to_layer;
462 if (paint_to_layer_ && !layer()) {
463 CreateLayer();
464 } else if (!paint_to_layer_ && layer()) {
465 DestroyLayer();
469 // RTL positioning -------------------------------------------------------------
471 gfx::Rect View::GetMirroredBounds() const {
472 gfx::Rect bounds(bounds_);
473 bounds.set_x(GetMirroredX());
474 return bounds;
477 gfx::Point View::GetMirroredPosition() const {
478 return gfx::Point(GetMirroredX(), y());
481 int View::GetMirroredX() const {
482 return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
485 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
486 return base::i18n::IsRTL() ?
487 (width() - bounds.x() - bounds.width()) : bounds.x();
490 int View::GetMirroredXInView(int x) const {
491 return base::i18n::IsRTL() ? width() - x : x;
494 int View::GetMirroredXWithWidthInView(int x, int w) const {
495 return base::i18n::IsRTL() ? width() - x - w : x;
498 // Layout ----------------------------------------------------------------------
500 void View::Layout() {
501 needs_layout_ = false;
503 // If we have a layout manager, let it handle the layout for us.
504 if (layout_manager_.get())
505 layout_manager_->Layout(this);
507 // Make sure to propagate the Layout() call to any children that haven't
508 // received it yet through the layout manager and need to be laid out. This
509 // is needed for the case when the child requires a layout but its bounds
510 // weren't changed by the layout manager. If there is no layout manager, we
511 // just propagate the Layout() call down the hierarchy, so whoever receives
512 // the call can take appropriate action.
513 for (int i = 0, count = child_count(); i < count; ++i) {
514 View* child = child_at(i);
515 if (child->needs_layout_ || !layout_manager_.get()) {
516 TRACE_EVENT1("views", "View::Layout", "class", child->GetClassName());
517 child->needs_layout_ = false;
518 child->Layout();
523 void View::InvalidateLayout() {
524 // Always invalidate up. This is needed to handle the case of us already being
525 // valid, but not our parent.
526 needs_layout_ = true;
527 if (parent_)
528 parent_->InvalidateLayout();
531 LayoutManager* View::GetLayoutManager() const {
532 return layout_manager_.get();
535 void View::SetLayoutManager(LayoutManager* layout_manager) {
536 if (layout_manager_.get())
537 layout_manager_->Uninstalled(this);
539 layout_manager_.reset(layout_manager);
540 if (layout_manager_.get())
541 layout_manager_->Installed(this);
544 void View::SnapLayerToPixelBoundary() {
545 if (!layer())
546 return;
548 if (snap_layer_to_pixel_boundary_ && layer()->parent() &&
549 layer()->GetCompositor()) {
550 ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer());
551 } else {
552 // Reset the offset.
553 layer()->SetSubpixelPositionOffset(gfx::Vector2dF());
557 // Attributes ------------------------------------------------------------------
559 const char* View::GetClassName() const {
560 return kViewClassName;
563 const View* View::GetAncestorWithClassName(const std::string& name) const {
564 for (const View* view = this; view; view = view->parent_) {
565 if (!strcmp(view->GetClassName(), name.c_str()))
566 return view;
568 return NULL;
571 View* View::GetAncestorWithClassName(const std::string& name) {
572 return const_cast<View*>(const_cast<const View*>(this)->
573 GetAncestorWithClassName(name));
576 const View* View::GetViewByID(int id) const {
577 if (id == id_)
578 return const_cast<View*>(this);
580 for (int i = 0, count = child_count(); i < count; ++i) {
581 const View* view = child_at(i)->GetViewByID(id);
582 if (view)
583 return view;
585 return NULL;
588 View* View::GetViewByID(int id) {
589 return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
592 void View::SetGroup(int gid) {
593 // Don't change the group id once it's set.
594 DCHECK(group_ == -1 || group_ == gid);
595 group_ = gid;
598 int View::GetGroup() const {
599 return group_;
602 bool View::IsGroupFocusTraversable() const {
603 return true;
606 void View::GetViewsInGroup(int group, Views* views) {
607 if (group_ == group)
608 views->push_back(this);
610 for (int i = 0, count = child_count(); i < count; ++i)
611 child_at(i)->GetViewsInGroup(group, views);
614 View* View::GetSelectedViewForGroup(int group) {
615 Views views;
616 GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
617 return views.empty() ? NULL : views[0];
620 // Coordinate conversion -------------------------------------------------------
622 // static
623 void View::ConvertPointToTarget(const View* source,
624 const View* target,
625 gfx::Point* point) {
626 DCHECK(source);
627 DCHECK(target);
628 if (source == target)
629 return;
631 const View* root = GetHierarchyRoot(target);
632 CHECK_EQ(GetHierarchyRoot(source), root);
634 if (source != root)
635 source->ConvertPointForAncestor(root, point);
637 if (target != root)
638 target->ConvertPointFromAncestor(root, point);
641 // static
642 void View::ConvertRectToTarget(const View* source,
643 const View* target,
644 gfx::RectF* rect) {
645 DCHECK(source);
646 DCHECK(target);
647 if (source == target)
648 return;
650 const View* root = GetHierarchyRoot(target);
651 CHECK_EQ(GetHierarchyRoot(source), root);
653 if (source != root)
654 source->ConvertRectForAncestor(root, rect);
656 if (target != root)
657 target->ConvertRectFromAncestor(root, rect);
660 // static
661 void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
662 DCHECK(src);
663 DCHECK(p);
665 src->ConvertPointForAncestor(NULL, p);
668 // static
669 void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
670 DCHECK(dest);
671 DCHECK(p);
673 dest->ConvertPointFromAncestor(NULL, p);
676 // static
677 void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
678 DCHECK(src);
679 DCHECK(p);
681 // If the view is not connected to a tree, there's nothing we can do.
682 const Widget* widget = src->GetWidget();
683 if (widget) {
684 ConvertPointToWidget(src, p);
685 *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
689 // static
690 void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
691 DCHECK(dst);
692 DCHECK(p);
694 const views::Widget* widget = dst->GetWidget();
695 if (!widget)
696 return;
697 *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
698 views::View::ConvertPointFromWidget(dst, p);
701 gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
702 gfx::RectF x_rect = rect;
703 GetTransform().TransformRect(&x_rect);
704 x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
705 // Pixels we partially occupy in the parent should be included.
706 return gfx::ToEnclosingRect(x_rect);
709 gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
710 gfx::Rect x_rect = rect;
711 for (const View* v = this; v; v = v->parent_)
712 x_rect = v->ConvertRectToParent(x_rect);
713 return x_rect;
716 // Painting --------------------------------------------------------------------
718 void View::SchedulePaint() {
719 SchedulePaintInRect(GetLocalBounds());
722 void View::SchedulePaintInRect(const gfx::Rect& rect) {
723 if (!visible_)
724 return;
726 if (layer()) {
727 layer()->SchedulePaint(rect);
728 } else if (parent_) {
729 // Translate the requested paint rect to the parent's coordinate system
730 // then pass this notification up to the parent.
731 parent_->SchedulePaintInRect(ConvertRectToParent(rect));
735 void View::Paint(const ui::PaintContext& parent_context) {
736 if (!visible_)
737 return;
738 if (size().IsEmpty())
739 return;
741 gfx::Vector2d offset_to_parent;
742 if (!layer()) {
743 // If the View has a layer() then it is a paint root. Otherwise, we need to
744 // add the offset from the parent into the total offset from the paint root.
745 DCHECK_IMPLIES(!parent(), bounds().origin() == gfx::Point());
746 offset_to_parent = GetMirroredPosition().OffsetFromOrigin();
748 ui::PaintContext context(parent_context, offset_to_parent);
750 bool is_invalidated = true;
751 if (context.CanCheckInvalid()) {
752 #if DCHECK_IS_ON()
753 gfx::Vector2d offset;
754 context.Visited(this);
755 View* view = this;
756 while (view->parent() && !view->layer()) {
757 DCHECK(view->GetTransform().IsIdentity());
758 offset += view->GetMirroredPosition().OffsetFromOrigin();
759 view = view->parent();
761 // The offset in the PaintContext should be the offset up to the paint root,
762 // which we compute and verify here.
763 DCHECK_EQ(context.PaintOffset().x(), offset.x());
764 DCHECK_EQ(context.PaintOffset().y(), offset.y());
765 // The above loop will stop when |view| is the paint root, which should be
766 // the root of the current paint walk, as verified by storing the root in
767 // the PaintContext.
768 DCHECK_EQ(context.RootVisited(), view);
769 #endif
771 // If the View wasn't invalidated, don't waste time painting it, the output
772 // would be culled.
773 is_invalidated = context.IsRectInvalid(GetLocalBounds());
776 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
778 // If the view is backed by a layer, it should paint with itself as the origin
779 // rather than relative to its parent.
780 ui::ClipTransformRecorder clip_transform_recorder(context);
781 if (!layer()) {
782 // Set the clip rect to the bounds of this View. Note that the X (or left)
783 // position we pass to ClipRect takes into consideration whether or not the
784 // View uses a right-to-left layout so that we paint the View in its
785 // mirrored position if need be.
786 gfx::Rect clip_rect_in_parent = bounds();
787 clip_rect_in_parent.Inset(clip_insets_);
788 if (parent_)
789 clip_rect_in_parent.set_x(
790 parent_->GetMirroredXForRect(clip_rect_in_parent));
791 clip_transform_recorder.ClipRect(clip_rect_in_parent);
793 // Translate the graphics such that 0,0 corresponds to where
794 // this View is located relative to its parent.
795 gfx::Transform transform_from_parent;
796 gfx::Vector2d offset_from_parent = GetMirroredPosition().OffsetFromOrigin();
797 transform_from_parent.Translate(offset_from_parent.x(),
798 offset_from_parent.y());
799 transform_from_parent.PreconcatTransform(GetTransform());
800 clip_transform_recorder.Transform(transform_from_parent);
803 if (is_invalidated || !paint_cache_.UseCache(context)) {
804 ui::PaintRecorder recorder(context, size(), &paint_cache_);
805 gfx::Canvas* canvas = recorder.canvas();
807 // If the View we are about to paint requested the canvas to be flipped, we
808 // should change the transform appropriately.
809 // The canvas mirroring is undone once the View is done painting so that we
810 // don't pass the canvas with the mirrored transform to Views that didn't
811 // request the canvas to be flipped.
812 if (FlipCanvasOnPaintForRTLUI()) {
813 canvas->Translate(gfx::Vector2d(width(), 0));
814 canvas->Scale(-1, 1);
817 // Delegate painting the contents of the View to the virtual OnPaint method.
818 OnPaint(canvas);
821 // View::Paint() recursion over the subtree.
822 PaintChildren(context);
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 const ui::InputMethod* View::GetInputMethod() const {
1015 Widget* widget = const_cast<Widget*>(GetWidget());
1016 return widget ? const_cast<const ui::InputMethod*>(widget->GetInputMethod())
1017 : nullptr;
1020 scoped_ptr<ViewTargeter>
1021 View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) {
1022 scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass();
1023 targeter_ = targeter.Pass();
1024 return old_targeter.Pass();
1027 ViewTargeter* View::GetEffectiveViewTargeter() const {
1028 DCHECK(GetWidget());
1029 ViewTargeter* view_targeter = targeter();
1030 if (!view_targeter)
1031 view_targeter = GetWidget()->GetRootView()->targeter();
1032 CHECK(view_targeter);
1033 return view_targeter;
1036 bool View::CanAcceptEvent(const ui::Event& event) {
1037 return IsDrawn();
1040 ui::EventTarget* View::GetParentTarget() {
1041 return parent_;
1044 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1045 return make_scoped_ptr(new ui::EventTargetIteratorImpl<View>(children_));
1048 ui::EventTargeter* View::GetEventTargeter() {
1049 return targeter_.get();
1052 void View::ConvertEventToTarget(ui::EventTarget* target,
1053 ui::LocatedEvent* event) {
1054 event->ConvertLocationToTarget(this, static_cast<View*>(target));
1057 // Accelerators ----------------------------------------------------------------
1059 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1060 if (!accelerators_.get())
1061 accelerators_.reset(new std::vector<ui::Accelerator>());
1063 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1064 accelerators_->end()) {
1065 accelerators_->push_back(accelerator);
1067 RegisterPendingAccelerators();
1070 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1071 if (!accelerators_.get()) {
1072 NOTREACHED() << "Removing non-existing accelerator";
1073 return;
1076 std::vector<ui::Accelerator>::iterator i(
1077 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1078 if (i == accelerators_->end()) {
1079 NOTREACHED() << "Removing non-existing accelerator";
1080 return;
1083 size_t index = i - accelerators_->begin();
1084 accelerators_->erase(i);
1085 if (index >= registered_accelerator_count_) {
1086 // The accelerator is not registered to FocusManager.
1087 return;
1089 --registered_accelerator_count_;
1091 // Providing we are attached to a Widget and registered with a focus manager,
1092 // we should de-register from that focus manager now.
1093 if (GetWidget() && accelerator_focus_manager_)
1094 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1097 void View::ResetAccelerators() {
1098 if (accelerators_.get())
1099 UnregisterAccelerators(false);
1102 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1103 return false;
1106 bool View::CanHandleAccelerators() const {
1107 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1110 // Focus -----------------------------------------------------------------------
1112 bool View::HasFocus() const {
1113 const FocusManager* focus_manager = GetFocusManager();
1114 return focus_manager && (focus_manager->GetFocusedView() == this);
1117 View* View::GetNextFocusableView() {
1118 return next_focusable_view_;
1121 const View* View::GetNextFocusableView() const {
1122 return next_focusable_view_;
1125 View* View::GetPreviousFocusableView() {
1126 return previous_focusable_view_;
1129 void View::SetNextFocusableView(View* view) {
1130 if (view)
1131 view->previous_focusable_view_ = this;
1132 next_focusable_view_ = view;
1135 void View::SetFocusable(bool focusable) {
1136 if (focusable_ == focusable)
1137 return;
1139 focusable_ = focusable;
1140 AdvanceFocusIfNecessary();
1143 bool View::IsFocusable() const {
1144 return focusable_ && enabled_ && IsDrawn();
1147 bool View::IsAccessibilityFocusable() const {
1148 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1151 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1152 if (accessibility_focusable_ == accessibility_focusable)
1153 return;
1155 accessibility_focusable_ = accessibility_focusable;
1156 AdvanceFocusIfNecessary();
1159 FocusManager* View::GetFocusManager() {
1160 Widget* widget = GetWidget();
1161 return widget ? widget->GetFocusManager() : NULL;
1164 const FocusManager* View::GetFocusManager() const {
1165 const Widget* widget = GetWidget();
1166 return widget ? widget->GetFocusManager() : NULL;
1169 void View::RequestFocus() {
1170 FocusManager* focus_manager = GetFocusManager();
1171 if (focus_manager && IsFocusable())
1172 focus_manager->SetFocusedView(this);
1175 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1176 return false;
1179 FocusTraversable* View::GetFocusTraversable() {
1180 return NULL;
1183 FocusTraversable* View::GetPaneFocusTraversable() {
1184 return NULL;
1187 // Tooltips --------------------------------------------------------------------
1189 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1190 return false;
1193 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1194 return false;
1197 // Context menus ---------------------------------------------------------------
1199 void View::ShowContextMenu(const gfx::Point& p,
1200 ui::MenuSourceType source_type) {
1201 if (!context_menu_controller_)
1202 return;
1204 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1207 // static
1208 bool View::ShouldShowContextMenuOnMousePress() {
1209 return kContextMenuOnMousePress;
1212 gfx::Point View::GetKeyboardContextMenuLocation() {
1213 gfx::Rect vis_bounds = GetVisibleBounds();
1214 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1215 vis_bounds.y() + vis_bounds.height() / 2);
1216 ConvertPointToScreen(this, &screen_point);
1217 return screen_point;
1220 // Drag and drop ---------------------------------------------------------------
1222 bool View::GetDropFormats(
1223 int* formats,
1224 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1225 return false;
1228 bool View::AreDropTypesRequired() {
1229 return false;
1232 bool View::CanDrop(const OSExchangeData& data) {
1233 // TODO(sky): when I finish up migration, this should default to true.
1234 return false;
1237 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1240 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1241 return ui::DragDropTypes::DRAG_NONE;
1244 void View::OnDragExited() {
1247 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1248 return ui::DragDropTypes::DRAG_NONE;
1251 void View::OnDragDone() {
1254 // static
1255 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1256 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1257 abs(delta.y()) > GetVerticalDragThreshold());
1260 // Accessibility----------------------------------------------------------------
1262 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1263 if (!native_view_accessibility_)
1264 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1265 if (native_view_accessibility_)
1266 return native_view_accessibility_->GetNativeObject();
1267 return NULL;
1270 void View::NotifyAccessibilityEvent(
1271 ui::AXEvent event_type,
1272 bool send_native_event) {
1273 if (ViewsDelegate::GetInstance())
1274 ViewsDelegate::GetInstance()->NotifyAccessibilityEvent(this, event_type);
1276 if (send_native_event && GetWidget()) {
1277 if (!native_view_accessibility_)
1278 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1279 if (native_view_accessibility_)
1280 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1284 // Scrolling -------------------------------------------------------------------
1286 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1287 // We must take RTL UI mirroring into account when adjusting the position of
1288 // the region.
1289 if (parent_) {
1290 gfx::Rect scroll_rect(rect);
1291 scroll_rect.Offset(GetMirroredX(), y());
1292 parent_->ScrollRectToVisible(scroll_rect);
1296 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1297 bool is_horizontal, bool is_positive) {
1298 return 0;
1301 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1302 bool is_horizontal, bool is_positive) {
1303 return 0;
1306 ////////////////////////////////////////////////////////////////////////////////
1307 // View, protected:
1309 // Size and disposition --------------------------------------------------------
1311 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1314 void View::PreferredSizeChanged() {
1315 InvalidateLayout();
1316 if (parent_)
1317 parent_->ChildPreferredSizeChanged(this);
1320 bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
1321 return false;
1324 void View::OnVisibleBoundsChanged() {
1327 // Tree operations -------------------------------------------------------------
1329 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1332 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1335 void View::NativeViewHierarchyChanged() {
1336 FocusManager* focus_manager = GetFocusManager();
1337 if (accelerator_focus_manager_ != focus_manager) {
1338 UnregisterAccelerators(true);
1340 if (focus_manager)
1341 RegisterPendingAccelerators();
1345 // Painting --------------------------------------------------------------------
1347 void View::PaintChildren(const ui::PaintContext& context) {
1348 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1349 for (int i = 0, count = child_count(); i < count; ++i)
1350 if (!child_at(i)->layer())
1351 child_at(i)->Paint(context);
1354 void View::OnPaint(gfx::Canvas* canvas) {
1355 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1356 OnPaintBackground(canvas);
1357 OnPaintBorder(canvas);
1360 void View::OnPaintBackground(gfx::Canvas* canvas) {
1361 if (background_.get()) {
1362 TRACE_EVENT2("views", "View::OnPaintBackground",
1363 "width", canvas->sk_canvas()->getDevice()->width(),
1364 "height", canvas->sk_canvas()->getDevice()->height());
1365 background_->Paint(canvas, this);
1369 void View::OnPaintBorder(gfx::Canvas* canvas) {
1370 if (border_.get()) {
1371 TRACE_EVENT2("views", "View::OnPaintBorder",
1372 "width", canvas->sk_canvas()->getDevice()->width(),
1373 "height", canvas->sk_canvas()->getDevice()->height());
1374 border_->Paint(*this, canvas);
1378 // Accelerated Painting --------------------------------------------------------
1380 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1381 // This method should not have the side-effect of creating the layer.
1382 if (layer())
1383 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1386 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1387 ui::Layer** layer_parent) {
1388 if (layer()) {
1389 if (layer_parent)
1390 *layer_parent = layer();
1391 return gfx::Vector2d();
1393 if (!parent_)
1394 return gfx::Vector2d();
1396 return gfx::Vector2d(GetMirroredX(), y()) +
1397 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1400 void View::UpdateParentLayer() {
1401 if (!layer())
1402 return;
1404 ui::Layer* parent_layer = NULL;
1405 gfx::Vector2d offset(GetMirroredX(), y());
1407 if (parent_)
1408 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1410 ReparentLayer(offset, parent_layer);
1413 void View::MoveLayerToParent(ui::Layer* parent_layer,
1414 const gfx::Point& point) {
1415 gfx::Point local_point(point);
1416 if (parent_layer != layer())
1417 local_point.Offset(GetMirroredX(), y());
1418 if (layer() && parent_layer != layer()) {
1419 parent_layer->Add(layer());
1420 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1421 width(), height()));
1422 } else {
1423 for (int i = 0, count = child_count(); i < count; ++i)
1424 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1428 void View::UpdateLayerVisibility() {
1429 bool visible = visible_;
1430 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1431 visible = v->visible();
1433 UpdateChildLayerVisibility(visible);
1436 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1437 if (layer()) {
1438 layer()->SetVisible(ancestor_visible && visible_);
1439 } else {
1440 for (int i = 0, count = child_count(); i < count; ++i)
1441 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1445 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1446 if (layer()) {
1447 SetLayerBounds(GetLocalBounds() + offset);
1448 } else {
1449 for (int i = 0, count = child_count(); i < count; ++i) {
1450 View* child = child_at(i);
1451 child->UpdateChildLayerBounds(
1452 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1457 void View::OnPaintLayer(const ui::PaintContext& context) {
1458 Paint(context);
1461 void View::OnDelegatedFrameDamage(
1462 const gfx::Rect& damage_rect_in_dip) {
1465 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1466 snap_layer_to_pixel_boundary_ =
1467 (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1468 SnapLayerToPixelBoundary();
1469 // Repainting with new scale factor will paint the content at the right scale.
1472 base::Closure View::PrepareForLayerBoundsChange() {
1473 return base::Closure();
1476 void View::ReorderLayers() {
1477 View* v = this;
1478 while (v && !v->layer())
1479 v = v->parent();
1481 Widget* widget = GetWidget();
1482 if (!v) {
1483 if (widget) {
1484 ui::Layer* layer = widget->GetLayer();
1485 if (layer)
1486 widget->GetRootView()->ReorderChildLayers(layer);
1488 } else {
1489 v->ReorderChildLayers(v->layer());
1492 if (widget) {
1493 // Reorder the widget's child NativeViews in case a child NativeView is
1494 // associated with a view (eg via a NativeViewHost). Always do the
1495 // reordering because the associated NativeView's layer (if it has one)
1496 // is parented to the widget's layer regardless of whether the host view has
1497 // an ancestor with a layer.
1498 widget->ReorderNativeViews();
1502 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1503 if (layer() && layer() != parent_layer) {
1504 DCHECK_EQ(parent_layer, layer()->parent());
1505 parent_layer->StackAtBottom(layer());
1506 } else {
1507 // Iterate backwards through the children so that a child with a layer
1508 // which is further to the back is stacked above one which is further to
1509 // the front.
1510 for (Views::reverse_iterator it(children_.rbegin());
1511 it != children_.rend(); ++it) {
1512 (*it)->ReorderChildLayers(parent_layer);
1517 // Input -----------------------------------------------------------------------
1519 View::DragInfo* View::GetDragInfo() {
1520 return parent_ ? parent_->GetDragInfo() : NULL;
1523 // Focus -----------------------------------------------------------------------
1525 void View::OnFocus() {
1526 // TODO(beng): Investigate whether it's possible for us to move this to
1527 // Focus().
1528 // By default, we clear the native focus. This ensures that no visible native
1529 // view as the focus and that we still receive keyboard inputs.
1530 FocusManager* focus_manager = GetFocusManager();
1531 if (focus_manager)
1532 focus_manager->ClearNativeFocus();
1534 // TODO(beng): Investigate whether it's possible for us to move this to
1535 // Focus().
1536 // Notify assistive technologies of the focus change.
1537 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1540 void View::OnBlur() {
1543 void View::Focus() {
1544 OnFocus();
1547 void View::Blur() {
1548 OnBlur();
1551 // Tooltips --------------------------------------------------------------------
1553 void View::TooltipTextChanged() {
1554 Widget* widget = GetWidget();
1555 // TooltipManager may be null if there is a problem creating it.
1556 if (widget && widget->GetTooltipManager())
1557 widget->GetTooltipManager()->TooltipTextChanged(this);
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 // Tree operations -------------------------------------------------------------
1733 void View::DoRemoveChildView(View* view,
1734 bool update_focus_cycle,
1735 bool update_tool_tip,
1736 bool delete_removed_view,
1737 View* new_parent) {
1738 DCHECK(view);
1740 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1741 scoped_ptr<View> view_to_be_deleted;
1742 if (i != children_.end()) {
1743 if (update_focus_cycle) {
1744 // Let's remove the view from the focus traversal.
1745 View* next_focusable = view->next_focusable_view_;
1746 View* prev_focusable = view->previous_focusable_view_;
1747 if (prev_focusable)
1748 prev_focusable->next_focusable_view_ = next_focusable;
1749 if (next_focusable)
1750 next_focusable->previous_focusable_view_ = prev_focusable;
1753 if (GetWidget()) {
1754 UnregisterChildrenForVisibleBoundsNotification(view);
1755 if (view->visible())
1756 view->SchedulePaint();
1757 GetWidget()->NotifyWillRemoveView(view);
1760 view->PropagateRemoveNotifications(this, new_parent);
1761 view->parent_ = NULL;
1762 view->UpdateLayerVisibility();
1764 if (delete_removed_view && !view->owned_by_client_)
1765 view_to_be_deleted.reset(view);
1767 children_.erase(i);
1770 if (update_tool_tip)
1771 UpdateTooltip();
1773 if (layout_manager_.get())
1774 layout_manager_->ViewRemoved(this, view);
1777 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1778 for (int i = 0, count = child_count(); i < count; ++i)
1779 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1781 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1782 for (View* v = this; v; v = v->parent_)
1783 v->ViewHierarchyChangedImpl(true, details);
1786 void View::PropagateAddNotifications(
1787 const ViewHierarchyChangedDetails& details) {
1788 for (int i = 0, count = child_count(); i < count; ++i)
1789 child_at(i)->PropagateAddNotifications(details);
1790 ViewHierarchyChangedImpl(true, details);
1793 void View::PropagateNativeViewHierarchyChanged() {
1794 for (int i = 0, count = child_count(); i < count; ++i)
1795 child_at(i)->PropagateNativeViewHierarchyChanged();
1796 NativeViewHierarchyChanged();
1799 void View::ViewHierarchyChangedImpl(
1800 bool register_accelerators,
1801 const ViewHierarchyChangedDetails& details) {
1802 if (register_accelerators) {
1803 if (details.is_add) {
1804 // If you get this registration, you are part of a subtree that has been
1805 // added to the view hierarchy.
1806 if (GetFocusManager())
1807 RegisterPendingAccelerators();
1808 } else {
1809 if (details.child == this)
1810 UnregisterAccelerators(true);
1814 if (details.is_add && layer() && !layer()->parent()) {
1815 UpdateParentLayer();
1816 Widget* widget = GetWidget();
1817 if (widget)
1818 widget->UpdateRootLayers();
1819 } else if (!details.is_add && details.child == this) {
1820 // Make sure the layers belonging to the subtree rooted at |child| get
1821 // removed from layers that do not belong in the same subtree.
1822 OrphanLayers();
1823 Widget* widget = GetWidget();
1824 if (widget)
1825 widget->UpdateRootLayers();
1828 ViewHierarchyChanged(details);
1829 details.parent->needs_layout_ = true;
1832 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1833 for (int i = 0, count = child_count(); i < count; ++i)
1834 child_at(i)->PropagateNativeThemeChanged(theme);
1835 OnNativeThemeChanged(theme);
1838 // Size and disposition --------------------------------------------------------
1840 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1841 for (int i = 0, count = child_count(); i < count; ++i)
1842 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1843 VisibilityChangedImpl(start, is_visible);
1846 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1847 VisibilityChanged(starting_from, is_visible);
1850 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1851 if (visible_) {
1852 // Paint the new bounds.
1853 SchedulePaintBoundsChanged(
1854 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1855 SCHEDULE_PAINT_SIZE_CHANGED);
1858 if (layer()) {
1859 if (parent_) {
1860 SetLayerBounds(GetLocalBounds() +
1861 gfx::Vector2d(GetMirroredX(), y()) +
1862 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1863 } else {
1864 SetLayerBounds(bounds_);
1867 // In RTL mode, if our width has changed, our children's mirrored bounds
1868 // will have changed. Update the child's layer bounds, or if it is not a
1869 // layer, the bounds of any layers inside the child.
1870 if (base::i18n::IsRTL() && bounds_.width() != previous_bounds.width()) {
1871 for (int i = 0; i < child_count(); ++i) {
1872 View* child = child_at(i);
1873 child->UpdateChildLayerBounds(
1874 gfx::Vector2d(child->GetMirroredX(), child->y()));
1877 } else {
1878 // If our bounds have changed, then any descendant layer bounds may have
1879 // changed. Update them accordingly.
1880 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1883 OnBoundsChanged(previous_bounds);
1885 if (previous_bounds.size() != size()) {
1886 needs_layout_ = false;
1887 Layout();
1890 if (GetNeedsNotificationWhenVisibleBoundsChange())
1891 OnVisibleBoundsChanged();
1893 // Notify interested Views that visible bounds within the root view may have
1894 // changed.
1895 if (descendants_to_notify_.get()) {
1896 for (Views::iterator i(descendants_to_notify_->begin());
1897 i != descendants_to_notify_->end(); ++i) {
1898 (*i)->OnVisibleBoundsChanged();
1903 // static
1904 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1905 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1906 view->RegisterForVisibleBoundsNotification();
1907 for (int i = 0; i < view->child_count(); ++i)
1908 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1911 // static
1912 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1913 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1914 view->UnregisterForVisibleBoundsNotification();
1915 for (int i = 0; i < view->child_count(); ++i)
1916 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1919 void View::RegisterForVisibleBoundsNotification() {
1920 if (registered_for_visible_bounds_notification_)
1921 return;
1923 registered_for_visible_bounds_notification_ = true;
1924 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1925 ancestor->AddDescendantToNotify(this);
1928 void View::UnregisterForVisibleBoundsNotification() {
1929 if (!registered_for_visible_bounds_notification_)
1930 return;
1932 registered_for_visible_bounds_notification_ = false;
1933 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1934 ancestor->RemoveDescendantToNotify(this);
1937 void View::AddDescendantToNotify(View* view) {
1938 DCHECK(view);
1939 if (!descendants_to_notify_.get())
1940 descendants_to_notify_.reset(new Views);
1941 descendants_to_notify_->push_back(view);
1944 void View::RemoveDescendantToNotify(View* view) {
1945 DCHECK(view && descendants_to_notify_.get());
1946 Views::iterator i(std::find(
1947 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1948 DCHECK(i != descendants_to_notify_->end());
1949 descendants_to_notify_->erase(i);
1950 if (descendants_to_notify_->empty())
1951 descendants_to_notify_.reset();
1954 void View::SetLayerBounds(const gfx::Rect& bounds) {
1955 layer()->SetBounds(bounds);
1956 SnapLayerToPixelBoundary();
1959 // Transformations -------------------------------------------------------------
1961 bool View::GetTransformRelativeTo(const View* ancestor,
1962 gfx::Transform* transform) const {
1963 const View* p = this;
1965 while (p && p != ancestor) {
1966 transform->ConcatTransform(p->GetTransform());
1967 gfx::Transform translation;
1968 translation.Translate(static_cast<float>(p->GetMirroredX()),
1969 static_cast<float>(p->y()));
1970 transform->ConcatTransform(translation);
1972 p = p->parent_;
1975 return p == ancestor;
1978 // Coordinate conversion -------------------------------------------------------
1980 bool View::ConvertPointForAncestor(const View* ancestor,
1981 gfx::Point* point) const {
1982 gfx::Transform trans;
1983 // TODO(sad): Have some way of caching the transformation results.
1984 bool result = GetTransformRelativeTo(ancestor, &trans);
1985 gfx::Point3F p(*point);
1986 trans.TransformPoint(&p);
1987 *point = gfx::ToFlooredPoint(p.AsPointF());
1988 return result;
1991 bool View::ConvertPointFromAncestor(const View* ancestor,
1992 gfx::Point* point) const {
1993 gfx::Transform trans;
1994 bool result = GetTransformRelativeTo(ancestor, &trans);
1995 gfx::Point3F p(*point);
1996 trans.TransformPointReverse(&p);
1997 *point = gfx::ToFlooredPoint(p.AsPointF());
1998 return result;
2001 bool View::ConvertRectForAncestor(const View* ancestor,
2002 gfx::RectF* rect) const {
2003 gfx::Transform trans;
2004 // TODO(sad): Have some way of caching the transformation results.
2005 bool result = GetTransformRelativeTo(ancestor, &trans);
2006 trans.TransformRect(rect);
2007 return result;
2010 bool View::ConvertRectFromAncestor(const View* ancestor,
2011 gfx::RectF* rect) const {
2012 gfx::Transform trans;
2013 bool result = GetTransformRelativeTo(ancestor, &trans);
2014 trans.TransformRectReverse(rect);
2015 return result;
2018 // Accelerated painting --------------------------------------------------------
2020 void View::CreateLayer() {
2021 // A new layer is being created for the view. So all the layers of the
2022 // sub-tree can inherit the visibility of the corresponding view.
2023 for (int i = 0, count = child_count(); i < count; ++i)
2024 child_at(i)->UpdateChildLayerVisibility(true);
2026 SetLayer(new ui::Layer());
2027 layer()->set_delegate(this);
2028 #if !defined(NDEBUG)
2029 layer()->set_name(GetClassName());
2030 #endif
2032 UpdateParentLayers();
2033 UpdateLayerVisibility();
2035 // The new layer needs to be ordered in the layer tree according
2036 // to the view tree. Children of this layer were added in order
2037 // in UpdateParentLayers().
2038 if (parent())
2039 parent()->ReorderLayers();
2041 Widget* widget = GetWidget();
2042 if (widget)
2043 widget->UpdateRootLayers();
2046 void View::UpdateParentLayers() {
2047 // Attach all top-level un-parented layers.
2048 if (layer() && !layer()->parent()) {
2049 UpdateParentLayer();
2050 } else {
2051 for (int i = 0, count = child_count(); i < count; ++i)
2052 child_at(i)->UpdateParentLayers();
2056 void View::OrphanLayers() {
2057 if (layer()) {
2058 if (layer()->parent())
2059 layer()->parent()->Remove(layer());
2061 // The layer belonging to this View has already been orphaned. It is not
2062 // necessary to orphan the child layers.
2063 return;
2065 for (int i = 0, count = child_count(); i < count; ++i)
2066 child_at(i)->OrphanLayers();
2069 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2070 layer()->SetBounds(GetLocalBounds() + offset);
2071 DCHECK_NE(layer(), parent_layer);
2072 if (parent_layer)
2073 parent_layer->Add(layer());
2074 layer()->SchedulePaint(GetLocalBounds());
2075 MoveLayerToParent(layer(), gfx::Point());
2078 void View::DestroyLayer() {
2079 ui::Layer* new_parent = layer()->parent();
2080 std::vector<ui::Layer*> children = layer()->children();
2081 for (size_t i = 0; i < children.size(); ++i) {
2082 layer()->Remove(children[i]);
2083 if (new_parent)
2084 new_parent->Add(children[i]);
2087 LayerOwner::DestroyLayer();
2089 if (new_parent)
2090 ReorderLayers();
2092 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2094 SchedulePaint();
2096 Widget* widget = GetWidget();
2097 if (widget)
2098 widget->UpdateRootLayers();
2101 // Input -----------------------------------------------------------------------
2103 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2104 int drag_operations =
2105 (enabled_ && event.IsOnlyLeftMouseButton() &&
2106 HitTestPoint(event.location())) ?
2107 GetDragOperations(event.location()) : 0;
2108 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2109 context_menu_controller_ : 0;
2110 View::DragInfo* drag_info = GetDragInfo();
2112 // TODO(sky): for debugging 360238.
2113 int storage_id = 0;
2114 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2115 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2116 ViewStorage* view_storage = ViewStorage::GetInstance();
2117 storage_id = view_storage->CreateStorageID();
2118 view_storage->StoreView(storage_id, this);
2121 const bool enabled = enabled_;
2122 const bool result = OnMousePressed(event);
2124 if (!enabled)
2125 return result;
2127 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2128 kContextMenuOnMousePress) {
2129 // Assume that if there is a context menu controller we won't be deleted
2130 // from mouse pressed.
2131 gfx::Point location(event.location());
2132 if (HitTestPoint(location)) {
2133 if (storage_id != 0)
2134 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2135 ConvertPointToScreen(this, &location);
2136 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2137 return true;
2141 // WARNING: we may have been deleted, don't use any View variables.
2142 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2143 drag_info->PossibleDrag(event.location());
2144 return true;
2146 return !!context_menu_controller || result;
2149 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2150 // Copy the field, that way if we're deleted after drag and drop no harm is
2151 // done.
2152 ContextMenuController* context_menu_controller = context_menu_controller_;
2153 const bool possible_drag = GetDragInfo()->possible_drag;
2154 if (possible_drag &&
2155 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2156 (!drag_controller_ ||
2157 drag_controller_->CanStartDragForView(
2158 this, GetDragInfo()->start_pt, event.location()))) {
2159 DoDrag(event, GetDragInfo()->start_pt,
2160 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2161 } else {
2162 if (OnMouseDragged(event))
2163 return true;
2164 // Fall through to return value based on context menu controller.
2166 // WARNING: we may have been deleted.
2167 return (context_menu_controller != NULL) || possible_drag;
2170 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2171 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2172 event.IsOnlyRightMouseButton()) {
2173 // Assume that if there is a context menu controller we won't be deleted
2174 // from mouse released.
2175 gfx::Point location(event.location());
2176 OnMouseReleased(event);
2177 if (HitTestPoint(location)) {
2178 ConvertPointToScreen(this, &location);
2179 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2181 } else {
2182 OnMouseReleased(event);
2184 // WARNING: we may have been deleted.
2187 // Accelerators ----------------------------------------------------------------
2189 void View::RegisterPendingAccelerators() {
2190 if (!accelerators_.get() ||
2191 registered_accelerator_count_ == accelerators_->size()) {
2192 // No accelerators are waiting for registration.
2193 return;
2196 if (!GetWidget()) {
2197 // The view is not yet attached to a widget, defer registration until then.
2198 return;
2201 accelerator_focus_manager_ = GetFocusManager();
2202 if (!accelerator_focus_manager_) {
2203 // Some crash reports seem to show that we may get cases where we have no
2204 // focus manager (see bug #1291225). This should never be the case, just
2205 // making sure we don't crash.
2206 NOTREACHED();
2207 return;
2209 for (std::vector<ui::Accelerator>::const_iterator i(
2210 accelerators_->begin() + registered_accelerator_count_);
2211 i != accelerators_->end(); ++i) {
2212 accelerator_focus_manager_->RegisterAccelerator(
2213 *i, ui::AcceleratorManager::kNormalPriority, this);
2215 registered_accelerator_count_ = accelerators_->size();
2218 void View::UnregisterAccelerators(bool leave_data_intact) {
2219 if (!accelerators_.get())
2220 return;
2222 if (GetWidget()) {
2223 if (accelerator_focus_manager_) {
2224 accelerator_focus_manager_->UnregisterAccelerators(this);
2225 accelerator_focus_manager_ = NULL;
2227 if (!leave_data_intact) {
2228 accelerators_->clear();
2229 accelerators_.reset();
2231 registered_accelerator_count_ = 0;
2235 // Focus -----------------------------------------------------------------------
2237 void View::InitFocusSiblings(View* v, int index) {
2238 int count = child_count();
2240 if (count == 0) {
2241 v->next_focusable_view_ = NULL;
2242 v->previous_focusable_view_ = NULL;
2243 } else {
2244 if (index == count) {
2245 // We are inserting at the end, but the end of the child list may not be
2246 // the last focusable element. Let's try to find an element with no next
2247 // focusable element to link to.
2248 View* last_focusable_view = NULL;
2249 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2250 if (!(*i)->next_focusable_view_) {
2251 last_focusable_view = *i;
2252 break;
2255 if (last_focusable_view == NULL) {
2256 // Hum... there is a cycle in the focus list. Let's just insert ourself
2257 // after the last child.
2258 View* prev = children_[index - 1];
2259 v->previous_focusable_view_ = prev;
2260 v->next_focusable_view_ = prev->next_focusable_view_;
2261 prev->next_focusable_view_->previous_focusable_view_ = v;
2262 prev->next_focusable_view_ = v;
2263 } else {
2264 last_focusable_view->next_focusable_view_ = v;
2265 v->next_focusable_view_ = NULL;
2266 v->previous_focusable_view_ = last_focusable_view;
2268 } else {
2269 View* prev = children_[index]->GetPreviousFocusableView();
2270 v->previous_focusable_view_ = prev;
2271 v->next_focusable_view_ = children_[index];
2272 if (prev)
2273 prev->next_focusable_view_ = v;
2274 children_[index]->previous_focusable_view_ = v;
2279 void View::AdvanceFocusIfNecessary() {
2280 // Focus should only be advanced if this is the focused view and has become
2281 // unfocusable. If the view is still focusable or is not focused, we can
2282 // return early avoiding furthur unnecessary checks. Focusability check is
2283 // performed first as it tends to be faster.
2284 if (IsAccessibilityFocusable() || !HasFocus())
2285 return;
2287 FocusManager* focus_manager = GetFocusManager();
2288 if (focus_manager)
2289 focus_manager->AdvanceFocusIfNecessary();
2292 // System events ---------------------------------------------------------------
2294 void View::PropagateThemeChanged() {
2295 for (int i = child_count() - 1; i >= 0; --i)
2296 child_at(i)->PropagateThemeChanged();
2297 OnThemeChanged();
2300 void View::PropagateLocaleChanged() {
2301 for (int i = child_count() - 1; i >= 0; --i)
2302 child_at(i)->PropagateLocaleChanged();
2303 OnLocaleChanged();
2306 void View::PropagateDeviceScaleFactorChanged(float device_scale_factor) {
2307 for (int i = child_count() - 1; i >= 0; --i)
2308 child_at(i)->PropagateDeviceScaleFactorChanged(device_scale_factor);
2310 // If the view is drawing to the layer, OnDeviceScaleFactorChanged() is called
2311 // through LayerDelegate callback.
2312 if (!layer())
2313 OnDeviceScaleFactorChanged(device_scale_factor);
2316 // Tooltips --------------------------------------------------------------------
2318 void View::UpdateTooltip() {
2319 Widget* widget = GetWidget();
2320 // TODO(beng): The TooltipManager NULL check can be removed when we
2321 // consolidate Init() methods and make views_unittests Init() all
2322 // Widgets that it uses.
2323 if (widget && widget->GetTooltipManager())
2324 widget->GetTooltipManager()->UpdateTooltip();
2327 // Drag and drop ---------------------------------------------------------------
2329 bool View::DoDrag(const ui::LocatedEvent& event,
2330 const gfx::Point& press_pt,
2331 ui::DragDropTypes::DragEventSource source) {
2332 int drag_operations = GetDragOperations(press_pt);
2333 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2334 return false;
2336 Widget* widget = GetWidget();
2337 // We should only start a drag from an event, implying we have a widget.
2338 DCHECK(widget);
2340 // Don't attempt to start a drag while in the process of dragging. This is
2341 // especially important on X where we can get multiple mouse move events when
2342 // we start the drag.
2343 if (widget->dragged_view())
2344 return false;
2346 OSExchangeData data;
2347 WriteDragData(press_pt, &data);
2349 // Message the RootView to do the drag and drop. That way if we're removed
2350 // the RootView can detect it and avoid calling us back.
2351 gfx::Point widget_location(event.location());
2352 ConvertPointToWidget(this, &widget_location);
2353 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2354 // WARNING: we may have been deleted.
2355 return true;
2358 } // namespace views