Make castv2 performance test work.
[chromium-blink-merge.git] / ui / views / view.cc
blob78659caf418cd1b5ee47d40b98e1841a3e4f659b
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/compositor/clip_transform_recorder.h"
23 #include "ui/compositor/compositor.h"
24 #include "ui/compositor/dip_util.h"
25 #include "ui/compositor/layer.h"
26 #include "ui/compositor/layer_animator.h"
27 #include "ui/compositor/paint_context.h"
28 #include "ui/compositor/paint_recorder.h"
29 #include "ui/events/event_target_iterator.h"
30 #include "ui/gfx/canvas.h"
31 #include "ui/gfx/geometry/point3_f.h"
32 #include "ui/gfx/geometry/point_conversions.h"
33 #include "ui/gfx/interpolated_transform.h"
34 #include "ui/gfx/path.h"
35 #include "ui/gfx/scoped_canvas.h"
36 #include "ui/gfx/screen.h"
37 #include "ui/gfx/skia_util.h"
38 #include "ui/gfx/transform.h"
39 #include "ui/native_theme/native_theme.h"
40 #include "ui/views/accessibility/native_view_accessibility.h"
41 #include "ui/views/background.h"
42 #include "ui/views/border.h"
43 #include "ui/views/context_menu_controller.h"
44 #include "ui/views/drag_controller.h"
45 #include "ui/views/focus/view_storage.h"
46 #include "ui/views/layout/layout_manager.h"
47 #include "ui/views/views_delegate.h"
48 #include "ui/views/widget/native_widget_private.h"
49 #include "ui/views/widget/root_view.h"
50 #include "ui/views/widget/tooltip_manager.h"
51 #include "ui/views/widget/widget.h"
53 #if defined(OS_WIN)
54 #include "base/win/scoped_gdi_object.h"
55 #endif
57 namespace views {
59 namespace {
61 #if defined(OS_WIN)
62 const bool kContextMenuOnMousePress = false;
63 #else
64 const bool kContextMenuOnMousePress = true;
65 #endif
67 // Default horizontal drag threshold in pixels.
68 // Same as what gtk uses.
69 const int kDefaultHorizontalDragThreshold = 8;
71 // Default vertical drag threshold in pixels.
72 // Same as what gtk uses.
73 const int kDefaultVerticalDragThreshold = 8;
75 // Returns the top view in |view|'s hierarchy.
76 const View* GetHierarchyRoot(const View* view) {
77 const View* root = view;
78 while (root && root->parent())
79 root = root->parent();
80 return root;
83 } // namespace
85 // static
86 ViewsDelegate* ViewsDelegate::views_delegate = NULL;
88 // static
89 const char View::kViewClassName[] = "View";
91 ////////////////////////////////////////////////////////////////////////////////
92 // View, public:
94 // Creation and lifetime -------------------------------------------------------
96 View::View()
97 : owned_by_client_(false),
98 id_(0),
99 group_(-1),
100 parent_(NULL),
101 visible_(true),
102 enabled_(true),
103 notify_enter_exit_on_child_(false),
104 registered_for_visible_bounds_notification_(false),
105 clip_insets_(0, 0, 0, 0),
106 needs_layout_(true),
107 snap_layer_to_pixel_boundary_(false),
108 flip_canvas_on_paint_for_rtl_ui_(false),
109 paint_to_layer_(false),
110 accelerator_focus_manager_(NULL),
111 registered_accelerator_count_(0),
112 next_focusable_view_(NULL),
113 previous_focusable_view_(NULL),
114 focusable_(false),
115 accessibility_focusable_(false),
116 context_menu_controller_(NULL),
117 drag_controller_(NULL),
118 native_view_accessibility_(NULL) {
121 View::~View() {
122 if (parent_)
123 parent_->RemoveChildView(this);
125 ViewStorage::GetInstance()->ViewRemoved(this);
127 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
128 (*i)->parent_ = NULL;
129 if (!(*i)->owned_by_client_)
130 delete *i;
133 // Release ownership of the native accessibility object, but it's
134 // reference-counted on some platforms, so it may not be deleted right away.
135 if (native_view_accessibility_)
136 native_view_accessibility_->Destroy();
139 // Tree operations -------------------------------------------------------------
141 const Widget* View::GetWidget() const {
142 // The root view holds a reference to this view hierarchy's Widget.
143 return parent_ ? parent_->GetWidget() : NULL;
146 Widget* View::GetWidget() {
147 return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
150 void View::AddChildView(View* view) {
151 if (view->parent_ == this)
152 return;
153 AddChildViewAt(view, child_count());
156 void View::AddChildViewAt(View* view, int index) {
157 CHECK_NE(view, this) << "You cannot add a view as its own child";
158 DCHECK_GE(index, 0);
159 DCHECK_LE(index, child_count());
161 // If |view| has a parent, remove it from its parent.
162 View* parent = view->parent_;
163 ui::NativeTheme* old_theme = NULL;
164 if (parent) {
165 old_theme = view->GetNativeTheme();
166 if (parent == this) {
167 ReorderChildView(view, index);
168 return;
170 parent->DoRemoveChildView(view, true, true, false, this);
173 // Sets the prev/next focus views.
174 InitFocusSiblings(view, index);
176 // Let's insert the view.
177 view->parent_ = this;
178 children_.insert(children_.begin() + index, view);
180 views::Widget* widget = GetWidget();
181 if (widget) {
182 const ui::NativeTheme* new_theme = view->GetNativeTheme();
183 if (new_theme != old_theme)
184 view->PropagateNativeThemeChanged(new_theme);
187 ViewHierarchyChangedDetails details(true, this, view, parent);
189 for (View* v = this; v; v = v->parent_)
190 v->ViewHierarchyChangedImpl(false, details);
192 view->PropagateAddNotifications(details);
193 UpdateTooltip();
194 if (widget) {
195 RegisterChildrenForVisibleBoundsNotification(view);
196 if (view->visible())
197 view->SchedulePaint();
200 if (layout_manager_.get())
201 layout_manager_->ViewAdded(this, view);
203 ReorderLayers();
205 // Make sure the visibility of the child layers are correct.
206 // If any of the parent View is hidden, then the layers of the subtree
207 // rooted at |this| should be hidden. Otherwise, all the child layers should
208 // inherit the visibility of the owner View.
209 UpdateLayerVisibility();
212 void View::ReorderChildView(View* view, int index) {
213 DCHECK_EQ(view->parent_, this);
214 if (index < 0)
215 index = child_count() - 1;
216 else if (index >= child_count())
217 return;
218 if (children_[index] == view)
219 return;
221 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
222 DCHECK(i != children_.end());
223 children_.erase(i);
225 // Unlink the view first
226 View* next_focusable = view->next_focusable_view_;
227 View* prev_focusable = view->previous_focusable_view_;
228 if (prev_focusable)
229 prev_focusable->next_focusable_view_ = next_focusable;
230 if (next_focusable)
231 next_focusable->previous_focusable_view_ = prev_focusable;
233 // Add it in the specified index now.
234 InitFocusSiblings(view, index);
235 children_.insert(children_.begin() + index, view);
237 ReorderLayers();
240 void View::RemoveChildView(View* view) {
241 DoRemoveChildView(view, true, true, false, NULL);
244 void View::RemoveAllChildViews(bool delete_children) {
245 while (!children_.empty())
246 DoRemoveChildView(children_.front(), false, false, delete_children, NULL);
247 UpdateTooltip();
250 bool View::Contains(const View* view) const {
251 for (const View* v = view; v; v = v->parent_) {
252 if (v == this)
253 return true;
255 return false;
258 int View::GetIndexOf(const View* view) const {
259 Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
260 return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
263 // Size and disposition --------------------------------------------------------
265 void View::SetBounds(int x, int y, int width, int height) {
266 SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
269 void View::SetBoundsRect(const gfx::Rect& bounds) {
270 if (bounds == bounds_) {
271 if (needs_layout_) {
272 needs_layout_ = false;
273 Layout();
275 return;
278 if (visible_) {
279 // Paint where the view is currently.
280 SchedulePaintBoundsChanged(
281 bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
282 SCHEDULE_PAINT_SIZE_CHANGED);
285 gfx::Rect prev = bounds_;
286 bounds_ = bounds;
287 BoundsChanged(prev);
290 void View::SetSize(const gfx::Size& size) {
291 SetBounds(x(), y(), size.width(), size.height());
294 void View::SetPosition(const gfx::Point& position) {
295 SetBounds(position.x(), position.y(), width(), height());
298 void View::SetX(int x) {
299 SetBounds(x, y(), width(), height());
302 void View::SetY(int y) {
303 SetBounds(x(), y, width(), height());
306 gfx::Rect View::GetContentsBounds() const {
307 gfx::Rect contents_bounds(GetLocalBounds());
308 if (border_.get())
309 contents_bounds.Inset(border_->GetInsets());
310 return contents_bounds;
313 gfx::Rect View::GetLocalBounds() const {
314 return gfx::Rect(size());
317 gfx::Rect View::GetLayerBoundsInPixel() const {
318 return layer()->GetTargetBounds();
321 gfx::Insets View::GetInsets() const {
322 return border_.get() ? border_->GetInsets() : gfx::Insets();
325 gfx::Rect View::GetVisibleBounds() const {
326 if (!IsDrawn())
327 return gfx::Rect();
328 gfx::Rect vis_bounds(GetLocalBounds());
329 gfx::Rect ancestor_bounds;
330 const View* view = this;
331 gfx::Transform transform;
333 while (view != NULL && !vis_bounds.IsEmpty()) {
334 transform.ConcatTransform(view->GetTransform());
335 gfx::Transform translation;
336 translation.Translate(static_cast<float>(view->GetMirroredX()),
337 static_cast<float>(view->y()));
338 transform.ConcatTransform(translation);
340 vis_bounds = view->ConvertRectToParent(vis_bounds);
341 const View* ancestor = view->parent_;
342 if (ancestor != NULL) {
343 ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
344 vis_bounds.Intersect(ancestor_bounds);
345 } else if (!view->GetWidget()) {
346 // If the view has no Widget, we're not visible. Return an empty rect.
347 return gfx::Rect();
349 view = ancestor;
351 if (vis_bounds.IsEmpty())
352 return vis_bounds;
353 // Convert back to this views coordinate system.
354 gfx::RectF views_vis_bounds(vis_bounds);
355 transform.TransformRectReverse(&views_vis_bounds);
356 // Partially visible pixels should be considered visible.
357 return gfx::ToEnclosingRect(views_vis_bounds);
360 gfx::Rect View::GetBoundsInScreen() const {
361 gfx::Point origin;
362 View::ConvertPointToScreen(this, &origin);
363 return gfx::Rect(origin, size());
366 gfx::Size View::GetPreferredSize() const {
367 if (layout_manager_.get())
368 return layout_manager_->GetPreferredSize(this);
369 return gfx::Size();
372 int View::GetBaseline() const {
373 return -1;
376 void View::SizeToPreferredSize() {
377 gfx::Size prefsize = GetPreferredSize();
378 if ((prefsize.width() != width()) || (prefsize.height() != height()))
379 SetBounds(x(), y(), prefsize.width(), prefsize.height());
382 gfx::Size View::GetMinimumSize() const {
383 return GetPreferredSize();
386 gfx::Size View::GetMaximumSize() const {
387 return gfx::Size();
390 int View::GetHeightForWidth(int w) const {
391 if (layout_manager_.get())
392 return layout_manager_->GetPreferredHeightForWidth(this, w);
393 return GetPreferredSize().height();
396 void View::SetVisible(bool visible) {
397 if (visible != visible_) {
398 // If the View is currently visible, schedule paint to refresh parent.
399 // TODO(beng): not sure we should be doing this if we have a layer.
400 if (visible_)
401 SchedulePaint();
403 visible_ = visible;
404 AdvanceFocusIfNecessary();
406 // Notify the parent.
407 if (parent_)
408 parent_->ChildVisibilityChanged(this);
410 // This notifies all sub-views recursively.
411 PropagateVisibilityNotifications(this, visible_);
412 UpdateLayerVisibility();
414 // If we are newly visible, schedule paint.
415 if (visible_)
416 SchedulePaint();
420 bool View::IsDrawn() const {
421 return visible_ && parent_ ? parent_->IsDrawn() : false;
424 void View::SetEnabled(bool enabled) {
425 if (enabled != enabled_) {
426 enabled_ = enabled;
427 AdvanceFocusIfNecessary();
428 OnEnabledChanged();
432 void View::OnEnabledChanged() {
433 SchedulePaint();
436 // Transformations -------------------------------------------------------------
438 gfx::Transform View::GetTransform() const {
439 return layer() ? layer()->transform() : gfx::Transform();
442 void View::SetTransform(const gfx::Transform& transform) {
443 if (transform.IsIdentity()) {
444 if (layer()) {
445 layer()->SetTransform(transform);
446 if (!paint_to_layer_)
447 DestroyLayer();
448 } else {
449 // Nothing.
451 } else {
452 if (!layer())
453 CreateLayer();
454 layer()->SetTransform(transform);
455 layer()->ScheduleDraw();
459 void View::SetPaintToLayer(bool paint_to_layer) {
460 if (paint_to_layer_ == paint_to_layer)
461 return;
463 paint_to_layer_ = paint_to_layer;
464 if (paint_to_layer_ && !layer()) {
465 CreateLayer();
466 } else if (!paint_to_layer_ && layer()) {
467 DestroyLayer();
471 // RTL positioning -------------------------------------------------------------
473 gfx::Rect View::GetMirroredBounds() const {
474 gfx::Rect bounds(bounds_);
475 bounds.set_x(GetMirroredX());
476 return bounds;
479 gfx::Point View::GetMirroredPosition() const {
480 return gfx::Point(GetMirroredX(), y());
483 int View::GetMirroredX() const {
484 return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
487 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
488 return base::i18n::IsRTL() ?
489 (width() - bounds.x() - bounds.width()) : bounds.x();
492 int View::GetMirroredXInView(int x) const {
493 return base::i18n::IsRTL() ? width() - x : x;
496 int View::GetMirroredXWithWidthInView(int x, int w) const {
497 return base::i18n::IsRTL() ? width() - x - w : x;
500 // Layout ----------------------------------------------------------------------
502 void View::Layout() {
503 needs_layout_ = false;
505 // If we have a layout manager, let it handle the layout for us.
506 if (layout_manager_.get())
507 layout_manager_->Layout(this);
509 // Make sure to propagate the Layout() call to any children that haven't
510 // received it yet through the layout manager and need to be laid out. This
511 // is needed for the case when the child requires a layout but its bounds
512 // weren't changed by the layout manager. If there is no layout manager, we
513 // just propagate the Layout() call down the hierarchy, so whoever receives
514 // the call can take appropriate action.
515 for (int i = 0, count = child_count(); i < count; ++i) {
516 View* child = child_at(i);
517 if (child->needs_layout_ || !layout_manager_.get()) {
518 TRACE_EVENT1("views", "View::Layout", "class", child->GetClassName());
519 child->needs_layout_ = false;
520 child->Layout();
525 void View::InvalidateLayout() {
526 // Always invalidate up. This is needed to handle the case of us already being
527 // valid, but not our parent.
528 needs_layout_ = true;
529 if (parent_)
530 parent_->InvalidateLayout();
533 LayoutManager* View::GetLayoutManager() const {
534 return layout_manager_.get();
537 void View::SetLayoutManager(LayoutManager* layout_manager) {
538 if (layout_manager_.get())
539 layout_manager_->Uninstalled(this);
541 layout_manager_.reset(layout_manager);
542 if (layout_manager_.get())
543 layout_manager_->Installed(this);
546 void View::SnapLayerToPixelBoundary() {
547 if (!layer())
548 return;
550 if (snap_layer_to_pixel_boundary_ && layer()->parent() &&
551 layer()->GetCompositor()) {
552 ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer());
553 } else {
554 // Reset the offset.
555 layer()->SetSubpixelPositionOffset(gfx::Vector2dF());
559 // Attributes ------------------------------------------------------------------
561 const char* View::GetClassName() const {
562 return kViewClassName;
565 const View* View::GetAncestorWithClassName(const std::string& name) const {
566 for (const View* view = this; view; view = view->parent_) {
567 if (!strcmp(view->GetClassName(), name.c_str()))
568 return view;
570 return NULL;
573 View* View::GetAncestorWithClassName(const std::string& name) {
574 return const_cast<View*>(const_cast<const View*>(this)->
575 GetAncestorWithClassName(name));
578 const View* View::GetViewByID(int id) const {
579 if (id == id_)
580 return const_cast<View*>(this);
582 for (int i = 0, count = child_count(); i < count; ++i) {
583 const View* view = child_at(i)->GetViewByID(id);
584 if (view)
585 return view;
587 return NULL;
590 View* View::GetViewByID(int id) {
591 return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
594 void View::SetGroup(int gid) {
595 // Don't change the group id once it's set.
596 DCHECK(group_ == -1 || group_ == gid);
597 group_ = gid;
600 int View::GetGroup() const {
601 return group_;
604 bool View::IsGroupFocusTraversable() const {
605 return true;
608 void View::GetViewsInGroup(int group, Views* views) {
609 if (group_ == group)
610 views->push_back(this);
612 for (int i = 0, count = child_count(); i < count; ++i)
613 child_at(i)->GetViewsInGroup(group, views);
616 View* View::GetSelectedViewForGroup(int group) {
617 Views views;
618 GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
619 return views.empty() ? NULL : views[0];
622 // Coordinate conversion -------------------------------------------------------
624 // static
625 void View::ConvertPointToTarget(const View* source,
626 const View* target,
627 gfx::Point* point) {
628 DCHECK(source);
629 DCHECK(target);
630 if (source == target)
631 return;
633 const View* root = GetHierarchyRoot(target);
634 CHECK_EQ(GetHierarchyRoot(source), root);
636 if (source != root)
637 source->ConvertPointForAncestor(root, point);
639 if (target != root)
640 target->ConvertPointFromAncestor(root, point);
643 // static
644 void View::ConvertRectToTarget(const View* source,
645 const View* target,
646 gfx::RectF* rect) {
647 DCHECK(source);
648 DCHECK(target);
649 if (source == target)
650 return;
652 const View* root = GetHierarchyRoot(target);
653 CHECK_EQ(GetHierarchyRoot(source), root);
655 if (source != root)
656 source->ConvertRectForAncestor(root, rect);
658 if (target != root)
659 target->ConvertRectFromAncestor(root, rect);
662 // static
663 void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
664 DCHECK(src);
665 DCHECK(p);
667 src->ConvertPointForAncestor(NULL, p);
670 // static
671 void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
672 DCHECK(dest);
673 DCHECK(p);
675 dest->ConvertPointFromAncestor(NULL, p);
678 // static
679 void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
680 DCHECK(src);
681 DCHECK(p);
683 // If the view is not connected to a tree, there's nothing we can do.
684 const Widget* widget = src->GetWidget();
685 if (widget) {
686 ConvertPointToWidget(src, p);
687 *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
691 // static
692 void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
693 DCHECK(dst);
694 DCHECK(p);
696 const views::Widget* widget = dst->GetWidget();
697 if (!widget)
698 return;
699 *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
700 views::View::ConvertPointFromWidget(dst, p);
703 gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
704 gfx::RectF x_rect = rect;
705 GetTransform().TransformRect(&x_rect);
706 x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
707 // Pixels we partially occupy in the parent should be included.
708 return gfx::ToEnclosingRect(x_rect);
711 gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
712 gfx::Rect x_rect = rect;
713 for (const View* v = this; v; v = v->parent_)
714 x_rect = v->ConvertRectToParent(x_rect);
715 return x_rect;
718 // Painting --------------------------------------------------------------------
720 void View::SchedulePaint() {
721 SchedulePaintInRect(GetLocalBounds());
724 void View::SchedulePaintInRect(const gfx::Rect& rect) {
725 if (!visible_)
726 return;
728 if (layer()) {
729 layer()->SchedulePaint(rect);
730 } else if (parent_) {
731 // Translate the requested paint rect to the parent's coordinate system
732 // then pass this notification up to the parent.
733 parent_->SchedulePaintInRect(ConvertRectToParent(rect));
737 void View::Paint(const ui::PaintContext& parent_context) {
738 if (!visible_)
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 =
749 parent_context.CloneWithPaintOffset(offset_to_parent);
751 if (context.CanCheckInvalidated()) {
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 if (!context.IsRectInvalidated(GetLocalBounds()))
774 return;
777 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
779 // If the view is backed by a layer, it should paint with itself as the origin
780 // rather than relative to its parent.
781 scoped_ptr<ui::ClipTransformRecorder> clip_transform_recorder;
782 if (!layer()) {
783 clip_transform_recorder.reset(new ui::ClipTransformRecorder(context));
785 // Set the clip rect to the bounds of this View. Note that the X (or left)
786 // position we pass to ClipRect takes into consideration whether or not the
787 // View uses a right-to-left layout so that we paint the View in its
788 // mirrored position if need be.
789 gfx::Rect clip_rect_in_parent = bounds();
790 clip_rect_in_parent.Inset(clip_insets_);
791 if (parent_)
792 clip_rect_in_parent.set_x(
793 parent_->GetMirroredXForRect(clip_rect_in_parent));
794 clip_transform_recorder->ClipRect(clip_rect_in_parent);
796 // Translate the graphics such that 0,0 corresponds to where
797 // this View is located relative to its parent.
798 gfx::Transform transform_from_parent;
799 gfx::Vector2d offset_from_parent = GetMirroredPosition().OffsetFromOrigin();
800 transform_from_parent.Translate(offset_from_parent.x(),
801 offset_from_parent.y());
802 transform_from_parent.PreconcatTransform(GetTransform());
803 clip_transform_recorder->Transform(transform_from_parent);
807 ui::PaintRecorder recorder(context);
808 gfx::Canvas* canvas = recorder.canvas();
809 gfx::ScopedCanvas scoped_canvas(canvas);
811 // If the View we are about to paint requested the canvas to be flipped, we
812 // should change the transform appropriately.
813 // The canvas mirroring is undone once the View is done painting so that we
814 // don't pass the canvas with the mirrored transform to Views that didn't
815 // request the canvas to be flipped.
816 if (FlipCanvasOnPaintForRTLUI()) {
817 canvas->Translate(gfx::Vector2d(width(), 0));
818 canvas->Scale(-1, 1);
821 // Delegate painting the contents of the View to the virtual OnPaint method.
822 OnPaint(canvas);
825 // View::Paint() recursion over the subtree.
826 PaintChildren(context);
829 void View::set_background(Background* b) {
830 background_.reset(b);
833 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
835 ui::ThemeProvider* View::GetThemeProvider() const {
836 const Widget* widget = GetWidget();
837 return widget ? widget->GetThemeProvider() : NULL;
840 const ui::NativeTheme* View::GetNativeTheme() const {
841 const Widget* widget = GetWidget();
842 return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
845 // Input -----------------------------------------------------------------------
847 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
848 return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
851 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
852 return GetEffectiveViewTargeter()->TargetForRect(this, rect);
855 bool View::CanProcessEventsWithinSubtree() const {
856 return true;
859 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
860 // TODO(tdanderson): Move this implementation into ViewTargetDelegate.
861 if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree())
862 return NULL;
864 // Walk the child Views recursively looking for the View that most
865 // tightly encloses the specified point.
866 for (int i = child_count() - 1; i >= 0; --i) {
867 View* child = child_at(i);
868 if (!child->visible())
869 continue;
871 gfx::Point point_in_child_coords(point);
872 ConvertPointToTarget(this, child, &point_in_child_coords);
873 View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
874 if (handler)
875 return handler;
877 return this;
880 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
881 #if defined(OS_WIN)
882 static ui::Cursor arrow;
883 if (!arrow.platform())
884 arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
885 return arrow;
886 #else
887 return gfx::kNullCursor;
888 #endif
891 bool View::HitTestPoint(const gfx::Point& point) const {
892 return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
895 bool View::HitTestRect(const gfx::Rect& rect) const {
896 return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect);
899 bool View::IsMouseHovered() {
900 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
901 // hovered.
902 if (!GetWidget())
903 return false;
905 // If mouse events are disabled, then the mouse cursor is invisible and
906 // is therefore not hovering over this button.
907 if (!GetWidget()->IsMouseEventsEnabled())
908 return false;
910 gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
911 GetWidget()->GetNativeView())->GetCursorScreenPoint());
912 ConvertPointFromScreen(this, &cursor_pos);
913 return HitTestPoint(cursor_pos);
916 bool View::OnMousePressed(const ui::MouseEvent& event) {
917 return false;
920 bool View::OnMouseDragged(const ui::MouseEvent& event) {
921 return false;
924 void View::OnMouseReleased(const ui::MouseEvent& event) {
927 void View::OnMouseCaptureLost() {
930 void View::OnMouseMoved(const ui::MouseEvent& event) {
933 void View::OnMouseEntered(const ui::MouseEvent& event) {
936 void View::OnMouseExited(const ui::MouseEvent& event) {
939 void View::SetMouseHandler(View* new_mouse_handler) {
940 // |new_mouse_handler| may be NULL.
941 if (parent_)
942 parent_->SetMouseHandler(new_mouse_handler);
945 bool View::OnKeyPressed(const ui::KeyEvent& event) {
946 return false;
949 bool View::OnKeyReleased(const ui::KeyEvent& event) {
950 return false;
953 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
954 return false;
957 void View::OnKeyEvent(ui::KeyEvent* event) {
958 bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
959 OnKeyReleased(*event);
960 if (consumed)
961 event->StopPropagation();
964 void View::OnMouseEvent(ui::MouseEvent* event) {
965 switch (event->type()) {
966 case ui::ET_MOUSE_PRESSED:
967 if (ProcessMousePressed(*event))
968 event->SetHandled();
969 return;
971 case ui::ET_MOUSE_MOVED:
972 if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
973 ui::EF_RIGHT_MOUSE_BUTTON |
974 ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
975 OnMouseMoved(*event);
976 return;
978 // FALL-THROUGH
979 case ui::ET_MOUSE_DRAGGED:
980 if (ProcessMouseDragged(*event))
981 event->SetHandled();
982 return;
984 case ui::ET_MOUSE_RELEASED:
985 ProcessMouseReleased(*event);
986 return;
988 case ui::ET_MOUSEWHEEL:
989 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
990 event->SetHandled();
991 break;
993 case ui::ET_MOUSE_ENTERED:
994 if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY)
995 NotifyAccessibilityEvent(ui::AX_EVENT_HOVER, true);
996 OnMouseEntered(*event);
997 break;
999 case ui::ET_MOUSE_EXITED:
1000 OnMouseExited(*event);
1001 break;
1003 default:
1004 return;
1008 void View::OnScrollEvent(ui::ScrollEvent* event) {
1011 void View::OnTouchEvent(ui::TouchEvent* event) {
1012 NOTREACHED() << "Views should not receive touch events.";
1015 void View::OnGestureEvent(ui::GestureEvent* event) {
1018 ui::TextInputClient* View::GetTextInputClient() {
1019 return NULL;
1022 InputMethod* View::GetInputMethod() {
1023 Widget* widget = GetWidget();
1024 return widget ? widget->GetInputMethod() : NULL;
1027 const InputMethod* View::GetInputMethod() const {
1028 const Widget* widget = GetWidget();
1029 return widget ? widget->GetInputMethod() : NULL;
1032 scoped_ptr<ViewTargeter>
1033 View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) {
1034 scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass();
1035 targeter_ = targeter.Pass();
1036 return old_targeter.Pass();
1039 ViewTargeter* View::GetEffectiveViewTargeter() const {
1040 DCHECK(GetWidget());
1041 ViewTargeter* view_targeter = targeter();
1042 if (!view_targeter)
1043 view_targeter = GetWidget()->GetRootView()->targeter();
1044 CHECK(view_targeter);
1045 return view_targeter;
1048 bool View::CanAcceptEvent(const ui::Event& event) {
1049 return IsDrawn();
1052 ui::EventTarget* View::GetParentTarget() {
1053 return parent_;
1056 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1057 return make_scoped_ptr(new ui::EventTargetIteratorImpl<View>(children_));
1060 ui::EventTargeter* View::GetEventTargeter() {
1061 return targeter_.get();
1064 void View::ConvertEventToTarget(ui::EventTarget* target,
1065 ui::LocatedEvent* event) {
1066 event->ConvertLocationToTarget(this, static_cast<View*>(target));
1069 // Accelerators ----------------------------------------------------------------
1071 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1072 if (!accelerators_.get())
1073 accelerators_.reset(new std::vector<ui::Accelerator>());
1075 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1076 accelerators_->end()) {
1077 accelerators_->push_back(accelerator);
1079 RegisterPendingAccelerators();
1082 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1083 if (!accelerators_.get()) {
1084 NOTREACHED() << "Removing non-existing accelerator";
1085 return;
1088 std::vector<ui::Accelerator>::iterator i(
1089 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1090 if (i == accelerators_->end()) {
1091 NOTREACHED() << "Removing non-existing accelerator";
1092 return;
1095 size_t index = i - accelerators_->begin();
1096 accelerators_->erase(i);
1097 if (index >= registered_accelerator_count_) {
1098 // The accelerator is not registered to FocusManager.
1099 return;
1101 --registered_accelerator_count_;
1103 // Providing we are attached to a Widget and registered with a focus manager,
1104 // we should de-register from that focus manager now.
1105 if (GetWidget() && accelerator_focus_manager_)
1106 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1109 void View::ResetAccelerators() {
1110 if (accelerators_.get())
1111 UnregisterAccelerators(false);
1114 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1115 return false;
1118 bool View::CanHandleAccelerators() const {
1119 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1122 // Focus -----------------------------------------------------------------------
1124 bool View::HasFocus() const {
1125 const FocusManager* focus_manager = GetFocusManager();
1126 return focus_manager && (focus_manager->GetFocusedView() == this);
1129 View* View::GetNextFocusableView() {
1130 return next_focusable_view_;
1133 const View* View::GetNextFocusableView() const {
1134 return next_focusable_view_;
1137 View* View::GetPreviousFocusableView() {
1138 return previous_focusable_view_;
1141 void View::SetNextFocusableView(View* view) {
1142 if (view)
1143 view->previous_focusable_view_ = this;
1144 next_focusable_view_ = view;
1147 void View::SetFocusable(bool focusable) {
1148 if (focusable_ == focusable)
1149 return;
1151 focusable_ = focusable;
1152 AdvanceFocusIfNecessary();
1155 bool View::IsFocusable() const {
1156 return focusable_ && enabled_ && IsDrawn();
1159 bool View::IsAccessibilityFocusable() const {
1160 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1163 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1164 if (accessibility_focusable_ == accessibility_focusable)
1165 return;
1167 accessibility_focusable_ = accessibility_focusable;
1168 AdvanceFocusIfNecessary();
1171 FocusManager* View::GetFocusManager() {
1172 Widget* widget = GetWidget();
1173 return widget ? widget->GetFocusManager() : NULL;
1176 const FocusManager* View::GetFocusManager() const {
1177 const Widget* widget = GetWidget();
1178 return widget ? widget->GetFocusManager() : NULL;
1181 void View::RequestFocus() {
1182 FocusManager* focus_manager = GetFocusManager();
1183 if (focus_manager && IsFocusable())
1184 focus_manager->SetFocusedView(this);
1187 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1188 return false;
1191 FocusTraversable* View::GetFocusTraversable() {
1192 return NULL;
1195 FocusTraversable* View::GetPaneFocusTraversable() {
1196 return NULL;
1199 // Tooltips --------------------------------------------------------------------
1201 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1202 return false;
1205 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1206 return false;
1209 // Context menus ---------------------------------------------------------------
1211 void View::ShowContextMenu(const gfx::Point& p,
1212 ui::MenuSourceType source_type) {
1213 if (!context_menu_controller_)
1214 return;
1216 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1219 // static
1220 bool View::ShouldShowContextMenuOnMousePress() {
1221 return kContextMenuOnMousePress;
1224 // Drag and drop ---------------------------------------------------------------
1226 bool View::GetDropFormats(
1227 int* formats,
1228 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1229 return false;
1232 bool View::AreDropTypesRequired() {
1233 return false;
1236 bool View::CanDrop(const OSExchangeData& data) {
1237 // TODO(sky): when I finish up migration, this should default to true.
1238 return false;
1241 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1244 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1245 return ui::DragDropTypes::DRAG_NONE;
1248 void View::OnDragExited() {
1251 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1252 return ui::DragDropTypes::DRAG_NONE;
1255 void View::OnDragDone() {
1258 // static
1259 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1260 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1261 abs(delta.y()) > GetVerticalDragThreshold());
1264 // Accessibility----------------------------------------------------------------
1266 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1267 if (!native_view_accessibility_)
1268 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1269 if (native_view_accessibility_)
1270 return native_view_accessibility_->GetNativeObject();
1271 return NULL;
1274 void View::NotifyAccessibilityEvent(
1275 ui::AXEvent event_type,
1276 bool send_native_event) {
1277 if (ViewsDelegate::views_delegate)
1278 ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1280 if (send_native_event && GetWidget()) {
1281 if (!native_view_accessibility_)
1282 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1283 if (native_view_accessibility_)
1284 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1288 // Scrolling -------------------------------------------------------------------
1290 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1291 // We must take RTL UI mirroring into account when adjusting the position of
1292 // the region.
1293 if (parent_) {
1294 gfx::Rect scroll_rect(rect);
1295 scroll_rect.Offset(GetMirroredX(), y());
1296 parent_->ScrollRectToVisible(scroll_rect);
1300 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1301 bool is_horizontal, bool is_positive) {
1302 return 0;
1305 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1306 bool is_horizontal, bool is_positive) {
1307 return 0;
1310 ////////////////////////////////////////////////////////////////////////////////
1311 // View, protected:
1313 // Size and disposition --------------------------------------------------------
1315 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1318 void View::PreferredSizeChanged() {
1319 InvalidateLayout();
1320 if (parent_)
1321 parent_->ChildPreferredSizeChanged(this);
1324 bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
1325 return false;
1328 void View::OnVisibleBoundsChanged() {
1331 // Tree operations -------------------------------------------------------------
1333 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1336 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1339 void View::NativeViewHierarchyChanged() {
1340 FocusManager* focus_manager = GetFocusManager();
1341 if (accelerator_focus_manager_ != focus_manager) {
1342 UnregisterAccelerators(true);
1344 if (focus_manager)
1345 RegisterPendingAccelerators();
1349 // Painting --------------------------------------------------------------------
1351 void View::PaintChildren(const ui::PaintContext& context) {
1352 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1353 for (int i = 0, count = child_count(); i < count; ++i)
1354 if (!child_at(i)->layer())
1355 child_at(i)->Paint(context);
1358 void View::OnPaint(gfx::Canvas* canvas) {
1359 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1360 OnPaintBackground(canvas);
1361 OnPaintBorder(canvas);
1364 void View::OnPaintBackground(gfx::Canvas* canvas) {
1365 if (background_.get()) {
1366 TRACE_EVENT2("views", "View::OnPaintBackground",
1367 "width", canvas->sk_canvas()->getDevice()->width(),
1368 "height", canvas->sk_canvas()->getDevice()->height());
1369 background_->Paint(canvas, this);
1373 void View::OnPaintBorder(gfx::Canvas* canvas) {
1374 if (border_.get()) {
1375 TRACE_EVENT2("views", "View::OnPaintBorder",
1376 "width", canvas->sk_canvas()->getDevice()->width(),
1377 "height", canvas->sk_canvas()->getDevice()->height());
1378 border_->Paint(*this, canvas);
1382 // Accelerated Painting --------------------------------------------------------
1384 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1385 // This method should not have the side-effect of creating the layer.
1386 if (layer())
1387 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1390 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1391 ui::Layer** layer_parent) {
1392 if (layer()) {
1393 if (layer_parent)
1394 *layer_parent = layer();
1395 return gfx::Vector2d();
1397 if (!parent_)
1398 return gfx::Vector2d();
1400 return gfx::Vector2d(GetMirroredX(), y()) +
1401 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1404 void View::UpdateParentLayer() {
1405 if (!layer())
1406 return;
1408 ui::Layer* parent_layer = NULL;
1409 gfx::Vector2d offset(GetMirroredX(), y());
1411 if (parent_)
1412 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1414 ReparentLayer(offset, parent_layer);
1417 void View::MoveLayerToParent(ui::Layer* parent_layer,
1418 const gfx::Point& point) {
1419 gfx::Point local_point(point);
1420 if (parent_layer != layer())
1421 local_point.Offset(GetMirroredX(), y());
1422 if (layer() && parent_layer != layer()) {
1423 parent_layer->Add(layer());
1424 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1425 width(), height()));
1426 } else {
1427 for (int i = 0, count = child_count(); i < count; ++i)
1428 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1432 void View::UpdateLayerVisibility() {
1433 bool visible = visible_;
1434 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1435 visible = v->visible();
1437 UpdateChildLayerVisibility(visible);
1440 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1441 if (layer()) {
1442 layer()->SetVisible(ancestor_visible && visible_);
1443 } else {
1444 for (int i = 0, count = child_count(); i < count; ++i)
1445 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1449 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1450 if (layer()) {
1451 SetLayerBounds(GetLocalBounds() + offset);
1452 } else {
1453 for (int i = 0, count = child_count(); i < count; ++i) {
1454 View* child = child_at(i);
1455 child->UpdateChildLayerBounds(
1456 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1461 void View::OnPaintLayer(const ui::PaintContext& context) {
1462 if (!layer()->fills_bounds_opaquely()) {
1463 ui::PaintRecorder recorder(context);
1464 recorder.canvas()->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1466 if (!visible_)
1467 return;
1468 Paint(context);
1471 void View::OnDelegatedFrameDamage(
1472 const gfx::Rect& damage_rect_in_dip) {
1475 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1476 snap_layer_to_pixel_boundary_ =
1477 (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1478 SnapLayerToPixelBoundary();
1479 // Repainting with new scale factor will paint the content at the right scale.
1482 base::Closure View::PrepareForLayerBoundsChange() {
1483 return base::Closure();
1486 void View::ReorderLayers() {
1487 View* v = this;
1488 while (v && !v->layer())
1489 v = v->parent();
1491 Widget* widget = GetWidget();
1492 if (!v) {
1493 if (widget) {
1494 ui::Layer* layer = widget->GetLayer();
1495 if (layer)
1496 widget->GetRootView()->ReorderChildLayers(layer);
1498 } else {
1499 v->ReorderChildLayers(v->layer());
1502 if (widget) {
1503 // Reorder the widget's child NativeViews in case a child NativeView is
1504 // associated with a view (eg via a NativeViewHost). Always do the
1505 // reordering because the associated NativeView's layer (if it has one)
1506 // is parented to the widget's layer regardless of whether the host view has
1507 // an ancestor with a layer.
1508 widget->ReorderNativeViews();
1512 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1513 if (layer() && layer() != parent_layer) {
1514 DCHECK_EQ(parent_layer, layer()->parent());
1515 parent_layer->StackAtBottom(layer());
1516 } else {
1517 // Iterate backwards through the children so that a child with a layer
1518 // which is further to the back is stacked above one which is further to
1519 // the front.
1520 for (Views::reverse_iterator it(children_.rbegin());
1521 it != children_.rend(); ++it) {
1522 (*it)->ReorderChildLayers(parent_layer);
1527 // Input -----------------------------------------------------------------------
1529 View::DragInfo* View::GetDragInfo() {
1530 return parent_ ? parent_->GetDragInfo() : NULL;
1533 // Focus -----------------------------------------------------------------------
1535 void View::OnFocus() {
1536 // TODO(beng): Investigate whether it's possible for us to move this to
1537 // Focus().
1538 // By default, we clear the native focus. This ensures that no visible native
1539 // view as the focus and that we still receive keyboard inputs.
1540 FocusManager* focus_manager = GetFocusManager();
1541 if (focus_manager)
1542 focus_manager->ClearNativeFocus();
1544 // TODO(beng): Investigate whether it's possible for us to move this to
1545 // Focus().
1546 // Notify assistive technologies of the focus change.
1547 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1550 void View::OnBlur() {
1553 void View::Focus() {
1554 OnFocus();
1557 void View::Blur() {
1558 OnBlur();
1561 // Tooltips --------------------------------------------------------------------
1563 void View::TooltipTextChanged() {
1564 Widget* widget = GetWidget();
1565 // TooltipManager may be null if there is a problem creating it.
1566 if (widget && widget->GetTooltipManager())
1567 widget->GetTooltipManager()->TooltipTextChanged(this);
1570 // Context menus ---------------------------------------------------------------
1572 gfx::Point View::GetKeyboardContextMenuLocation() {
1573 gfx::Rect vis_bounds = GetVisibleBounds();
1574 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1575 vis_bounds.y() + vis_bounds.height() / 2);
1576 ConvertPointToScreen(this, &screen_point);
1577 return screen_point;
1580 // Drag and drop ---------------------------------------------------------------
1582 int View::GetDragOperations(const gfx::Point& press_pt) {
1583 return drag_controller_ ?
1584 drag_controller_->GetDragOperationsForView(this, press_pt) :
1585 ui::DragDropTypes::DRAG_NONE;
1588 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1589 DCHECK(drag_controller_);
1590 drag_controller_->WriteDragDataForView(this, press_pt, data);
1593 bool View::InDrag() {
1594 Widget* widget = GetWidget();
1595 return widget ? widget->dragged_view() == this : false;
1598 int View::GetHorizontalDragThreshold() {
1599 // TODO(jennyz): This value may need to be adjusted for different platforms
1600 // and for different display density.
1601 return kDefaultHorizontalDragThreshold;
1604 int View::GetVerticalDragThreshold() {
1605 // TODO(jennyz): This value may need to be adjusted for different platforms
1606 // and for different display density.
1607 return kDefaultVerticalDragThreshold;
1610 // Debugging -------------------------------------------------------------------
1612 #if !defined(NDEBUG)
1614 std::string View::PrintViewGraph(bool first) {
1615 return DoPrintViewGraph(first, this);
1618 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1619 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1620 const size_t kMaxPointerStringLength = 19;
1622 std::string result;
1624 if (first)
1625 result.append("digraph {\n");
1627 // Node characteristics.
1628 char p[kMaxPointerStringLength];
1630 const std::string class_name(GetClassName());
1631 size_t base_name_index = class_name.find_last_of('/');
1632 if (base_name_index == std::string::npos)
1633 base_name_index = 0;
1634 else
1635 base_name_index++;
1637 char bounds_buffer[512];
1639 // Information about current node.
1640 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1641 result.append(" N");
1642 result.append(p + 2);
1643 result.append(" [label=\"");
1645 result.append(class_name.substr(base_name_index).c_str());
1647 base::snprintf(bounds_buffer,
1648 arraysize(bounds_buffer),
1649 "\\n bounds: (%d, %d), (%dx%d)",
1650 bounds().x(),
1651 bounds().y(),
1652 bounds().width(),
1653 bounds().height());
1654 result.append(bounds_buffer);
1656 gfx::DecomposedTransform decomp;
1657 if (!GetTransform().IsIdentity() &&
1658 gfx::DecomposeTransform(&decomp, GetTransform())) {
1659 base::snprintf(bounds_buffer,
1660 arraysize(bounds_buffer),
1661 "\\n translation: (%f, %f)",
1662 decomp.translate[0],
1663 decomp.translate[1]);
1664 result.append(bounds_buffer);
1666 base::snprintf(bounds_buffer,
1667 arraysize(bounds_buffer),
1668 "\\n rotation: %3.2f",
1669 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1670 result.append(bounds_buffer);
1672 base::snprintf(bounds_buffer,
1673 arraysize(bounds_buffer),
1674 "\\n scale: (%2.4f, %2.4f)",
1675 decomp.scale[0],
1676 decomp.scale[1]);
1677 result.append(bounds_buffer);
1680 result.append("\"");
1681 if (!parent_)
1682 result.append(", shape=box");
1683 if (layer()) {
1684 if (layer()->has_external_content())
1685 result.append(", color=green");
1686 else
1687 result.append(", color=red");
1689 if (layer()->fills_bounds_opaquely())
1690 result.append(", style=filled");
1692 result.append("]\n");
1694 // Link to parent.
1695 if (parent_) {
1696 char pp[kMaxPointerStringLength];
1698 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1699 result.append(" N");
1700 result.append(pp + 2);
1701 result.append(" -> N");
1702 result.append(p + 2);
1703 result.append("\n");
1706 // Children.
1707 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1708 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1710 if (first)
1711 result.append("}\n");
1713 return result;
1715 #endif
1717 ////////////////////////////////////////////////////////////////////////////////
1718 // View, private:
1720 // DropInfo --------------------------------------------------------------------
1722 void View::DragInfo::Reset() {
1723 possible_drag = false;
1724 start_pt = gfx::Point();
1727 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1728 possible_drag = true;
1729 start_pt = p;
1732 // Painting --------------------------------------------------------------------
1734 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1735 // If we have a layer and the View's size did not change, we do not need to
1736 // schedule any paints since the layer will be redrawn at its new location
1737 // during the next Draw() cycle in the compositor.
1738 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1739 // Otherwise, if the size changes or we don't have a layer then we need to
1740 // use SchedulePaint to invalidate the area occupied by the View.
1741 SchedulePaint();
1742 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1743 // The compositor doesn't Draw() until something on screen changes, so
1744 // if our position changes but nothing is being animated on screen, then
1745 // tell the compositor to redraw the scene. We know layer() exists due to
1746 // the above if clause.
1747 layer()->ScheduleDraw();
1751 // Tree operations -------------------------------------------------------------
1753 void View::DoRemoveChildView(View* view,
1754 bool update_focus_cycle,
1755 bool update_tool_tip,
1756 bool delete_removed_view,
1757 View* new_parent) {
1758 DCHECK(view);
1760 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1761 scoped_ptr<View> view_to_be_deleted;
1762 if (i != children_.end()) {
1763 if (update_focus_cycle) {
1764 // Let's remove the view from the focus traversal.
1765 View* next_focusable = view->next_focusable_view_;
1766 View* prev_focusable = view->previous_focusable_view_;
1767 if (prev_focusable)
1768 prev_focusable->next_focusable_view_ = next_focusable;
1769 if (next_focusable)
1770 next_focusable->previous_focusable_view_ = prev_focusable;
1773 if (GetWidget()) {
1774 UnregisterChildrenForVisibleBoundsNotification(view);
1775 if (view->visible())
1776 view->SchedulePaint();
1777 GetWidget()->NotifyWillRemoveView(view);
1780 view->PropagateRemoveNotifications(this, new_parent);
1781 view->parent_ = NULL;
1782 view->UpdateLayerVisibility();
1784 if (delete_removed_view && !view->owned_by_client_)
1785 view_to_be_deleted.reset(view);
1787 children_.erase(i);
1790 if (update_tool_tip)
1791 UpdateTooltip();
1793 if (layout_manager_.get())
1794 layout_manager_->ViewRemoved(this, view);
1797 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1798 for (int i = 0, count = child_count(); i < count; ++i)
1799 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1801 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1802 for (View* v = this; v; v = v->parent_)
1803 v->ViewHierarchyChangedImpl(true, details);
1806 void View::PropagateAddNotifications(
1807 const ViewHierarchyChangedDetails& details) {
1808 for (int i = 0, count = child_count(); i < count; ++i)
1809 child_at(i)->PropagateAddNotifications(details);
1810 ViewHierarchyChangedImpl(true, details);
1813 void View::PropagateNativeViewHierarchyChanged() {
1814 for (int i = 0, count = child_count(); i < count; ++i)
1815 child_at(i)->PropagateNativeViewHierarchyChanged();
1816 NativeViewHierarchyChanged();
1819 void View::ViewHierarchyChangedImpl(
1820 bool register_accelerators,
1821 const ViewHierarchyChangedDetails& details) {
1822 if (register_accelerators) {
1823 if (details.is_add) {
1824 // If you get this registration, you are part of a subtree that has been
1825 // added to the view hierarchy.
1826 if (GetFocusManager())
1827 RegisterPendingAccelerators();
1828 } else {
1829 if (details.child == this)
1830 UnregisterAccelerators(true);
1834 if (details.is_add && layer() && !layer()->parent()) {
1835 UpdateParentLayer();
1836 Widget* widget = GetWidget();
1837 if (widget)
1838 widget->UpdateRootLayers();
1839 } else if (!details.is_add && details.child == this) {
1840 // Make sure the layers belonging to the subtree rooted at |child| get
1841 // removed from layers that do not belong in the same subtree.
1842 OrphanLayers();
1843 Widget* widget = GetWidget();
1844 if (widget)
1845 widget->UpdateRootLayers();
1848 ViewHierarchyChanged(details);
1849 details.parent->needs_layout_ = true;
1852 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1853 for (int i = 0, count = child_count(); i < count; ++i)
1854 child_at(i)->PropagateNativeThemeChanged(theme);
1855 OnNativeThemeChanged(theme);
1858 // Size and disposition --------------------------------------------------------
1860 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1861 for (int i = 0, count = child_count(); i < count; ++i)
1862 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1863 VisibilityChangedImpl(start, is_visible);
1866 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1867 VisibilityChanged(starting_from, is_visible);
1870 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1871 if (visible_) {
1872 // Paint the new bounds.
1873 SchedulePaintBoundsChanged(
1874 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1875 SCHEDULE_PAINT_SIZE_CHANGED);
1878 if (layer()) {
1879 if (parent_) {
1880 SetLayerBounds(GetLocalBounds() +
1881 gfx::Vector2d(GetMirroredX(), y()) +
1882 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1883 } else {
1884 SetLayerBounds(bounds_);
1887 // In RTL mode, if our width has changed, our children's mirrored bounds
1888 // will have changed. Update the child's layer bounds, or if it is not a
1889 // layer, the bounds of any layers inside the child.
1890 if (base::i18n::IsRTL() && bounds_.width() != previous_bounds.width()) {
1891 for (int i = 0; i < child_count(); ++i) {
1892 View* child = child_at(i);
1893 child->UpdateChildLayerBounds(
1894 gfx::Vector2d(child->GetMirroredX(), child->y()));
1897 } else {
1898 // If our bounds have changed, then any descendant layer bounds may have
1899 // changed. Update them accordingly.
1900 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1903 OnBoundsChanged(previous_bounds);
1905 if (previous_bounds.size() != size()) {
1906 needs_layout_ = false;
1907 Layout();
1910 if (GetNeedsNotificationWhenVisibleBoundsChange())
1911 OnVisibleBoundsChanged();
1913 // Notify interested Views that visible bounds within the root view may have
1914 // changed.
1915 if (descendants_to_notify_.get()) {
1916 for (Views::iterator i(descendants_to_notify_->begin());
1917 i != descendants_to_notify_->end(); ++i) {
1918 (*i)->OnVisibleBoundsChanged();
1923 // static
1924 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1925 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1926 view->RegisterForVisibleBoundsNotification();
1927 for (int i = 0; i < view->child_count(); ++i)
1928 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1931 // static
1932 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1933 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1934 view->UnregisterForVisibleBoundsNotification();
1935 for (int i = 0; i < view->child_count(); ++i)
1936 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1939 void View::RegisterForVisibleBoundsNotification() {
1940 if (registered_for_visible_bounds_notification_)
1941 return;
1943 registered_for_visible_bounds_notification_ = true;
1944 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1945 ancestor->AddDescendantToNotify(this);
1948 void View::UnregisterForVisibleBoundsNotification() {
1949 if (!registered_for_visible_bounds_notification_)
1950 return;
1952 registered_for_visible_bounds_notification_ = false;
1953 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1954 ancestor->RemoveDescendantToNotify(this);
1957 void View::AddDescendantToNotify(View* view) {
1958 DCHECK(view);
1959 if (!descendants_to_notify_.get())
1960 descendants_to_notify_.reset(new Views);
1961 descendants_to_notify_->push_back(view);
1964 void View::RemoveDescendantToNotify(View* view) {
1965 DCHECK(view && descendants_to_notify_.get());
1966 Views::iterator i(std::find(
1967 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1968 DCHECK(i != descendants_to_notify_->end());
1969 descendants_to_notify_->erase(i);
1970 if (descendants_to_notify_->empty())
1971 descendants_to_notify_.reset();
1974 void View::SetLayerBounds(const gfx::Rect& bounds) {
1975 layer()->SetBounds(bounds);
1976 SnapLayerToPixelBoundary();
1979 // Transformations -------------------------------------------------------------
1981 bool View::GetTransformRelativeTo(const View* ancestor,
1982 gfx::Transform* transform) const {
1983 const View* p = this;
1985 while (p && p != ancestor) {
1986 transform->ConcatTransform(p->GetTransform());
1987 gfx::Transform translation;
1988 translation.Translate(static_cast<float>(p->GetMirroredX()),
1989 static_cast<float>(p->y()));
1990 transform->ConcatTransform(translation);
1992 p = p->parent_;
1995 return p == ancestor;
1998 // Coordinate conversion -------------------------------------------------------
2000 bool View::ConvertPointForAncestor(const View* ancestor,
2001 gfx::Point* point) const {
2002 gfx::Transform trans;
2003 // TODO(sad): Have some way of caching the transformation results.
2004 bool result = GetTransformRelativeTo(ancestor, &trans);
2005 gfx::Point3F p(*point);
2006 trans.TransformPoint(&p);
2007 *point = gfx::ToFlooredPoint(p.AsPointF());
2008 return result;
2011 bool View::ConvertPointFromAncestor(const View* ancestor,
2012 gfx::Point* point) const {
2013 gfx::Transform trans;
2014 bool result = GetTransformRelativeTo(ancestor, &trans);
2015 gfx::Point3F p(*point);
2016 trans.TransformPointReverse(&p);
2017 *point = gfx::ToFlooredPoint(p.AsPointF());
2018 return result;
2021 bool View::ConvertRectForAncestor(const View* ancestor,
2022 gfx::RectF* rect) const {
2023 gfx::Transform trans;
2024 // TODO(sad): Have some way of caching the transformation results.
2025 bool result = GetTransformRelativeTo(ancestor, &trans);
2026 trans.TransformRect(rect);
2027 return result;
2030 bool View::ConvertRectFromAncestor(const View* ancestor,
2031 gfx::RectF* rect) const {
2032 gfx::Transform trans;
2033 bool result = GetTransformRelativeTo(ancestor, &trans);
2034 trans.TransformRectReverse(rect);
2035 return result;
2038 // Accelerated painting --------------------------------------------------------
2040 void View::CreateLayer() {
2041 // A new layer is being created for the view. So all the layers of the
2042 // sub-tree can inherit the visibility of the corresponding view.
2043 for (int i = 0, count = child_count(); i < count; ++i)
2044 child_at(i)->UpdateChildLayerVisibility(true);
2046 SetLayer(new ui::Layer());
2047 layer()->set_delegate(this);
2048 #if !defined(NDEBUG)
2049 layer()->set_name(GetClassName());
2050 #endif
2052 UpdateParentLayers();
2053 UpdateLayerVisibility();
2055 // The new layer needs to be ordered in the layer tree according
2056 // to the view tree. Children of this layer were added in order
2057 // in UpdateParentLayers().
2058 if (parent())
2059 parent()->ReorderLayers();
2061 Widget* widget = GetWidget();
2062 if (widget)
2063 widget->UpdateRootLayers();
2066 void View::UpdateParentLayers() {
2067 // Attach all top-level un-parented layers.
2068 if (layer() && !layer()->parent()) {
2069 UpdateParentLayer();
2070 } else {
2071 for (int i = 0, count = child_count(); i < count; ++i)
2072 child_at(i)->UpdateParentLayers();
2076 void View::OrphanLayers() {
2077 if (layer()) {
2078 if (layer()->parent())
2079 layer()->parent()->Remove(layer());
2081 // The layer belonging to this View has already been orphaned. It is not
2082 // necessary to orphan the child layers.
2083 return;
2085 for (int i = 0, count = child_count(); i < count; ++i)
2086 child_at(i)->OrphanLayers();
2089 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2090 layer()->SetBounds(GetLocalBounds() + offset);
2091 DCHECK_NE(layer(), parent_layer);
2092 if (parent_layer)
2093 parent_layer->Add(layer());
2094 layer()->SchedulePaint(GetLocalBounds());
2095 MoveLayerToParent(layer(), gfx::Point());
2098 void View::DestroyLayer() {
2099 ui::Layer* new_parent = layer()->parent();
2100 std::vector<ui::Layer*> children = layer()->children();
2101 for (size_t i = 0; i < children.size(); ++i) {
2102 layer()->Remove(children[i]);
2103 if (new_parent)
2104 new_parent->Add(children[i]);
2107 LayerOwner::DestroyLayer();
2109 if (new_parent)
2110 ReorderLayers();
2112 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2114 SchedulePaint();
2116 Widget* widget = GetWidget();
2117 if (widget)
2118 widget->UpdateRootLayers();
2121 // Input -----------------------------------------------------------------------
2123 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2124 int drag_operations =
2125 (enabled_ && event.IsOnlyLeftMouseButton() &&
2126 HitTestPoint(event.location())) ?
2127 GetDragOperations(event.location()) : 0;
2128 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2129 context_menu_controller_ : 0;
2130 View::DragInfo* drag_info = GetDragInfo();
2132 // TODO(sky): for debugging 360238.
2133 int storage_id = 0;
2134 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2135 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2136 ViewStorage* view_storage = ViewStorage::GetInstance();
2137 storage_id = view_storage->CreateStorageID();
2138 view_storage->StoreView(storage_id, this);
2141 const bool enabled = enabled_;
2142 const bool result = OnMousePressed(event);
2144 if (!enabled)
2145 return result;
2147 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2148 kContextMenuOnMousePress) {
2149 // Assume that if there is a context menu controller we won't be deleted
2150 // from mouse pressed.
2151 gfx::Point location(event.location());
2152 if (HitTestPoint(location)) {
2153 if (storage_id != 0)
2154 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2155 ConvertPointToScreen(this, &location);
2156 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2157 return true;
2161 // WARNING: we may have been deleted, don't use any View variables.
2162 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2163 drag_info->PossibleDrag(event.location());
2164 return true;
2166 return !!context_menu_controller || result;
2169 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2170 // Copy the field, that way if we're deleted after drag and drop no harm is
2171 // done.
2172 ContextMenuController* context_menu_controller = context_menu_controller_;
2173 const bool possible_drag = GetDragInfo()->possible_drag;
2174 if (possible_drag &&
2175 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2176 (!drag_controller_ ||
2177 drag_controller_->CanStartDragForView(
2178 this, GetDragInfo()->start_pt, event.location()))) {
2179 DoDrag(event, GetDragInfo()->start_pt,
2180 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2181 } else {
2182 if (OnMouseDragged(event))
2183 return true;
2184 // Fall through to return value based on context menu controller.
2186 // WARNING: we may have been deleted.
2187 return (context_menu_controller != NULL) || possible_drag;
2190 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2191 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2192 event.IsOnlyRightMouseButton()) {
2193 // Assume that if there is a context menu controller we won't be deleted
2194 // from mouse released.
2195 gfx::Point location(event.location());
2196 OnMouseReleased(event);
2197 if (HitTestPoint(location)) {
2198 ConvertPointToScreen(this, &location);
2199 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2201 } else {
2202 OnMouseReleased(event);
2204 // WARNING: we may have been deleted.
2207 // Accelerators ----------------------------------------------------------------
2209 void View::RegisterPendingAccelerators() {
2210 if (!accelerators_.get() ||
2211 registered_accelerator_count_ == accelerators_->size()) {
2212 // No accelerators are waiting for registration.
2213 return;
2216 if (!GetWidget()) {
2217 // The view is not yet attached to a widget, defer registration until then.
2218 return;
2221 accelerator_focus_manager_ = GetFocusManager();
2222 if (!accelerator_focus_manager_) {
2223 // Some crash reports seem to show that we may get cases where we have no
2224 // focus manager (see bug #1291225). This should never be the case, just
2225 // making sure we don't crash.
2226 NOTREACHED();
2227 return;
2229 for (std::vector<ui::Accelerator>::const_iterator i(
2230 accelerators_->begin() + registered_accelerator_count_);
2231 i != accelerators_->end(); ++i) {
2232 accelerator_focus_manager_->RegisterAccelerator(
2233 *i, ui::AcceleratorManager::kNormalPriority, this);
2235 registered_accelerator_count_ = accelerators_->size();
2238 void View::UnregisterAccelerators(bool leave_data_intact) {
2239 if (!accelerators_.get())
2240 return;
2242 if (GetWidget()) {
2243 if (accelerator_focus_manager_) {
2244 accelerator_focus_manager_->UnregisterAccelerators(this);
2245 accelerator_focus_manager_ = NULL;
2247 if (!leave_data_intact) {
2248 accelerators_->clear();
2249 accelerators_.reset();
2251 registered_accelerator_count_ = 0;
2255 // Focus -----------------------------------------------------------------------
2257 void View::InitFocusSiblings(View* v, int index) {
2258 int count = child_count();
2260 if (count == 0) {
2261 v->next_focusable_view_ = NULL;
2262 v->previous_focusable_view_ = NULL;
2263 } else {
2264 if (index == count) {
2265 // We are inserting at the end, but the end of the child list may not be
2266 // the last focusable element. Let's try to find an element with no next
2267 // focusable element to link to.
2268 View* last_focusable_view = NULL;
2269 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2270 if (!(*i)->next_focusable_view_) {
2271 last_focusable_view = *i;
2272 break;
2275 if (last_focusable_view == NULL) {
2276 // Hum... there is a cycle in the focus list. Let's just insert ourself
2277 // after the last child.
2278 View* prev = children_[index - 1];
2279 v->previous_focusable_view_ = prev;
2280 v->next_focusable_view_ = prev->next_focusable_view_;
2281 prev->next_focusable_view_->previous_focusable_view_ = v;
2282 prev->next_focusable_view_ = v;
2283 } else {
2284 last_focusable_view->next_focusable_view_ = v;
2285 v->next_focusable_view_ = NULL;
2286 v->previous_focusable_view_ = last_focusable_view;
2288 } else {
2289 View* prev = children_[index]->GetPreviousFocusableView();
2290 v->previous_focusable_view_ = prev;
2291 v->next_focusable_view_ = children_[index];
2292 if (prev)
2293 prev->next_focusable_view_ = v;
2294 children_[index]->previous_focusable_view_ = v;
2299 void View::AdvanceFocusIfNecessary() {
2300 // Focus should only be advanced if this is the focused view and has become
2301 // unfocusable. If the view is still focusable or is not focused, we can
2302 // return early avoiding furthur unnecessary checks. Focusability check is
2303 // performed first as it tends to be faster.
2304 if (IsAccessibilityFocusable() || !HasFocus())
2305 return;
2307 FocusManager* focus_manager = GetFocusManager();
2308 if (focus_manager)
2309 focus_manager->AdvanceFocusIfNecessary();
2312 // System events ---------------------------------------------------------------
2314 void View::PropagateThemeChanged() {
2315 for (int i = child_count() - 1; i >= 0; --i)
2316 child_at(i)->PropagateThemeChanged();
2317 OnThemeChanged();
2320 void View::PropagateLocaleChanged() {
2321 for (int i = child_count() - 1; i >= 0; --i)
2322 child_at(i)->PropagateLocaleChanged();
2323 OnLocaleChanged();
2326 void View::PropagateDeviceScaleFactorChanged(float device_scale_factor) {
2327 for (int i = child_count() - 1; i >= 0; --i)
2328 child_at(i)->PropagateDeviceScaleFactorChanged(device_scale_factor);
2330 // If the view is drawing to the layer, OnDeviceScaleFactorChanged() is called
2331 // through LayerDelegate callback.
2332 if (!layer())
2333 OnDeviceScaleFactorChanged(device_scale_factor);
2336 // Tooltips --------------------------------------------------------------------
2338 void View::UpdateTooltip() {
2339 Widget* widget = GetWidget();
2340 // TODO(beng): The TooltipManager NULL check can be removed when we
2341 // consolidate Init() methods and make views_unittests Init() all
2342 // Widgets that it uses.
2343 if (widget && widget->GetTooltipManager())
2344 widget->GetTooltipManager()->UpdateTooltip();
2347 // Drag and drop ---------------------------------------------------------------
2349 bool View::DoDrag(const ui::LocatedEvent& event,
2350 const gfx::Point& press_pt,
2351 ui::DragDropTypes::DragEventSource source) {
2352 int drag_operations = GetDragOperations(press_pt);
2353 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2354 return false;
2356 Widget* widget = GetWidget();
2357 // We should only start a drag from an event, implying we have a widget.
2358 DCHECK(widget);
2360 // Don't attempt to start a drag while in the process of dragging. This is
2361 // especially important on X where we can get multiple mouse move events when
2362 // we start the drag.
2363 if (widget->dragged_view())
2364 return false;
2366 OSExchangeData data;
2367 WriteDragData(press_pt, &data);
2369 // Message the RootView to do the drag and drop. That way if we're removed
2370 // the RootView can detect it and avoid calling us back.
2371 gfx::Point widget_location(event.location());
2372 ConvertPointToWidget(this, &widget_location);
2373 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2374 // WARNING: we may have been deleted.
2375 return true;
2378 } // namespace views