Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / ui / views / view.cc
blob0b6efdf1086b52cf535a4b253d5fb92f70749d9c
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(parent_context, offset_to_parent);
750 bool is_invalidated = true;
751 if (context.CanCheckInvalid()) {
752 #if DCHECK_IS_ON()
753 gfx::Vector2d offset;
754 context.Visited(this);
755 View* view = this;
756 while (view->parent() && !view->layer()) {
757 DCHECK(view->GetTransform().IsIdentity());
758 offset += view->GetMirroredPosition().OffsetFromOrigin();
759 view = view->parent();
761 // The offset in the PaintContext should be the offset up to the paint root,
762 // which we compute and verify here.
763 DCHECK_EQ(context.PaintOffset().x(), offset.x());
764 DCHECK_EQ(context.PaintOffset().y(), offset.y());
765 // The above loop will stop when |view| is the paint root, which should be
766 // the root of the current paint walk, as verified by storing the root in
767 // the PaintContext.
768 DCHECK_EQ(context.RootVisited(), view);
769 #endif
771 // If the View wasn't invalidated, don't waste time painting it, the output
772 // would be culled.
773 is_invalidated = context.IsRectInvalid(GetLocalBounds());
776 if (!is_invalidated && context.ShouldEarlyOutOfPaintingWhenValid())
777 return;
779 TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
781 // If the view is backed by a layer, it should paint with itself as the origin
782 // rather than relative to its parent.
783 ui::ClipTransformRecorder clip_transform_recorder(context);
784 if (!layer()) {
785 // Set the clip rect to the bounds of this View. Note that the X (or left)
786 // position we pass to ClipRect takes into consideration whether or not the
787 // View uses a right-to-left layout so that we paint the View in its
788 // mirrored position if need be.
789 gfx::Rect clip_rect_in_parent = bounds();
790 clip_rect_in_parent.Inset(clip_insets_);
791 if (parent_)
792 clip_rect_in_parent.set_x(
793 parent_->GetMirroredXForRect(clip_rect_in_parent));
794 clip_transform_recorder.ClipRect(clip_rect_in_parent);
796 // Translate the graphics such that 0,0 corresponds to where
797 // this View is located relative to its parent.
798 gfx::Transform transform_from_parent;
799 gfx::Vector2d offset_from_parent = GetMirroredPosition().OffsetFromOrigin();
800 transform_from_parent.Translate(offset_from_parent.x(),
801 offset_from_parent.y());
802 transform_from_parent.PreconcatTransform(GetTransform());
803 clip_transform_recorder.Transform(transform_from_parent);
806 if (is_invalidated || !paint_cache_.UseCache(context)) {
807 ui::PaintRecorder recorder(context, &paint_cache_);
808 gfx::Canvas* canvas = recorder.canvas();
809 // TODO(danakj): This is not needed with impl-side/slimming paint.
810 gfx::ScopedCanvas scoped_canvas(canvas);
812 // If the View we are about to paint requested the canvas to be flipped, we
813 // should change the transform appropriately.
814 // The canvas mirroring is undone once the View is done painting so that we
815 // don't pass the canvas with the mirrored transform to Views that didn't
816 // request the canvas to be flipped.
817 if (FlipCanvasOnPaintForRTLUI()) {
818 canvas->Translate(gfx::Vector2d(width(), 0));
819 canvas->Scale(-1, 1);
822 // Delegate painting the contents of the View to the virtual OnPaint method.
823 OnPaint(canvas);
826 // View::Paint() recursion over the subtree.
827 PaintChildren(context);
830 void View::set_background(Background* b) {
831 background_.reset(b);
834 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
836 ui::ThemeProvider* View::GetThemeProvider() const {
837 const Widget* widget = GetWidget();
838 return widget ? widget->GetThemeProvider() : NULL;
841 const ui::NativeTheme* View::GetNativeTheme() const {
842 const Widget* widget = GetWidget();
843 return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
846 // Input -----------------------------------------------------------------------
848 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
849 return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
852 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
853 return GetEffectiveViewTargeter()->TargetForRect(this, rect);
856 bool View::CanProcessEventsWithinSubtree() const {
857 return true;
860 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
861 // TODO(tdanderson): Move this implementation into ViewTargetDelegate.
862 if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree())
863 return NULL;
865 // Walk the child Views recursively looking for the View that most
866 // tightly encloses the specified point.
867 for (int i = child_count() - 1; i >= 0; --i) {
868 View* child = child_at(i);
869 if (!child->visible())
870 continue;
872 gfx::Point point_in_child_coords(point);
873 ConvertPointToTarget(this, child, &point_in_child_coords);
874 View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
875 if (handler)
876 return handler;
878 return this;
881 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
882 #if defined(OS_WIN)
883 static ui::Cursor arrow;
884 if (!arrow.platform())
885 arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
886 return arrow;
887 #else
888 return gfx::kNullCursor;
889 #endif
892 bool View::HitTestPoint(const gfx::Point& point) const {
893 return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
896 bool View::HitTestRect(const gfx::Rect& rect) const {
897 return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect);
900 bool View::IsMouseHovered() {
901 // If we haven't yet been placed in an onscreen view hierarchy, we can't be
902 // hovered.
903 if (!GetWidget())
904 return false;
906 // If mouse events are disabled, then the mouse cursor is invisible and
907 // is therefore not hovering over this button.
908 if (!GetWidget()->IsMouseEventsEnabled())
909 return false;
911 gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
912 GetWidget()->GetNativeView())->GetCursorScreenPoint());
913 ConvertPointFromScreen(this, &cursor_pos);
914 return HitTestPoint(cursor_pos);
917 bool View::OnMousePressed(const ui::MouseEvent& event) {
918 return false;
921 bool View::OnMouseDragged(const ui::MouseEvent& event) {
922 return false;
925 void View::OnMouseReleased(const ui::MouseEvent& event) {
928 void View::OnMouseCaptureLost() {
931 void View::OnMouseMoved(const ui::MouseEvent& event) {
934 void View::OnMouseEntered(const ui::MouseEvent& event) {
937 void View::OnMouseExited(const ui::MouseEvent& event) {
940 void View::SetMouseHandler(View* new_mouse_handler) {
941 // |new_mouse_handler| may be NULL.
942 if (parent_)
943 parent_->SetMouseHandler(new_mouse_handler);
946 bool View::OnKeyPressed(const ui::KeyEvent& event) {
947 return false;
950 bool View::OnKeyReleased(const ui::KeyEvent& event) {
951 return false;
954 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
955 return false;
958 void View::OnKeyEvent(ui::KeyEvent* event) {
959 bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
960 OnKeyReleased(*event);
961 if (consumed)
962 event->StopPropagation();
965 void View::OnMouseEvent(ui::MouseEvent* event) {
966 switch (event->type()) {
967 case ui::ET_MOUSE_PRESSED:
968 if (ProcessMousePressed(*event))
969 event->SetHandled();
970 return;
972 case ui::ET_MOUSE_MOVED:
973 if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
974 ui::EF_RIGHT_MOUSE_BUTTON |
975 ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
976 OnMouseMoved(*event);
977 return;
979 // FALL-THROUGH
980 case ui::ET_MOUSE_DRAGGED:
981 if (ProcessMouseDragged(*event))
982 event->SetHandled();
983 return;
985 case ui::ET_MOUSE_RELEASED:
986 ProcessMouseReleased(*event);
987 return;
989 case ui::ET_MOUSEWHEEL:
990 if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
991 event->SetHandled();
992 break;
994 case ui::ET_MOUSE_ENTERED:
995 if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY)
996 NotifyAccessibilityEvent(ui::AX_EVENT_HOVER, true);
997 OnMouseEntered(*event);
998 break;
1000 case ui::ET_MOUSE_EXITED:
1001 OnMouseExited(*event);
1002 break;
1004 default:
1005 return;
1009 void View::OnScrollEvent(ui::ScrollEvent* event) {
1012 void View::OnTouchEvent(ui::TouchEvent* event) {
1013 NOTREACHED() << "Views should not receive touch events.";
1016 void View::OnGestureEvent(ui::GestureEvent* event) {
1019 ui::TextInputClient* View::GetTextInputClient() {
1020 return NULL;
1023 InputMethod* View::GetInputMethod() {
1024 Widget* widget = GetWidget();
1025 return widget ? widget->GetInputMethod() : NULL;
1028 const InputMethod* View::GetInputMethod() const {
1029 const Widget* widget = GetWidget();
1030 return widget ? widget->GetInputMethod() : NULL;
1033 scoped_ptr<ViewTargeter>
1034 View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) {
1035 scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass();
1036 targeter_ = targeter.Pass();
1037 return old_targeter.Pass();
1040 ViewTargeter* View::GetEffectiveViewTargeter() const {
1041 DCHECK(GetWidget());
1042 ViewTargeter* view_targeter = targeter();
1043 if (!view_targeter)
1044 view_targeter = GetWidget()->GetRootView()->targeter();
1045 CHECK(view_targeter);
1046 return view_targeter;
1049 bool View::CanAcceptEvent(const ui::Event& event) {
1050 return IsDrawn();
1053 ui::EventTarget* View::GetParentTarget() {
1054 return parent_;
1057 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1058 return make_scoped_ptr(new ui::EventTargetIteratorImpl<View>(children_));
1061 ui::EventTargeter* View::GetEventTargeter() {
1062 return targeter_.get();
1065 void View::ConvertEventToTarget(ui::EventTarget* target,
1066 ui::LocatedEvent* event) {
1067 event->ConvertLocationToTarget(this, static_cast<View*>(target));
1070 // Accelerators ----------------------------------------------------------------
1072 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1073 if (!accelerators_.get())
1074 accelerators_.reset(new std::vector<ui::Accelerator>());
1076 if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1077 accelerators_->end()) {
1078 accelerators_->push_back(accelerator);
1080 RegisterPendingAccelerators();
1083 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1084 if (!accelerators_.get()) {
1085 NOTREACHED() << "Removing non-existing accelerator";
1086 return;
1089 std::vector<ui::Accelerator>::iterator i(
1090 std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1091 if (i == accelerators_->end()) {
1092 NOTREACHED() << "Removing non-existing accelerator";
1093 return;
1096 size_t index = i - accelerators_->begin();
1097 accelerators_->erase(i);
1098 if (index >= registered_accelerator_count_) {
1099 // The accelerator is not registered to FocusManager.
1100 return;
1102 --registered_accelerator_count_;
1104 // Providing we are attached to a Widget and registered with a focus manager,
1105 // we should de-register from that focus manager now.
1106 if (GetWidget() && accelerator_focus_manager_)
1107 accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1110 void View::ResetAccelerators() {
1111 if (accelerators_.get())
1112 UnregisterAccelerators(false);
1115 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1116 return false;
1119 bool View::CanHandleAccelerators() const {
1120 return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1123 // Focus -----------------------------------------------------------------------
1125 bool View::HasFocus() const {
1126 const FocusManager* focus_manager = GetFocusManager();
1127 return focus_manager && (focus_manager->GetFocusedView() == this);
1130 View* View::GetNextFocusableView() {
1131 return next_focusable_view_;
1134 const View* View::GetNextFocusableView() const {
1135 return next_focusable_view_;
1138 View* View::GetPreviousFocusableView() {
1139 return previous_focusable_view_;
1142 void View::SetNextFocusableView(View* view) {
1143 if (view)
1144 view->previous_focusable_view_ = this;
1145 next_focusable_view_ = view;
1148 void View::SetFocusable(bool focusable) {
1149 if (focusable_ == focusable)
1150 return;
1152 focusable_ = focusable;
1153 AdvanceFocusIfNecessary();
1156 bool View::IsFocusable() const {
1157 return focusable_ && enabled_ && IsDrawn();
1160 bool View::IsAccessibilityFocusable() const {
1161 return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1164 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1165 if (accessibility_focusable_ == accessibility_focusable)
1166 return;
1168 accessibility_focusable_ = accessibility_focusable;
1169 AdvanceFocusIfNecessary();
1172 FocusManager* View::GetFocusManager() {
1173 Widget* widget = GetWidget();
1174 return widget ? widget->GetFocusManager() : NULL;
1177 const FocusManager* View::GetFocusManager() const {
1178 const Widget* widget = GetWidget();
1179 return widget ? widget->GetFocusManager() : NULL;
1182 void View::RequestFocus() {
1183 FocusManager* focus_manager = GetFocusManager();
1184 if (focus_manager && IsFocusable())
1185 focus_manager->SetFocusedView(this);
1188 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1189 return false;
1192 FocusTraversable* View::GetFocusTraversable() {
1193 return NULL;
1196 FocusTraversable* View::GetPaneFocusTraversable() {
1197 return NULL;
1200 // Tooltips --------------------------------------------------------------------
1202 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1203 return false;
1206 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1207 return false;
1210 // Context menus ---------------------------------------------------------------
1212 void View::ShowContextMenu(const gfx::Point& p,
1213 ui::MenuSourceType source_type) {
1214 if (!context_menu_controller_)
1215 return;
1217 context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1220 // static
1221 bool View::ShouldShowContextMenuOnMousePress() {
1222 return kContextMenuOnMousePress;
1225 gfx::Point View::GetKeyboardContextMenuLocation() {
1226 gfx::Rect vis_bounds = GetVisibleBounds();
1227 gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1228 vis_bounds.y() + vis_bounds.height() / 2);
1229 ConvertPointToScreen(this, &screen_point);
1230 return screen_point;
1233 // Drag and drop ---------------------------------------------------------------
1235 bool View::GetDropFormats(
1236 int* formats,
1237 std::set<OSExchangeData::CustomFormat>* custom_formats) {
1238 return false;
1241 bool View::AreDropTypesRequired() {
1242 return false;
1245 bool View::CanDrop(const OSExchangeData& data) {
1246 // TODO(sky): when I finish up migration, this should default to true.
1247 return false;
1250 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1253 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1254 return ui::DragDropTypes::DRAG_NONE;
1257 void View::OnDragExited() {
1260 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1261 return ui::DragDropTypes::DRAG_NONE;
1264 void View::OnDragDone() {
1267 // static
1268 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1269 return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1270 abs(delta.y()) > GetVerticalDragThreshold());
1273 // Accessibility----------------------------------------------------------------
1275 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1276 if (!native_view_accessibility_)
1277 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1278 if (native_view_accessibility_)
1279 return native_view_accessibility_->GetNativeObject();
1280 return NULL;
1283 void View::NotifyAccessibilityEvent(
1284 ui::AXEvent event_type,
1285 bool send_native_event) {
1286 if (ViewsDelegate::views_delegate)
1287 ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1289 if (send_native_event && GetWidget()) {
1290 if (!native_view_accessibility_)
1291 native_view_accessibility_ = NativeViewAccessibility::Create(this);
1292 if (native_view_accessibility_)
1293 native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1297 // Scrolling -------------------------------------------------------------------
1299 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1300 // We must take RTL UI mirroring into account when adjusting the position of
1301 // the region.
1302 if (parent_) {
1303 gfx::Rect scroll_rect(rect);
1304 scroll_rect.Offset(GetMirroredX(), y());
1305 parent_->ScrollRectToVisible(scroll_rect);
1309 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1310 bool is_horizontal, bool is_positive) {
1311 return 0;
1314 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1315 bool is_horizontal, bool is_positive) {
1316 return 0;
1319 ////////////////////////////////////////////////////////////////////////////////
1320 // View, protected:
1322 // Size and disposition --------------------------------------------------------
1324 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1327 void View::PreferredSizeChanged() {
1328 InvalidateLayout();
1329 if (parent_)
1330 parent_->ChildPreferredSizeChanged(this);
1333 bool View::GetNeedsNotificationWhenVisibleBoundsChange() const {
1334 return false;
1337 void View::OnVisibleBoundsChanged() {
1340 // Tree operations -------------------------------------------------------------
1342 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1345 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1348 void View::NativeViewHierarchyChanged() {
1349 FocusManager* focus_manager = GetFocusManager();
1350 if (accelerator_focus_manager_ != focus_manager) {
1351 UnregisterAccelerators(true);
1353 if (focus_manager)
1354 RegisterPendingAccelerators();
1358 // Painting --------------------------------------------------------------------
1360 void View::PaintChildren(const ui::PaintContext& context) {
1361 TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1362 for (int i = 0, count = child_count(); i < count; ++i)
1363 if (!child_at(i)->layer())
1364 child_at(i)->Paint(context);
1367 void View::OnPaint(gfx::Canvas* canvas) {
1368 TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1369 OnPaintBackground(canvas);
1370 OnPaintBorder(canvas);
1373 void View::OnPaintBackground(gfx::Canvas* canvas) {
1374 if (background_.get()) {
1375 TRACE_EVENT2("views", "View::OnPaintBackground",
1376 "width", canvas->sk_canvas()->getDevice()->width(),
1377 "height", canvas->sk_canvas()->getDevice()->height());
1378 background_->Paint(canvas, this);
1382 void View::OnPaintBorder(gfx::Canvas* canvas) {
1383 if (border_.get()) {
1384 TRACE_EVENT2("views", "View::OnPaintBorder",
1385 "width", canvas->sk_canvas()->getDevice()->width(),
1386 "height", canvas->sk_canvas()->getDevice()->height());
1387 border_->Paint(*this, canvas);
1391 // Accelerated Painting --------------------------------------------------------
1393 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1394 // This method should not have the side-effect of creating the layer.
1395 if (layer())
1396 layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1399 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1400 ui::Layer** layer_parent) {
1401 if (layer()) {
1402 if (layer_parent)
1403 *layer_parent = layer();
1404 return gfx::Vector2d();
1406 if (!parent_)
1407 return gfx::Vector2d();
1409 return gfx::Vector2d(GetMirroredX(), y()) +
1410 parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1413 void View::UpdateParentLayer() {
1414 if (!layer())
1415 return;
1417 ui::Layer* parent_layer = NULL;
1418 gfx::Vector2d offset(GetMirroredX(), y());
1420 if (parent_)
1421 offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1423 ReparentLayer(offset, parent_layer);
1426 void View::MoveLayerToParent(ui::Layer* parent_layer,
1427 const gfx::Point& point) {
1428 gfx::Point local_point(point);
1429 if (parent_layer != layer())
1430 local_point.Offset(GetMirroredX(), y());
1431 if (layer() && parent_layer != layer()) {
1432 parent_layer->Add(layer());
1433 SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1434 width(), height()));
1435 } else {
1436 for (int i = 0, count = child_count(); i < count; ++i)
1437 child_at(i)->MoveLayerToParent(parent_layer, local_point);
1441 void View::UpdateLayerVisibility() {
1442 bool visible = visible_;
1443 for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1444 visible = v->visible();
1446 UpdateChildLayerVisibility(visible);
1449 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1450 if (layer()) {
1451 layer()->SetVisible(ancestor_visible && visible_);
1452 } else {
1453 for (int i = 0, count = child_count(); i < count; ++i)
1454 child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1458 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1459 if (layer()) {
1460 SetLayerBounds(GetLocalBounds() + offset);
1461 } else {
1462 for (int i = 0, count = child_count(); i < count; ++i) {
1463 View* child = child_at(i);
1464 child->UpdateChildLayerBounds(
1465 offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1470 void View::OnPaintLayer(const ui::PaintContext& context) {
1471 if (!layer()->fills_bounds_opaquely()) {
1472 ui::PaintRecorder recorder(context);
1473 recorder.canvas()->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1475 if (!visible_)
1476 return;
1477 Paint(context);
1480 void View::OnDelegatedFrameDamage(
1481 const gfx::Rect& damage_rect_in_dip) {
1484 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1485 snap_layer_to_pixel_boundary_ =
1486 (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1487 SnapLayerToPixelBoundary();
1488 // Repainting with new scale factor will paint the content at the right scale.
1491 base::Closure View::PrepareForLayerBoundsChange() {
1492 return base::Closure();
1495 void View::ReorderLayers() {
1496 View* v = this;
1497 while (v && !v->layer())
1498 v = v->parent();
1500 Widget* widget = GetWidget();
1501 if (!v) {
1502 if (widget) {
1503 ui::Layer* layer = widget->GetLayer();
1504 if (layer)
1505 widget->GetRootView()->ReorderChildLayers(layer);
1507 } else {
1508 v->ReorderChildLayers(v->layer());
1511 if (widget) {
1512 // Reorder the widget's child NativeViews in case a child NativeView is
1513 // associated with a view (eg via a NativeViewHost). Always do the
1514 // reordering because the associated NativeView's layer (if it has one)
1515 // is parented to the widget's layer regardless of whether the host view has
1516 // an ancestor with a layer.
1517 widget->ReorderNativeViews();
1521 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1522 if (layer() && layer() != parent_layer) {
1523 DCHECK_EQ(parent_layer, layer()->parent());
1524 parent_layer->StackAtBottom(layer());
1525 } else {
1526 // Iterate backwards through the children so that a child with a layer
1527 // which is further to the back is stacked above one which is further to
1528 // the front.
1529 for (Views::reverse_iterator it(children_.rbegin());
1530 it != children_.rend(); ++it) {
1531 (*it)->ReorderChildLayers(parent_layer);
1536 // Input -----------------------------------------------------------------------
1538 View::DragInfo* View::GetDragInfo() {
1539 return parent_ ? parent_->GetDragInfo() : NULL;
1542 // Focus -----------------------------------------------------------------------
1544 void View::OnFocus() {
1545 // TODO(beng): Investigate whether it's possible for us to move this to
1546 // Focus().
1547 // By default, we clear the native focus. This ensures that no visible native
1548 // view as the focus and that we still receive keyboard inputs.
1549 FocusManager* focus_manager = GetFocusManager();
1550 if (focus_manager)
1551 focus_manager->ClearNativeFocus();
1553 // TODO(beng): Investigate whether it's possible for us to move this to
1554 // Focus().
1555 // Notify assistive technologies of the focus change.
1556 NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1559 void View::OnBlur() {
1562 void View::Focus() {
1563 OnFocus();
1566 void View::Blur() {
1567 OnBlur();
1570 // Tooltips --------------------------------------------------------------------
1572 void View::TooltipTextChanged() {
1573 Widget* widget = GetWidget();
1574 // TooltipManager may be null if there is a problem creating it.
1575 if (widget && widget->GetTooltipManager())
1576 widget->GetTooltipManager()->TooltipTextChanged(this);
1579 // Drag and drop ---------------------------------------------------------------
1581 int View::GetDragOperations(const gfx::Point& press_pt) {
1582 return drag_controller_ ?
1583 drag_controller_->GetDragOperationsForView(this, press_pt) :
1584 ui::DragDropTypes::DRAG_NONE;
1587 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1588 DCHECK(drag_controller_);
1589 drag_controller_->WriteDragDataForView(this, press_pt, data);
1592 bool View::InDrag() {
1593 Widget* widget = GetWidget();
1594 return widget ? widget->dragged_view() == this : false;
1597 int View::GetHorizontalDragThreshold() {
1598 // TODO(jennyz): This value may need to be adjusted for different platforms
1599 // and for different display density.
1600 return kDefaultHorizontalDragThreshold;
1603 int View::GetVerticalDragThreshold() {
1604 // TODO(jennyz): This value may need to be adjusted for different platforms
1605 // and for different display density.
1606 return kDefaultVerticalDragThreshold;
1609 // Debugging -------------------------------------------------------------------
1611 #if !defined(NDEBUG)
1613 std::string View::PrintViewGraph(bool first) {
1614 return DoPrintViewGraph(first, this);
1617 std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
1618 // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
1619 const size_t kMaxPointerStringLength = 19;
1621 std::string result;
1623 if (first)
1624 result.append("digraph {\n");
1626 // Node characteristics.
1627 char p[kMaxPointerStringLength];
1629 const std::string class_name(GetClassName());
1630 size_t base_name_index = class_name.find_last_of('/');
1631 if (base_name_index == std::string::npos)
1632 base_name_index = 0;
1633 else
1634 base_name_index++;
1636 char bounds_buffer[512];
1638 // Information about current node.
1639 base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
1640 result.append(" N");
1641 result.append(p + 2);
1642 result.append(" [label=\"");
1644 result.append(class_name.substr(base_name_index).c_str());
1646 base::snprintf(bounds_buffer,
1647 arraysize(bounds_buffer),
1648 "\\n bounds: (%d, %d), (%dx%d)",
1649 bounds().x(),
1650 bounds().y(),
1651 bounds().width(),
1652 bounds().height());
1653 result.append(bounds_buffer);
1655 gfx::DecomposedTransform decomp;
1656 if (!GetTransform().IsIdentity() &&
1657 gfx::DecomposeTransform(&decomp, GetTransform())) {
1658 base::snprintf(bounds_buffer,
1659 arraysize(bounds_buffer),
1660 "\\n translation: (%f, %f)",
1661 decomp.translate[0],
1662 decomp.translate[1]);
1663 result.append(bounds_buffer);
1665 base::snprintf(bounds_buffer,
1666 arraysize(bounds_buffer),
1667 "\\n rotation: %3.2f",
1668 std::acos(decomp.quaternion[3]) * 360.0 / M_PI);
1669 result.append(bounds_buffer);
1671 base::snprintf(bounds_buffer,
1672 arraysize(bounds_buffer),
1673 "\\n scale: (%2.4f, %2.4f)",
1674 decomp.scale[0],
1675 decomp.scale[1]);
1676 result.append(bounds_buffer);
1679 result.append("\"");
1680 if (!parent_)
1681 result.append(", shape=box");
1682 if (layer()) {
1683 if (layer()->has_external_content())
1684 result.append(", color=green");
1685 else
1686 result.append(", color=red");
1688 if (layer()->fills_bounds_opaquely())
1689 result.append(", style=filled");
1691 result.append("]\n");
1693 // Link to parent.
1694 if (parent_) {
1695 char pp[kMaxPointerStringLength];
1697 base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
1698 result.append(" N");
1699 result.append(pp + 2);
1700 result.append(" -> N");
1701 result.append(p + 2);
1702 result.append("\n");
1705 // Children.
1706 for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
1707 result.append(view_with_children->child_at(i)->PrintViewGraph(false));
1709 if (first)
1710 result.append("}\n");
1712 return result;
1714 #endif
1716 ////////////////////////////////////////////////////////////////////////////////
1717 // View, private:
1719 // DropInfo --------------------------------------------------------------------
1721 void View::DragInfo::Reset() {
1722 possible_drag = false;
1723 start_pt = gfx::Point();
1726 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1727 possible_drag = true;
1728 start_pt = p;
1731 // Painting --------------------------------------------------------------------
1733 void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
1734 // If we have a layer and the View's size did not change, we do not need to
1735 // schedule any paints since the layer will be redrawn at its new location
1736 // during the next Draw() cycle in the compositor.
1737 if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
1738 // Otherwise, if the size changes or we don't have a layer then we need to
1739 // use SchedulePaint to invalidate the area occupied by the View.
1740 SchedulePaint();
1741 } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
1742 // The compositor doesn't Draw() until something on screen changes, so
1743 // if our position changes but nothing is being animated on screen, then
1744 // tell the compositor to redraw the scene. We know layer() exists due to
1745 // the above if clause.
1746 layer()->ScheduleDraw();
1750 // Tree operations -------------------------------------------------------------
1752 void View::DoRemoveChildView(View* view,
1753 bool update_focus_cycle,
1754 bool update_tool_tip,
1755 bool delete_removed_view,
1756 View* new_parent) {
1757 DCHECK(view);
1759 const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1760 scoped_ptr<View> view_to_be_deleted;
1761 if (i != children_.end()) {
1762 if (update_focus_cycle) {
1763 // Let's remove the view from the focus traversal.
1764 View* next_focusable = view->next_focusable_view_;
1765 View* prev_focusable = view->previous_focusable_view_;
1766 if (prev_focusable)
1767 prev_focusable->next_focusable_view_ = next_focusable;
1768 if (next_focusable)
1769 next_focusable->previous_focusable_view_ = prev_focusable;
1772 if (GetWidget()) {
1773 UnregisterChildrenForVisibleBoundsNotification(view);
1774 if (view->visible())
1775 view->SchedulePaint();
1776 GetWidget()->NotifyWillRemoveView(view);
1779 view->PropagateRemoveNotifications(this, new_parent);
1780 view->parent_ = NULL;
1781 view->UpdateLayerVisibility();
1783 if (delete_removed_view && !view->owned_by_client_)
1784 view_to_be_deleted.reset(view);
1786 children_.erase(i);
1789 if (update_tool_tip)
1790 UpdateTooltip();
1792 if (layout_manager_.get())
1793 layout_manager_->ViewRemoved(this, view);
1796 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1797 for (int i = 0, count = child_count(); i < count; ++i)
1798 child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1800 ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1801 for (View* v = this; v; v = v->parent_)
1802 v->ViewHierarchyChangedImpl(true, details);
1805 void View::PropagateAddNotifications(
1806 const ViewHierarchyChangedDetails& details) {
1807 for (int i = 0, count = child_count(); i < count; ++i)
1808 child_at(i)->PropagateAddNotifications(details);
1809 ViewHierarchyChangedImpl(true, details);
1812 void View::PropagateNativeViewHierarchyChanged() {
1813 for (int i = 0, count = child_count(); i < count; ++i)
1814 child_at(i)->PropagateNativeViewHierarchyChanged();
1815 NativeViewHierarchyChanged();
1818 void View::ViewHierarchyChangedImpl(
1819 bool register_accelerators,
1820 const ViewHierarchyChangedDetails& details) {
1821 if (register_accelerators) {
1822 if (details.is_add) {
1823 // If you get this registration, you are part of a subtree that has been
1824 // added to the view hierarchy.
1825 if (GetFocusManager())
1826 RegisterPendingAccelerators();
1827 } else {
1828 if (details.child == this)
1829 UnregisterAccelerators(true);
1833 if (details.is_add && layer() && !layer()->parent()) {
1834 UpdateParentLayer();
1835 Widget* widget = GetWidget();
1836 if (widget)
1837 widget->UpdateRootLayers();
1838 } else if (!details.is_add && details.child == this) {
1839 // Make sure the layers belonging to the subtree rooted at |child| get
1840 // removed from layers that do not belong in the same subtree.
1841 OrphanLayers();
1842 Widget* widget = GetWidget();
1843 if (widget)
1844 widget->UpdateRootLayers();
1847 ViewHierarchyChanged(details);
1848 details.parent->needs_layout_ = true;
1851 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1852 for (int i = 0, count = child_count(); i < count; ++i)
1853 child_at(i)->PropagateNativeThemeChanged(theme);
1854 OnNativeThemeChanged(theme);
1857 // Size and disposition --------------------------------------------------------
1859 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1860 for (int i = 0, count = child_count(); i < count; ++i)
1861 child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1862 VisibilityChangedImpl(start, is_visible);
1865 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1866 VisibilityChanged(starting_from, is_visible);
1869 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1870 if (visible_) {
1871 // Paint the new bounds.
1872 SchedulePaintBoundsChanged(
1873 bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1874 SCHEDULE_PAINT_SIZE_CHANGED);
1877 if (layer()) {
1878 if (parent_) {
1879 SetLayerBounds(GetLocalBounds() +
1880 gfx::Vector2d(GetMirroredX(), y()) +
1881 parent_->CalculateOffsetToAncestorWithLayer(NULL));
1882 } else {
1883 SetLayerBounds(bounds_);
1886 // In RTL mode, if our width has changed, our children's mirrored bounds
1887 // will have changed. Update the child's layer bounds, or if it is not a
1888 // layer, the bounds of any layers inside the child.
1889 if (base::i18n::IsRTL() && bounds_.width() != previous_bounds.width()) {
1890 for (int i = 0; i < child_count(); ++i) {
1891 View* child = child_at(i);
1892 child->UpdateChildLayerBounds(
1893 gfx::Vector2d(child->GetMirroredX(), child->y()));
1896 } else {
1897 // If our bounds have changed, then any descendant layer bounds may have
1898 // changed. Update them accordingly.
1899 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1902 OnBoundsChanged(previous_bounds);
1904 if (previous_bounds.size() != size()) {
1905 needs_layout_ = false;
1906 Layout();
1909 if (GetNeedsNotificationWhenVisibleBoundsChange())
1910 OnVisibleBoundsChanged();
1912 // Notify interested Views that visible bounds within the root view may have
1913 // changed.
1914 if (descendants_to_notify_.get()) {
1915 for (Views::iterator i(descendants_to_notify_->begin());
1916 i != descendants_to_notify_->end(); ++i) {
1917 (*i)->OnVisibleBoundsChanged();
1922 // static
1923 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1924 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1925 view->RegisterForVisibleBoundsNotification();
1926 for (int i = 0; i < view->child_count(); ++i)
1927 RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1930 // static
1931 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1932 if (view->GetNeedsNotificationWhenVisibleBoundsChange())
1933 view->UnregisterForVisibleBoundsNotification();
1934 for (int i = 0; i < view->child_count(); ++i)
1935 UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1938 void View::RegisterForVisibleBoundsNotification() {
1939 if (registered_for_visible_bounds_notification_)
1940 return;
1942 registered_for_visible_bounds_notification_ = true;
1943 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1944 ancestor->AddDescendantToNotify(this);
1947 void View::UnregisterForVisibleBoundsNotification() {
1948 if (!registered_for_visible_bounds_notification_)
1949 return;
1951 registered_for_visible_bounds_notification_ = false;
1952 for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1953 ancestor->RemoveDescendantToNotify(this);
1956 void View::AddDescendantToNotify(View* view) {
1957 DCHECK(view);
1958 if (!descendants_to_notify_.get())
1959 descendants_to_notify_.reset(new Views);
1960 descendants_to_notify_->push_back(view);
1963 void View::RemoveDescendantToNotify(View* view) {
1964 DCHECK(view && descendants_to_notify_.get());
1965 Views::iterator i(std::find(
1966 descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1967 DCHECK(i != descendants_to_notify_->end());
1968 descendants_to_notify_->erase(i);
1969 if (descendants_to_notify_->empty())
1970 descendants_to_notify_.reset();
1973 void View::SetLayerBounds(const gfx::Rect& bounds) {
1974 layer()->SetBounds(bounds);
1975 SnapLayerToPixelBoundary();
1978 // Transformations -------------------------------------------------------------
1980 bool View::GetTransformRelativeTo(const View* ancestor,
1981 gfx::Transform* transform) const {
1982 const View* p = this;
1984 while (p && p != ancestor) {
1985 transform->ConcatTransform(p->GetTransform());
1986 gfx::Transform translation;
1987 translation.Translate(static_cast<float>(p->GetMirroredX()),
1988 static_cast<float>(p->y()));
1989 transform->ConcatTransform(translation);
1991 p = p->parent_;
1994 return p == ancestor;
1997 // Coordinate conversion -------------------------------------------------------
1999 bool View::ConvertPointForAncestor(const View* ancestor,
2000 gfx::Point* point) const {
2001 gfx::Transform trans;
2002 // TODO(sad): Have some way of caching the transformation results.
2003 bool result = GetTransformRelativeTo(ancestor, &trans);
2004 gfx::Point3F p(*point);
2005 trans.TransformPoint(&p);
2006 *point = gfx::ToFlooredPoint(p.AsPointF());
2007 return result;
2010 bool View::ConvertPointFromAncestor(const View* ancestor,
2011 gfx::Point* point) const {
2012 gfx::Transform trans;
2013 bool result = GetTransformRelativeTo(ancestor, &trans);
2014 gfx::Point3F p(*point);
2015 trans.TransformPointReverse(&p);
2016 *point = gfx::ToFlooredPoint(p.AsPointF());
2017 return result;
2020 bool View::ConvertRectForAncestor(const View* ancestor,
2021 gfx::RectF* rect) const {
2022 gfx::Transform trans;
2023 // TODO(sad): Have some way of caching the transformation results.
2024 bool result = GetTransformRelativeTo(ancestor, &trans);
2025 trans.TransformRect(rect);
2026 return result;
2029 bool View::ConvertRectFromAncestor(const View* ancestor,
2030 gfx::RectF* rect) const {
2031 gfx::Transform trans;
2032 bool result = GetTransformRelativeTo(ancestor, &trans);
2033 trans.TransformRectReverse(rect);
2034 return result;
2037 // Accelerated painting --------------------------------------------------------
2039 void View::CreateLayer() {
2040 // A new layer is being created for the view. So all the layers of the
2041 // sub-tree can inherit the visibility of the corresponding view.
2042 for (int i = 0, count = child_count(); i < count; ++i)
2043 child_at(i)->UpdateChildLayerVisibility(true);
2045 SetLayer(new ui::Layer());
2046 layer()->set_delegate(this);
2047 #if !defined(NDEBUG)
2048 layer()->set_name(GetClassName());
2049 #endif
2051 UpdateParentLayers();
2052 UpdateLayerVisibility();
2054 // The new layer needs to be ordered in the layer tree according
2055 // to the view tree. Children of this layer were added in order
2056 // in UpdateParentLayers().
2057 if (parent())
2058 parent()->ReorderLayers();
2060 Widget* widget = GetWidget();
2061 if (widget)
2062 widget->UpdateRootLayers();
2065 void View::UpdateParentLayers() {
2066 // Attach all top-level un-parented layers.
2067 if (layer() && !layer()->parent()) {
2068 UpdateParentLayer();
2069 } else {
2070 for (int i = 0, count = child_count(); i < count; ++i)
2071 child_at(i)->UpdateParentLayers();
2075 void View::OrphanLayers() {
2076 if (layer()) {
2077 if (layer()->parent())
2078 layer()->parent()->Remove(layer());
2080 // The layer belonging to this View has already been orphaned. It is not
2081 // necessary to orphan the child layers.
2082 return;
2084 for (int i = 0, count = child_count(); i < count; ++i)
2085 child_at(i)->OrphanLayers();
2088 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2089 layer()->SetBounds(GetLocalBounds() + offset);
2090 DCHECK_NE(layer(), parent_layer);
2091 if (parent_layer)
2092 parent_layer->Add(layer());
2093 layer()->SchedulePaint(GetLocalBounds());
2094 MoveLayerToParent(layer(), gfx::Point());
2097 void View::DestroyLayer() {
2098 ui::Layer* new_parent = layer()->parent();
2099 std::vector<ui::Layer*> children = layer()->children();
2100 for (size_t i = 0; i < children.size(); ++i) {
2101 layer()->Remove(children[i]);
2102 if (new_parent)
2103 new_parent->Add(children[i]);
2106 LayerOwner::DestroyLayer();
2108 if (new_parent)
2109 ReorderLayers();
2111 UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2113 SchedulePaint();
2115 Widget* widget = GetWidget();
2116 if (widget)
2117 widget->UpdateRootLayers();
2120 // Input -----------------------------------------------------------------------
2122 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2123 int drag_operations =
2124 (enabled_ && event.IsOnlyLeftMouseButton() &&
2125 HitTestPoint(event.location())) ?
2126 GetDragOperations(event.location()) : 0;
2127 ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2128 context_menu_controller_ : 0;
2129 View::DragInfo* drag_info = GetDragInfo();
2131 // TODO(sky): for debugging 360238.
2132 int storage_id = 0;
2133 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2134 kContextMenuOnMousePress && HitTestPoint(event.location())) {
2135 ViewStorage* view_storage = ViewStorage::GetInstance();
2136 storage_id = view_storage->CreateStorageID();
2137 view_storage->StoreView(storage_id, this);
2140 const bool enabled = enabled_;
2141 const bool result = OnMousePressed(event);
2143 if (!enabled)
2144 return result;
2146 if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2147 kContextMenuOnMousePress) {
2148 // Assume that if there is a context menu controller we won't be deleted
2149 // from mouse pressed.
2150 gfx::Point location(event.location());
2151 if (HitTestPoint(location)) {
2152 if (storage_id != 0)
2153 CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2154 ConvertPointToScreen(this, &location);
2155 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2156 return true;
2160 // WARNING: we may have been deleted, don't use any View variables.
2161 if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2162 drag_info->PossibleDrag(event.location());
2163 return true;
2165 return !!context_menu_controller || result;
2168 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2169 // Copy the field, that way if we're deleted after drag and drop no harm is
2170 // done.
2171 ContextMenuController* context_menu_controller = context_menu_controller_;
2172 const bool possible_drag = GetDragInfo()->possible_drag;
2173 if (possible_drag &&
2174 ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2175 (!drag_controller_ ||
2176 drag_controller_->CanStartDragForView(
2177 this, GetDragInfo()->start_pt, event.location()))) {
2178 DoDrag(event, GetDragInfo()->start_pt,
2179 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2180 } else {
2181 if (OnMouseDragged(event))
2182 return true;
2183 // Fall through to return value based on context menu controller.
2185 // WARNING: we may have been deleted.
2186 return (context_menu_controller != NULL) || possible_drag;
2189 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2190 if (!kContextMenuOnMousePress && context_menu_controller_ &&
2191 event.IsOnlyRightMouseButton()) {
2192 // Assume that if there is a context menu controller we won't be deleted
2193 // from mouse released.
2194 gfx::Point location(event.location());
2195 OnMouseReleased(event);
2196 if (HitTestPoint(location)) {
2197 ConvertPointToScreen(this, &location);
2198 ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2200 } else {
2201 OnMouseReleased(event);
2203 // WARNING: we may have been deleted.
2206 // Accelerators ----------------------------------------------------------------
2208 void View::RegisterPendingAccelerators() {
2209 if (!accelerators_.get() ||
2210 registered_accelerator_count_ == accelerators_->size()) {
2211 // No accelerators are waiting for registration.
2212 return;
2215 if (!GetWidget()) {
2216 // The view is not yet attached to a widget, defer registration until then.
2217 return;
2220 accelerator_focus_manager_ = GetFocusManager();
2221 if (!accelerator_focus_manager_) {
2222 // Some crash reports seem to show that we may get cases where we have no
2223 // focus manager (see bug #1291225). This should never be the case, just
2224 // making sure we don't crash.
2225 NOTREACHED();
2226 return;
2228 for (std::vector<ui::Accelerator>::const_iterator i(
2229 accelerators_->begin() + registered_accelerator_count_);
2230 i != accelerators_->end(); ++i) {
2231 accelerator_focus_manager_->RegisterAccelerator(
2232 *i, ui::AcceleratorManager::kNormalPriority, this);
2234 registered_accelerator_count_ = accelerators_->size();
2237 void View::UnregisterAccelerators(bool leave_data_intact) {
2238 if (!accelerators_.get())
2239 return;
2241 if (GetWidget()) {
2242 if (accelerator_focus_manager_) {
2243 accelerator_focus_manager_->UnregisterAccelerators(this);
2244 accelerator_focus_manager_ = NULL;
2246 if (!leave_data_intact) {
2247 accelerators_->clear();
2248 accelerators_.reset();
2250 registered_accelerator_count_ = 0;
2254 // Focus -----------------------------------------------------------------------
2256 void View::InitFocusSiblings(View* v, int index) {
2257 int count = child_count();
2259 if (count == 0) {
2260 v->next_focusable_view_ = NULL;
2261 v->previous_focusable_view_ = NULL;
2262 } else {
2263 if (index == count) {
2264 // We are inserting at the end, but the end of the child list may not be
2265 // the last focusable element. Let's try to find an element with no next
2266 // focusable element to link to.
2267 View* last_focusable_view = NULL;
2268 for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2269 if (!(*i)->next_focusable_view_) {
2270 last_focusable_view = *i;
2271 break;
2274 if (last_focusable_view == NULL) {
2275 // Hum... there is a cycle in the focus list. Let's just insert ourself
2276 // after the last child.
2277 View* prev = children_[index - 1];
2278 v->previous_focusable_view_ = prev;
2279 v->next_focusable_view_ = prev->next_focusable_view_;
2280 prev->next_focusable_view_->previous_focusable_view_ = v;
2281 prev->next_focusable_view_ = v;
2282 } else {
2283 last_focusable_view->next_focusable_view_ = v;
2284 v->next_focusable_view_ = NULL;
2285 v->previous_focusable_view_ = last_focusable_view;
2287 } else {
2288 View* prev = children_[index]->GetPreviousFocusableView();
2289 v->previous_focusable_view_ = prev;
2290 v->next_focusable_view_ = children_[index];
2291 if (prev)
2292 prev->next_focusable_view_ = v;
2293 children_[index]->previous_focusable_view_ = v;
2298 void View::AdvanceFocusIfNecessary() {
2299 // Focus should only be advanced if this is the focused view and has become
2300 // unfocusable. If the view is still focusable or is not focused, we can
2301 // return early avoiding furthur unnecessary checks. Focusability check is
2302 // performed first as it tends to be faster.
2303 if (IsAccessibilityFocusable() || !HasFocus())
2304 return;
2306 FocusManager* focus_manager = GetFocusManager();
2307 if (focus_manager)
2308 focus_manager->AdvanceFocusIfNecessary();
2311 // System events ---------------------------------------------------------------
2313 void View::PropagateThemeChanged() {
2314 for (int i = child_count() - 1; i >= 0; --i)
2315 child_at(i)->PropagateThemeChanged();
2316 OnThemeChanged();
2319 void View::PropagateLocaleChanged() {
2320 for (int i = child_count() - 1; i >= 0; --i)
2321 child_at(i)->PropagateLocaleChanged();
2322 OnLocaleChanged();
2325 void View::PropagateDeviceScaleFactorChanged(float device_scale_factor) {
2326 for (int i = child_count() - 1; i >= 0; --i)
2327 child_at(i)->PropagateDeviceScaleFactorChanged(device_scale_factor);
2329 // If the view is drawing to the layer, OnDeviceScaleFactorChanged() is called
2330 // through LayerDelegate callback.
2331 if (!layer())
2332 OnDeviceScaleFactorChanged(device_scale_factor);
2335 // Tooltips --------------------------------------------------------------------
2337 void View::UpdateTooltip() {
2338 Widget* widget = GetWidget();
2339 // TODO(beng): The TooltipManager NULL check can be removed when we
2340 // consolidate Init() methods and make views_unittests Init() all
2341 // Widgets that it uses.
2342 if (widget && widget->GetTooltipManager())
2343 widget->GetTooltipManager()->UpdateTooltip();
2346 // Drag and drop ---------------------------------------------------------------
2348 bool View::DoDrag(const ui::LocatedEvent& event,
2349 const gfx::Point& press_pt,
2350 ui::DragDropTypes::DragEventSource source) {
2351 int drag_operations = GetDragOperations(press_pt);
2352 if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2353 return false;
2355 Widget* widget = GetWidget();
2356 // We should only start a drag from an event, implying we have a widget.
2357 DCHECK(widget);
2359 // Don't attempt to start a drag while in the process of dragging. This is
2360 // especially important on X where we can get multiple mouse move events when
2361 // we start the drag.
2362 if (widget->dragged_view())
2363 return false;
2365 OSExchangeData data;
2366 WriteDragData(press_pt, &data);
2368 // Message the RootView to do the drag and drop. That way if we're removed
2369 // the RootView can detect it and avoid calling us back.
2370 gfx::Point widget_location(event.location());
2371 ConvertPointToWidget(this, &widget_location);
2372 widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2373 // WARNING: we may have been deleted.
2374 return true;
2377 } // namespace views