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