ui: Cache the output of View::OnPaint when the View isn't invalid.
[chromium-blink-merge.git] / ui / views / view.cc
blobc79cc6c85de1c23cf005a3ee7df3acba5471c23b
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 bool is_invalidated = true;
752 if (context.CanCheckInvalid()) {
753 #if DCHECK_IS_ON()
754 gfx::Vector2d offset;
755 context.Visited(this);
756 View* view = this;
757 while (view->parent() && !view->layer()) {
758 DCHECK(view->GetTransform().IsIdentity());
759 offset += view->GetMirroredPosition().OffsetFromOrigin();
760 view = view->parent();
762 // The offset in the PaintContext should be the offset up to the paint root,
763 // which we compute and verify here.
764 DCHECK_EQ(context.PaintOffset().x(), offset.x());
765 DCHECK_EQ(context.PaintOffset().y(), offset.y());
766 // The above loop will stop when |view| is the paint root, which should be
767 // the root of the current paint walk, as verified by storing the root in
768 // the PaintContext.
769 DCHECK_EQ(context.RootVisited(), view);
770 #endif
772 // If the View wasn't invalidated, don't waste time painting it, the output
773 // would be culled.
774 is_invalidated = context.IsRectInvalid(GetLocalBounds());
777 if (!is_invalidated && context.ShouldEarlyOutOfPaintingWhenValid())
778 return;
780 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
782 // If the view is backed by a layer, it should paint with itself as the origin
783 // rather than relative to its parent.
784 scoped_ptr<ui::ClipTransformRecorder> clip_transform_recorder;
785 if (!layer()) {
786 clip_transform_recorder.reset(new ui::ClipTransformRecorder(context));
788 // Set the clip rect to the bounds of this View. Note that the X (or left)
789 // position we pass to ClipRect takes into consideration whether or not the
790 // View uses a right-to-left layout so that we paint the View in its
791 // mirrored position if need be.
792 gfx::Rect clip_rect_in_parent = bounds();
793 clip_rect_in_parent.Inset(clip_insets_);
794 if (parent_)
795 clip_rect_in_parent.set_x(
796 parent_->GetMirroredXForRect(clip_rect_in_parent));
797 clip_transform_recorder->ClipRect(clip_rect_in_parent);
799 // Translate the graphics such that 0,0 corresponds to where
800 // this View is located relative to its parent.
801 gfx::Transform transform_from_parent;
802 gfx::Vector2d offset_from_parent = GetMirroredPosition().OffsetFromOrigin();
803 transform_from_parent.Translate(offset_from_parent.x(),
804 offset_from_parent.y());
805 transform_from_parent.PreconcatTransform(GetTransform());
806 clip_transform_recorder->Transform(transform_from_parent);
809 if (is_invalidated || !paint_cache_.UseCache(context)) {
810 ui::PaintRecorder recorder(context, &paint_cache_);
811 gfx::Canvas* canvas = recorder.canvas();
812 gfx::ScopedCanvas scoped_canvas(canvas);
814 // If the View we are about to paint requested the canvas to be flipped, we
815 // should change the transform appropriately.
816 // The canvas mirroring is undone once the View is done painting so that we
817 // don't pass the canvas with the mirrored transform to Views that didn't
818 // request the canvas to be flipped.
819 if (FlipCanvasOnPaintForRTLUI()) {
820 canvas->Translate(gfx::Vector2d(width(), 0));
821 canvas->Scale(-1, 1);
824 // Delegate painting the contents of the View to the virtual OnPaint method.
825 OnPaint(canvas);
828 // View::Paint() recursion over the subtree.
829 PaintChildren(context);
832 void View::set_background(Background* b) {
833 background_.reset(b);
836 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
838 ui::ThemeProvider* View::GetThemeProvider() const {
839 const Widget* widget = GetWidget();
840 return widget ? widget->GetThemeProvider() : NULL;
843 const ui::NativeTheme* View::GetNativeTheme() const {
844 const Widget* widget = GetWidget();
845 return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
848 // Input -----------------------------------------------------------------------
850 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
851 return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
854 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
855 return GetEffectiveViewTargeter()->TargetForRect(this, rect);
858 bool View::CanProcessEventsWithinSubtree() const {
859 return true;
862 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
863 // TODO(tdanderson): Move this implementation into ViewTargetDelegate.
864 if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree())
865 return NULL;
867 // Walk the child Views recursively looking for the View that most
868 // tightly encloses the specified point.
869 for (int i = child_count() - 1; i >= 0; --i) {
870 View* child = child_at(i);
871 if (!child->visible())
872 continue;
874 gfx::Point point_in_child_coords(point);
875 ConvertPointToTarget(this, child, &point_in_child_coords);
876 View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
877 if (handler)
878 return handler;
880 return this;
883 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
884 #if defined(OS_WIN)
885 static ui::Cursor arrow;
886 if (!arrow.platform())
887 arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
888 return arrow;
889 #else
890 return gfx::kNullCursor;
891 #endif
894 bool View::HitTestPoint(const gfx::Point& point) const {
895 return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
898 bool View::HitTestRect(const gfx::Rect& rect) const {
899 return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect);
902 bool View::IsMouseHovered() {
903 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
904 // hovered.
905 if (!GetWidget())
906 return false;
908 // If mouse events are disabled, then the mouse cursor is invisible and
909 // is therefore not hovering over this button.
910 if (!GetWidget()->IsMouseEventsEnabled())
911 return false;
913 gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
914 GetWidget()->GetNativeView())->GetCursorScreenPoint());
915 ConvertPointFromScreen(this, &cursor_pos);
916 return HitTestPoint(cursor_pos);
919 bool View::OnMousePressed(const ui::MouseEvent& event) {
920 return false;
923 bool View::OnMouseDragged(const ui::MouseEvent& event) {
924 return false;
927 void View::OnMouseReleased(const ui::MouseEvent& event) {
930 void View::OnMouseCaptureLost() {
933 void View::OnMouseMoved(const ui::MouseEvent& event) {
936 void View::OnMouseEntered(const ui::MouseEvent& event) {
939 void View::OnMouseExited(const ui::MouseEvent& event) {
942 void View::SetMouseHandler(View* new_mouse_handler) {
943 // |new_mouse_handler| may be NULL.
944 if (parent_)
945 parent_->SetMouseHandler(new_mouse_handler);
948 bool View::OnKeyPressed(const ui::KeyEvent& event) {
949 return false;
952 bool View::OnKeyReleased(const ui::KeyEvent& event) {
953 return false;
956 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
957 return false;
960 void View::OnKeyEvent(ui::KeyEvent* event) {
961 bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
962 OnKeyReleased(*event);
963 if (consumed)
964 event->StopPropagation();
967 void View::OnMouseEvent(ui::MouseEvent* event) {
968 switch (event->type()) {
969 case ui::ET_MOUSE_PRESSED:
970 if (ProcessMousePressed(*event))
971 event->SetHandled();
972 return;
974 case ui::ET_MOUSE_MOVED:
975 if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
976 ui::EF_RIGHT_MOUSE_BUTTON |
977 ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
978 OnMouseMoved(*event);
979 return;
981 // FALL-THROUGH
982 case ui::ET_MOUSE_DRAGGED:
983 if (ProcessMouseDragged(*event))
984 event->SetHandled();
985 return;
987 case ui::ET_MOUSE_RELEASED:
988 ProcessMouseReleased(*event);
989 return;
991 case ui::ET_MOUSEWHEEL:
992 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
993 event->SetHandled();
994 break;
996 case ui::ET_MOUSE_ENTERED:
997 if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY)
998 NotifyAccessibilityEvent(ui::AX_EVENT_HOVER, true);
999 OnMouseEntered(*event);
1000 break;
1002 case ui::ET_MOUSE_EXITED:
1003 OnMouseExited(*event);
1004 break;
1006 default:
1007 return;
1011 void View::OnScrollEvent(ui::ScrollEvent* event) {
1014 void View::OnTouchEvent(ui::TouchEvent* event) {
1015 NOTREACHED() << "Views should not receive touch events.";
1018 void View::OnGestureEvent(ui::GestureEvent* event) {
1021 ui::TextInputClient* View::GetTextInputClient() {
1022 return NULL;
1025 InputMethod* View::GetInputMethod() {
1026 Widget* widget = GetWidget();
1027 return widget ? widget->GetInputMethod() : NULL;
1030 const InputMethod* View::GetInputMethod() const {
1031 const Widget* widget = GetWidget();
1032 return widget ? widget->GetInputMethod() : NULL;
1035 scoped_ptr<ViewTargeter>
1036 View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) {
1037 scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass();
1038 targeter_ = targeter.Pass();
1039 return old_targeter.Pass();
1042 ViewTargeter* View::GetEffectiveViewTargeter() const {
1043 DCHECK(GetWidget());
1044 ViewTargeter* view_targeter = targeter();
1045 if (!view_targeter)
1046 view_targeter = GetWidget()->GetRootView()->targeter();
1047 CHECK(view_targeter);
1048 return view_targeter;
1051 bool View::CanAcceptEvent(const ui::Event& event) {
1052 return IsDrawn();
1055 ui::EventTarget* View::GetParentTarget() {
1056 return parent_;
1059 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1060 return make_scoped_ptr(new ui::EventTargetIteratorImpl<View>(children_));
1063 ui::EventTargeter* View::GetEventTargeter() {
1064 return targeter_.get();
1067 void View::ConvertEventToTarget(ui::EventTarget* target,
1068 ui::LocatedEvent* event) {
1069 event->ConvertLocationToTarget(this, static_cast<View*>(target));
1072 // Accelerators ----------------------------------------------------------------
1074 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1075 if (!accelerators_.get())
1076 accelerators_.reset(new std::vector<ui::Accelerator>());
1078 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1079 accelerators_->end()) {
1080 accelerators_->push_back(accelerator);
1082 RegisterPendingAccelerators();
1085 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1086 if (!accelerators_.get()) {
1087 NOTREACHED() << "Removing non-existing accelerator";
1088 return;
1091 std::vector<ui::Accelerator>::iterator i(
1092 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1093 if (i == accelerators_->end()) {
1094 NOTREACHED() << "Removing non-existing accelerator";
1095 return;
1098 size_t index = i - accelerators_->begin();
1099 accelerators_->erase(i);
1100 if (index >= registered_accelerator_count_) {
1101 // The accelerator is not registered to FocusManager.
1102 return;
1104 --registered_accelerator_count_;
1106 // Providing we are attached to a Widget and registered with a focus manager,
1107 // we should de-register from that focus manager now.
1108 if (GetWidget() && accelerator_focus_manager_)
1109 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1112 void View::ResetAccelerators() {
1113 if (accelerators_.get())
1114 UnregisterAccelerators(false);
1117 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1118 return false;
1121 bool View::CanHandleAccelerators() const {
1122 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1125 // Focus -----------------------------------------------------------------------
1127 bool View::HasFocus() const {
1128 const FocusManager* focus_manager = GetFocusManager();
1129 return focus_manager && (focus_manager->GetFocusedView() == this);
1132 View* View::GetNextFocusableView() {
1133 return next_focusable_view_;
1136 const View* View::GetNextFocusableView() const {
1137 return next_focusable_view_;
1140 View* View::GetPreviousFocusableView() {
1141 return previous_focusable_view_;
1144 void View::SetNextFocusableView(View* view) {
1145 if (view)
1146 view->previous_focusable_view_ = this;
1147 next_focusable_view_ = view;
1150 void View::SetFocusable(bool focusable) {
1151 if (focusable_ == focusable)
1152 return;
1154 focusable_ = focusable;
1155 AdvanceFocusIfNecessary();
1158 bool View::IsFocusable() const {
1159 return focusable_ && enabled_ && IsDrawn();
1162 bool View::IsAccessibilityFocusable() const {
1163 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1166 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1167 if (accessibility_focusable_ == accessibility_focusable)
1168 return;
1170 accessibility_focusable_ = accessibility_focusable;
1171 AdvanceFocusIfNecessary();
1174 FocusManager* View::GetFocusManager() {
1175 Widget* widget = GetWidget();
1176 return widget ? widget->GetFocusManager() : NULL;
1179 const FocusManager* View::GetFocusManager() const {
1180 const Widget* widget = GetWidget();
1181 return widget ? widget->GetFocusManager() : NULL;
1184 void View::RequestFocus() {
1185 FocusManager* focus_manager = GetFocusManager();
1186 if (focus_manager && IsFocusable())
1187 focus_manager->SetFocusedView(this);
1190 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1191 return false;
1194 FocusTraversable* View::GetFocusTraversable() {
1195 return NULL;
1198 FocusTraversable* View::GetPaneFocusTraversable() {
1199 return NULL;
1202 // Tooltips --------------------------------------------------------------------
1204 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1205 return false;
1208 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1209 return false;
1212 // Context menus ---------------------------------------------------------------
1214 void View::ShowContextMenu(const gfx::Point& p,
1215 ui::MenuSourceType source_type) {
1216 if (!context_menu_controller_)
1217 return;
1219 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1222 // static
1223 bool View::ShouldShowContextMenuOnMousePress() {
1224 return kContextMenuOnMousePress;
1227 // Drag and drop ---------------------------------------------------------------
1229 bool View::GetDropFormats(
1230 int* formats,
1231 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1232 return false;
1235 bool View::AreDropTypesRequired() {
1236 return false;
1239 bool View::CanDrop(const OSExchangeData& data) {
1240 // TODO(sky): when I finish up migration, this should default to true.
1241 return false;
1244 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1247 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1248 return ui::DragDropTypes::DRAG_NONE;
1251 void View::OnDragExited() {
1254 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1255 return ui::DragDropTypes::DRAG_NONE;
1258 void View::OnDragDone() {
1261 // static
1262 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1263 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1264 abs(delta.y()) > GetVerticalDragThreshold());
1267 // Accessibility----------------------------------------------------------------
1269 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1270 if (!native_view_accessibility_)
1271 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1272 if (native_view_accessibility_)
1273 return native_view_accessibility_->GetNativeObject();
1274 return NULL;
1277 void View::NotifyAccessibilityEvent(
1278 ui::AXEvent event_type,
1279 bool send_native_event) {
1280 if (ViewsDelegate::views_delegate)
1281 ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1283 if (send_native_event && GetWidget()) {
1284 if (!native_view_accessibility_)
1285 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1286 if (native_view_accessibility_)
1287 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1291 // Scrolling -------------------------------------------------------------------
1293 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1294 // We must take RTL UI mirroring into account when adjusting the position of
1295 // the region.
1296 if (parent_) {
1297 gfx::Rect scroll_rect(rect);
1298 scroll_rect.Offset(GetMirroredX(), y());
1299 parent_->ScrollRectToVisible(scroll_rect);
1303 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1304 bool is_horizontal, bool is_positive) {
1305 return 0;
1308 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1309 bool is_horizontal, bool is_positive) {
1310 return 0;
1313 ////////////////////////////////////////////////////////////////////////////////
1314 // View, protected:
1316 // Size and disposition --------------------------------------------------------
1318 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1321 void View::PreferredSizeChanged() {
1322 InvalidateLayout();
1323 if (parent_)
1324 parent_->ChildPreferredSizeChanged(this);
1327 bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
1328 return false;
1331 void View::OnVisibleBoundsChanged() {
1334 // Tree operations -------------------------------------------------------------
1336 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1339 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1342 void View::NativeViewHierarchyChanged() {
1343 FocusManager* focus_manager = GetFocusManager();
1344 if (accelerator_focus_manager_ != focus_manager) {
1345 UnregisterAccelerators(true);
1347 if (focus_manager)
1348 RegisterPendingAccelerators();
1352 // Painting --------------------------------------------------------------------
1354 void View::PaintChildren(const ui::PaintContext& context) {
1355 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1356 for (int i = 0, count = child_count(); i < count; ++i)
1357 if (!child_at(i)->layer())
1358 child_at(i)->Paint(context);
1361 void View::OnPaint(gfx::Canvas* canvas) {
1362 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1363 OnPaintBackground(canvas);
1364 OnPaintBorder(canvas);
1367 void View::OnPaintBackground(gfx::Canvas* canvas) {
1368 if (background_.get()) {
1369 TRACE_EVENT2("views", "View::OnPaintBackground",
1370 "width", canvas->sk_canvas()->getDevice()->width(),
1371 "height", canvas->sk_canvas()->getDevice()->height());
1372 background_->Paint(canvas, this);
1376 void View::OnPaintBorder(gfx::Canvas* canvas) {
1377 if (border_.get()) {
1378 TRACE_EVENT2("views", "View::OnPaintBorder",
1379 "width", canvas->sk_canvas()->getDevice()->width(),
1380 "height", canvas->sk_canvas()->getDevice()->height());
1381 border_->Paint(*this, canvas);
1385 // Accelerated Painting --------------------------------------------------------
1387 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1388 // This method should not have the side-effect of creating the layer.
1389 if (layer())
1390 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1393 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1394 ui::Layer** layer_parent) {
1395 if (layer()) {
1396 if (layer_parent)
1397 *layer_parent = layer();
1398 return gfx::Vector2d();
1400 if (!parent_)
1401 return gfx::Vector2d();
1403 return gfx::Vector2d(GetMirroredX(), y()) +
1404 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1407 void View::UpdateParentLayer() {
1408 if (!layer())
1409 return;
1411 ui::Layer* parent_layer = NULL;
1412 gfx::Vector2d offset(GetMirroredX(), y());
1414 if (parent_)
1415 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1417 ReparentLayer(offset, parent_layer);
1420 void View::MoveLayerToParent(ui::Layer* parent_layer,
1421 const gfx::Point& point) {
1422 gfx::Point local_point(point);
1423 if (parent_layer != layer())
1424 local_point.Offset(GetMirroredX(), y());
1425 if (layer() && parent_layer != layer()) {
1426 parent_layer->Add(layer());
1427 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1428 width(), height()));
1429 } else {
1430 for (int i = 0, count = child_count(); i < count; ++i)
1431 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1435 void View::UpdateLayerVisibility() {
1436 bool visible = visible_;
1437 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1438 visible = v->visible();
1440 UpdateChildLayerVisibility(visible);
1443 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1444 if (layer()) {
1445 layer()->SetVisible(ancestor_visible && visible_);
1446 } else {
1447 for (int i = 0, count = child_count(); i < count; ++i)
1448 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1452 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1453 if (layer()) {
1454 SetLayerBounds(GetLocalBounds() + offset);
1455 } else {
1456 for (int i = 0, count = child_count(); i < count; ++i) {
1457 View* child = child_at(i);
1458 child->UpdateChildLayerBounds(
1459 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1464 void View::OnPaintLayer(const ui::PaintContext& context) {
1465 if (!layer()->fills_bounds_opaquely()) {
1466 ui::PaintRecorder recorder(context);
1467 recorder.canvas()->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1469 if (!visible_)
1470 return;
1471 Paint(context);
1474 void View::OnDelegatedFrameDamage(
1475 const gfx::Rect& damage_rect_in_dip) {
1478 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1479 snap_layer_to_pixel_boundary_ =
1480 (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1481 SnapLayerToPixelBoundary();
1482 // Repainting with new scale factor will paint the content at the right scale.
1485 base::Closure View::PrepareForLayerBoundsChange() {
1486 return base::Closure();
1489 void View::ReorderLayers() {
1490 View* v = this;
1491 while (v && !v->layer())
1492 v = v->parent();
1494 Widget* widget = GetWidget();
1495 if (!v) {
1496 if (widget) {
1497 ui::Layer* layer = widget->GetLayer();
1498 if (layer)
1499 widget->GetRootView()->ReorderChildLayers(layer);
1501 } else {
1502 v->ReorderChildLayers(v->layer());
1505 if (widget) {
1506 // Reorder the widget's child NativeViews in case a child NativeView is
1507 // associated with a view (eg via a NativeViewHost). Always do the
1508 // reordering because the associated NativeView's layer (if it has one)
1509 // is parented to the widget's layer regardless of whether the host view has
1510 // an ancestor with a layer.
1511 widget->ReorderNativeViews();
1515 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1516 if (layer() && layer() != parent_layer) {
1517 DCHECK_EQ(parent_layer, layer()->parent());
1518 parent_layer->StackAtBottom(layer());
1519 } else {
1520 // Iterate backwards through the children so that a child with a layer
1521 // which is further to the back is stacked above one which is further to
1522 // the front.
1523 for (Views::reverse_iterator it(children_.rbegin());
1524 it != children_.rend(); ++it) {
1525 (*it)->ReorderChildLayers(parent_layer);
1530 // Input -----------------------------------------------------------------------
1532 View::DragInfo* View::GetDragInfo() {
1533 return parent_ ? parent_->GetDragInfo() : NULL;
1536 // Focus -----------------------------------------------------------------------
1538 void View::OnFocus() {
1539 // TODO(beng): Investigate whether it's possible for us to move this to
1540 // Focus().
1541 // By default, we clear the native focus. This ensures that no visible native
1542 // view as the focus and that we still receive keyboard inputs.
1543 FocusManager* focus_manager = GetFocusManager();
1544 if (focus_manager)
1545 focus_manager->ClearNativeFocus();
1547 // TODO(beng): Investigate whether it's possible for us to move this to
1548 // Focus().
1549 // Notify assistive technologies of the focus change.
1550 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1553 void View::OnBlur() {
1556 void View::Focus() {
1557 OnFocus();
1560 void View::Blur() {
1561 OnBlur();
1564 // Tooltips --------------------------------------------------------------------
1566 void View::TooltipTextChanged() {
1567 Widget* widget = GetWidget();
1568 // TooltipManager may be null if there is a problem creating it.
1569 if (widget && widget->GetTooltipManager())
1570 widget->GetTooltipManager()->TooltipTextChanged(this);
1573 // Context menus ---------------------------------------------------------------
1575 gfx::Point View::GetKeyboardContextMenuLocation() {
1576 gfx::Rect vis_bounds = GetVisibleBounds();
1577 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1578 vis_bounds.y() + vis_bounds.height() / 2);
1579 ConvertPointToScreen(this, &screen_point);
1580 return screen_point;
1583 // Drag and drop ---------------------------------------------------------------
1585 int View::GetDragOperations(const gfx::Point& press_pt) {
1586 return drag_controller_ ?
1587 drag_controller_->GetDragOperationsForView(this, press_pt) :
1588 ui::DragDropTypes::DRAG_NONE;
1591 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1592 DCHECK(drag_controller_);
1593 drag_controller_->WriteDragDataForView(this, press_pt, data);
1596 bool View::InDrag() {
1597 Widget* widget = GetWidget();
1598 return widget ? widget->dragged_view() == this : false;
1601 int View::GetHorizontalDragThreshold() {
1602 // TODO(jennyz): This value may need to be adjusted for different platforms
1603 // and for different display density.
1604 return kDefaultHorizontalDragThreshold;
1607 int View::GetVerticalDragThreshold() {
1608 // TODO(jennyz): This value may need to be adjusted for different platforms
1609 // and for different display density.
1610 return kDefaultVerticalDragThreshold;
1613 // Debugging -------------------------------------------------------------------
1615 #if !defined(NDEBUG)
1617 std::string View::PrintViewGraph(bool first) {
1618 return DoPrintViewGraph(first, this);
1621 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1622 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1623 const size_t kMaxPointerStringLength = 19;
1625 std::string result;
1627 if (first)
1628 result.append("digraph {\n");
1630 // Node characteristics.
1631 char p[kMaxPointerStringLength];
1633 const std::string class_name(GetClassName());
1634 size_t base_name_index = class_name.find_last_of('/');
1635 if (base_name_index == std::string::npos)
1636 base_name_index = 0;
1637 else
1638 base_name_index++;
1640 char bounds_buffer[512];
1642 // Information about current node.
1643 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1644 result.append(" N");
1645 result.append(p + 2);
1646 result.append(" [label=\"");
1648 result.append(class_name.substr(base_name_index).c_str());
1650 base::snprintf(bounds_buffer,
1651 arraysize(bounds_buffer),
1652 "\\n bounds: (%d, %d), (%dx%d)",
1653 bounds().x(),
1654 bounds().y(),
1655 bounds().width(),
1656 bounds().height());
1657 result.append(bounds_buffer);
1659 gfx::DecomposedTransform decomp;
1660 if (!GetTransform().IsIdentity() &&
1661 gfx::DecomposeTransform(&decomp, GetTransform())) {
1662 base::snprintf(bounds_buffer,
1663 arraysize(bounds_buffer),
1664 "\\n translation: (%f, %f)",
1665 decomp.translate[0],
1666 decomp.translate[1]);
1667 result.append(bounds_buffer);
1669 base::snprintf(bounds_buffer,
1670 arraysize(bounds_buffer),
1671 "\\n rotation: %3.2f",
1672 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1673 result.append(bounds_buffer);
1675 base::snprintf(bounds_buffer,
1676 arraysize(bounds_buffer),
1677 "\\n scale: (%2.4f, %2.4f)",
1678 decomp.scale[0],
1679 decomp.scale[1]);
1680 result.append(bounds_buffer);
1683 result.append("\"");
1684 if (!parent_)
1685 result.append(", shape=box");
1686 if (layer()) {
1687 if (layer()->has_external_content())
1688 result.append(", color=green");
1689 else
1690 result.append(", color=red");
1692 if (layer()->fills_bounds_opaquely())
1693 result.append(", style=filled");
1695 result.append("]\n");
1697 // Link to parent.
1698 if (parent_) {
1699 char pp[kMaxPointerStringLength];
1701 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1702 result.append(" N");
1703 result.append(pp + 2);
1704 result.append(" -> N");
1705 result.append(p + 2);
1706 result.append("\n");
1709 // Children.
1710 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1711 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1713 if (first)
1714 result.append("}\n");
1716 return result;
1718 #endif
1720 ////////////////////////////////////////////////////////////////////////////////
1721 // View, private:
1723 // DropInfo --------------------------------------------------------------------
1725 void View::DragInfo::Reset() {
1726 possible_drag = false;
1727 start_pt = gfx::Point();
1730 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1731 possible_drag = true;
1732 start_pt = p;
1735 // Painting --------------------------------------------------------------------
1737 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1738 // If we have a layer and the View's size did not change, we do not need to
1739 // schedule any paints since the layer will be redrawn at its new location
1740 // during the next Draw() cycle in the compositor.
1741 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1742 // Otherwise, if the size changes or we don't have a layer then we need to
1743 // use SchedulePaint to invalidate the area occupied by the View.
1744 SchedulePaint();
1745 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1746 // The compositor doesn't Draw() until something on screen changes, so
1747 // if our position changes but nothing is being animated on screen, then
1748 // tell the compositor to redraw the scene. We know layer() exists due to
1749 // the above if clause.
1750 layer()->ScheduleDraw();
1754 // Tree operations -------------------------------------------------------------
1756 void View::DoRemoveChildView(View* view,
1757 bool update_focus_cycle,
1758 bool update_tool_tip,
1759 bool delete_removed_view,
1760 View* new_parent) {
1761 DCHECK(view);
1763 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1764 scoped_ptr<View> view_to_be_deleted;
1765 if (i != children_.end()) {
1766 if (update_focus_cycle) {
1767 // Let's remove the view from the focus traversal.
1768 View* next_focusable = view->next_focusable_view_;
1769 View* prev_focusable = view->previous_focusable_view_;
1770 if (prev_focusable)
1771 prev_focusable->next_focusable_view_ = next_focusable;
1772 if (next_focusable)
1773 next_focusable->previous_focusable_view_ = prev_focusable;
1776 if (GetWidget()) {
1777 UnregisterChildrenForVisibleBoundsNotification(view);
1778 if (view->visible())
1779 view->SchedulePaint();
1780 GetWidget()->NotifyWillRemoveView(view);
1783 view->PropagateRemoveNotifications(this, new_parent);
1784 view->parent_ = NULL;
1785 view->UpdateLayerVisibility();
1787 if (delete_removed_view && !view->owned_by_client_)
1788 view_to_be_deleted.reset(view);
1790 children_.erase(i);
1793 if (update_tool_tip)
1794 UpdateTooltip();
1796 if (layout_manager_.get())
1797 layout_manager_->ViewRemoved(this, view);
1800 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1801 for (int i = 0, count = child_count(); i < count; ++i)
1802 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1804 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1805 for (View* v = this; v; v = v->parent_)
1806 v->ViewHierarchyChangedImpl(true, details);
1809 void View::PropagateAddNotifications(
1810 const ViewHierarchyChangedDetails& details) {
1811 for (int i = 0, count = child_count(); i < count; ++i)
1812 child_at(i)->PropagateAddNotifications(details);
1813 ViewHierarchyChangedImpl(true, details);
1816 void View::PropagateNativeViewHierarchyChanged() {
1817 for (int i = 0, count = child_count(); i < count; ++i)
1818 child_at(i)->PropagateNativeViewHierarchyChanged();
1819 NativeViewHierarchyChanged();
1822 void View::ViewHierarchyChangedImpl(
1823 bool register_accelerators,
1824 const ViewHierarchyChangedDetails& details) {
1825 if (register_accelerators) {
1826 if (details.is_add) {
1827 // If you get this registration, you are part of a subtree that has been
1828 // added to the view hierarchy.
1829 if (GetFocusManager())
1830 RegisterPendingAccelerators();
1831 } else {
1832 if (details.child == this)
1833 UnregisterAccelerators(true);
1837 if (details.is_add && layer() && !layer()->parent()) {
1838 UpdateParentLayer();
1839 Widget* widget = GetWidget();
1840 if (widget)
1841 widget->UpdateRootLayers();
1842 } else if (!details.is_add && details.child == this) {
1843 // Make sure the layers belonging to the subtree rooted at |child| get
1844 // removed from layers that do not belong in the same subtree.
1845 OrphanLayers();
1846 Widget* widget = GetWidget();
1847 if (widget)
1848 widget->UpdateRootLayers();
1851 ViewHierarchyChanged(details);
1852 details.parent->needs_layout_ = true;
1855 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1856 for (int i = 0, count = child_count(); i < count; ++i)
1857 child_at(i)->PropagateNativeThemeChanged(theme);
1858 OnNativeThemeChanged(theme);
1861 // Size and disposition --------------------------------------------------------
1863 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1864 for (int i = 0, count = child_count(); i < count; ++i)
1865 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1866 VisibilityChangedImpl(start, is_visible);
1869 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1870 VisibilityChanged(starting_from, is_visible);
1873 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1874 if (visible_) {
1875 // Paint the new bounds.
1876 SchedulePaintBoundsChanged(
1877 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1878 SCHEDULE_PAINT_SIZE_CHANGED);
1881 if (layer()) {
1882 if (parent_) {
1883 SetLayerBounds(GetLocalBounds() +
1884 gfx::Vector2d(GetMirroredX(), y()) +
1885 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1886 } else {
1887 SetLayerBounds(bounds_);
1890 // In RTL mode, if our width has changed, our children's mirrored bounds
1891 // will have changed. Update the child's layer bounds, or if it is not a
1892 // layer, the bounds of any layers inside the child.
1893 if (base::i18n::IsRTL() && bounds_.width() != previous_bounds.width()) {
1894 for (int i = 0; i < child_count(); ++i) {
1895 View* child = child_at(i);
1896 child->UpdateChildLayerBounds(
1897 gfx::Vector2d(child->GetMirroredX(), child->y()));
1900 } else {
1901 // If our bounds have changed, then any descendant layer bounds may have
1902 // changed. Update them accordingly.
1903 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1906 OnBoundsChanged(previous_bounds);
1908 if (previous_bounds.size() != size()) {
1909 needs_layout_ = false;
1910 Layout();
1913 if (GetNeedsNotificationWhenVisibleBoundsChange())
1914 OnVisibleBoundsChanged();
1916 // Notify interested Views that visible bounds within the root view may have
1917 // changed.
1918 if (descendants_to_notify_.get()) {
1919 for (Views::iterator i(descendants_to_notify_->begin());
1920 i != descendants_to_notify_->end(); ++i) {
1921 (*i)->OnVisibleBoundsChanged();
1926 // static
1927 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1928 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1929 view->RegisterForVisibleBoundsNotification();
1930 for (int i = 0; i < view->child_count(); ++i)
1931 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1934 // static
1935 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1936 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1937 view->UnregisterForVisibleBoundsNotification();
1938 for (int i = 0; i < view->child_count(); ++i)
1939 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1942 void View::RegisterForVisibleBoundsNotification() {
1943 if (registered_for_visible_bounds_notification_)
1944 return;
1946 registered_for_visible_bounds_notification_ = true;
1947 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1948 ancestor->AddDescendantToNotify(this);
1951 void View::UnregisterForVisibleBoundsNotification() {
1952 if (!registered_for_visible_bounds_notification_)
1953 return;
1955 registered_for_visible_bounds_notification_ = false;
1956 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1957 ancestor->RemoveDescendantToNotify(this);
1960 void View::AddDescendantToNotify(View* view) {
1961 DCHECK(view);
1962 if (!descendants_to_notify_.get())
1963 descendants_to_notify_.reset(new Views);
1964 descendants_to_notify_->push_back(view);
1967 void View::RemoveDescendantToNotify(View* view) {
1968 DCHECK(view && descendants_to_notify_.get());
1969 Views::iterator i(std::find(
1970 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1971 DCHECK(i != descendants_to_notify_->end());
1972 descendants_to_notify_->erase(i);
1973 if (descendants_to_notify_->empty())
1974 descendants_to_notify_.reset();
1977 void View::SetLayerBounds(const gfx::Rect& bounds) {
1978 layer()->SetBounds(bounds);
1979 SnapLayerToPixelBoundary();
1982 // Transformations -------------------------------------------------------------
1984 bool View::GetTransformRelativeTo(const View* ancestor,
1985 gfx::Transform* transform) const {
1986 const View* p = this;
1988 while (p && p != ancestor) {
1989 transform->ConcatTransform(p->GetTransform());
1990 gfx::Transform translation;
1991 translation.Translate(static_cast<float>(p->GetMirroredX()),
1992 static_cast<float>(p->y()));
1993 transform->ConcatTransform(translation);
1995 p = p->parent_;
1998 return p == ancestor;
2001 // Coordinate conversion -------------------------------------------------------
2003 bool View::ConvertPointForAncestor(const View* ancestor,
2004 gfx::Point* point) const {
2005 gfx::Transform trans;
2006 // TODO(sad): Have some way of caching the transformation results.
2007 bool result = GetTransformRelativeTo(ancestor, &trans);
2008 gfx::Point3F p(*point);
2009 trans.TransformPoint(&p);
2010 *point = gfx::ToFlooredPoint(p.AsPointF());
2011 return result;
2014 bool View::ConvertPointFromAncestor(const View* ancestor,
2015 gfx::Point* point) const {
2016 gfx::Transform trans;
2017 bool result = GetTransformRelativeTo(ancestor, &trans);
2018 gfx::Point3F p(*point);
2019 trans.TransformPointReverse(&p);
2020 *point = gfx::ToFlooredPoint(p.AsPointF());
2021 return result;
2024 bool View::ConvertRectForAncestor(const View* ancestor,
2025 gfx::RectF* rect) const {
2026 gfx::Transform trans;
2027 // TODO(sad): Have some way of caching the transformation results.
2028 bool result = GetTransformRelativeTo(ancestor, &trans);
2029 trans.TransformRect(rect);
2030 return result;
2033 bool View::ConvertRectFromAncestor(const View* ancestor,
2034 gfx::RectF* rect) const {
2035 gfx::Transform trans;
2036 bool result = GetTransformRelativeTo(ancestor, &trans);
2037 trans.TransformRectReverse(rect);
2038 return result;
2041 // Accelerated painting --------------------------------------------------------
2043 void View::CreateLayer() {
2044 // A new layer is being created for the view. So all the layers of the
2045 // sub-tree can inherit the visibility of the corresponding view.
2046 for (int i = 0, count = child_count(); i < count; ++i)
2047 child_at(i)->UpdateChildLayerVisibility(true);
2049 SetLayer(new ui::Layer());
2050 layer()->set_delegate(this);
2051 #if !defined(NDEBUG)
2052 layer()->set_name(GetClassName());
2053 #endif
2055 UpdateParentLayers();
2056 UpdateLayerVisibility();
2058 // The new layer needs to be ordered in the layer tree according
2059 // to the view tree. Children of this layer were added in order
2060 // in UpdateParentLayers().
2061 if (parent())
2062 parent()->ReorderLayers();
2064 Widget* widget = GetWidget();
2065 if (widget)
2066 widget->UpdateRootLayers();
2069 void View::UpdateParentLayers() {
2070 // Attach all top-level un-parented layers.
2071 if (layer() && !layer()->parent()) {
2072 UpdateParentLayer();
2073 } else {
2074 for (int i = 0, count = child_count(); i < count; ++i)
2075 child_at(i)->UpdateParentLayers();
2079 void View::OrphanLayers() {
2080 if (layer()) {
2081 if (layer()->parent())
2082 layer()->parent()->Remove(layer());
2084 // The layer belonging to this View has already been orphaned. It is not
2085 // necessary to orphan the child layers.
2086 return;
2088 for (int i = 0, count = child_count(); i < count; ++i)
2089 child_at(i)->OrphanLayers();
2092 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2093 layer()->SetBounds(GetLocalBounds() + offset);
2094 DCHECK_NE(layer(), parent_layer);
2095 if (parent_layer)
2096 parent_layer->Add(layer());
2097 layer()->SchedulePaint(GetLocalBounds());
2098 MoveLayerToParent(layer(), gfx::Point());
2101 void View::DestroyLayer() {
2102 ui::Layer* new_parent = layer()->parent();
2103 std::vector<ui::Layer*> children = layer()->children();
2104 for (size_t i = 0; i < children.size(); ++i) {
2105 layer()->Remove(children[i]);
2106 if (new_parent)
2107 new_parent->Add(children[i]);
2110 LayerOwner::DestroyLayer();
2112 if (new_parent)
2113 ReorderLayers();
2115 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2117 SchedulePaint();
2119 Widget* widget = GetWidget();
2120 if (widget)
2121 widget->UpdateRootLayers();
2124 // Input -----------------------------------------------------------------------
2126 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2127 int drag_operations =
2128 (enabled_ && event.IsOnlyLeftMouseButton() &&
2129 HitTestPoint(event.location())) ?
2130 GetDragOperations(event.location()) : 0;
2131 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2132 context_menu_controller_ : 0;
2133 View::DragInfo* drag_info = GetDragInfo();
2135 // TODO(sky): for debugging 360238.
2136 int storage_id = 0;
2137 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2138 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2139 ViewStorage* view_storage = ViewStorage::GetInstance();
2140 storage_id = view_storage->CreateStorageID();
2141 view_storage->StoreView(storage_id, this);
2144 const bool enabled = enabled_;
2145 const bool result = OnMousePressed(event);
2147 if (!enabled)
2148 return result;
2150 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2151 kContextMenuOnMousePress) {
2152 // Assume that if there is a context menu controller we won't be deleted
2153 // from mouse pressed.
2154 gfx::Point location(event.location());
2155 if (HitTestPoint(location)) {
2156 if (storage_id != 0)
2157 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2158 ConvertPointToScreen(this, &location);
2159 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2160 return true;
2164 // WARNING: we may have been deleted, don't use any View variables.
2165 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2166 drag_info->PossibleDrag(event.location());
2167 return true;
2169 return !!context_menu_controller || result;
2172 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2173 // Copy the field, that way if we're deleted after drag and drop no harm is
2174 // done.
2175 ContextMenuController* context_menu_controller = context_menu_controller_;
2176 const bool possible_drag = GetDragInfo()->possible_drag;
2177 if (possible_drag &&
2178 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2179 (!drag_controller_ ||
2180 drag_controller_->CanStartDragForView(
2181 this, GetDragInfo()->start_pt, event.location()))) {
2182 DoDrag(event, GetDragInfo()->start_pt,
2183 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2184 } else {
2185 if (OnMouseDragged(event))
2186 return true;
2187 // Fall through to return value based on context menu controller.
2189 // WARNING: we may have been deleted.
2190 return (context_menu_controller != NULL) || possible_drag;
2193 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2194 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2195 event.IsOnlyRightMouseButton()) {
2196 // Assume that if there is a context menu controller we won't be deleted
2197 // from mouse released.
2198 gfx::Point location(event.location());
2199 OnMouseReleased(event);
2200 if (HitTestPoint(location)) {
2201 ConvertPointToScreen(this, &location);
2202 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2204 } else {
2205 OnMouseReleased(event);
2207 // WARNING: we may have been deleted.
2210 // Accelerators ----------------------------------------------------------------
2212 void View::RegisterPendingAccelerators() {
2213 if (!accelerators_.get() ||
2214 registered_accelerator_count_ == accelerators_->size()) {
2215 // No accelerators are waiting for registration.
2216 return;
2219 if (!GetWidget()) {
2220 // The view is not yet attached to a widget, defer registration until then.
2221 return;
2224 accelerator_focus_manager_ = GetFocusManager();
2225 if (!accelerator_focus_manager_) {
2226 // Some crash reports seem to show that we may get cases where we have no
2227 // focus manager (see bug #1291225). This should never be the case, just
2228 // making sure we don't crash.
2229 NOTREACHED();
2230 return;
2232 for (std::vector<ui::Accelerator>::const_iterator i(
2233 accelerators_->begin() + registered_accelerator_count_);
2234 i != accelerators_->end(); ++i) {
2235 accelerator_focus_manager_->RegisterAccelerator(
2236 *i, ui::AcceleratorManager::kNormalPriority, this);
2238 registered_accelerator_count_ = accelerators_->size();
2241 void View::UnregisterAccelerators(bool leave_data_intact) {
2242 if (!accelerators_.get())
2243 return;
2245 if (GetWidget()) {
2246 if (accelerator_focus_manager_) {
2247 accelerator_focus_manager_->UnregisterAccelerators(this);
2248 accelerator_focus_manager_ = NULL;
2250 if (!leave_data_intact) {
2251 accelerators_->clear();
2252 accelerators_.reset();
2254 registered_accelerator_count_ = 0;
2258 // Focus -----------------------------------------------------------------------
2260 void View::InitFocusSiblings(View* v, int index) {
2261 int count = child_count();
2263 if (count == 0) {
2264 v->next_focusable_view_ = NULL;
2265 v->previous_focusable_view_ = NULL;
2266 } else {
2267 if (index == count) {
2268 // We are inserting at the end, but the end of the child list may not be
2269 // the last focusable element. Let's try to find an element with no next
2270 // focusable element to link to.
2271 View* last_focusable_view = NULL;
2272 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2273 if (!(*i)->next_focusable_view_) {
2274 last_focusable_view = *i;
2275 break;
2278 if (last_focusable_view == NULL) {
2279 // Hum... there is a cycle in the focus list. Let's just insert ourself
2280 // after the last child.
2281 View* prev = children_[index - 1];
2282 v->previous_focusable_view_ = prev;
2283 v->next_focusable_view_ = prev->next_focusable_view_;
2284 prev->next_focusable_view_->previous_focusable_view_ = v;
2285 prev->next_focusable_view_ = v;
2286 } else {
2287 last_focusable_view->next_focusable_view_ = v;
2288 v->next_focusable_view_ = NULL;
2289 v->previous_focusable_view_ = last_focusable_view;
2291 } else {
2292 View* prev = children_[index]->GetPreviousFocusableView();
2293 v->previous_focusable_view_ = prev;
2294 v->next_focusable_view_ = children_[index];
2295 if (prev)
2296 prev->next_focusable_view_ = v;
2297 children_[index]->previous_focusable_view_ = v;
2302 void View::AdvanceFocusIfNecessary() {
2303 // Focus should only be advanced if this is the focused view and has become
2304 // unfocusable. If the view is still focusable or is not focused, we can
2305 // return early avoiding furthur unnecessary checks. Focusability check is
2306 // performed first as it tends to be faster.
2307 if (IsAccessibilityFocusable() || !HasFocus())
2308 return;
2310 FocusManager* focus_manager = GetFocusManager();
2311 if (focus_manager)
2312 focus_manager->AdvanceFocusIfNecessary();
2315 // System events ---------------------------------------------------------------
2317 void View::PropagateThemeChanged() {
2318 for (int i = child_count() - 1; i >= 0; --i)
2319 child_at(i)->PropagateThemeChanged();
2320 OnThemeChanged();
2323 void View::PropagateLocaleChanged() {
2324 for (int i = child_count() - 1; i >= 0; --i)
2325 child_at(i)->PropagateLocaleChanged();
2326 OnLocaleChanged();
2329 void View::PropagateDeviceScaleFactorChanged(float device_scale_factor) {
2330 for (int i = child_count() - 1; i >= 0; --i)
2331 child_at(i)->PropagateDeviceScaleFactorChanged(device_scale_factor);
2333 // If the view is drawing to the layer, OnDeviceScaleFactorChanged() is called
2334 // through LayerDelegate callback.
2335 if (!layer())
2336 OnDeviceScaleFactorChanged(device_scale_factor);
2339 // Tooltips --------------------------------------------------------------------
2341 void View::UpdateTooltip() {
2342 Widget* widget = GetWidget();
2343 // TODO(beng): The TooltipManager NULL check can be removed when we
2344 // consolidate Init() methods and make views_unittests Init() all
2345 // Widgets that it uses.
2346 if (widget && widget->GetTooltipManager())
2347 widget->GetTooltipManager()->UpdateTooltip();
2350 // Drag and drop ---------------------------------------------------------------
2352 bool View::DoDrag(const ui::LocatedEvent& event,
2353 const gfx::Point& press_pt,
2354 ui::DragDropTypes::DragEventSource source) {
2355 int drag_operations = GetDragOperations(press_pt);
2356 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2357 return false;
2359 Widget* widget = GetWidget();
2360 // We should only start a drag from an event, implying we have a widget.
2361 DCHECK(widget);
2363 // Don't attempt to start a drag while in the process of dragging. This is
2364 // especially important on X where we can get multiple mouse move events when
2365 // we start the drag.
2366 if (widget->dragged_view())
2367 return false;
2369 OSExchangeData data;
2370 WriteDragData(press_pt, &data);
2372 // Message the RootView to do the drag and drop. That way if we're removed
2373 // the RootView can detect it and avoid calling us back.
2374 gfx::Point widget_location(event.location());
2375 ConvertPointToWidget(this, &widget_location);
2376 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2377 // WARNING: we may have been deleted.
2378 return true;
2381 } // namespace views