011954079b218a9b539f063f8e2c2fec82afb9f6
[platform/framework/web/crosswalk.git] / src / ui / views / view.cc
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.
4
5 #define _USE_MATH_DEFINES // For VC++ to get M_PI. This has to be first.
6
7 #include "ui/views/view.h"
8
9 #include <algorithm>
10 #include <cmath>
11
12 #include "base/debug/trace_event.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.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/compositor.h"
23 #include "ui/compositor/dip_util.h"
24 #include "ui/compositor/layer.h"
25 #include "ui/compositor/layer_animator.h"
26 #include "ui/events/event_target_iterator.h"
27 #include "ui/gfx/canvas.h"
28 #include "ui/gfx/interpolated_transform.h"
29 #include "ui/gfx/path.h"
30 #include "ui/gfx/point3_f.h"
31 #include "ui/gfx/point_conversions.h"
32 #include "ui/gfx/scoped_canvas.h"
33 #include "ui/gfx/screen.h"
34 #include "ui/gfx/skia_util.h"
35 #include "ui/gfx/transform.h"
36 #include "ui/native_theme/native_theme.h"
37 #include "ui/views/accessibility/native_view_accessibility.h"
38 #include "ui/views/background.h"
39 #include "ui/views/border.h"
40 #include "ui/views/context_menu_controller.h"
41 #include "ui/views/drag_controller.h"
42 #include "ui/views/focus/view_storage.h"
43 #include "ui/views/layout/layout_manager.h"
44 #include "ui/views/views_delegate.h"
45 #include "ui/views/widget/native_widget_private.h"
46 #include "ui/views/widget/root_view.h"
47 #include "ui/views/widget/tooltip_manager.h"
48 #include "ui/views/widget/widget.h"
49
50 #if defined(OS_WIN)
51 #include "base/win/scoped_gdi_object.h"
52 #endif
53
54 namespace {
55
56 #if defined(OS_WIN)
57 const bool kContextMenuOnMousePress = false;
58 #else
59 const bool kContextMenuOnMousePress = true;
60 #endif
61
62 // Default horizontal drag threshold in pixels.
63 // Same as what gtk uses.
64 const int kDefaultHorizontalDragThreshold = 8;
65
66 // Default vertical drag threshold in pixels.
67 // Same as what gtk uses.
68 const int kDefaultVerticalDragThreshold = 8;
69
70 // Returns the top view in |view|'s hierarchy.
71 const views::View* GetHierarchyRoot(const views::View* view) {
72   const views::View* root = view;
73   while (root && root->parent())
74     root = root->parent();
75   return root;
76 }
77
78 }  // namespace
79
80 namespace views {
81
82 namespace internal {
83
84 }  // namespace internal
85
86 // static
87 ViewsDelegate* ViewsDelegate::views_delegate = NULL;
88
89 // static
90 const char View::kViewClassName[] = "View";
91
92 ////////////////////////////////////////////////////////////////////////////////
93 // View, public:
94
95 // Creation and lifetime -------------------------------------------------------
96
97 View::View()
98     : owned_by_client_(false),
99       id_(0),
100       group_(-1),
101       parent_(NULL),
102       visible_(true),
103       enabled_(true),
104       notify_enter_exit_on_child_(false),
105       registered_for_visible_bounds_notification_(false),
106       root_bounds_dirty_(true),
107       clip_insets_(0, 0, 0, 0),
108       needs_layout_(true),
109       snap_layer_to_pixel_boundary_(false),
110       flip_canvas_on_paint_for_rtl_ui_(false),
111       paint_to_layer_(false),
112       accelerator_focus_manager_(NULL),
113       registered_accelerator_count_(0),
114       next_focusable_view_(NULL),
115       previous_focusable_view_(NULL),
116       focusable_(false),
117       accessibility_focusable_(false),
118       context_menu_controller_(NULL),
119       drag_controller_(NULL),
120       native_view_accessibility_(NULL) {
121 }
122
123 View::~View() {
124   if (parent_)
125     parent_->RemoveChildView(this);
126
127   ViewStorage::GetInstance()->ViewRemoved(this);
128
129   for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
130     (*i)->parent_ = NULL;
131     if (!(*i)->owned_by_client_)
132       delete *i;
133   }
134
135   // Release ownership of the native accessibility object, but it's
136   // reference-counted on some platforms, so it may not be deleted right away.
137   if (native_view_accessibility_)
138     native_view_accessibility_->Destroy();
139 }
140
141 // Tree operations -------------------------------------------------------------
142
143 const Widget* View::GetWidget() const {
144   // The root view holds a reference to this view hierarchy's Widget.
145   return parent_ ? parent_->GetWidget() : NULL;
146 }
147
148 Widget* View::GetWidget() {
149   return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
150 }
151
152 void View::AddChildView(View* view) {
153   if (view->parent_ == this)
154     return;
155   AddChildViewAt(view, child_count());
156 }
157
158 void View::AddChildViewAt(View* view, int index) {
159   CHECK_NE(view, this) << "You cannot add a view as its own child";
160   DCHECK_GE(index, 0);
161   DCHECK_LE(index, child_count());
162
163   // If |view| has a parent, remove it from its parent.
164   View* parent = view->parent_;
165   ui::NativeTheme* old_theme = NULL;
166   if (parent) {
167     old_theme = view->GetNativeTheme();
168     if (parent == this) {
169       ReorderChildView(view, index);
170       return;
171     }
172     parent->DoRemoveChildView(view, true, true, false, this);
173   }
174
175   // Sets the prev/next focus views.
176   InitFocusSiblings(view, index);
177
178   // Let's insert the view.
179   view->parent_ = this;
180   children_.insert(children_.begin() + index, view);
181
182   // Instruct the view to recompute its root bounds on next Paint().
183   view->SetRootBoundsDirty(true);
184
185   views::Widget* widget = GetWidget();
186   if (widget) {
187     const ui::NativeTheme* new_theme = view->GetNativeTheme();
188     if (new_theme != old_theme)
189       view->PropagateNativeThemeChanged(new_theme);
190   }
191
192   ViewHierarchyChangedDetails details(true, this, view, parent);
193
194   for (View* v = this; v; v = v->parent_)
195     v->ViewHierarchyChangedImpl(false, details);
196
197   view->PropagateAddNotifications(details);
198   UpdateTooltip();
199   if (widget) {
200     RegisterChildrenForVisibleBoundsNotification(view);
201     if (view->visible())
202       view->SchedulePaint();
203   }
204
205   if (layout_manager_.get())
206     layout_manager_->ViewAdded(this, view);
207
208   ReorderLayers();
209
210   // Make sure the visibility of the child layers are correct.
211   // If any of the parent View is hidden, then the layers of the subtree
212   // rooted at |this| should be hidden. Otherwise, all the child layers should
213   // inherit the visibility of the owner View.
214   UpdateLayerVisibility();
215 }
216
217 void View::ReorderChildView(View* view, int index) {
218   DCHECK_EQ(view->parent_, this);
219   if (index < 0)
220     index = child_count() - 1;
221   else if (index >= child_count())
222     return;
223   if (children_[index] == view)
224     return;
225
226   const Views::iterator i(std::find(children_.begin(), children_.end(), view));
227   DCHECK(i != children_.end());
228   children_.erase(i);
229
230   // Unlink the view first
231   View* next_focusable = view->next_focusable_view_;
232   View* prev_focusable = view->previous_focusable_view_;
233   if (prev_focusable)
234     prev_focusable->next_focusable_view_ = next_focusable;
235   if (next_focusable)
236     next_focusable->previous_focusable_view_ = prev_focusable;
237
238   // Add it in the specified index now.
239   InitFocusSiblings(view, index);
240   children_.insert(children_.begin() + index, view);
241
242   ReorderLayers();
243 }
244
245 void View::RemoveChildView(View* view) {
246   DoRemoveChildView(view, true, true, false, NULL);
247 }
248
249 void View::RemoveAllChildViews(bool delete_children) {
250   while (!children_.empty())
251     DoRemoveChildView(children_.front(), false, false, delete_children, NULL);
252   UpdateTooltip();
253 }
254
255 bool View::Contains(const View* view) const {
256   for (const View* v = view; v; v = v->parent_) {
257     if (v == this)
258       return true;
259   }
260   return false;
261 }
262
263 int View::GetIndexOf(const View* view) const {
264   Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
265   return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
266 }
267
268 // Size and disposition --------------------------------------------------------
269
270 void View::SetBounds(int x, int y, int width, int height) {
271   SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
272 }
273
274 void View::SetBoundsRect(const gfx::Rect& bounds) {
275   if (bounds == bounds_) {
276     if (needs_layout_) {
277       needs_layout_ = false;
278       Layout();
279     }
280     return;
281   }
282
283   if (visible_) {
284     // Paint where the view is currently.
285     SchedulePaintBoundsChanged(
286         bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
287         SCHEDULE_PAINT_SIZE_CHANGED);
288   }
289
290   gfx::Rect prev = bounds_;
291   bounds_ = bounds;
292   BoundsChanged(prev);
293 }
294
295 void View::SetSize(const gfx::Size& size) {
296   SetBounds(x(), y(), size.width(), size.height());
297 }
298
299 void View::SetPosition(const gfx::Point& position) {
300   SetBounds(position.x(), position.y(), width(), height());
301 }
302
303 void View::SetX(int x) {
304   SetBounds(x, y(), width(), height());
305 }
306
307 void View::SetY(int y) {
308   SetBounds(x(), y, width(), height());
309 }
310
311 gfx::Rect View::GetContentsBounds() const {
312   gfx::Rect contents_bounds(GetLocalBounds());
313   if (border_.get())
314     contents_bounds.Inset(border_->GetInsets());
315   return contents_bounds;
316 }
317
318 gfx::Rect View::GetLocalBounds() const {
319   return gfx::Rect(size());
320 }
321
322 gfx::Rect View::GetLayerBoundsInPixel() const {
323   return layer()->GetTargetBounds();
324 }
325
326 gfx::Insets View::GetInsets() const {
327   return border_.get() ? border_->GetInsets() : gfx::Insets();
328 }
329
330 gfx::Rect View::GetVisibleBounds() const {
331   if (!IsDrawn())
332     return gfx::Rect();
333   gfx::Rect vis_bounds(GetLocalBounds());
334   gfx::Rect ancestor_bounds;
335   const View* view = this;
336   gfx::Transform transform;
337
338   while (view != NULL && !vis_bounds.IsEmpty()) {
339     transform.ConcatTransform(view->GetTransform());
340     gfx::Transform translation;
341     translation.Translate(static_cast<float>(view->GetMirroredX()),
342                           static_cast<float>(view->y()));
343     transform.ConcatTransform(translation);
344
345     vis_bounds = view->ConvertRectToParent(vis_bounds);
346     const View* ancestor = view->parent_;
347     if (ancestor != NULL) {
348       ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
349       vis_bounds.Intersect(ancestor_bounds);
350     } else if (!view->GetWidget()) {
351       // If the view has no Widget, we're not visible. Return an empty rect.
352       return gfx::Rect();
353     }
354     view = ancestor;
355   }
356   if (vis_bounds.IsEmpty())
357     return vis_bounds;
358   // Convert back to this views coordinate system.
359   gfx::RectF views_vis_bounds(vis_bounds);
360   transform.TransformRectReverse(&views_vis_bounds);
361   // Partially visible pixels should be considered visible.
362   return gfx::ToEnclosingRect(views_vis_bounds);
363 }
364
365 gfx::Rect View::GetBoundsInScreen() const {
366   gfx::Point origin;
367   View::ConvertPointToScreen(this, &origin);
368   return gfx::Rect(origin, size());
369 }
370
371 gfx::Size View::GetPreferredSize() const {
372   if (layout_manager_.get())
373     return layout_manager_->GetPreferredSize(this);
374   return gfx::Size();
375 }
376
377 int View::GetBaseline() const {
378   return -1;
379 }
380
381 void View::SizeToPreferredSize() {
382   gfx::Size prefsize = GetPreferredSize();
383   if ((prefsize.width() != width()) || (prefsize.height() != height()))
384     SetBounds(x(), y(), prefsize.width(), prefsize.height());
385 }
386
387 gfx::Size View::GetMinimumSize() const {
388   return GetPreferredSize();
389 }
390
391 gfx::Size View::GetMaximumSize() const {
392   return gfx::Size();
393 }
394
395 int View::GetHeightForWidth(int w) const {
396   if (layout_manager_.get())
397     return layout_manager_->GetPreferredHeightForWidth(this, w);
398   return GetPreferredSize().height();
399 }
400
401 void View::SetVisible(bool visible) {
402   if (visible != visible_) {
403     // If the View is currently visible, schedule paint to refresh parent.
404     // TODO(beng): not sure we should be doing this if we have a layer.
405     if (visible_)
406       SchedulePaint();
407
408     visible_ = visible;
409     AdvanceFocusIfNecessary();
410
411     // Notify the parent.
412     if (parent_)
413       parent_->ChildVisibilityChanged(this);
414
415     // This notifies all sub-views recursively.
416     PropagateVisibilityNotifications(this, visible_);
417     UpdateLayerVisibility();
418
419     // If we are newly visible, schedule paint.
420     if (visible_) {
421       SchedulePaint();
422     } else {
423       // We're never painted when hidden, so no need to be in the BoundsTree.
424       BoundsTree* bounds_tree = GetBoundsTreeFromPaintRoot();
425       if (bounds_tree)
426         RemoveRootBounds(bounds_tree);
427     }
428   }
429 }
430
431 bool View::IsDrawn() const {
432   return visible_ && parent_ ? parent_->IsDrawn() : false;
433 }
434
435 void View::SetEnabled(bool enabled) {
436   if (enabled != enabled_) {
437     enabled_ = enabled;
438     AdvanceFocusIfNecessary();
439     OnEnabledChanged();
440   }
441 }
442
443 void View::OnEnabledChanged() {
444   SchedulePaint();
445 }
446
447 // Transformations -------------------------------------------------------------
448
449 gfx::Transform View::GetTransform() const {
450   return layer() ? layer()->transform() : gfx::Transform();
451 }
452
453 void View::SetTransform(const gfx::Transform& transform) {
454   if (transform.IsIdentity()) {
455     if (layer()) {
456       layer()->SetTransform(transform);
457       if (!paint_to_layer_)
458         DestroyLayer();
459     } else {
460       // Nothing.
461     }
462   } else {
463     if (!layer())
464       CreateLayer();
465     layer()->SetTransform(transform);
466     layer()->ScheduleDraw();
467   }
468 }
469
470 void View::SetPaintToLayer(bool paint_to_layer) {
471   if (paint_to_layer_ == paint_to_layer)
472     return;
473
474   // If this is a change in state we will also need to update bounds trees.
475   if (paint_to_layer) {
476     // Gaining a layer means becoming a paint root. We must remove ourselves
477     // from our old paint root, if we had one. Traverse up view tree to find old
478     // paint root.
479     View* old_paint_root = parent_;
480     while (old_paint_root && !old_paint_root->IsPaintRoot())
481       old_paint_root = old_paint_root->parent_;
482
483     // Remove our and our children's bounds from the old tree. This will also
484     // mark all of our bounds as dirty.
485     if (old_paint_root && old_paint_root->bounds_tree_)
486       RemoveRootBounds(old_paint_root->bounds_tree_.get());
487
488   } else {
489     // Losing a layer means we are no longer a paint root, so delete our
490     // bounds tree and mark ourselves as dirty for future insertion into our
491     // new paint root's bounds tree.
492     bounds_tree_.reset();
493     SetRootBoundsDirty(true);
494   }
495
496   paint_to_layer_ = paint_to_layer;
497   if (paint_to_layer_ && !layer()) {
498     CreateLayer();
499   } else if (!paint_to_layer_ && layer()) {
500     DestroyLayer();
501   }
502 }
503
504 // RTL positioning -------------------------------------------------------------
505
506 gfx::Rect View::GetMirroredBounds() const {
507   gfx::Rect bounds(bounds_);
508   bounds.set_x(GetMirroredX());
509   return bounds;
510 }
511
512 gfx::Point View::GetMirroredPosition() const {
513   return gfx::Point(GetMirroredX(), y());
514 }
515
516 int View::GetMirroredX() const {
517   return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
518 }
519
520 int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
521   return base::i18n::IsRTL() ?
522       (width() - bounds.x() - bounds.width()) : bounds.x();
523 }
524
525 int View::GetMirroredXInView(int x) const {
526   return base::i18n::IsRTL() ? width() - x : x;
527 }
528
529 int View::GetMirroredXWithWidthInView(int x, int w) const {
530   return base::i18n::IsRTL() ? width() - x - w : x;
531 }
532
533 // Layout ----------------------------------------------------------------------
534
535 void View::Layout() {
536   needs_layout_ = false;
537
538   // If we have a layout manager, let it handle the layout for us.
539   if (layout_manager_.get())
540     layout_manager_->Layout(this);
541
542   // Make sure to propagate the Layout() call to any children that haven't
543   // received it yet through the layout manager and need to be laid out. This
544   // is needed for the case when the child requires a layout but its bounds
545   // weren't changed by the layout manager. If there is no layout manager, we
546   // just propagate the Layout() call down the hierarchy, so whoever receives
547   // the call can take appropriate action.
548   for (int i = 0, count = child_count(); i < count; ++i) {
549     View* child = child_at(i);
550     if (child->needs_layout_ || !layout_manager_.get()) {
551       child->needs_layout_ = false;
552       child->Layout();
553     }
554   }
555 }
556
557 void View::InvalidateLayout() {
558   // Always invalidate up. This is needed to handle the case of us already being
559   // valid, but not our parent.
560   needs_layout_ = true;
561   if (parent_)
562     parent_->InvalidateLayout();
563 }
564
565 LayoutManager* View::GetLayoutManager() const {
566   return layout_manager_.get();
567 }
568
569 void View::SetLayoutManager(LayoutManager* layout_manager) {
570   if (layout_manager_.get())
571     layout_manager_->Uninstalled(this);
572
573   layout_manager_.reset(layout_manager);
574   if (layout_manager_.get())
575     layout_manager_->Installed(this);
576 }
577
578 void View::SnapLayerToPixelBoundary() {
579   if (!layer())
580     return;
581
582   if (snap_layer_to_pixel_boundary_ && layer()->parent() &&
583       layer()->GetCompositor()) {
584     ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer());
585   } else {
586     // Reset the offset.
587     layer()->SetSubpixelPositionOffset(gfx::Vector2dF());
588   }
589 }
590
591 // Attributes ------------------------------------------------------------------
592
593 const char* View::GetClassName() const {
594   return kViewClassName;
595 }
596
597 const View* View::GetAncestorWithClassName(const std::string& name) const {
598   for (const View* view = this; view; view = view->parent_) {
599     if (!strcmp(view->GetClassName(), name.c_str()))
600       return view;
601   }
602   return NULL;
603 }
604
605 View* View::GetAncestorWithClassName(const std::string& name) {
606   return const_cast<View*>(const_cast<const View*>(this)->
607       GetAncestorWithClassName(name));
608 }
609
610 const View* View::GetViewByID(int id) const {
611   if (id == id_)
612     return const_cast<View*>(this);
613
614   for (int i = 0, count = child_count(); i < count; ++i) {
615     const View* view = child_at(i)->GetViewByID(id);
616     if (view)
617       return view;
618   }
619   return NULL;
620 }
621
622 View* View::GetViewByID(int id) {
623   return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
624 }
625
626 void View::SetGroup(int gid) {
627   // Don't change the group id once it's set.
628   DCHECK(group_ == -1 || group_ == gid);
629   group_ = gid;
630 }
631
632 int View::GetGroup() const {
633   return group_;
634 }
635
636 bool View::IsGroupFocusTraversable() const {
637   return true;
638 }
639
640 void View::GetViewsInGroup(int group, Views* views) {
641   if (group_ == group)
642     views->push_back(this);
643
644   for (int i = 0, count = child_count(); i < count; ++i)
645     child_at(i)->GetViewsInGroup(group, views);
646 }
647
648 View* View::GetSelectedViewForGroup(int group) {
649   Views views;
650   GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
651   return views.empty() ? NULL : views[0];
652 }
653
654 // Coordinate conversion -------------------------------------------------------
655
656 // static
657 void View::ConvertPointToTarget(const View* source,
658                                 const View* target,
659                                 gfx::Point* point) {
660   DCHECK(source);
661   DCHECK(target);
662   if (source == target)
663     return;
664
665   const View* root = GetHierarchyRoot(target);
666   CHECK_EQ(GetHierarchyRoot(source), root);
667
668   if (source != root)
669     source->ConvertPointForAncestor(root, point);
670
671   if (target != root)
672     target->ConvertPointFromAncestor(root, point);
673 }
674
675 // static
676 void View::ConvertRectToTarget(const View* source,
677                                const View* target,
678                                gfx::RectF* rect) {
679   DCHECK(source);
680   DCHECK(target);
681   if (source == target)
682     return;
683
684   const View* root = GetHierarchyRoot(target);
685   CHECK_EQ(GetHierarchyRoot(source), root);
686
687   if (source != root)
688     source->ConvertRectForAncestor(root, rect);
689
690   if (target != root)
691     target->ConvertRectFromAncestor(root, rect);
692 }
693
694 // static
695 void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
696   DCHECK(src);
697   DCHECK(p);
698
699   src->ConvertPointForAncestor(NULL, p);
700 }
701
702 // static
703 void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
704   DCHECK(dest);
705   DCHECK(p);
706
707   dest->ConvertPointFromAncestor(NULL, p);
708 }
709
710 // static
711 void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
712   DCHECK(src);
713   DCHECK(p);
714
715   // If the view is not connected to a tree, there's nothing we can do.
716   const Widget* widget = src->GetWidget();
717   if (widget) {
718     ConvertPointToWidget(src, p);
719     *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
720   }
721 }
722
723 // static
724 void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
725   DCHECK(dst);
726   DCHECK(p);
727
728   const views::Widget* widget = dst->GetWidget();
729   if (!widget)
730     return;
731   *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin();
732   views::View::ConvertPointFromWidget(dst, p);
733 }
734
735 gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
736   gfx::RectF x_rect = rect;
737   GetTransform().TransformRect(&x_rect);
738   x_rect.Offset(GetMirroredPosition().OffsetFromOrigin());
739   // Pixels we partially occupy in the parent should be included.
740   return gfx::ToEnclosingRect(x_rect);
741 }
742
743 gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
744   gfx::Rect x_rect = rect;
745   for (const View* v = this; v; v = v->parent_)
746     x_rect = v->ConvertRectToParent(x_rect);
747   return x_rect;
748 }
749
750 // Painting --------------------------------------------------------------------
751
752 void View::SchedulePaint() {
753   SchedulePaintInRect(GetLocalBounds());
754 }
755
756 void View::SchedulePaintInRect(const gfx::Rect& rect) {
757   if (!visible_)
758     return;
759
760   if (layer()) {
761     layer()->SchedulePaint(rect);
762   } else if (parent_) {
763     // Translate the requested paint rect to the parent's coordinate system
764     // then pass this notification up to the parent.
765     parent_->SchedulePaintInRect(ConvertRectToParent(rect));
766   }
767 }
768
769 void View::Paint(gfx::Canvas* canvas, const CullSet& cull_set) {
770   // The cull_set may allow us to skip painting without canvas construction or
771   // even canvas rect intersection.
772   if (cull_set.ShouldPaint(this)) {
773     TRACE_EVENT1("views", "View::Paint", "class", GetClassName());
774
775     gfx::ScopedCanvas scoped_canvas(canvas);
776
777     // Paint this View and its children, setting the clip rect to the bounds
778     // of this View and translating the origin to the local bounds' top left
779     // point.
780     //
781     // Note that the X (or left) position we pass to ClipRectInt takes into
782     // consideration whether or not the view uses a right-to-left layout so that
783     // we paint our view in its mirrored position if need be.
784     gfx::Rect clip_rect = bounds();
785     clip_rect.Inset(clip_insets_);
786     if (parent_)
787       clip_rect.set_x(parent_->GetMirroredXForRect(clip_rect));
788     canvas->ClipRect(clip_rect);
789     if (canvas->IsClipEmpty())
790       return;
791
792     // Non-empty clip, translate the graphics such that 0,0 corresponds to where
793     // this view is located (related to its parent).
794     canvas->Translate(GetMirroredPosition().OffsetFromOrigin());
795     canvas->Transform(GetTransform());
796
797     // If we are a paint root, we need to construct our own CullSet object for
798     // propagation to our children.
799     if (IsPaintRoot()) {
800       if (!bounds_tree_)
801         bounds_tree_.reset(new BoundsTree(2, 5));
802
803       // Recompute our bounds tree as needed.
804       UpdateRootBounds(bounds_tree_.get(), gfx::Vector2d());
805
806       // Grab the clip rect from the supplied canvas to use as the query rect.
807       gfx::Rect canvas_bounds;
808       if (!canvas->GetClipBounds(&canvas_bounds)) {
809         NOTREACHED() << "Failed to get clip bounds from the canvas!";
810         return;
811       }
812
813       // Now query our bounds_tree_ for a set of damaged views that intersect
814       // our canvas bounds.
815       scoped_ptr<base::hash_set<intptr_t> > damaged_views(
816           new base::hash_set<intptr_t>());
817       bounds_tree_->AppendIntersectingRecords(
818           canvas_bounds, damaged_views.get());
819       // Construct a CullSet to wrap the damaged views set, it will delete it
820       // for us on scope exit.
821       CullSet paint_root_cull_set(damaged_views.Pass());
822       // Paint all descendents using our new cull set.
823       PaintCommon(canvas, paint_root_cull_set);
824     } else {
825       // Not a paint root, so we can proceed as normal.
826       PaintCommon(canvas, cull_set);
827     }
828   }
829 }
830
831 void View::set_background(Background* b) {
832   background_.reset(b);
833 }
834
835 void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); }
836
837 ui::ThemeProvider* View::GetThemeProvider() const {
838   const Widget* widget = GetWidget();
839   return widget ? widget->GetThemeProvider() : NULL;
840 }
841
842 const ui::NativeTheme* View::GetNativeTheme() const {
843   const Widget* widget = GetWidget();
844   return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance();
845 }
846
847 // Input -----------------------------------------------------------------------
848
849 View* View::GetEventHandlerForPoint(const gfx::Point& point) {
850   return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1)));
851 }
852
853 View* View::GetEventHandlerForRect(const gfx::Rect& rect) {
854   return GetEffectiveViewTargeter()->TargetForRect(this, rect);
855 }
856
857 bool View::CanProcessEventsWithinSubtree() const {
858   return true;
859 }
860
861 View* View::GetTooltipHandlerForPoint(const gfx::Point& point) {
862   // TODO(tdanderson): Move this implementation into ViewTargetDelegate.
863   if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree())
864     return NULL;
865
866   // Walk the child Views recursively looking for the View that most
867   // tightly encloses the specified point.
868   for (int i = child_count() - 1; i >= 0; --i) {
869     View* child = child_at(i);
870     if (!child->visible())
871       continue;
872
873     gfx::Point point_in_child_coords(point);
874     ConvertPointToTarget(this, child, &point_in_child_coords);
875     View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords);
876     if (handler)
877       return handler;
878   }
879   return this;
880 }
881
882 gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) {
883 #if defined(OS_WIN)
884   static ui::Cursor arrow;
885   if (!arrow.platform())
886     arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW));
887   return arrow;
888 #else
889   return gfx::kNullCursor;
890 #endif
891 }
892
893 bool View::HitTestPoint(const gfx::Point& point) const {
894   return HitTestRect(gfx::Rect(point, gfx::Size(1, 1)));
895 }
896
897 bool View::HitTestRect(const gfx::Rect& rect) const {
898   return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect);
899 }
900
901 bool View::IsMouseHovered() {
902   // If we haven't yet been placed in an onscreen view hierarchy, we can't be
903   // hovered.
904   if (!GetWidget())
905     return false;
906
907   // If mouse events are disabled, then the mouse cursor is invisible and
908   // is therefore not hovering over this button.
909   if (!GetWidget()->IsMouseEventsEnabled())
910     return false;
911
912   gfx::Point cursor_pos(gfx::Screen::GetScreenFor(
913       GetWidget()->GetNativeView())->GetCursorScreenPoint());
914   ConvertPointFromScreen(this, &cursor_pos);
915   return HitTestPoint(cursor_pos);
916 }
917
918 bool View::OnMousePressed(const ui::MouseEvent& event) {
919   return false;
920 }
921
922 bool View::OnMouseDragged(const ui::MouseEvent& event) {
923   return false;
924 }
925
926 void View::OnMouseReleased(const ui::MouseEvent& event) {
927 }
928
929 void View::OnMouseCaptureLost() {
930 }
931
932 void View::OnMouseMoved(const ui::MouseEvent& event) {
933 }
934
935 void View::OnMouseEntered(const ui::MouseEvent& event) {
936 }
937
938 void View::OnMouseExited(const ui::MouseEvent& event) {
939 }
940
941 void View::SetMouseHandler(View* new_mouse_handler) {
942   // |new_mouse_handler| may be NULL.
943   if (parent_)
944     parent_->SetMouseHandler(new_mouse_handler);
945 }
946
947 bool View::OnKeyPressed(const ui::KeyEvent& event) {
948   return false;
949 }
950
951 bool View::OnKeyReleased(const ui::KeyEvent& event) {
952   return false;
953 }
954
955 bool View::OnMouseWheel(const ui::MouseWheelEvent& event) {
956   return false;
957 }
958
959 void View::OnKeyEvent(ui::KeyEvent* event) {
960   bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) :
961                                                           OnKeyReleased(*event);
962   if (consumed)
963     event->StopPropagation();
964 }
965
966 void View::OnMouseEvent(ui::MouseEvent* event) {
967   switch (event->type()) {
968     case ui::ET_MOUSE_PRESSED:
969       if (ProcessMousePressed(*event))
970         event->SetHandled();
971       return;
972
973     case ui::ET_MOUSE_MOVED:
974       if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON |
975                              ui::EF_RIGHT_MOUSE_BUTTON |
976                              ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) {
977         OnMouseMoved(*event);
978         return;
979       }
980       // FALL-THROUGH
981     case ui::ET_MOUSE_DRAGGED:
982       if (ProcessMouseDragged(*event))
983         event->SetHandled();
984       return;
985
986     case ui::ET_MOUSE_RELEASED:
987       ProcessMouseReleased(*event);
988       return;
989
990     case ui::ET_MOUSEWHEEL:
991       if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event)))
992         event->SetHandled();
993       break;
994
995     case ui::ET_MOUSE_ENTERED:
996       if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY)
997         NotifyAccessibilityEvent(ui::AX_EVENT_HOVER, true);
998       OnMouseEntered(*event);
999       break;
1000
1001     case ui::ET_MOUSE_EXITED:
1002       OnMouseExited(*event);
1003       break;
1004
1005     default:
1006       return;
1007   }
1008 }
1009
1010 void View::OnScrollEvent(ui::ScrollEvent* event) {
1011 }
1012
1013 void View::OnTouchEvent(ui::TouchEvent* event) {
1014   NOTREACHED() << "Views should not receive touch events.";
1015 }
1016
1017 void View::OnGestureEvent(ui::GestureEvent* event) {
1018 }
1019
1020 ui::TextInputClient* View::GetTextInputClient() {
1021   return NULL;
1022 }
1023
1024 InputMethod* View::GetInputMethod() {
1025   Widget* widget = GetWidget();
1026   return widget ? widget->GetInputMethod() : NULL;
1027 }
1028
1029 const InputMethod* View::GetInputMethod() const {
1030   const Widget* widget = GetWidget();
1031   return widget ? widget->GetInputMethod() : NULL;
1032 }
1033
1034 scoped_ptr<ViewTargeter>
1035 View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) {
1036   scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass();
1037   targeter_ = targeter.Pass();
1038   return old_targeter.Pass();
1039 }
1040
1041 ViewTargeter* View::GetEffectiveViewTargeter() const {
1042   DCHECK(GetWidget());
1043   ViewTargeter* view_targeter = targeter();
1044   if (!view_targeter)
1045     view_targeter = GetWidget()->GetRootView()->targeter();
1046   CHECK(view_targeter);
1047   return view_targeter;
1048 }
1049
1050 bool View::CanAcceptEvent(const ui::Event& event) {
1051   return IsDrawn();
1052 }
1053
1054 ui::EventTarget* View::GetParentTarget() {
1055   return parent_;
1056 }
1057
1058 scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() const {
1059   return scoped_ptr<ui::EventTargetIterator>(
1060       new ui::EventTargetIteratorImpl<View>(children_));
1061 }
1062
1063 ui::EventTargeter* View::GetEventTargeter() {
1064   return targeter_.get();
1065 }
1066
1067 void View::ConvertEventToTarget(ui::EventTarget* target,
1068                                 ui::LocatedEvent* event) {
1069   event->ConvertLocationToTarget(this, static_cast<View*>(target));
1070 }
1071
1072 // Accelerators ----------------------------------------------------------------
1073
1074 void View::AddAccelerator(const ui::Accelerator& accelerator) {
1075   if (!accelerators_.get())
1076     accelerators_.reset(new std::vector<ui::Accelerator>());
1077
1078   if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
1079       accelerators_->end()) {
1080     accelerators_->push_back(accelerator);
1081   }
1082   RegisterPendingAccelerators();
1083 }
1084
1085 void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
1086   if (!accelerators_.get()) {
1087     NOTREACHED() << "Removing non-existing accelerator";
1088     return;
1089   }
1090
1091   std::vector<ui::Accelerator>::iterator i(
1092       std::find(accelerators_->begin(), accelerators_->end(), accelerator));
1093   if (i == accelerators_->end()) {
1094     NOTREACHED() << "Removing non-existing accelerator";
1095     return;
1096   }
1097
1098   size_t index = i - accelerators_->begin();
1099   accelerators_->erase(i);
1100   if (index >= registered_accelerator_count_) {
1101     // The accelerator is not registered to FocusManager.
1102     return;
1103   }
1104   --registered_accelerator_count_;
1105
1106   // Providing we are attached to a Widget and registered with a focus manager,
1107   // we should de-register from that focus manager now.
1108   if (GetWidget() && accelerator_focus_manager_)
1109     accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
1110 }
1111
1112 void View::ResetAccelerators() {
1113   if (accelerators_.get())
1114     UnregisterAccelerators(false);
1115 }
1116
1117 bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
1118   return false;
1119 }
1120
1121 bool View::CanHandleAccelerators() const {
1122   return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
1123 }
1124
1125 // Focus -----------------------------------------------------------------------
1126
1127 bool View::HasFocus() const {
1128   const FocusManager* focus_manager = GetFocusManager();
1129   return focus_manager && (focus_manager->GetFocusedView() == this);
1130 }
1131
1132 View* View::GetNextFocusableView() {
1133   return next_focusable_view_;
1134 }
1135
1136 const View* View::GetNextFocusableView() const {
1137   return next_focusable_view_;
1138 }
1139
1140 View* View::GetPreviousFocusableView() {
1141   return previous_focusable_view_;
1142 }
1143
1144 void View::SetNextFocusableView(View* view) {
1145   if (view)
1146     view->previous_focusable_view_ = this;
1147   next_focusable_view_ = view;
1148 }
1149
1150 void View::SetFocusable(bool focusable) {
1151   if (focusable_ == focusable)
1152     return;
1153
1154   focusable_ = focusable;
1155   AdvanceFocusIfNecessary();
1156 }
1157
1158 bool View::IsFocusable() const {
1159   return focusable_ && enabled_ && IsDrawn();
1160 }
1161
1162 bool View::IsAccessibilityFocusable() const {
1163   return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
1164 }
1165
1166 void View::SetAccessibilityFocusable(bool accessibility_focusable) {
1167   if (accessibility_focusable_ == accessibility_focusable)
1168     return;
1169
1170   accessibility_focusable_ = accessibility_focusable;
1171   AdvanceFocusIfNecessary();
1172 }
1173
1174 FocusManager* View::GetFocusManager() {
1175   Widget* widget = GetWidget();
1176   return widget ? widget->GetFocusManager() : NULL;
1177 }
1178
1179 const FocusManager* View::GetFocusManager() const {
1180   const Widget* widget = GetWidget();
1181   return widget ? widget->GetFocusManager() : NULL;
1182 }
1183
1184 void View::RequestFocus() {
1185   FocusManager* focus_manager = GetFocusManager();
1186   if (focus_manager && IsFocusable())
1187     focus_manager->SetFocusedView(this);
1188 }
1189
1190 bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
1191   return false;
1192 }
1193
1194 FocusTraversable* View::GetFocusTraversable() {
1195   return NULL;
1196 }
1197
1198 FocusTraversable* View::GetPaneFocusTraversable() {
1199   return NULL;
1200 }
1201
1202 // Tooltips --------------------------------------------------------------------
1203
1204 bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
1205   return false;
1206 }
1207
1208 bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
1209   return false;
1210 }
1211
1212 // Context menus ---------------------------------------------------------------
1213
1214 void View::ShowContextMenu(const gfx::Point& p,
1215                            ui::MenuSourceType source_type) {
1216   if (!context_menu_controller_)
1217     return;
1218
1219   context_menu_controller_->ShowContextMenuForView(this, p, source_type);
1220 }
1221
1222 // static
1223 bool View::ShouldShowContextMenuOnMousePress() {
1224   return kContextMenuOnMousePress;
1225 }
1226
1227 // Drag and drop ---------------------------------------------------------------
1228
1229 bool View::GetDropFormats(
1230       int* formats,
1231       std::set<OSExchangeData::CustomFormat>* custom_formats) {
1232   return false;
1233 }
1234
1235 bool View::AreDropTypesRequired() {
1236   return false;
1237 }
1238
1239 bool View::CanDrop(const OSExchangeData& data) {
1240   // TODO(sky): when I finish up migration, this should default to true.
1241   return false;
1242 }
1243
1244 void View::OnDragEntered(const ui::DropTargetEvent& event) {
1245 }
1246
1247 int View::OnDragUpdated(const ui::DropTargetEvent& event) {
1248   return ui::DragDropTypes::DRAG_NONE;
1249 }
1250
1251 void View::OnDragExited() {
1252 }
1253
1254 int View::OnPerformDrop(const ui::DropTargetEvent& event) {
1255   return ui::DragDropTypes::DRAG_NONE;
1256 }
1257
1258 void View::OnDragDone() {
1259 }
1260
1261 // static
1262 bool View::ExceededDragThreshold(const gfx::Vector2d& delta) {
1263   return (abs(delta.x()) > GetHorizontalDragThreshold() ||
1264           abs(delta.y()) > GetVerticalDragThreshold());
1265 }
1266
1267 // Accessibility----------------------------------------------------------------
1268
1269 gfx::NativeViewAccessible View::GetNativeViewAccessible() {
1270   if (!native_view_accessibility_)
1271     native_view_accessibility_ = NativeViewAccessibility::Create(this);
1272   if (native_view_accessibility_)
1273     return native_view_accessibility_->GetNativeObject();
1274   return NULL;
1275 }
1276
1277 void View::NotifyAccessibilityEvent(
1278     ui::AXEvent event_type,
1279     bool send_native_event) {
1280   if (ViewsDelegate::views_delegate)
1281     ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type);
1282
1283   if (send_native_event && GetWidget()) {
1284     if (!native_view_accessibility_)
1285       native_view_accessibility_ = NativeViewAccessibility::Create(this);
1286     if (native_view_accessibility_)
1287       native_view_accessibility_->NotifyAccessibilityEvent(event_type);
1288   }
1289 }
1290
1291 // Scrolling -------------------------------------------------------------------
1292
1293 void View::ScrollRectToVisible(const gfx::Rect& rect) {
1294   // We must take RTL UI mirroring into account when adjusting the position of
1295   // the region.
1296   if (parent_) {
1297     gfx::Rect scroll_rect(rect);
1298     scroll_rect.Offset(GetMirroredX(), y());
1299     parent_->ScrollRectToVisible(scroll_rect);
1300   }
1301 }
1302
1303 int View::GetPageScrollIncrement(ScrollView* scroll_view,
1304                                  bool is_horizontal, bool is_positive) {
1305   return 0;
1306 }
1307
1308 int View::GetLineScrollIncrement(ScrollView* scroll_view,
1309                                  bool is_horizontal, bool is_positive) {
1310   return 0;
1311 }
1312
1313 ////////////////////////////////////////////////////////////////////////////////
1314 // View, protected:
1315
1316 // Size and disposition --------------------------------------------------------
1317
1318 void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1319 }
1320
1321 void View::PreferredSizeChanged() {
1322   InvalidateLayout();
1323   if (parent_)
1324     parent_->ChildPreferredSizeChanged(this);
1325 }
1326
1327 bool View::NeedsNotificationWhenVisibleBoundsChange() const {
1328   return false;
1329 }
1330
1331 void View::OnVisibleBoundsChanged() {
1332 }
1333
1334 // Tree operations -------------------------------------------------------------
1335
1336 void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
1337 }
1338
1339 void View::VisibilityChanged(View* starting_from, bool is_visible) {
1340 }
1341
1342 void View::NativeViewHierarchyChanged() {
1343   FocusManager* focus_manager = GetFocusManager();
1344   if (accelerator_focus_manager_ != focus_manager) {
1345     UnregisterAccelerators(true);
1346
1347     if (focus_manager)
1348       RegisterPendingAccelerators();
1349   }
1350 }
1351
1352 // Painting --------------------------------------------------------------------
1353
1354 void View::PaintChildren(gfx::Canvas* canvas, const CullSet& cull_set) {
1355   TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName());
1356   for (int i = 0, count = child_count(); i < count; ++i)
1357     if (!child_at(i)->layer())
1358       child_at(i)->Paint(canvas, cull_set);
1359 }
1360
1361 void View::OnPaint(gfx::Canvas* canvas) {
1362   TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName());
1363   OnPaintBackground(canvas);
1364   OnPaintBorder(canvas);
1365 }
1366
1367 void View::OnPaintBackground(gfx::Canvas* canvas) {
1368   if (background_.get()) {
1369     TRACE_EVENT2("views", "View::OnPaintBackground",
1370                  "width", canvas->sk_canvas()->getDevice()->width(),
1371                  "height", canvas->sk_canvas()->getDevice()->height());
1372     background_->Paint(canvas, this);
1373   }
1374 }
1375
1376 void View::OnPaintBorder(gfx::Canvas* canvas) {
1377   if (border_.get()) {
1378     TRACE_EVENT2("views", "View::OnPaintBorder",
1379                  "width", canvas->sk_canvas()->getDevice()->width(),
1380                  "height", canvas->sk_canvas()->getDevice()->height());
1381     border_->Paint(*this, canvas);
1382   }
1383 }
1384
1385 bool View::IsPaintRoot() {
1386   return paint_to_layer_ || !parent_;
1387 }
1388
1389 // Accelerated Painting --------------------------------------------------------
1390
1391 void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
1392   // This method should not have the side-effect of creating the layer.
1393   if (layer())
1394     layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
1395 }
1396
1397 gfx::Vector2d View::CalculateOffsetToAncestorWithLayer(
1398     ui::Layer** layer_parent) {
1399   if (layer()) {
1400     if (layer_parent)
1401       *layer_parent = layer();
1402     return gfx::Vector2d();
1403   }
1404   if (!parent_)
1405     return gfx::Vector2d();
1406
1407   return gfx::Vector2d(GetMirroredX(), y()) +
1408       parent_->CalculateOffsetToAncestorWithLayer(layer_parent);
1409 }
1410
1411 void View::UpdateParentLayer() {
1412   if (!layer())
1413     return;
1414
1415   ui::Layer* parent_layer = NULL;
1416   gfx::Vector2d offset(GetMirroredX(), y());
1417
1418   if (parent_)
1419     offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer);
1420
1421   ReparentLayer(offset, parent_layer);
1422 }
1423
1424 void View::MoveLayerToParent(ui::Layer* parent_layer,
1425                              const gfx::Point& point) {
1426   gfx::Point local_point(point);
1427   if (parent_layer != layer())
1428     local_point.Offset(GetMirroredX(), y());
1429   if (layer() && parent_layer != layer()) {
1430     parent_layer->Add(layer());
1431     SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
1432                              width(), height()));
1433   } else {
1434     for (int i = 0, count = child_count(); i < count; ++i)
1435       child_at(i)->MoveLayerToParent(parent_layer, local_point);
1436   }
1437 }
1438
1439 void View::UpdateLayerVisibility() {
1440   bool visible = visible_;
1441   for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
1442     visible = v->visible();
1443
1444   UpdateChildLayerVisibility(visible);
1445 }
1446
1447 void View::UpdateChildLayerVisibility(bool ancestor_visible) {
1448   if (layer()) {
1449     layer()->SetVisible(ancestor_visible && visible_);
1450   } else {
1451     for (int i = 0, count = child_count(); i < count; ++i)
1452       child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
1453   }
1454 }
1455
1456 void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) {
1457   if (layer()) {
1458     SetLayerBounds(GetLocalBounds() + offset);
1459   } else {
1460     for (int i = 0, count = child_count(); i < count; ++i) {
1461       View* child = child_at(i);
1462       child->UpdateChildLayerBounds(
1463           offset + gfx::Vector2d(child->GetMirroredX(), child->y()));
1464     }
1465   }
1466 }
1467
1468 void View::OnPaintLayer(gfx::Canvas* canvas) {
1469   if (!layer() || !layer()->fills_bounds_opaquely())
1470     canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
1471   PaintCommon(canvas, CullSet());
1472 }
1473
1474 void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
1475   snap_layer_to_pixel_boundary_ =
1476       (device_scale_factor - std::floor(device_scale_factor)) != 0.0f;
1477   SnapLayerToPixelBoundary();
1478   // Repainting with new scale factor will paint the content at the right scale.
1479 }
1480
1481 base::Closure View::PrepareForLayerBoundsChange() {
1482   return base::Closure();
1483 }
1484
1485 void View::ReorderLayers() {
1486   View* v = this;
1487   while (v && !v->layer())
1488     v = v->parent();
1489
1490   Widget* widget = GetWidget();
1491   if (!v) {
1492     if (widget) {
1493       ui::Layer* layer = widget->GetLayer();
1494       if (layer)
1495         widget->GetRootView()->ReorderChildLayers(layer);
1496     }
1497   } else {
1498     v->ReorderChildLayers(v->layer());
1499   }
1500
1501   if (widget) {
1502     // Reorder the widget's child NativeViews in case a child NativeView is
1503     // associated with a view (eg via a NativeViewHost). Always do the
1504     // reordering because the associated NativeView's layer (if it has one)
1505     // is parented to the widget's layer regardless of whether the host view has
1506     // an ancestor with a layer.
1507     widget->ReorderNativeViews();
1508   }
1509 }
1510
1511 void View::ReorderChildLayers(ui::Layer* parent_layer) {
1512   if (layer() && layer() != parent_layer) {
1513     DCHECK_EQ(parent_layer, layer()->parent());
1514     parent_layer->StackAtBottom(layer());
1515   } else {
1516     // Iterate backwards through the children so that a child with a layer
1517     // which is further to the back is stacked above one which is further to
1518     // the front.
1519     for (Views::reverse_iterator it(children_.rbegin());
1520          it != children_.rend(); ++it) {
1521       (*it)->ReorderChildLayers(parent_layer);
1522     }
1523   }
1524 }
1525
1526 // Input -----------------------------------------------------------------------
1527
1528 View::DragInfo* View::GetDragInfo() {
1529   return parent_ ? parent_->GetDragInfo() : NULL;
1530 }
1531
1532 // Focus -----------------------------------------------------------------------
1533
1534 void View::OnFocus() {
1535   // TODO(beng): Investigate whether it's possible for us to move this to
1536   //             Focus().
1537   // By default, we clear the native focus. This ensures that no visible native
1538   // view as the focus and that we still receive keyboard inputs.
1539   FocusManager* focus_manager = GetFocusManager();
1540   if (focus_manager)
1541     focus_manager->ClearNativeFocus();
1542
1543   // TODO(beng): Investigate whether it's possible for us to move this to
1544   //             Focus().
1545   // Notify assistive technologies of the focus change.
1546   NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true);
1547 }
1548
1549 void View::OnBlur() {
1550 }
1551
1552 void View::Focus() {
1553   OnFocus();
1554 }
1555
1556 void View::Blur() {
1557   OnBlur();
1558 }
1559
1560 // Tooltips --------------------------------------------------------------------
1561
1562 void View::TooltipTextChanged() {
1563   Widget* widget = GetWidget();
1564   // TooltipManager may be null if there is a problem creating it.
1565   if (widget && widget->GetTooltipManager())
1566     widget->GetTooltipManager()->TooltipTextChanged(this);
1567 }
1568
1569 // Context menus ---------------------------------------------------------------
1570
1571 gfx::Point View::GetKeyboardContextMenuLocation() {
1572   gfx::Rect vis_bounds = GetVisibleBounds();
1573   gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
1574                           vis_bounds.y() + vis_bounds.height() / 2);
1575   ConvertPointToScreen(this, &screen_point);
1576   return screen_point;
1577 }
1578
1579 // Drag and drop ---------------------------------------------------------------
1580
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;
1585 }
1586
1587 void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
1588   DCHECK(drag_controller_);
1589   drag_controller_->WriteDragDataForView(this, press_pt, data);
1590 }
1591
1592 bool View::InDrag() {
1593   Widget* widget = GetWidget();
1594   return widget ? widget->dragged_view() == this : false;
1595 }
1596
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;
1601 }
1602
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;
1607 }
1608
1609 // Debugging -------------------------------------------------------------------
1610
1611 #if !defined(NDEBUG)
1612
1613 std::string View::PrintViewGraph(bool first) {
1614   return DoPrintViewGraph(first, this);
1615 }
1616
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;
1620
1621   std::string result;
1622
1623   if (first)
1624     result.append("digraph {\n");
1625
1626   // Node characteristics.
1627   char p[kMaxPointerStringLength];
1628
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++;
1635
1636   char bounds_buffer[512];
1637
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=\"");
1643
1644   result.append(class_name.substr(base_name_index).c_str());
1645
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);
1654
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);
1664
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);
1670
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);
1677   }
1678
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");
1687
1688     if (layer()->fills_bounds_opaquely())
1689       result.append(", style=filled");
1690   }
1691   result.append("]\n");
1692
1693   // Link to parent.
1694   if (parent_) {
1695     char pp[kMaxPointerStringLength];
1696
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");
1703   }
1704
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));
1708
1709   if (first)
1710     result.append("}\n");
1711
1712   return result;
1713 }
1714 #endif
1715
1716 ////////////////////////////////////////////////////////////////////////////////
1717 // View, private:
1718
1719 // DropInfo --------------------------------------------------------------------
1720
1721 void View::DragInfo::Reset() {
1722   possible_drag = false;
1723   start_pt = gfx::Point();
1724 }
1725
1726 void View::DragInfo::PossibleDrag(const gfx::Point& p) {
1727   possible_drag = true;
1728   start_pt = p;
1729 }
1730
1731 // Painting --------------------------------------------------------------------
1732
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();
1747   }
1748 }
1749
1750 void View::PaintCommon(gfx::Canvas* canvas, const CullSet& cull_set) {
1751   if (!visible_)
1752     return;
1753
1754   {
1755     // If the View we are about to paint requested the canvas to be flipped, we
1756     // should change the transform appropriately.
1757     // The canvas mirroring is undone once the View is done painting so that we
1758     // don't pass the canvas with the mirrored transform to Views that didn't
1759     // request the canvas to be flipped.
1760     gfx::ScopedCanvas scoped(canvas);
1761     if (FlipCanvasOnPaintForRTLUI()) {
1762       canvas->Translate(gfx::Vector2d(width(), 0));
1763       canvas->Scale(-1, 1);
1764     }
1765
1766     OnPaint(canvas);
1767   }
1768
1769   PaintChildren(canvas, cull_set);
1770 }
1771
1772 // Tree operations -------------------------------------------------------------
1773
1774 void View::DoRemoveChildView(View* view,
1775                              bool update_focus_cycle,
1776                              bool update_tool_tip,
1777                              bool delete_removed_view,
1778                              View* new_parent) {
1779   DCHECK(view);
1780
1781   const Views::iterator i(std::find(children_.begin(), children_.end(), view));
1782   scoped_ptr<View> view_to_be_deleted;
1783   if (i != children_.end()) {
1784     if (update_focus_cycle) {
1785       // Let's remove the view from the focus traversal.
1786       View* next_focusable = view->next_focusable_view_;
1787       View* prev_focusable = view->previous_focusable_view_;
1788       if (prev_focusable)
1789         prev_focusable->next_focusable_view_ = next_focusable;
1790       if (next_focusable)
1791         next_focusable->previous_focusable_view_ = prev_focusable;
1792     }
1793
1794     if (GetWidget()) {
1795       UnregisterChildrenForVisibleBoundsNotification(view);
1796       if (view->visible())
1797         view->SchedulePaint();
1798       GetWidget()->NotifyWillRemoveView(view);
1799     }
1800
1801     // Remove the bounds of this child and any of its descendants from our
1802     // paint root bounds tree.
1803     BoundsTree* bounds_tree = GetBoundsTreeFromPaintRoot();
1804     if (bounds_tree)
1805       view->RemoveRootBounds(bounds_tree);
1806
1807     view->PropagateRemoveNotifications(this, new_parent);
1808     view->parent_ = NULL;
1809     view->UpdateLayerVisibility();
1810
1811     if (delete_removed_view && !view->owned_by_client_)
1812       view_to_be_deleted.reset(view);
1813
1814     children_.erase(i);
1815   }
1816
1817   if (update_tool_tip)
1818     UpdateTooltip();
1819
1820   if (layout_manager_.get())
1821     layout_manager_->ViewRemoved(this, view);
1822 }
1823
1824 void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) {
1825   for (int i = 0, count = child_count(); i < count; ++i)
1826     child_at(i)->PropagateRemoveNotifications(old_parent, new_parent);
1827
1828   ViewHierarchyChangedDetails details(false, old_parent, this, new_parent);
1829   for (View* v = this; v; v = v->parent_)
1830     v->ViewHierarchyChangedImpl(true, details);
1831 }
1832
1833 void View::PropagateAddNotifications(
1834     const ViewHierarchyChangedDetails& details) {
1835   for (int i = 0, count = child_count(); i < count; ++i)
1836     child_at(i)->PropagateAddNotifications(details);
1837   ViewHierarchyChangedImpl(true, details);
1838 }
1839
1840 void View::PropagateNativeViewHierarchyChanged() {
1841   for (int i = 0, count = child_count(); i < count; ++i)
1842     child_at(i)->PropagateNativeViewHierarchyChanged();
1843   NativeViewHierarchyChanged();
1844 }
1845
1846 void View::ViewHierarchyChangedImpl(
1847     bool register_accelerators,
1848     const ViewHierarchyChangedDetails& details) {
1849   if (register_accelerators) {
1850     if (details.is_add) {
1851       // If you get this registration, you are part of a subtree that has been
1852       // added to the view hierarchy.
1853       if (GetFocusManager())
1854         RegisterPendingAccelerators();
1855     } else {
1856       if (details.child == this)
1857         UnregisterAccelerators(true);
1858     }
1859   }
1860
1861   if (details.is_add && layer() && !layer()->parent()) {
1862     UpdateParentLayer();
1863     Widget* widget = GetWidget();
1864     if (widget)
1865       widget->UpdateRootLayers();
1866   } else if (!details.is_add && details.child == this) {
1867     // Make sure the layers belonging to the subtree rooted at |child| get
1868     // removed from layers that do not belong in the same subtree.
1869     OrphanLayers();
1870     Widget* widget = GetWidget();
1871     if (widget)
1872       widget->UpdateRootLayers();
1873   }
1874
1875   ViewHierarchyChanged(details);
1876   details.parent->needs_layout_ = true;
1877 }
1878
1879 void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) {
1880   for (int i = 0, count = child_count(); i < count; ++i)
1881     child_at(i)->PropagateNativeThemeChanged(theme);
1882   OnNativeThemeChanged(theme);
1883 }
1884
1885 // Size and disposition --------------------------------------------------------
1886
1887 void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
1888   for (int i = 0, count = child_count(); i < count; ++i)
1889     child_at(i)->PropagateVisibilityNotifications(start, is_visible);
1890   VisibilityChangedImpl(start, is_visible);
1891 }
1892
1893 void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
1894   VisibilityChanged(starting_from, is_visible);
1895 }
1896
1897 void View::BoundsChanged(const gfx::Rect& previous_bounds) {
1898   // Mark our bounds as dirty for the paint root, also see if we need to
1899   // recompute our children's bounds due to origin change.
1900   bool origin_changed =
1901       previous_bounds.OffsetFromOrigin() != bounds_.OffsetFromOrigin();
1902   SetRootBoundsDirty(origin_changed);
1903
1904   if (visible_) {
1905     // Paint the new bounds.
1906     SchedulePaintBoundsChanged(
1907         bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
1908         SCHEDULE_PAINT_SIZE_CHANGED);
1909   }
1910
1911   if (layer()) {
1912     if (parent_) {
1913       SetLayerBounds(GetLocalBounds() +
1914                      gfx::Vector2d(GetMirroredX(), y()) +
1915                      parent_->CalculateOffsetToAncestorWithLayer(NULL));
1916     } else {
1917       SetLayerBounds(bounds_);
1918     }
1919   } else {
1920     // If our bounds have changed, then any descendant layer bounds may have
1921     // changed. Update them accordingly.
1922     UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
1923   }
1924
1925   OnBoundsChanged(previous_bounds);
1926
1927   if (previous_bounds.size() != size()) {
1928     needs_layout_ = false;
1929     Layout();
1930   }
1931
1932   if (NeedsNotificationWhenVisibleBoundsChange())
1933     OnVisibleBoundsChanged();
1934
1935   // Notify interested Views that visible bounds within the root view may have
1936   // changed.
1937   if (descendants_to_notify_.get()) {
1938     for (Views::iterator i(descendants_to_notify_->begin());
1939          i != descendants_to_notify_->end(); ++i) {
1940       (*i)->OnVisibleBoundsChanged();
1941     }
1942   }
1943 }
1944
1945 // static
1946 void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
1947   if (view->NeedsNotificationWhenVisibleBoundsChange())
1948     view->RegisterForVisibleBoundsNotification();
1949   for (int i = 0; i < view->child_count(); ++i)
1950     RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
1951 }
1952
1953 // static
1954 void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
1955   if (view->NeedsNotificationWhenVisibleBoundsChange())
1956     view->UnregisterForVisibleBoundsNotification();
1957   for (int i = 0; i < view->child_count(); ++i)
1958     UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
1959 }
1960
1961 void View::RegisterForVisibleBoundsNotification() {
1962   if (registered_for_visible_bounds_notification_)
1963     return;
1964
1965   registered_for_visible_bounds_notification_ = true;
1966   for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1967     ancestor->AddDescendantToNotify(this);
1968 }
1969
1970 void View::UnregisterForVisibleBoundsNotification() {
1971   if (!registered_for_visible_bounds_notification_)
1972     return;
1973
1974   registered_for_visible_bounds_notification_ = false;
1975   for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
1976     ancestor->RemoveDescendantToNotify(this);
1977 }
1978
1979 void View::AddDescendantToNotify(View* view) {
1980   DCHECK(view);
1981   if (!descendants_to_notify_.get())
1982     descendants_to_notify_.reset(new Views);
1983   descendants_to_notify_->push_back(view);
1984 }
1985
1986 void View::RemoveDescendantToNotify(View* view) {
1987   DCHECK(view && descendants_to_notify_.get());
1988   Views::iterator i(std::find(
1989       descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
1990   DCHECK(i != descendants_to_notify_->end());
1991   descendants_to_notify_->erase(i);
1992   if (descendants_to_notify_->empty())
1993     descendants_to_notify_.reset();
1994 }
1995
1996 void View::SetLayerBounds(const gfx::Rect& bounds) {
1997   layer()->SetBounds(bounds);
1998   SnapLayerToPixelBoundary();
1999 }
2000
2001 void View::SetRootBoundsDirty(bool origin_changed) {
2002   root_bounds_dirty_ = true;
2003
2004   if (origin_changed) {
2005     // Inform our children that their root bounds are dirty, as their relative
2006     // coordinates in paint root space have changed since ours have changed.
2007     for (Views::const_iterator i(children_.begin()); i != children_.end();
2008          ++i) {
2009       if (!(*i)->IsPaintRoot())
2010         (*i)->SetRootBoundsDirty(origin_changed);
2011     }
2012   }
2013 }
2014
2015 void View::UpdateRootBounds(BoundsTree* tree, const gfx::Vector2d& offset) {
2016   // If we're not visible no need to update BoundsTree. When we are made visible
2017   // the BoundsTree will be updated appropriately.
2018   if (!visible_)
2019     return;
2020
2021   if (!root_bounds_dirty_ && children_.empty())
2022     return;
2023
2024   // No need to recompute bounds if we haven't flagged ours as dirty.
2025   TRACE_EVENT1("views", "View::UpdateRootBounds", "class", GetClassName());
2026
2027   // Add our own offset to the provided offset, for our own bounds update and
2028   // for propagation to our children if needed.
2029   gfx::Vector2d view_offset = offset + GetMirroredBounds().OffsetFromOrigin();
2030
2031   // If our bounds have changed we must re-insert our new bounds to the tree.
2032   if (root_bounds_dirty_) {
2033     root_bounds_dirty_ = false;
2034     gfx::Rect bounds(
2035         view_offset.x(), view_offset.y(), bounds_.width(), bounds_.height());
2036     tree->Insert(bounds, reinterpret_cast<intptr_t>(this));
2037   }
2038
2039   // Update our children's bounds if needed.
2040   for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
2041     // We don't descend in to layer views for bounds recomputation, as they
2042     // manage their own RTree as paint roots.
2043     if (!(*i)->IsPaintRoot())
2044       (*i)->UpdateRootBounds(tree, view_offset);
2045   }
2046 }
2047
2048 void View::RemoveRootBounds(BoundsTree* tree) {
2049   tree->Remove(reinterpret_cast<intptr_t>(this));
2050
2051   root_bounds_dirty_ = true;
2052
2053   for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
2054     if (!(*i)->IsPaintRoot())
2055       (*i)->RemoveRootBounds(tree);
2056   }
2057 }
2058
2059 View::BoundsTree* View::GetBoundsTreeFromPaintRoot() {
2060   BoundsTree* bounds_tree = bounds_tree_.get();
2061   View* paint_root = this;
2062   while (!bounds_tree && !paint_root->IsPaintRoot()) {
2063     // Assumption is that if IsPaintRoot() is false then parent_ is valid.
2064     DCHECK(paint_root);
2065     paint_root = paint_root->parent_;
2066     bounds_tree = paint_root->bounds_tree_.get();
2067   }
2068
2069   return bounds_tree;
2070 }
2071
2072 // Transformations -------------------------------------------------------------
2073
2074 bool View::GetTransformRelativeTo(const View* ancestor,
2075                                   gfx::Transform* transform) const {
2076   const View* p = this;
2077
2078   while (p && p != ancestor) {
2079     transform->ConcatTransform(p->GetTransform());
2080     gfx::Transform translation;
2081     translation.Translate(static_cast<float>(p->GetMirroredX()),
2082                           static_cast<float>(p->y()));
2083     transform->ConcatTransform(translation);
2084
2085     p = p->parent_;
2086   }
2087
2088   return p == ancestor;
2089 }
2090
2091 // Coordinate conversion -------------------------------------------------------
2092
2093 bool View::ConvertPointForAncestor(const View* ancestor,
2094                                    gfx::Point* point) const {
2095   gfx::Transform trans;
2096   // TODO(sad): Have some way of caching the transformation results.
2097   bool result = GetTransformRelativeTo(ancestor, &trans);
2098   gfx::Point3F p(*point);
2099   trans.TransformPoint(&p);
2100   *point = gfx::ToFlooredPoint(p.AsPointF());
2101   return result;
2102 }
2103
2104 bool View::ConvertPointFromAncestor(const View* ancestor,
2105                                     gfx::Point* point) const {
2106   gfx::Transform trans;
2107   bool result = GetTransformRelativeTo(ancestor, &trans);
2108   gfx::Point3F p(*point);
2109   trans.TransformPointReverse(&p);
2110   *point = gfx::ToFlooredPoint(p.AsPointF());
2111   return result;
2112 }
2113
2114 bool View::ConvertRectForAncestor(const View* ancestor,
2115                                   gfx::RectF* rect) const {
2116   gfx::Transform trans;
2117   // TODO(sad): Have some way of caching the transformation results.
2118   bool result = GetTransformRelativeTo(ancestor, &trans);
2119   trans.TransformRect(rect);
2120   return result;
2121 }
2122
2123 bool View::ConvertRectFromAncestor(const View* ancestor,
2124                                    gfx::RectF* rect) const {
2125   gfx::Transform trans;
2126   bool result = GetTransformRelativeTo(ancestor, &trans);
2127   trans.TransformRectReverse(rect);
2128   return result;
2129 }
2130
2131 // Accelerated painting --------------------------------------------------------
2132
2133 void View::CreateLayer() {
2134   // A new layer is being created for the view. So all the layers of the
2135   // sub-tree can inherit the visibility of the corresponding view.
2136   for (int i = 0, count = child_count(); i < count; ++i)
2137     child_at(i)->UpdateChildLayerVisibility(true);
2138
2139   SetLayer(new ui::Layer());
2140   layer()->set_delegate(this);
2141 #if !defined(NDEBUG)
2142   layer()->set_name(GetClassName());
2143 #endif
2144
2145   UpdateParentLayers();
2146   UpdateLayerVisibility();
2147
2148   // The new layer needs to be ordered in the layer tree according
2149   // to the view tree. Children of this layer were added in order
2150   // in UpdateParentLayers().
2151   if (parent())
2152     parent()->ReorderLayers();
2153
2154   Widget* widget = GetWidget();
2155   if (widget)
2156     widget->UpdateRootLayers();
2157 }
2158
2159 void View::UpdateParentLayers() {
2160   // Attach all top-level un-parented layers.
2161   if (layer() && !layer()->parent()) {
2162     UpdateParentLayer();
2163   } else {
2164     for (int i = 0, count = child_count(); i < count; ++i)
2165       child_at(i)->UpdateParentLayers();
2166   }
2167 }
2168
2169 void View::OrphanLayers() {
2170   if (layer()) {
2171     if (layer()->parent())
2172       layer()->parent()->Remove(layer());
2173
2174     // The layer belonging to this View has already been orphaned. It is not
2175     // necessary to orphan the child layers.
2176     return;
2177   }
2178   for (int i = 0, count = child_count(); i < count; ++i)
2179     child_at(i)->OrphanLayers();
2180 }
2181
2182 void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) {
2183   layer()->SetBounds(GetLocalBounds() + offset);
2184   DCHECK_NE(layer(), parent_layer);
2185   if (parent_layer)
2186     parent_layer->Add(layer());
2187   layer()->SchedulePaint(GetLocalBounds());
2188   MoveLayerToParent(layer(), gfx::Point());
2189 }
2190
2191 void View::DestroyLayer() {
2192   ui::Layer* new_parent = layer()->parent();
2193   std::vector<ui::Layer*> children = layer()->children();
2194   for (size_t i = 0; i < children.size(); ++i) {
2195     layer()->Remove(children[i]);
2196     if (new_parent)
2197       new_parent->Add(children[i]);
2198   }
2199
2200   LayerOwner::DestroyLayer();
2201
2202   if (new_parent)
2203     ReorderLayers();
2204
2205   UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL));
2206
2207   SchedulePaint();
2208
2209   Widget* widget = GetWidget();
2210   if (widget)
2211     widget->UpdateRootLayers();
2212 }
2213
2214 // Input -----------------------------------------------------------------------
2215
2216 bool View::ProcessMousePressed(const ui::MouseEvent& event) {
2217   int drag_operations =
2218       (enabled_ && event.IsOnlyLeftMouseButton() &&
2219        HitTestPoint(event.location())) ?
2220        GetDragOperations(event.location()) : 0;
2221   ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
2222       context_menu_controller_ : 0;
2223   View::DragInfo* drag_info = GetDragInfo();
2224
2225   // TODO(sky): for debugging 360238.
2226   int storage_id = 0;
2227   if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2228       kContextMenuOnMousePress && HitTestPoint(event.location())) {
2229     ViewStorage* view_storage = ViewStorage::GetInstance();
2230     storage_id = view_storage->CreateStorageID();
2231     view_storage->StoreView(storage_id, this);
2232   }
2233
2234   const bool enabled = enabled_;
2235   const bool result = OnMousePressed(event);
2236
2237   if (!enabled)
2238     return result;
2239
2240   if (event.IsOnlyRightMouseButton() && context_menu_controller &&
2241       kContextMenuOnMousePress) {
2242     // Assume that if there is a context menu controller we won't be deleted
2243     // from mouse pressed.
2244     gfx::Point location(event.location());
2245     if (HitTestPoint(location)) {
2246       if (storage_id != 0)
2247         CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id));
2248       ConvertPointToScreen(this, &location);
2249       ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2250       return true;
2251     }
2252   }
2253
2254   // WARNING: we may have been deleted, don't use any View variables.
2255   if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
2256     drag_info->PossibleDrag(event.location());
2257     return true;
2258   }
2259   return !!context_menu_controller || result;
2260 }
2261
2262 bool View::ProcessMouseDragged(const ui::MouseEvent& event) {
2263   // Copy the field, that way if we're deleted after drag and drop no harm is
2264   // done.
2265   ContextMenuController* context_menu_controller = context_menu_controller_;
2266   const bool possible_drag = GetDragInfo()->possible_drag;
2267   if (possible_drag &&
2268       ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) &&
2269       (!drag_controller_ ||
2270        drag_controller_->CanStartDragForView(
2271            this, GetDragInfo()->start_pt, event.location()))) {
2272     DoDrag(event, GetDragInfo()->start_pt,
2273            ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
2274   } else {
2275     if (OnMouseDragged(event))
2276       return true;
2277     // Fall through to return value based on context menu controller.
2278   }
2279   // WARNING: we may have been deleted.
2280   return (context_menu_controller != NULL) || possible_drag;
2281 }
2282
2283 void View::ProcessMouseReleased(const ui::MouseEvent& event) {
2284   if (!kContextMenuOnMousePress && context_menu_controller_ &&
2285       event.IsOnlyRightMouseButton()) {
2286     // Assume that if there is a context menu controller we won't be deleted
2287     // from mouse released.
2288     gfx::Point location(event.location());
2289     OnMouseReleased(event);
2290     if (HitTestPoint(location)) {
2291       ConvertPointToScreen(this, &location);
2292       ShowContextMenu(location, ui::MENU_SOURCE_MOUSE);
2293     }
2294   } else {
2295     OnMouseReleased(event);
2296   }
2297   // WARNING: we may have been deleted.
2298 }
2299
2300 // Accelerators ----------------------------------------------------------------
2301
2302 void View::RegisterPendingAccelerators() {
2303   if (!accelerators_.get() ||
2304       registered_accelerator_count_ == accelerators_->size()) {
2305     // No accelerators are waiting for registration.
2306     return;
2307   }
2308
2309   if (!GetWidget()) {
2310     // The view is not yet attached to a widget, defer registration until then.
2311     return;
2312   }
2313
2314   accelerator_focus_manager_ = GetFocusManager();
2315   if (!accelerator_focus_manager_) {
2316     // Some crash reports seem to show that we may get cases where we have no
2317     // focus manager (see bug #1291225).  This should never be the case, just
2318     // making sure we don't crash.
2319     NOTREACHED();
2320     return;
2321   }
2322   for (std::vector<ui::Accelerator>::const_iterator i(
2323            accelerators_->begin() + registered_accelerator_count_);
2324        i != accelerators_->end(); ++i) {
2325     accelerator_focus_manager_->RegisterAccelerator(
2326         *i, ui::AcceleratorManager::kNormalPriority, this);
2327   }
2328   registered_accelerator_count_ = accelerators_->size();
2329 }
2330
2331 void View::UnregisterAccelerators(bool leave_data_intact) {
2332   if (!accelerators_.get())
2333     return;
2334
2335   if (GetWidget()) {
2336     if (accelerator_focus_manager_) {
2337       accelerator_focus_manager_->UnregisterAccelerators(this);
2338       accelerator_focus_manager_ = NULL;
2339     }
2340     if (!leave_data_intact) {
2341       accelerators_->clear();
2342       accelerators_.reset();
2343     }
2344     registered_accelerator_count_ = 0;
2345   }
2346 }
2347
2348 // Focus -----------------------------------------------------------------------
2349
2350 void View::InitFocusSiblings(View* v, int index) {
2351   int count = child_count();
2352
2353   if (count == 0) {
2354     v->next_focusable_view_ = NULL;
2355     v->previous_focusable_view_ = NULL;
2356   } else {
2357     if (index == count) {
2358       // We are inserting at the end, but the end of the child list may not be
2359       // the last focusable element. Let's try to find an element with no next
2360       // focusable element to link to.
2361       View* last_focusable_view = NULL;
2362       for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
2363           if (!(*i)->next_focusable_view_) {
2364             last_focusable_view = *i;
2365             break;
2366           }
2367       }
2368       if (last_focusable_view == NULL) {
2369         // Hum... there is a cycle in the focus list. Let's just insert ourself
2370         // after the last child.
2371         View* prev = children_[index - 1];
2372         v->previous_focusable_view_ = prev;
2373         v->next_focusable_view_ = prev->next_focusable_view_;
2374         prev->next_focusable_view_->previous_focusable_view_ = v;
2375         prev->next_focusable_view_ = v;
2376       } else {
2377         last_focusable_view->next_focusable_view_ = v;
2378         v->next_focusable_view_ = NULL;
2379         v->previous_focusable_view_ = last_focusable_view;
2380       }
2381     } else {
2382       View* prev = children_[index]->GetPreviousFocusableView();
2383       v->previous_focusable_view_ = prev;
2384       v->next_focusable_view_ = children_[index];
2385       if (prev)
2386         prev->next_focusable_view_ = v;
2387       children_[index]->previous_focusable_view_ = v;
2388     }
2389   }
2390 }
2391
2392 void View::AdvanceFocusIfNecessary() {
2393   // Focus should only be advanced if this is the focused view and has become
2394   // unfocusable. If the view is still focusable or is not focused, we can
2395   // return early avoiding furthur unnecessary checks. Focusability check is
2396   // performed first as it tends to be faster.
2397   if (IsAccessibilityFocusable() || !HasFocus())
2398     return;
2399
2400   FocusManager* focus_manager = GetFocusManager();
2401   if (focus_manager)
2402     focus_manager->AdvanceFocusIfNecessary();
2403 }
2404
2405 // System events ---------------------------------------------------------------
2406
2407 void View::PropagateThemeChanged() {
2408   for (int i = child_count() - 1; i >= 0; --i)
2409     child_at(i)->PropagateThemeChanged();
2410   OnThemeChanged();
2411 }
2412
2413 void View::PropagateLocaleChanged() {
2414   for (int i = child_count() - 1; i >= 0; --i)
2415     child_at(i)->PropagateLocaleChanged();
2416   OnLocaleChanged();
2417 }
2418
2419 // Tooltips --------------------------------------------------------------------
2420
2421 void View::UpdateTooltip() {
2422   Widget* widget = GetWidget();
2423   // TODO(beng): The TooltipManager NULL check can be removed when we
2424   //             consolidate Init() methods and make views_unittests Init() all
2425   //             Widgets that it uses.
2426   if (widget && widget->GetTooltipManager())
2427     widget->GetTooltipManager()->UpdateTooltip();
2428 }
2429
2430 // Drag and drop ---------------------------------------------------------------
2431
2432 bool View::DoDrag(const ui::LocatedEvent& event,
2433                   const gfx::Point& press_pt,
2434                   ui::DragDropTypes::DragEventSource source) {
2435   int drag_operations = GetDragOperations(press_pt);
2436   if (drag_operations == ui::DragDropTypes::DRAG_NONE)
2437     return false;
2438
2439   Widget* widget = GetWidget();
2440   // We should only start a drag from an event, implying we have a widget.
2441   DCHECK(widget);
2442
2443   // Don't attempt to start a drag while in the process of dragging. This is
2444   // especially important on X where we can get multiple mouse move events when
2445   // we start the drag.
2446   if (widget->dragged_view())
2447     return false;
2448
2449   OSExchangeData data;
2450   WriteDragData(press_pt, &data);
2451
2452   // Message the RootView to do the drag and drop. That way if we're removed
2453   // the RootView can detect it and avoid calling us back.
2454   gfx::Point widget_location(event.location());
2455   ConvertPointToWidget(this, &widget_location);
2456   widget->RunShellDrag(this, data, widget_location, drag_operations, source);
2457   // WARNING: we may have been deleted.
2458   return true;
2459 }
2460
2461 }  // namespace views