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