chrome/browser/extensions: Remove use of MessageLoopProxy and deprecated MessageLoop...
[chromium-blink-merge.git] / ui / views / view.cc
blob8dded154610496f188c9cd32c729e642fcb7c695
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 const char View::kViewClassName[] = "View";
88 ////////////////////////////////////////////////////////////////////////////////
89 // View, public:
91 // Creation and lifetime -------------------------------------------------------
93 View::View()
94 : owned_by_client_(false),
95 id_(0),
96 group_(-1),
97 parent_(NULL),
98 visible_(true),
99 enabled_(true),
100 notify_enter_exit_on_child_(false),
101 registered_for_visible_bounds_notification_(false),
102 clip_insets_(0, 0, 0, 0),
103 needs_layout_(true),
104 snap_layer_to_pixel_boundary_(false),
105 flip_canvas_on_paint_for_rtl_ui_(false),
106 paint_to_layer_(false),
107 accelerator_focus_manager_(NULL),
108 registered_accelerator_count_(0),
109 next_focusable_view_(NULL),
110 previous_focusable_view_(NULL),
111 focusable_(false),
112 accessibility_focusable_(false),
113 context_menu_controller_(NULL),
114 drag_controller_(NULL),
115 native_view_accessibility_(NULL) {
118 View::~View() {
119 if (parent_)
120 parent_->RemoveChildView(this);
122 ViewStorage::GetInstance()->ViewRemoved(this);
124 for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
125 (*i)->parent_ = NULL;
126 if (!(*i)->owned_by_client_)
127 delete *i;
130 // Release ownership of the native accessibility object, but it's
131 // reference-counted on some platforms, so it may not be deleted right away.
132 if (native_view_accessibility_)
133 native_view_accessibility_->Destroy();
136 // Tree operations -------------------------------------------------------------
138 const Widget* View::GetWidget() const {
139 // The root view holds a reference to this view hierarchy's Widget.
140 return parent_ ? parent_->GetWidget() : NULL;
143 Widget* View::GetWidget() {
144 return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
147 void View::AddChildView(View* view) {
148 if (view->parent_ == this)
149 return;
150 AddChildViewAt(view, child_count());
153 void View::AddChildViewAt(View* view, int index) {
154 CHECK_NE(view, this) << "You cannot add a view as its own child";
155 DCHECK_GE(index, 0);
156 DCHECK_LE(index, child_count());
158 // If |view| has a parent, remove it from its parent.
159 View* parent = view->parent_;
160 ui::NativeTheme* old_theme = NULL;
161 if (parent) {
162 old_theme = view->GetNativeTheme();
163 if (parent == this) {
164 ReorderChildView(view, index);
165 return;
167 parent->DoRemoveChildView(view, true, true, false, this);
170 // Sets the prev/next focus views.
171 InitFocusSiblings(view, index);
173 // Let's insert the view.
174 view->parent_ = this;
175 children_.insert(children_.begin() + index, view);
177 views::Widget* widget = GetWidget();
178 if (widget) {
179 const ui::NativeTheme* new_theme = view->GetNativeTheme();
180 if (new_theme != old_theme)
181 view->PropagateNativeThemeChanged(new_theme);
184 ViewHierarchyChangedDetails details(true, this, view, parent);
186 for (View* v = this; v; v = v->parent_)
187 v->ViewHierarchyChangedImpl(false, details);
189 view->PropagateAddNotifications(details);
190 UpdateTooltip();
191 if (widget) {
192 RegisterChildrenForVisibleBoundsNotification(view);
193 if (view->visible())
194 view->SchedulePaint();
197 if (layout_manager_.get())
198 layout_manager_->ViewAdded(this, view);
200 ReorderLayers();
202 // Make sure the visibility of the child layers are correct.
203 // If any of the parent View is hidden, then the layers of the subtree
204 // rooted at |this| should be hidden. Otherwise, all the child layers should
205 // inherit the visibility of the owner View.
206 UpdateLayerVisibility();
209 void View::ReorderChildView(View* view, int index) {
210 DCHECK_EQ(view->parent_, this);
211 if (index < 0)
212 index = child_count() - 1;
213 else if (index >= child_count())
214 return;
215 if (children_[index] == view)
216 return;
218 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
219 DCHECK(i != children_.end());
220 children_.erase(i);
222 // Unlink the view first
223 View* next_focusable = view->next_focusable_view_;
224 View* prev_focusable = view->previous_focusable_view_;
225 if (prev_focusable)
226 prev_focusable->next_focusable_view_ = next_focusable;
227 if (next_focusable)
228 next_focusable->previous_focusable_view_ = prev_focusable;
230 // Add it in the specified index now.
231 InitFocusSiblings(view, index);
232 children_.insert(children_.begin() + index, view);
234 ReorderLayers();
237 void View::RemoveChildView(View* view) {
238 DoRemoveChildView(view, true, true, false, NULL);
241 void View::RemoveAllChildViews(bool delete_children) {
242 while (!children_.empty())
243 DoRemoveChildView(children_.front(), false, false, delete_children, NULL);
244 UpdateTooltip();
247 bool View::Contains(const View* view) const {
248 for (const View* v = view; v; v = v->parent_) {
249 if (v == this)
250 return true;
252 return false;
255 int View::GetIndexOf(const View* view) const {
256 Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
257 return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
260 // Size and disposition --------------------------------------------------------
262 void View::SetBounds(int x, int y, int width, int height) {
263 SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
266 void View::SetBoundsRect(const gfx::Rect& bounds) {
267 if (bounds == bounds_) {
268 if (needs_layout_) {
269 needs_layout_ = false;
270 Layout();
272 return;
275 if (visible_) {
276 // Paint where the view is currently.
277 SchedulePaintBoundsChanged(
278 bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
279 SCHEDULE_PAINT_SIZE_CHANGED);
282 gfx::Rect prev = bounds_;
283 bounds_ = bounds;
284 BoundsChanged(prev);
287 void View::SetSize(const gfx::Size& size) {
288 SetBounds(x(), y(), size.width(), size.height());
291 void View::SetPosition(const gfx::Point& position) {
292 SetBounds(position.x(), position.y(), width(), height());
295 void View::SetX(int x) {
296 SetBounds(x, y(), width(), height());
299 void View::SetY(int y) {
300 SetBounds(x(), y, width(), height());
303 gfx::Rect View::GetContentsBounds() const {
304 gfx::Rect contents_bounds(GetLocalBounds());
305 if (border_.get())
306 contents_bounds.Inset(border_->GetInsets());
307 return contents_bounds;
310 gfx::Rect View::GetLocalBounds() const {
311 return gfx::Rect(size());
314 gfx::Rect View::GetLayerBoundsInPixel() const {
315 return layer()->GetTargetBounds();
318 gfx::Insets View::GetInsets() const {
319 return border_.get() ? border_->GetInsets() : gfx::Insets();
322 gfx::Rect View::GetVisibleBounds() const {
323 if (!IsDrawn())
324 return gfx::Rect();
325 gfx::Rect vis_bounds(GetLocalBounds());
326 gfx::Rect ancestor_bounds;
327 const View* view = this;
328 gfx::Transform transform;
330 while (view != NULL && !vis_bounds.IsEmpty()) {
331 transform.ConcatTransform(view->GetTransform());
332 gfx::Transform translation;
333 translation.Translate(static_cast<float>(view->GetMirroredX()),
334 static_cast<float>(view->y()));
335 transform.ConcatTransform(translation);
337 vis_bounds = view->ConvertRectToParent(vis_bounds);
338 const View* ancestor = view->parent_;
339 if (ancestor != NULL) {
340 ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
341 vis_bounds.Intersect(ancestor_bounds);
342 } else if (!view->GetWidget()) {
343 // If the view has no Widget, we're not visible. Return an empty rect.
344 return gfx::Rect();
346 view = ancestor;
348 if (vis_bounds.IsEmpty())
349 return vis_bounds;
350 // Convert back to this views coordinate system.
351 gfx::RectF views_vis_bounds(vis_bounds);
352 transform.TransformRectReverse(&views_vis_bounds);
353 // Partially visible pixels should be considered visible.
354 return gfx::ToEnclosingRect(views_vis_bounds);
357 gfx::Rect View::GetBoundsInScreen() const {
358 gfx::Point origin;
359 View::ConvertPointToScreen(this, &origin);
360 return gfx::Rect(origin, size());
363 gfx::Size View::GetPreferredSize() const {
364 if (layout_manager_.get())
365 return layout_manager_->GetPreferredSize(this);
366 return gfx::Size();
369 int View::GetBaseline() const {
370 return -1;
373 void View::SizeToPreferredSize() {
374 gfx::Size prefsize = GetPreferredSize();
375 if ((prefsize.width() != width()) || (prefsize.height() != height()))
376 SetBounds(x(), y(), prefsize.width(), prefsize.height());
379 gfx::Size View::GetMinimumSize() const {
380 return GetPreferredSize();
383 gfx::Size View::GetMaximumSize() const {
384 return gfx::Size();
387 int View::GetHeightForWidth(int w) const {
388 if (layout_manager_.get())
389 return layout_manager_->GetPreferredHeightForWidth(this, w);
390 return GetPreferredSize().height();
393 void View::SetVisible(bool visible) {
394 if (visible != visible_) {
395 // If the View is currently visible, schedule paint to refresh parent.
396 // TODO(beng): not sure we should be doing this if we have a layer.
397 if (visible_)
398 SchedulePaint();
400 visible_ = visible;
401 AdvanceFocusIfNecessary();
403 // Notify the parent.
404 if (parent_)
405 parent_->ChildVisibilityChanged(this);
407 // This notifies all sub-views recursively.
408 PropagateVisibilityNotifications(this, visible_);
409 UpdateLayerVisibility();
411 // If we are newly visible, schedule paint.
412 if (visible_)
413 SchedulePaint();
417 bool View::IsDrawn() const {
418 return visible_ && parent_ ? parent_->IsDrawn() : false;
421 void View::SetEnabled(bool enabled) {
422 if (enabled != enabled_) {
423 enabled_ = enabled;
424 AdvanceFocusIfNecessary();
425 OnEnabledChanged();
429 void View::OnEnabledChanged() {
430 SchedulePaint();
433 // Transformations -------------------------------------------------------------
435 gfx::Transform View::GetTransform() const {
436 return layer() ? layer()->transform() : gfx::Transform();
439 void View::SetTransform(const gfx::Transform& transform) {
440 if (transform.IsIdentity()) {
441 if (layer()) {
442 layer()->SetTransform(transform);
443 if (!paint_to_layer_)
444 DestroyLayer();
445 } else {
446 // Nothing.
448 } else {
449 if (!layer())
450 CreateLayer();
451 layer()->SetTransform(transform);
452 layer()->ScheduleDraw();
456 void View::SetPaintToLayer(bool paint_to_layer) {
457 if (paint_to_layer_ == paint_to_layer)
458 return;
460 paint_to_layer_ = paint_to_layer;
461 if (paint_to_layer_ && !layer()) {
462 CreateLayer();
463 } else if (!paint_to_layer_ && layer()) {
464 DestroyLayer();
468 // RTL positioning -------------------------------------------------------------
470 gfx::Rect View::GetMirroredBounds() const {
471 gfx::Rect bounds(bounds_);
472 bounds.set_x(GetMirroredX());
473 return bounds;
476 gfx::Point View::GetMirroredPosition() const {
477 return gfx::Point(GetMirroredX(), y());
480 int View::GetMirroredX() const {
481 return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
484 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
485 return base::i18n::IsRTL() ?
486 (width() - bounds.x() - bounds.width()) : bounds.x();
489 int View::GetMirroredXInView(int x) const {
490 return base::i18n::IsRTL() ? width() - x : x;
493 int View::GetMirroredXWithWidthInView(int x, int w) const {
494 return base::i18n::IsRTL() ? width() - x - w : x;
497 // Layout ----------------------------------------------------------------------
499 void View::Layout() {
500 needs_layout_ = false;
502 // If we have a layout manager, let it handle the layout for us.
503 if (layout_manager_.get())
504 layout_manager_->Layout(this);
506 // Make sure to propagate the Layout() call to any children that haven't
507 // received it yet through the layout manager and need to be laid out. This
508 // is needed for the case when the child requires a layout but its bounds
509 // weren't changed by the layout manager. If there is no layout manager, we
510 // just propagate the Layout() call down the hierarchy, so whoever receives
511 // the call can take appropriate action.
512 for (int i = 0, count = child_count(); i < count; ++i) {
513 View* child = child_at(i);
514 if (child->needs_layout_ || !layout_manager_.get()) {
515 TRACE_EVENT1("views", "View::Layout", "class", child->GetClassName());
516 child->needs_layout_ = false;
517 child->Layout();
522 void View::InvalidateLayout() {
523 // Always invalidate up. This is needed to handle the case of us already being
524 // valid, but not our parent.
525 needs_layout_ = true;
526 if (parent_)
527 parent_->InvalidateLayout();
530 LayoutManager* View::GetLayoutManager() const {
531 return layout_manager_.get();
534 void View::SetLayoutManager(LayoutManager* layout_manager) {
535 if (layout_manager_.get())
536 layout_manager_->Uninstalled(this);
538 layout_manager_.reset(layout_manager);
539 if (layout_manager_.get())
540 layout_manager_->Installed(this);
543 void View::SnapLayerToPixelBoundary() {
544 if (!layer())
545 return;
547 if (snap_layer_to_pixel_boundary_ && layer()->parent() &&
548 layer()->GetCompositor()) {
549 ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer());
550 } else {
551 // Reset the offset.
552 layer()->SetSubpixelPositionOffset(gfx::Vector2dF());
556 // Attributes ------------------------------------------------------------------
558 const char* View::GetClassName() const {
559 return kViewClassName;
562 const View* View::GetAncestorWithClassName(const std::string& name) const {
563 for (const View* view = this; view; view = view->parent_) {
564 if (!strcmp(view->GetClassName(), name.c_str()))
565 return view;
567 return NULL;
570 View* View::GetAncestorWithClassName(const std::string& name) {
571 return const_cast<View*>(const_cast<const View*>(this)->
572 GetAncestorWithClassName(name));
575 const View* View::GetViewByID(int id) const {
576 if (id == id_)
577 return const_cast<View*>(this);
579 for (int i = 0, count = child_count(); i < count; ++i) {
580 const View* view = child_at(i)->GetViewByID(id);
581 if (view)
582 return view;
584 return NULL;
587 View* View::GetViewByID(int id) {
588 return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
591 void View::SetGroup(int gid) {
592 // Don't change the group id once it's set.
593 DCHECK(group_ == -1 || group_ == gid);
594 group_ = gid;
597 int View::GetGroup() const {
598 return group_;
601 bool View::IsGroupFocusTraversable() const {
602 return true;
605 void View::GetViewsInGroup(int group, Views* views) {
606 if (group_ == group)
607 views->push_back(this);
609 for (int i = 0, count = child_count(); i < count; ++i)
610 child_at(i)->GetViewsInGroup(group, views);
613 View* View::GetSelectedViewForGroup(int group) {
614 Views views;
615 GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
616 return views.empty() ? NULL : views[0];
619 // Coordinate conversion -------------------------------------------------------
621 // static
622 void View::ConvertPointToTarget(const View* source,
623 const View* target,
624 gfx::Point* point) {
625 DCHECK(source);
626 DCHECK(target);
627 if (source == target)
628 return;
630 const View* root = GetHierarchyRoot(target);
631 CHECK_EQ(GetHierarchyRoot(source), root);
633 if (source != root)
634 source->ConvertPointForAncestor(root, point);
636 if (target != root)
637 target->ConvertPointFromAncestor(root, point);
640 // static
641 void View::ConvertRectToTarget(const View* source,
642 const View* target,
643 gfx::RectF* rect) {
644 DCHECK(source);
645 DCHECK(target);
646 if (source == target)
647 return;
649 const View* root = GetHierarchyRoot(target);
650 CHECK_EQ(GetHierarchyRoot(source), root);
652 if (source != root)
653 source->ConvertRectForAncestor(root, rect);
655 if (target != root)
656 target->ConvertRectFromAncestor(root, rect);
659 // static
660 void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
661 DCHECK(src);
662 DCHECK(p);
664 src->ConvertPointForAncestor(NULL, p);
667 // static
668 void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
669 DCHECK(dest);
670 DCHECK(p);
672 dest->ConvertPointFromAncestor(NULL, p);
675 // static
676 void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
677 DCHECK(src);
678 DCHECK(p);
680 // If the view is not connected to a tree, there's nothing we can do.
681 const Widget* widget = src->GetWidget();
682 if (widget) {
683 ConvertPointToWidget(src, p);
684 *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
688 // static
689 void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
690 DCHECK(dst);
691 DCHECK(p);
693 const views::Widget* widget = dst->GetWidget();
694 if (!widget)
695 return;
696 *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
697 views::View::ConvertPointFromWidget(dst, p);
700 gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
701 gfx::RectF x_rect = rect;
702 GetTransform().TransformRect(&x_rect);
703 x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
704 // Pixels we partially occupy in the parent should be included.
705 return gfx::ToEnclosingRect(x_rect);
708 gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
709 gfx::Rect x_rect = rect;
710 for (const View* v = this; v; v = v->parent_)
711 x_rect = v->ConvertRectToParent(x_rect);
712 return x_rect;
715 // Painting --------------------------------------------------------------------
717 void View::SchedulePaint() {
718 SchedulePaintInRect(GetLocalBounds());
721 void View::SchedulePaintInRect(const gfx::Rect& rect) {
722 if (!visible_)
723 return;
725 if (layer()) {
726 layer()->SchedulePaint(rect);
727 } else if (parent_) {
728 // Translate the requested paint rect to the parent's coordinate system
729 // then pass this notification up to the parent.
730 parent_->SchedulePaintInRect(ConvertRectToParent(rect));
734 void View::Paint(const ui::PaintContext& parent_context) {
735 if (!visible_)
736 return;
737 if (size().IsEmpty())
738 return;
740 gfx::Vector2d offset_to_parent;
741 if (!layer()) {
742 // If the View has a layer() then it is a paint root. Otherwise, we need to
743 // add the offset from the parent into the total offset from the paint root.
744 DCHECK_IMPLIES(!parent(), bounds().origin() == gfx::Point());
745 offset_to_parent = GetMirroredPosition().OffsetFromOrigin();
747 ui::PaintContext context(parent_context, offset_to_parent);
749 bool is_invalidated = true;
750 if (context.CanCheckInvalid()) {
751 #if DCHECK_IS_ON()
752 gfx::Vector2d offset;
753 context.Visited(this);
754 View* view = this;
755 while (view->parent() && !view->layer()) {
756 DCHECK(view->GetTransform().IsIdentity());
757 offset += view->GetMirroredPosition().OffsetFromOrigin();
758 view = view->parent();
760 // The offset in the PaintContext should be the offset up to the paint root,
761 // which we compute and verify here.
762 DCHECK_EQ(context.PaintOffset().x(), offset.x());
763 DCHECK_EQ(context.PaintOffset().y(), offset.y());
764 // The above loop will stop when |view| is the paint root, which should be
765 // the root of the current paint walk, as verified by storing the root in
766 // the PaintContext.
767 DCHECK_EQ(context.RootVisited(), view);
768 #endif
770 // If the View wasn't invalidated, don't waste time painting it, the output
771 // would be culled.
772 is_invalidated = context.IsRectInvalid(GetLocalBounds());
775 if (!is_invalidated && context.ShouldEarlyOutOfPaintingWhenValid())
776 return;
778 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
780 // If the view is backed by a layer, it should paint with itself as the origin
781 // rather than relative to its parent.
782 ui::ClipTransformRecorder clip_transform_recorder(context);
783 if (!layer()) {
784 // Set the clip rect to the bounds of this View. Note that the X (or left)
785 // position we pass to ClipRect takes into consideration whether or not the
786 // View uses a right-to-left layout so that we paint the View in its
787 // mirrored position if need be.
788 gfx::Rect clip_rect_in_parent = bounds();
789 clip_rect_in_parent.Inset(clip_insets_);
790 if (parent_)
791 clip_rect_in_parent.set_x(
792 parent_->GetMirroredXForRect(clip_rect_in_parent));
793 clip_transform_recorder.ClipRect(clip_rect_in_parent);
795 // Translate the graphics such that 0,0 corresponds to where
796 // this View is located relative to its parent.
797 gfx::Transform transform_from_parent;
798 gfx::Vector2d offset_from_parent = GetMirroredPosition().OffsetFromOrigin();
799 transform_from_parent.Translate(offset_from_parent.x(),
800 offset_from_parent.y());
801 transform_from_parent.PreconcatTransform(GetTransform());
802 clip_transform_recorder.Transform(transform_from_parent);
805 if (is_invalidated || !paint_cache_.UseCache(context)) {
806 ui::PaintRecorder recorder(context, &paint_cache_);
807 gfx::Canvas* canvas = recorder.canvas();
808 // TODO(danakj): This is not needed with impl-side/slimming paint.
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 gfx::Point View::GetKeyboardContextMenuLocation() {
1225 gfx::Rect vis_bounds = GetVisibleBounds();
1226 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1227 vis_bounds.y() + vis_bounds.height() / 2);
1228 ConvertPointToScreen(this, &screen_point);
1229 return screen_point;
1232 // Drag and drop ---------------------------------------------------------------
1234 bool View::GetDropFormats(
1235 int* formats,
1236 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1237 return false;
1240 bool View::AreDropTypesRequired() {
1241 return false;
1244 bool View::CanDrop(const OSExchangeData& data) {
1245 // TODO(sky): when I finish up migration, this should default to true.
1246 return false;
1249 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1252 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1253 return ui::DragDropTypes::DRAG_NONE;
1256 void View::OnDragExited() {
1259 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1260 return ui::DragDropTypes::DRAG_NONE;
1263 void View::OnDragDone() {
1266 // static
1267 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1268 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1269 abs(delta.y()) > GetVerticalDragThreshold());
1272 // Accessibility----------------------------------------------------------------
1274 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1275 if (!native_view_accessibility_)
1276 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1277 if (native_view_accessibility_)
1278 return native_view_accessibility_->GetNativeObject();
1279 return NULL;
1282 void View::NotifyAccessibilityEvent(
1283 ui::AXEvent event_type,
1284 bool send_native_event) {
1285 if (ViewsDelegate::GetInstance())
1286 ViewsDelegate::GetInstance()->NotifyAccessibilityEvent(this, event_type);
1288 if (send_native_event && GetWidget()) {
1289 if (!native_view_accessibility_)
1290 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1291 if (native_view_accessibility_)
1292 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1296 // Scrolling -------------------------------------------------------------------
1298 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1299 // We must take RTL UI mirroring into account when adjusting the position of
1300 // the region.
1301 if (parent_) {
1302 gfx::Rect scroll_rect(rect);
1303 scroll_rect.Offset(GetMirroredX(), y());
1304 parent_->ScrollRectToVisible(scroll_rect);
1308 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1309 bool is_horizontal, bool is_positive) {
1310 return 0;
1313 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1314 bool is_horizontal, bool is_positive) {
1315 return 0;
1318 ////////////////////////////////////////////////////////////////////////////////
1319 // View, protected:
1321 // Size and disposition --------------------------------------------------------
1323 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1326 void View::PreferredSizeChanged() {
1327 InvalidateLayout();
1328 if (parent_)
1329 parent_->ChildPreferredSizeChanged(this);
1332 bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
1333 return false;
1336 void View::OnVisibleBoundsChanged() {
1339 // Tree operations -------------------------------------------------------------
1341 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1344 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1347 void View::NativeViewHierarchyChanged() {
1348 FocusManager* focus_manager = GetFocusManager();
1349 if (accelerator_focus_manager_ != focus_manager) {
1350 UnregisterAccelerators(true);
1352 if (focus_manager)
1353 RegisterPendingAccelerators();
1357 // Painting --------------------------------------------------------------------
1359 void View::PaintChildren(const ui::PaintContext& context) {
1360 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1361 for (int i = 0, count = child_count(); i < count; ++i)
1362 if (!child_at(i)->layer())
1363 child_at(i)->Paint(context);
1366 void View::OnPaint(gfx::Canvas* canvas) {
1367 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1368 OnPaintBackground(canvas);
1369 OnPaintBorder(canvas);
1372 void View::OnPaintBackground(gfx::Canvas* canvas) {
1373 if (background_.get()) {
1374 TRACE_EVENT2("views", "View::OnPaintBackground",
1375 "width", canvas->sk_canvas()->getDevice()->width(),
1376 "height", canvas->sk_canvas()->getDevice()->height());
1377 background_->Paint(canvas, this);
1381 void View::OnPaintBorder(gfx::Canvas* canvas) {
1382 if (border_.get()) {
1383 TRACE_EVENT2("views", "View::OnPaintBorder",
1384 "width", canvas->sk_canvas()->getDevice()->width(),
1385 "height", canvas->sk_canvas()->getDevice()->height());
1386 border_->Paint(*this, canvas);
1390 // Accelerated Painting --------------------------------------------------------
1392 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1393 // This method should not have the side-effect of creating the layer.
1394 if (layer())
1395 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1398 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1399 ui::Layer** layer_parent) {
1400 if (layer()) {
1401 if (layer_parent)
1402 *layer_parent = layer();
1403 return gfx::Vector2d();
1405 if (!parent_)
1406 return gfx::Vector2d();
1408 return gfx::Vector2d(GetMirroredX(), y()) +
1409 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1412 void View::UpdateParentLayer() {
1413 if (!layer())
1414 return;
1416 ui::Layer* parent_layer = NULL;
1417 gfx::Vector2d offset(GetMirroredX(), y());
1419 if (parent_)
1420 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1422 ReparentLayer(offset, parent_layer);
1425 void View::MoveLayerToParent(ui::Layer* parent_layer,
1426 const gfx::Point& point) {
1427 gfx::Point local_point(point);
1428 if (parent_layer != layer())
1429 local_point.Offset(GetMirroredX(), y());
1430 if (layer() && parent_layer != layer()) {
1431 parent_layer->Add(layer());
1432 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1433 width(), height()));
1434 } else {
1435 for (int i = 0, count = child_count(); i < count; ++i)
1436 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1440 void View::UpdateLayerVisibility() {
1441 bool visible = visible_;
1442 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1443 visible = v->visible();
1445 UpdateChildLayerVisibility(visible);
1448 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1449 if (layer()) {
1450 layer()->SetVisible(ancestor_visible && visible_);
1451 } else {
1452 for (int i = 0, count = child_count(); i < count; ++i)
1453 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1457 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1458 if (layer()) {
1459 SetLayerBounds(GetLocalBounds() + offset);
1460 } else {
1461 for (int i = 0, count = child_count(); i < count; ++i) {
1462 View* child = child_at(i);
1463 child->UpdateChildLayerBounds(
1464 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1469 void View::OnPaintLayer(const ui::PaintContext& context) {
1470 if (!layer()->fills_bounds_opaquely()) {
1471 ui::PaintRecorder recorder(context);
1472 recorder.canvas()->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1474 if (!visible_)
1475 return;
1476 Paint(context);
1479 void View::OnDelegatedFrameDamage(
1480 const gfx::Rect& damage_rect_in_dip) {
1483 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1484 snap_layer_to_pixel_boundary_ =
1485 (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1486 SnapLayerToPixelBoundary();
1487 // Repainting with new scale factor will paint the content at the right scale.
1490 base::Closure View::PrepareForLayerBoundsChange() {
1491 return base::Closure();
1494 void View::ReorderLayers() {
1495 View* v = this;
1496 while (v && !v->layer())
1497 v = v->parent();
1499 Widget* widget = GetWidget();
1500 if (!v) {
1501 if (widget) {
1502 ui::Layer* layer = widget->GetLayer();
1503 if (layer)
1504 widget->GetRootView()->ReorderChildLayers(layer);
1506 } else {
1507 v->ReorderChildLayers(v->layer());
1510 if (widget) {
1511 // Reorder the widget's child NativeViews in case a child NativeView is
1512 // associated with a view (eg via a NativeViewHost). Always do the
1513 // reordering because the associated NativeView's layer (if it has one)
1514 // is parented to the widget's layer regardless of whether the host view has
1515 // an ancestor with a layer.
1516 widget->ReorderNativeViews();
1520 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1521 if (layer() && layer() != parent_layer) {
1522 DCHECK_EQ(parent_layer, layer()->parent());
1523 parent_layer->StackAtBottom(layer());
1524 } else {
1525 // Iterate backwards through the children so that a child with a layer
1526 // which is further to the back is stacked above one which is further to
1527 // the front.
1528 for (Views::reverse_iterator it(children_.rbegin());
1529 it != children_.rend(); ++it) {
1530 (*it)->ReorderChildLayers(parent_layer);
1535 // Input -----------------------------------------------------------------------
1537 View::DragInfo* View::GetDragInfo() {
1538 return parent_ ? parent_->GetDragInfo() : NULL;
1541 // Focus -----------------------------------------------------------------------
1543 void View::OnFocus() {
1544 // TODO(beng): Investigate whether it's possible for us to move this to
1545 // Focus().
1546 // By default, we clear the native focus. This ensures that no visible native
1547 // view as the focus and that we still receive keyboard inputs.
1548 FocusManager* focus_manager = GetFocusManager();
1549 if (focus_manager)
1550 focus_manager->ClearNativeFocus();
1552 // TODO(beng): Investigate whether it's possible for us to move this to
1553 // Focus().
1554 // Notify assistive technologies of the focus change.
1555 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1558 void View::OnBlur() {
1561 void View::Focus() {
1562 OnFocus();
1565 void View::Blur() {
1566 OnBlur();
1569 // Tooltips --------------------------------------------------------------------
1571 void View::TooltipTextChanged() {
1572 Widget* widget = GetWidget();
1573 // TooltipManager may be null if there is a problem creating it.
1574 if (widget && widget->GetTooltipManager())
1575 widget->GetTooltipManager()->TooltipTextChanged(this);
1578 // Drag and drop ---------------------------------------------------------------
1580 int View::GetDragOperations(const gfx::Point& press_pt) {
1581 return drag_controller_ ?
1582 drag_controller_->GetDragOperationsForView(this, press_pt) :
1583 ui::DragDropTypes::DRAG_NONE;
1586 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1587 DCHECK(drag_controller_);
1588 drag_controller_->WriteDragDataForView(this, press_pt, data);
1591 bool View::InDrag() {
1592 Widget* widget = GetWidget();
1593 return widget ? widget->dragged_view() == this : false;
1596 int View::GetHorizontalDragThreshold() {
1597 // TODO(jennyz): This value may need to be adjusted for different platforms
1598 // and for different display density.
1599 return kDefaultHorizontalDragThreshold;
1602 int View::GetVerticalDragThreshold() {
1603 // TODO(jennyz): This value may need to be adjusted for different platforms
1604 // and for different display density.
1605 return kDefaultVerticalDragThreshold;
1608 // Debugging -------------------------------------------------------------------
1610 #if !defined(NDEBUG)
1612 std::string View::PrintViewGraph(bool first) {
1613 return DoPrintViewGraph(first, this);
1616 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1617 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1618 const size_t kMaxPointerStringLength = 19;
1620 std::string result;
1622 if (first)
1623 result.append("digraph {\n");
1625 // Node characteristics.
1626 char p[kMaxPointerStringLength];
1628 const std::string class_name(GetClassName());
1629 size_t base_name_index = class_name.find_last_of('/');
1630 if (base_name_index == std::string::npos)
1631 base_name_index = 0;
1632 else
1633 base_name_index++;
1635 char bounds_buffer[512];
1637 // Information about current node.
1638 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1639 result.append(" N");
1640 result.append(p + 2);
1641 result.append(" [label=\"");
1643 result.append(class_name.substr(base_name_index).c_str());
1645 base::snprintf(bounds_buffer,
1646 arraysize(bounds_buffer),
1647 "\\n bounds: (%d, %d), (%dx%d)",
1648 bounds().x(),
1649 bounds().y(),
1650 bounds().width(),
1651 bounds().height());
1652 result.append(bounds_buffer);
1654 gfx::DecomposedTransform decomp;
1655 if (!GetTransform().IsIdentity() &&
1656 gfx::DecomposeTransform(&decomp, GetTransform())) {
1657 base::snprintf(bounds_buffer,
1658 arraysize(bounds_buffer),
1659 "\\n translation: (%f, %f)",
1660 decomp.translate[0],
1661 decomp.translate[1]);
1662 result.append(bounds_buffer);
1664 base::snprintf(bounds_buffer,
1665 arraysize(bounds_buffer),
1666 "\\n rotation: %3.2f",
1667 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1668 result.append(bounds_buffer);
1670 base::snprintf(bounds_buffer,
1671 arraysize(bounds_buffer),
1672 "\\n scale: (%2.4f, %2.4f)",
1673 decomp.scale[0],
1674 decomp.scale[1]);
1675 result.append(bounds_buffer);
1678 result.append("\"");
1679 if (!parent_)
1680 result.append(", shape=box");
1681 if (layer()) {
1682 if (layer()->has_external_content())
1683 result.append(", color=green");
1684 else
1685 result.append(", color=red");
1687 if (layer()->fills_bounds_opaquely())
1688 result.append(", style=filled");
1690 result.append("]\n");
1692 // Link to parent.
1693 if (parent_) {
1694 char pp[kMaxPointerStringLength];
1696 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1697 result.append(" N");
1698 result.append(pp + 2);
1699 result.append(" -> N");
1700 result.append(p + 2);
1701 result.append("\n");
1704 // Children.
1705 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1706 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1708 if (first)
1709 result.append("}\n");
1711 return result;
1713 #endif
1715 ////////////////////////////////////////////////////////////////////////////////
1716 // View, private:
1718 // DropInfo --------------------------------------------------------------------
1720 void View::DragInfo::Reset() {
1721 possible_drag = false;
1722 start_pt = gfx::Point();
1725 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1726 possible_drag = true;
1727 start_pt = p;
1730 // Painting --------------------------------------------------------------------
1732 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1733 // If we have a layer and the View's size did not change, we do not need to
1734 // schedule any paints since the layer will be redrawn at its new location
1735 // during the next Draw() cycle in the compositor.
1736 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1737 // Otherwise, if the size changes or we don't have a layer then we need to
1738 // use SchedulePaint to invalidate the area occupied by the View.
1739 SchedulePaint();
1740 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1741 // The compositor doesn't Draw() until something on screen changes, so
1742 // if our position changes but nothing is being animated on screen, then
1743 // tell the compositor to redraw the scene. We know layer() exists due to
1744 // the above if clause.
1745 layer()->ScheduleDraw();
1749 // Tree operations -------------------------------------------------------------
1751 void View::DoRemoveChildView(View* view,
1752 bool update_focus_cycle,
1753 bool update_tool_tip,
1754 bool delete_removed_view,
1755 View* new_parent) {
1756 DCHECK(view);
1758 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1759 scoped_ptr<View> view_to_be_deleted;
1760 if (i != children_.end()) {
1761 if (update_focus_cycle) {
1762 // Let's remove the view from the focus traversal.
1763 View* next_focusable = view->next_focusable_view_;
1764 View* prev_focusable = view->previous_focusable_view_;
1765 if (prev_focusable)
1766 prev_focusable->next_focusable_view_ = next_focusable;
1767 if (next_focusable)
1768 next_focusable->previous_focusable_view_ = prev_focusable;
1771 if (GetWidget()) {
1772 UnregisterChildrenForVisibleBoundsNotification(view);
1773 if (view->visible())
1774 view->SchedulePaint();
1775 GetWidget()->NotifyWillRemoveView(view);
1778 view->PropagateRemoveNotifications(this, new_parent);
1779 view->parent_ = NULL;
1780 view->UpdateLayerVisibility();
1782 if (delete_removed_view && !view->owned_by_client_)
1783 view_to_be_deleted.reset(view);
1785 children_.erase(i);
1788 if (update_tool_tip)
1789 UpdateTooltip();
1791 if (layout_manager_.get())
1792 layout_manager_->ViewRemoved(this, view);
1795 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1796 for (int i = 0, count = child_count(); i < count; ++i)
1797 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1799 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1800 for (View* v = this; v; v = v->parent_)
1801 v->ViewHierarchyChangedImpl(true, details);
1804 void View::PropagateAddNotifications(
1805 const ViewHierarchyChangedDetails& details) {
1806 for (int i = 0, count = child_count(); i < count; ++i)
1807 child_at(i)->PropagateAddNotifications(details);
1808 ViewHierarchyChangedImpl(true, details);
1811 void View::PropagateNativeViewHierarchyChanged() {
1812 for (int i = 0, count = child_count(); i < count; ++i)
1813 child_at(i)->PropagateNativeViewHierarchyChanged();
1814 NativeViewHierarchyChanged();
1817 void View::ViewHierarchyChangedImpl(
1818 bool register_accelerators,
1819 const ViewHierarchyChangedDetails& details) {
1820 if (register_accelerators) {
1821 if (details.is_add) {
1822 // If you get this registration, you are part of a subtree that has been
1823 // added to the view hierarchy.
1824 if (GetFocusManager())
1825 RegisterPendingAccelerators();
1826 } else {
1827 if (details.child == this)
1828 UnregisterAccelerators(true);
1832 if (details.is_add && layer() && !layer()->parent()) {
1833 UpdateParentLayer();
1834 Widget* widget = GetWidget();
1835 if (widget)
1836 widget->UpdateRootLayers();
1837 } else if (!details.is_add && details.child == this) {
1838 // Make sure the layers belonging to the subtree rooted at |child| get
1839 // removed from layers that do not belong in the same subtree.
1840 OrphanLayers();
1841 Widget* widget = GetWidget();
1842 if (widget)
1843 widget->UpdateRootLayers();
1846 ViewHierarchyChanged(details);
1847 details.parent->needs_layout_ = true;
1850 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1851 for (int i = 0, count = child_count(); i < count; ++i)
1852 child_at(i)->PropagateNativeThemeChanged(theme);
1853 OnNativeThemeChanged(theme);
1856 // Size and disposition --------------------------------------------------------
1858 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1859 for (int i = 0, count = child_count(); i < count; ++i)
1860 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1861 VisibilityChangedImpl(start, is_visible);
1864 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1865 VisibilityChanged(starting_from, is_visible);
1868 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1869 if (visible_) {
1870 // Paint the new bounds.
1871 SchedulePaintBoundsChanged(
1872 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1873 SCHEDULE_PAINT_SIZE_CHANGED);
1876 if (layer()) {
1877 if (parent_) {
1878 SetLayerBounds(GetLocalBounds() +
1879 gfx::Vector2d(GetMirroredX(), y()) +
1880 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1881 } else {
1882 SetLayerBounds(bounds_);
1885 // In RTL mode, if our width has changed, our children's mirrored bounds
1886 // will have changed. Update the child's layer bounds, or if it is not a
1887 // layer, the bounds of any layers inside the child.
1888 if (base::i18n::IsRTL() && bounds_.width() != previous_bounds.width()) {
1889 for (int i = 0; i < child_count(); ++i) {
1890 View* child = child_at(i);
1891 child->UpdateChildLayerBounds(
1892 gfx::Vector2d(child->GetMirroredX(), child->y()));
1895 } else {
1896 // If our bounds have changed, then any descendant layer bounds may have
1897 // changed. Update them accordingly.
1898 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1901 OnBoundsChanged(previous_bounds);
1903 if (previous_bounds.size() != size()) {
1904 needs_layout_ = false;
1905 Layout();
1908 if (GetNeedsNotificationWhenVisibleBoundsChange())
1909 OnVisibleBoundsChanged();
1911 // Notify interested Views that visible bounds within the root view may have
1912 // changed.
1913 if (descendants_to_notify_.get()) {
1914 for (Views::iterator i(descendants_to_notify_->begin());
1915 i != descendants_to_notify_->end(); ++i) {
1916 (*i)->OnVisibleBoundsChanged();
1921 // static
1922 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1923 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1924 view->RegisterForVisibleBoundsNotification();
1925 for (int i = 0; i < view->child_count(); ++i)
1926 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1929 // static
1930 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1931 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1932 view->UnregisterForVisibleBoundsNotification();
1933 for (int i = 0; i < view->child_count(); ++i)
1934 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1937 void View::RegisterForVisibleBoundsNotification() {
1938 if (registered_for_visible_bounds_notification_)
1939 return;
1941 registered_for_visible_bounds_notification_ = true;
1942 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1943 ancestor->AddDescendantToNotify(this);
1946 void View::UnregisterForVisibleBoundsNotification() {
1947 if (!registered_for_visible_bounds_notification_)
1948 return;
1950 registered_for_visible_bounds_notification_ = false;
1951 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1952 ancestor->RemoveDescendantToNotify(this);
1955 void View::AddDescendantToNotify(View* view) {
1956 DCHECK(view);
1957 if (!descendants_to_notify_.get())
1958 descendants_to_notify_.reset(new Views);
1959 descendants_to_notify_->push_back(view);
1962 void View::RemoveDescendantToNotify(View* view) {
1963 DCHECK(view && descendants_to_notify_.get());
1964 Views::iterator i(std::find(
1965 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1966 DCHECK(i != descendants_to_notify_->end());
1967 descendants_to_notify_->erase(i);
1968 if (descendants_to_notify_->empty())
1969 descendants_to_notify_.reset();
1972 void View::SetLayerBounds(const gfx::Rect& bounds) {
1973 layer()->SetBounds(bounds);
1974 SnapLayerToPixelBoundary();
1977 // Transformations -------------------------------------------------------------
1979 bool View::GetTransformRelativeTo(const View* ancestor,
1980 gfx::Transform* transform) const {
1981 const View* p = this;
1983 while (p && p != ancestor) {
1984 transform->ConcatTransform(p->GetTransform());
1985 gfx::Transform translation;
1986 translation.Translate(static_cast<float>(p->GetMirroredX()),
1987 static_cast<float>(p->y()));
1988 transform->ConcatTransform(translation);
1990 p = p->parent_;
1993 return p == ancestor;
1996 // Coordinate conversion -------------------------------------------------------
1998 bool View::ConvertPointForAncestor(const View* ancestor,
1999 gfx::Point* point) const {
2000 gfx::Transform trans;
2001 // TODO(sad): Have some way of caching the transformation results.
2002 bool result = GetTransformRelativeTo(ancestor, &trans);
2003 gfx::Point3F p(*point);
2004 trans.TransformPoint(&p);
2005 *point = gfx::ToFlooredPoint(p.AsPointF());
2006 return result;
2009 bool View::ConvertPointFromAncestor(const View* ancestor,
2010 gfx::Point* point) const {
2011 gfx::Transform trans;
2012 bool result = GetTransformRelativeTo(ancestor, &trans);
2013 gfx::Point3F p(*point);
2014 trans.TransformPointReverse(&p);
2015 *point = gfx::ToFlooredPoint(p.AsPointF());
2016 return result;
2019 bool View::ConvertRectForAncestor(const View* ancestor,
2020 gfx::RectF* rect) const {
2021 gfx::Transform trans;
2022 // TODO(sad): Have some way of caching the transformation results.
2023 bool result = GetTransformRelativeTo(ancestor, &trans);
2024 trans.TransformRect(rect);
2025 return result;
2028 bool View::ConvertRectFromAncestor(const View* ancestor,
2029 gfx::RectF* rect) const {
2030 gfx::Transform trans;
2031 bool result = GetTransformRelativeTo(ancestor, &trans);
2032 trans.TransformRectReverse(rect);
2033 return result;
2036 // Accelerated painting --------------------------------------------------------
2038 void View::CreateLayer() {
2039 // A new layer is being created for the view. So all the layers of the
2040 // sub-tree can inherit the visibility of the corresponding view.
2041 for (int i = 0, count = child_count(); i < count; ++i)
2042 child_at(i)->UpdateChildLayerVisibility(true);
2044 SetLayer(new ui::Layer());
2045 layer()->set_delegate(this);
2046 #if !defined(NDEBUG)
2047 layer()->set_name(GetClassName());
2048 #endif
2050 UpdateParentLayers();
2051 UpdateLayerVisibility();
2053 // The new layer needs to be ordered in the layer tree according
2054 // to the view tree. Children of this layer were added in order
2055 // in UpdateParentLayers().
2056 if (parent())
2057 parent()->ReorderLayers();
2059 Widget* widget = GetWidget();
2060 if (widget)
2061 widget->UpdateRootLayers();
2064 void View::UpdateParentLayers() {
2065 // Attach all top-level un-parented layers.
2066 if (layer() && !layer()->parent()) {
2067 UpdateParentLayer();
2068 } else {
2069 for (int i = 0, count = child_count(); i < count; ++i)
2070 child_at(i)->UpdateParentLayers();
2074 void View::OrphanLayers() {
2075 if (layer()) {
2076 if (layer()->parent())
2077 layer()->parent()->Remove(layer());
2079 // The layer belonging to this View has already been orphaned. It is not
2080 // necessary to orphan the child layers.
2081 return;
2083 for (int i = 0, count = child_count(); i < count; ++i)
2084 child_at(i)->OrphanLayers();
2087 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2088 layer()->SetBounds(GetLocalBounds() + offset);
2089 DCHECK_NE(layer(), parent_layer);
2090 if (parent_layer)
2091 parent_layer->Add(layer());
2092 layer()->SchedulePaint(GetLocalBounds());
2093 MoveLayerToParent(layer(), gfx::Point());
2096 void View::DestroyLayer() {
2097 ui::Layer* new_parent = layer()->parent();
2098 std::vector<ui::Layer*> children = layer()->children();
2099 for (size_t i = 0; i < children.size(); ++i) {
2100 layer()->Remove(children[i]);
2101 if (new_parent)
2102 new_parent->Add(children[i]);
2105 LayerOwner::DestroyLayer();
2107 if (new_parent)
2108 ReorderLayers();
2110 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2112 SchedulePaint();
2114 Widget* widget = GetWidget();
2115 if (widget)
2116 widget->UpdateRootLayers();
2119 // Input -----------------------------------------------------------------------
2121 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2122 int drag_operations =
2123 (enabled_ && event.IsOnlyLeftMouseButton() &&
2124 HitTestPoint(event.location())) ?
2125 GetDragOperations(event.location()) : 0;
2126 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2127 context_menu_controller_ : 0;
2128 View::DragInfo* drag_info = GetDragInfo();
2130 // TODO(sky): for debugging 360238.
2131 int storage_id = 0;
2132 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2133 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2134 ViewStorage* view_storage = ViewStorage::GetInstance();
2135 storage_id = view_storage->CreateStorageID();
2136 view_storage->StoreView(storage_id, this);
2139 const bool enabled = enabled_;
2140 const bool result = OnMousePressed(event);
2142 if (!enabled)
2143 return result;
2145 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2146 kContextMenuOnMousePress) {
2147 // Assume that if there is a context menu controller we won't be deleted
2148 // from mouse pressed.
2149 gfx::Point location(event.location());
2150 if (HitTestPoint(location)) {
2151 if (storage_id != 0)
2152 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2153 ConvertPointToScreen(this, &location);
2154 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2155 return true;
2159 // WARNING: we may have been deleted, don't use any View variables.
2160 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2161 drag_info->PossibleDrag(event.location());
2162 return true;
2164 return !!context_menu_controller || result;
2167 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2168 // Copy the field, that way if we're deleted after drag and drop no harm is
2169 // done.
2170 ContextMenuController* context_menu_controller = context_menu_controller_;
2171 const bool possible_drag = GetDragInfo()->possible_drag;
2172 if (possible_drag &&
2173 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2174 (!drag_controller_ ||
2175 drag_controller_->CanStartDragForView(
2176 this, GetDragInfo()->start_pt, event.location()))) {
2177 DoDrag(event, GetDragInfo()->start_pt,
2178 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2179 } else {
2180 if (OnMouseDragged(event))
2181 return true;
2182 // Fall through to return value based on context menu controller.
2184 // WARNING: we may have been deleted.
2185 return (context_menu_controller != NULL) || possible_drag;
2188 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2189 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2190 event.IsOnlyRightMouseButton()) {
2191 // Assume that if there is a context menu controller we won't be deleted
2192 // from mouse released.
2193 gfx::Point location(event.location());
2194 OnMouseReleased(event);
2195 if (HitTestPoint(location)) {
2196 ConvertPointToScreen(this, &location);
2197 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2199 } else {
2200 OnMouseReleased(event);
2202 // WARNING: we may have been deleted.
2205 // Accelerators ----------------------------------------------------------------
2207 void View::RegisterPendingAccelerators() {
2208 if (!accelerators_.get() ||
2209 registered_accelerator_count_ == accelerators_->size()) {
2210 // No accelerators are waiting for registration.
2211 return;
2214 if (!GetWidget()) {
2215 // The view is not yet attached to a widget, defer registration until then.
2216 return;
2219 accelerator_focus_manager_ = GetFocusManager();
2220 if (!accelerator_focus_manager_) {
2221 // Some crash reports seem to show that we may get cases where we have no
2222 // focus manager (see bug #1291225). This should never be the case, just
2223 // making sure we don't crash.
2224 NOTREACHED();
2225 return;
2227 for (std::vector<ui::Accelerator>::const_iterator i(
2228 accelerators_->begin() + registered_accelerator_count_);
2229 i != accelerators_->end(); ++i) {
2230 accelerator_focus_manager_->RegisterAccelerator(
2231 *i, ui::AcceleratorManager::kNormalPriority, this);
2233 registered_accelerator_count_ = accelerators_->size();
2236 void View::UnregisterAccelerators(bool leave_data_intact) {
2237 if (!accelerators_.get())
2238 return;
2240 if (GetWidget()) {
2241 if (accelerator_focus_manager_) {
2242 accelerator_focus_manager_->UnregisterAccelerators(this);
2243 accelerator_focus_manager_ = NULL;
2245 if (!leave_data_intact) {
2246 accelerators_->clear();
2247 accelerators_.reset();
2249 registered_accelerator_count_ = 0;
2253 // Focus -----------------------------------------------------------------------
2255 void View::InitFocusSiblings(View* v, int index) {
2256 int count = child_count();
2258 if (count == 0) {
2259 v->next_focusable_view_ = NULL;
2260 v->previous_focusable_view_ = NULL;
2261 } else {
2262 if (index == count) {
2263 // We are inserting at the end, but the end of the child list may not be
2264 // the last focusable element. Let's try to find an element with no next
2265 // focusable element to link to.
2266 View* last_focusable_view = NULL;
2267 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2268 if (!(*i)->next_focusable_view_) {
2269 last_focusable_view = *i;
2270 break;
2273 if (last_focusable_view == NULL) {
2274 // Hum... there is a cycle in the focus list. Let's just insert ourself
2275 // after the last child.
2276 View* prev = children_[index - 1];
2277 v->previous_focusable_view_ = prev;
2278 v->next_focusable_view_ = prev->next_focusable_view_;
2279 prev->next_focusable_view_->previous_focusable_view_ = v;
2280 prev->next_focusable_view_ = v;
2281 } else {
2282 last_focusable_view->next_focusable_view_ = v;
2283 v->next_focusable_view_ = NULL;
2284 v->previous_focusable_view_ = last_focusable_view;
2286 } else {
2287 View* prev = children_[index]->GetPreviousFocusableView();
2288 v->previous_focusable_view_ = prev;
2289 v->next_focusable_view_ = children_[index];
2290 if (prev)
2291 prev->next_focusable_view_ = v;
2292 children_[index]->previous_focusable_view_ = v;
2297 void View::AdvanceFocusIfNecessary() {
2298 // Focus should only be advanced if this is the focused view and has become
2299 // unfocusable. If the view is still focusable or is not focused, we can
2300 // return early avoiding furthur unnecessary checks. Focusability check is
2301 // performed first as it tends to be faster.
2302 if (IsAccessibilityFocusable() || !HasFocus())
2303 return;
2305 FocusManager* focus_manager = GetFocusManager();
2306 if (focus_manager)
2307 focus_manager->AdvanceFocusIfNecessary();
2310 // System events ---------------------------------------------------------------
2312 void View::PropagateThemeChanged() {
2313 for (int i = child_count() - 1; i >= 0; --i)
2314 child_at(i)->PropagateThemeChanged();
2315 OnThemeChanged();
2318 void View::PropagateLocaleChanged() {
2319 for (int i = child_count() - 1; i >= 0; --i)
2320 child_at(i)->PropagateLocaleChanged();
2321 OnLocaleChanged();
2324 void View::PropagateDeviceScaleFactorChanged(float device_scale_factor) {
2325 for (int i = child_count() - 1; i >= 0; --i)
2326 child_at(i)->PropagateDeviceScaleFactorChanged(device_scale_factor);
2328 // If the view is drawing to the layer, OnDeviceScaleFactorChanged() is called
2329 // through LayerDelegate callback.
2330 if (!layer())
2331 OnDeviceScaleFactorChanged(device_scale_factor);
2334 // Tooltips --------------------------------------------------------------------
2336 void View::UpdateTooltip() {
2337 Widget* widget = GetWidget();
2338 // TODO(beng): The TooltipManager NULL check can be removed when we
2339 // consolidate Init() methods and make views_unittests Init() all
2340 // Widgets that it uses.
2341 if (widget && widget->GetTooltipManager())
2342 widget->GetTooltipManager()->UpdateTooltip();
2345 // Drag and drop ---------------------------------------------------------------
2347 bool View::DoDrag(const ui::LocatedEvent& event,
2348 const gfx::Point& press_pt,
2349 ui::DragDropTypes::DragEventSource source) {
2350 int drag_operations = GetDragOperations(press_pt);
2351 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2352 return false;
2354 Widget* widget = GetWidget();
2355 // We should only start a drag from an event, implying we have a widget.
2356 DCHECK(widget);
2358 // Don't attempt to start a drag while in the process of dragging. This is
2359 // especially important on X where we can get multiple mouse move events when
2360 // we start the drag.
2361 if (widget->dragged_view())
2362 return false;
2364 OSExchangeData data;
2365 WriteDragData(press_pt, &data);
2367 // Message the RootView to do the drag and drop. That way if we're removed
2368 // the RootView can detect it and avoid calling us back.
2369 gfx::Point widget_location(event.location());
2370 ConvertPointToWidget(this, &widget_location);
2371 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2372 // WARNING: we may have been deleted.
2373 return true;
2376 } // namespace views