Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / ash / shelf / shelf_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 #include "ash/shelf/shelf_view.h"
6
7 #include <algorithm>
8
9 #include "ash/ash_constants.h"
10 #include "ash/ash_switches.h"
11 #include "ash/drag_drop/drag_image_view.h"
12 #include "ash/metrics/user_metrics_recorder.h"
13 #include "ash/root_window_controller.h"
14 #include "ash/scoped_target_root_window.h"
15 #include "ash/shelf/alternate_app_list_button.h"
16 #include "ash/shelf/app_list_button.h"
17 #include "ash/shelf/overflow_bubble.h"
18 #include "ash/shelf/overflow_bubble_view.h"
19 #include "ash/shelf/overflow_button.h"
20 #include "ash/shelf/shelf_button.h"
21 #include "ash/shelf/shelf_constants.h"
22 #include "ash/shelf/shelf_delegate.h"
23 #include "ash/shelf/shelf_icon_observer.h"
24 #include "ash/shelf/shelf_item_delegate.h"
25 #include "ash/shelf/shelf_item_delegate_manager.h"
26 #include "ash/shelf/shelf_layout_manager.h"
27 #include "ash/shelf/shelf_menu_model.h"
28 #include "ash/shelf/shelf_model.h"
29 #include "ash/shelf/shelf_tooltip_manager.h"
30 #include "ash/shelf/shelf_widget.h"
31 #include "ash/shell.h"
32 #include "ash/wm/coordinate_conversion.h"
33 #include "base/auto_reset.h"
34 #include "base/memory/scoped_ptr.h"
35 #include "base/metrics/histogram.h"
36 #include "grit/ash_resources.h"
37 #include "grit/ash_strings.h"
38 #include "ui/aura/client/screen_position_client.h"
39 #include "ui/aura/root_window.h"
40 #include "ui/aura/window.h"
41 #include "ui/base/accessibility/accessible_view_state.h"
42 #include "ui/base/l10n/l10n_util.h"
43 #include "ui/base/models/simple_menu_model.h"
44 #include "ui/base/resource/resource_bundle.h"
45 #include "ui/compositor/layer.h"
46 #include "ui/compositor/layer_animator.h"
47 #include "ui/compositor/scoped_animation_duration_scale_mode.h"
48 #include "ui/gfx/canvas.h"
49 #include "ui/gfx/point.h"
50 #include "ui/views/animation/bounds_animator.h"
51 #include "ui/views/border.h"
52 #include "ui/views/controls/button/image_button.h"
53 #include "ui/views/controls/menu/menu_model_adapter.h"
54 #include "ui/views/controls/menu/menu_runner.h"
55 #include "ui/views/focus/focus_search.h"
56 #include "ui/views/view_model.h"
57 #include "ui/views/view_model_utils.h"
58 #include "ui/views/widget/widget.h"
59
60 using gfx::Animation;
61 using views::View;
62
63 namespace ash {
64 namespace internal {
65
66 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM = 0;
67 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT = 1;
68 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT = 2;
69 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT = 3;
70
71 // Default amount content is inset on the left edge.
72 const int kDefaultLeadingInset = 8;
73
74 // Minimum distance before drag starts.
75 const int kMinimumDragDistance = 8;
76
77 // Size between the buttons.
78 const int kButtonSpacing = 4;
79 const int kAlternateButtonSpacing = 10;
80
81 // Size allocated to for each button.
82 const int kButtonSize = 44;
83
84 // Additional spacing for the left and right side of icons.
85 const int kHorizontalIconSpacing = 2;
86
87 // Inset for items which do not have an icon.
88 const int kHorizontalNoIconInsetSpacing =
89     kHorizontalIconSpacing + kDefaultLeadingInset;
90
91 // The proportion of the shelf space reserved for non-panel icons. Panels
92 // may flow into this space but will be put into the overflow bubble if there
93 // is contention for the space.
94 const float kReservedNonPanelIconProportion = 0.67f;
95
96 // This is the command id of the menu item which contains the name of the menu.
97 const int kCommandIdOfMenuName = 0;
98
99 // The background color of the active item in the list.
100 const SkColor kActiveListItemBackgroundColor = SkColorSetRGB(203 , 219, 241);
101
102 // The background color of the active & hovered item in the list.
103 const SkColor kFocusedActiveListItemBackgroundColor =
104     SkColorSetRGB(193, 211, 236);
105
106 // The text color of the caption item in a list.
107 const SkColor kCaptionItemForegroundColor = SK_ColorBLACK;
108
109 // The maximum allowable length of a menu line of an application menu in pixels.
110 const int kMaximumAppMenuItemLength = 350;
111
112 // The distance of the cursor from the outer rim of the shelf before it
113 // separates.
114 const int kRipOffDistance = 48;
115
116 // The rip off drag and drop proxy image should get scaled by this factor.
117 const float kDragAndDropProxyScale = 1.5f;
118
119 // The opacity represents that this partially disappeared item will get removed.
120 const float kDraggedImageOpacity = 0.5f;
121
122 namespace {
123
124 // A class to temporarily disable a given bounds animator.
125 class BoundsAnimatorDisabler {
126  public:
127   BoundsAnimatorDisabler(views::BoundsAnimator* bounds_animator)
128       : old_duration_(bounds_animator->GetAnimationDuration()),
129         bounds_animator_(bounds_animator) {
130     bounds_animator_->SetAnimationDuration(1);
131   }
132
133   ~BoundsAnimatorDisabler() {
134     bounds_animator_->SetAnimationDuration(old_duration_);
135   }
136
137  private:
138   // The previous animation duration.
139   int old_duration_;
140   // The bounds animator which gets used.
141   views::BoundsAnimator* bounds_animator_;
142
143   DISALLOW_COPY_AND_ASSIGN(BoundsAnimatorDisabler);
144 };
145
146 // The MenuModelAdapter gets slightly changed to adapt the menu appearance to
147 // our requirements.
148 class ShelfMenuModelAdapter : public views::MenuModelAdapter {
149  public:
150   explicit ShelfMenuModelAdapter(ShelfMenuModel* menu_model);
151
152   // views::MenuModelAdapter:
153   virtual const gfx::FontList* GetLabelFontList(int command_id) const OVERRIDE;
154   virtual bool IsCommandEnabled(int id) const OVERRIDE;
155   virtual void GetHorizontalIconMargins(int id,
156                                         int icon_size,
157                                         int* left_margin,
158                                         int* right_margin) const OVERRIDE;
159   virtual bool GetForegroundColor(int command_id,
160                                   bool is_hovered,
161                                   SkColor* override_color) const OVERRIDE;
162   virtual bool GetBackgroundColor(int command_id,
163                                   bool is_hovered,
164                                   SkColor* override_color) const OVERRIDE;
165   virtual int GetMaxWidthForMenu(views::MenuItemView* menu) OVERRIDE;
166   virtual bool ShouldReserveSpaceForSubmenuIndicator() const OVERRIDE;
167
168  private:
169   ShelfMenuModel* menu_model_;
170
171   DISALLOW_COPY_AND_ASSIGN(ShelfMenuModelAdapter);
172 };
173
174 ShelfMenuModelAdapter::ShelfMenuModelAdapter(ShelfMenuModel* menu_model)
175     : MenuModelAdapter(menu_model),
176       menu_model_(menu_model) {
177 }
178
179 const gfx::FontList* ShelfMenuModelAdapter::GetLabelFontList(
180     int command_id) const {
181   if (command_id != kCommandIdOfMenuName)
182     return MenuModelAdapter::GetLabelFontList(command_id);
183
184   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
185   return &rb.GetFontList(ui::ResourceBundle::BoldFont);
186 }
187
188 bool ShelfMenuModelAdapter::IsCommandEnabled(int id) const {
189   return id != kCommandIdOfMenuName;
190 }
191
192 bool ShelfMenuModelAdapter::GetForegroundColor(int command_id,
193                                                bool is_hovered,
194                                                SkColor* override_color) const {
195   if (command_id != kCommandIdOfMenuName)
196     return false;
197
198   *override_color = kCaptionItemForegroundColor;
199   return true;
200 }
201
202 bool ShelfMenuModelAdapter::GetBackgroundColor(int command_id,
203                                                bool is_hovered,
204                                                SkColor* override_color) const {
205   if (!menu_model_->IsCommandActive(command_id))
206     return false;
207
208   *override_color = is_hovered ? kFocusedActiveListItemBackgroundColor :
209                                  kActiveListItemBackgroundColor;
210   return true;
211 }
212
213 void ShelfMenuModelAdapter::GetHorizontalIconMargins(int command_id,
214                                                      int icon_size,
215                                                      int* left_margin,
216                                                      int* right_margin) const {
217   *left_margin = kHorizontalIconSpacing;
218   *right_margin = (command_id != kCommandIdOfMenuName) ?
219       kHorizontalIconSpacing : -(icon_size + kHorizontalNoIconInsetSpacing);
220 }
221
222 int ShelfMenuModelAdapter::GetMaxWidthForMenu(views::MenuItemView* menu) {
223   return kMaximumAppMenuItemLength;
224 }
225
226 bool ShelfMenuModelAdapter::ShouldReserveSpaceForSubmenuIndicator() const {
227   return false;
228 }
229
230 // Custom FocusSearch used to navigate the shelf in the order items are in
231 // the ViewModel.
232 class ShelfFocusSearch : public views::FocusSearch {
233  public:
234   explicit ShelfFocusSearch(views::ViewModel* view_model)
235       : FocusSearch(NULL, true, true),
236         view_model_(view_model) {}
237   virtual ~ShelfFocusSearch() {}
238
239   // views::FocusSearch overrides:
240   virtual View* FindNextFocusableView(
241       View* starting_view,
242       bool reverse,
243       Direction direction,
244       bool check_starting_view,
245       views::FocusTraversable** focus_traversable,
246       View** focus_traversable_view) OVERRIDE {
247     int index = view_model_->GetIndexOfView(starting_view);
248     if (index == -1)
249       return view_model_->view_at(0);
250
251     if (reverse) {
252       --index;
253       if (index < 0)
254         index = view_model_->view_size() - 1;
255     } else {
256       ++index;
257       if (index >= view_model_->view_size())
258         index = 0;
259     }
260     return view_model_->view_at(index);
261   }
262
263  private:
264   views::ViewModel* view_model_;
265
266   DISALLOW_COPY_AND_ASSIGN(ShelfFocusSearch);
267 };
268
269 // AnimationDelegate used when inserting a new item. This steadily increases the
270 // opacity of the layer as the animation progress.
271 class FadeInAnimationDelegate
272     : public views::BoundsAnimator::OwnedAnimationDelegate {
273  public:
274   explicit FadeInAnimationDelegate(views::View* view) : view_(view) {}
275   virtual ~FadeInAnimationDelegate() {}
276
277   // AnimationDelegate overrides:
278   virtual void AnimationProgressed(const Animation* animation) OVERRIDE {
279     view_->layer()->SetOpacity(animation->GetCurrentValue());
280     view_->layer()->ScheduleDraw();
281   }
282   virtual void AnimationEnded(const Animation* animation) OVERRIDE {
283     view_->layer()->SetOpacity(1.0f);
284     view_->layer()->ScheduleDraw();
285   }
286   virtual void AnimationCanceled(const Animation* animation) OVERRIDE {
287     view_->layer()->SetOpacity(1.0f);
288     view_->layer()->ScheduleDraw();
289   }
290
291  private:
292   views::View* view_;
293
294   DISALLOW_COPY_AND_ASSIGN(FadeInAnimationDelegate);
295 };
296
297 void ReflectItemStatus(const ShelfItem& item, ShelfButton* button) {
298   switch (item.status) {
299     case STATUS_CLOSED:
300       button->ClearState(ShelfButton::STATE_ACTIVE);
301       button->ClearState(ShelfButton::STATE_RUNNING);
302       button->ClearState(ShelfButton::STATE_ATTENTION);
303       break;
304     case STATUS_RUNNING:
305       button->ClearState(ShelfButton::STATE_ACTIVE);
306       button->AddState(ShelfButton::STATE_RUNNING);
307       button->ClearState(ShelfButton::STATE_ATTENTION);
308       break;
309     case STATUS_ACTIVE:
310       button->AddState(ShelfButton::STATE_ACTIVE);
311       button->ClearState(ShelfButton::STATE_RUNNING);
312       button->ClearState(ShelfButton::STATE_ATTENTION);
313       break;
314     case STATUS_ATTENTION:
315       button->ClearState(ShelfButton::STATE_ACTIVE);
316       button->ClearState(ShelfButton::STATE_RUNNING);
317       button->AddState(ShelfButton::STATE_ATTENTION);
318       break;
319   }
320 }
321
322 }  // namespace
323
324 // AnimationDelegate used when deleting an item. This steadily decreased the
325 // opacity of the layer as the animation progress.
326 class ShelfView::FadeOutAnimationDelegate
327     : public views::BoundsAnimator::OwnedAnimationDelegate {
328  public:
329   FadeOutAnimationDelegate(ShelfView* host, views::View* view)
330       : shelf_view_(host),
331         view_(view) {}
332   virtual ~FadeOutAnimationDelegate() {}
333
334   // AnimationDelegate overrides:
335   virtual void AnimationProgressed(const Animation* animation) OVERRIDE {
336     view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
337     view_->layer()->ScheduleDraw();
338   }
339   virtual void AnimationEnded(const Animation* animation) OVERRIDE {
340     shelf_view_->OnFadeOutAnimationEnded();
341   }
342   virtual void AnimationCanceled(const Animation* animation) OVERRIDE {
343   }
344
345  private:
346   ShelfView* shelf_view_;
347   scoped_ptr<views::View> view_;
348
349   DISALLOW_COPY_AND_ASSIGN(FadeOutAnimationDelegate);
350 };
351
352 // AnimationDelegate used to trigger fading an element in. When an item is
353 // inserted this delegate is attached to the animation that expands the size of
354 // the item.  When done it kicks off another animation to fade the item in.
355 class ShelfView::StartFadeAnimationDelegate
356     : public views::BoundsAnimator::OwnedAnimationDelegate {
357  public:
358   StartFadeAnimationDelegate(ShelfView* host,
359                              views::View* view)
360       : shelf_view_(host),
361         view_(view) {}
362   virtual ~StartFadeAnimationDelegate() {}
363
364   // AnimationDelegate overrides:
365   virtual void AnimationEnded(const Animation* animation) OVERRIDE {
366     shelf_view_->FadeIn(view_);
367   }
368   virtual void AnimationCanceled(const Animation* animation) OVERRIDE {
369     view_->layer()->SetOpacity(1.0f);
370   }
371
372  private:
373   ShelfView* shelf_view_;
374   views::View* view_;
375
376   DISALLOW_COPY_AND_ASSIGN(StartFadeAnimationDelegate);
377 };
378
379 ShelfView::ShelfView(ShelfModel* model,
380                      ShelfDelegate* delegate,
381                      ShelfLayoutManager* manager)
382     : model_(model),
383       delegate_(delegate),
384       view_model_(new views::ViewModel),
385       first_visible_index_(0),
386       last_visible_index_(-1),
387       overflow_button_(NULL),
388       owner_overflow_bubble_(NULL),
389       drag_pointer_(NONE),
390       drag_view_(NULL),
391       drag_offset_(0),
392       start_drag_index_(-1),
393       context_menu_id_(0),
394       leading_inset_(kDefaultLeadingInset),
395       cancelling_drag_model_changed_(false),
396       last_hidden_index_(0),
397       closing_event_time_(base::TimeDelta()),
398       got_deleted_(NULL),
399       drag_and_drop_item_pinned_(false),
400       drag_and_drop_shelf_id_(0),
401       dragged_off_shelf_(false),
402       snap_back_from_rip_off_view_(NULL),
403       item_manager_(Shell::GetInstance()->shelf_item_delegate_manager()),
404       layout_manager_(manager),
405       overflow_mode_(false),
406       main_shelf_(NULL),
407       dragged_off_from_overflow_to_shelf_(false) {
408   DCHECK(model_);
409   bounds_animator_.reset(new views::BoundsAnimator(this));
410   bounds_animator_->AddObserver(this);
411   set_context_menu_controller(this);
412   focus_search_.reset(new ShelfFocusSearch(view_model_.get()));
413   tooltip_.reset(new ShelfTooltipManager(manager, this));
414 }
415
416 ShelfView::~ShelfView() {
417   bounds_animator_->RemoveObserver(this);
418   model_->RemoveObserver(this);
419   // If we are inside the MenuRunner, we need to know if we were getting
420   // deleted while it was running.
421   if (got_deleted_)
422     *got_deleted_ = true;
423 }
424
425 void ShelfView::Init() {
426   model_->AddObserver(this);
427
428   const ShelfItems& items(model_->items());
429   for (ShelfItems::const_iterator i = items.begin(); i != items.end(); ++i) {
430     views::View* child = CreateViewForItem(*i);
431     child->SetPaintToLayer(true);
432     view_model_->Add(child, static_cast<int>(i - items.begin()));
433     AddChildView(child);
434   }
435   ShelfStatusChanged();
436   overflow_button_ = new OverflowButton(this);
437   overflow_button_->set_context_menu_controller(this);
438   ConfigureChildView(overflow_button_);
439   AddChildView(overflow_button_);
440   UpdateFirstButtonPadding();
441
442   // We'll layout when our bounds change.
443 }
444
445 void ShelfView::OnShelfAlignmentChanged() {
446   UpdateFirstButtonPadding();
447   overflow_button_->OnShelfAlignmentChanged();
448   LayoutToIdealBounds();
449   for (int i=0; i < view_model_->view_size(); ++i) {
450     // TODO: remove when AppIcon is a Shelf Button.
451     if (TYPE_APP_LIST == model_->items()[i].type &&
452         !ash::switches::UseAlternateShelfLayout()) {
453       static_cast<AppListButton*>(view_model_->view_at(i))->SetImageAlignment(
454           layout_manager_->SelectValueForShelfAlignment(
455               views::ImageButton::ALIGN_CENTER,
456               views::ImageButton::ALIGN_LEFT,
457               views::ImageButton::ALIGN_RIGHT,
458               views::ImageButton::ALIGN_CENTER),
459           layout_manager_->SelectValueForShelfAlignment(
460               views::ImageButton::ALIGN_TOP,
461               views::ImageButton::ALIGN_MIDDLE,
462               views::ImageButton::ALIGN_MIDDLE,
463               views::ImageButton::ALIGN_BOTTOM));
464     }
465     if (i >= first_visible_index_ && i <= last_visible_index_)
466       view_model_->view_at(i)->Layout();
467   }
468   tooltip_->Close();
469   if (overflow_bubble_)
470     overflow_bubble_->Hide();
471 }
472
473 void ShelfView::SchedulePaintForAllButtons() {
474   for (int i = 0; i < view_model_->view_size(); ++i) {
475     if (i >= first_visible_index_ && i <= last_visible_index_)
476       view_model_->view_at(i)->SchedulePaint();
477   }
478   if (overflow_button_ && overflow_button_->visible())
479     overflow_button_->SchedulePaint();
480 }
481
482 gfx::Rect ShelfView::GetIdealBoundsOfItemIcon(ShelfID id) {
483   int index = model_->ItemIndexByID(id);
484   if (index == -1 || (index > last_visible_index_ &&
485                       index < model_->FirstPanelIndex()))
486     return gfx::Rect();
487   const gfx::Rect& ideal_bounds(view_model_->ideal_bounds(index));
488   DCHECK_NE(TYPE_APP_LIST, model_->items()[index].type);
489   ShelfButton* button = static_cast<ShelfButton*>(view_model_->view_at(index));
490   gfx::Rect icon_bounds = button->GetIconBounds();
491   return gfx::Rect(GetMirroredXWithWidthInView(
492                        ideal_bounds.x() + icon_bounds.x(), icon_bounds.width()),
493                    ideal_bounds.y() + icon_bounds.y(),
494                    icon_bounds.width(),
495                    icon_bounds.height());
496 }
497
498 void ShelfView::UpdatePanelIconPosition(ShelfID id,
499                                         const gfx::Point& midpoint) {
500   int current_index = model_->ItemIndexByID(id);
501   int first_panel_index = model_->FirstPanelIndex();
502   if (current_index < first_panel_index)
503     return;
504
505   gfx::Point midpoint_in_view(GetMirroredXInView(midpoint.x()),
506                               midpoint.y());
507   int target_index = current_index;
508   while (target_index > first_panel_index &&
509          layout_manager_->PrimaryAxisValue(
510              view_model_->ideal_bounds(target_index).x(),
511              view_model_->ideal_bounds(target_index).y()) >
512          layout_manager_->PrimaryAxisValue(midpoint_in_view.x(),
513                                            midpoint_in_view.y())) {
514     --target_index;
515   }
516   while (target_index < view_model_->view_size() - 1 &&
517          layout_manager_->PrimaryAxisValue(
518              view_model_->ideal_bounds(target_index).right(),
519              view_model_->ideal_bounds(target_index).bottom()) <
520          layout_manager_->PrimaryAxisValue(midpoint_in_view.x(),
521                                            midpoint_in_view.y())) {
522     ++target_index;
523   }
524   if (current_index != target_index)
525     model_->Move(current_index, target_index);
526 }
527
528 bool ShelfView::IsShowingMenu() const {
529   return (launcher_menu_runner_.get() &&
530        launcher_menu_runner_->IsRunning());
531 }
532
533 bool ShelfView::IsShowingOverflowBubble() const {
534   return overflow_bubble_.get() && overflow_bubble_->IsShowing();
535 }
536
537 views::View* ShelfView::GetAppListButtonView() const {
538   for (int i = 0; i < model_->item_count(); ++i) {
539     if (model_->items()[i].type == TYPE_APP_LIST)
540       return view_model_->view_at(i);
541   }
542
543   NOTREACHED() << "Applist button not found";
544   return NULL;
545 }
546
547 ////////////////////////////////////////////////////////////////////////////////
548 // ShelfView, FocusTraversable implementation:
549
550 views::FocusSearch* ShelfView::GetFocusSearch() {
551   return focus_search_.get();
552 }
553
554 views::FocusTraversable* ShelfView::GetFocusTraversableParent() {
555   return parent()->GetFocusTraversable();
556 }
557
558 View* ShelfView::GetFocusTraversableParentView() {
559   return this;
560 }
561
562 void ShelfView::CreateDragIconProxy(
563     const gfx::Point& location_in_screen_coordinates,
564     const gfx::ImageSkia& icon,
565     views::View* replaced_view,
566     const gfx::Vector2d& cursor_offset_from_center,
567     float scale_factor) {
568   drag_replaced_view_ = replaced_view;
569   drag_image_.reset(new ash::internal::DragImageView(
570       drag_replaced_view_->GetWidget()->GetNativeWindow()->GetRootWindow(),
571       ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE));
572   drag_image_->SetImage(icon);
573   gfx::Size size = drag_image_->GetPreferredSize();
574   size.set_width(size.width() * scale_factor);
575   size.set_height(size.height() * scale_factor);
576   drag_image_offset_ = gfx::Vector2d(size.width() / 2, size.height() / 2) +
577                        cursor_offset_from_center;
578   gfx::Rect drag_image_bounds(
579       location_in_screen_coordinates - drag_image_offset_,
580       size);
581   drag_image_->SetBoundsInScreen(drag_image_bounds);
582   drag_image_->SetWidgetVisible(true);
583 }
584
585 void ShelfView::UpdateDragIconProxy(
586     const gfx::Point& location_in_screen_coordinates) {
587   // TODO(jennyz): Investigate why drag_image_ becomes NULL at this point per
588   // crbug.com/34722, while the app list item is still being dragged around.
589   if (drag_image_) {
590     drag_image_->SetScreenPosition(
591         location_in_screen_coordinates - drag_image_offset_);
592   }
593 }
594
595 void ShelfView::DestroyDragIconProxy() {
596   drag_image_.reset();
597   drag_image_offset_ = gfx::Vector2d(0, 0);
598 }
599
600 bool ShelfView::StartDrag(const std::string& app_id,
601                           const gfx::Point& location_in_screen_coordinates) {
602   // Bail if an operation is already going on - or the cursor is not inside.
603   // This could happen if mouse / touch operations overlap.
604   if (drag_and_drop_shelf_id_ ||
605       !GetBoundsInScreen().Contains(location_in_screen_coordinates))
606     return false;
607
608   // If the AppsGridView (which was dispatching this event) was opened by our
609   // button, ShelfView dragging operations are locked and we have to unlock.
610   CancelDrag(-1);
611   drag_and_drop_item_pinned_ = false;
612   drag_and_drop_app_id_ = app_id;
613   drag_and_drop_shelf_id_ =
614       delegate_->GetShelfIDForAppID(drag_and_drop_app_id_);
615   // Check if the application is known and pinned - if not, we have to pin it so
616   // that we can re-arrange the shelf order accordingly. Note that items have
617   // to be pinned to give them the same (order) possibilities as a shortcut.
618   // When an item is dragged from overflow to shelf, IsShowingOverflowBubble()
619   // returns true. At this time, we don't need to pin the item.
620   if (!IsShowingOverflowBubble() &&
621       (!drag_and_drop_shelf_id_ ||
622        !delegate_->IsAppPinned(app_id))) {
623     delegate_->PinAppWithID(app_id);
624     drag_and_drop_shelf_id_ =
625         delegate_->GetShelfIDForAppID(drag_and_drop_app_id_);
626     if (!drag_and_drop_shelf_id_)
627       return false;
628     drag_and_drop_item_pinned_ = true;
629   }
630   views::View* drag_and_drop_view = view_model_->view_at(
631       model_->ItemIndexByID(drag_and_drop_shelf_id_));
632   DCHECK(drag_and_drop_view);
633
634   // Since there is already an icon presented by the caller, we hide this item
635   // for now. That has to be done by reducing the size since the visibility will
636   // change once a regrouping animation is performed.
637   pre_drag_and_drop_size_ = drag_and_drop_view->size();
638   drag_and_drop_view->SetSize(gfx::Size());
639
640   // First we have to center the mouse cursor over the item.
641   gfx::Point pt = drag_and_drop_view->GetBoundsInScreen().CenterPoint();
642   views::View::ConvertPointFromScreen(drag_and_drop_view, &pt);
643   gfx::Point point_in_root = location_in_screen_coordinates;
644   ash::wm::ConvertPointFromScreen(
645       ash::wm::GetRootWindowAt(location_in_screen_coordinates),
646       &point_in_root);
647   ui::MouseEvent event(ui::ET_MOUSE_PRESSED, pt, point_in_root, 0, 0);
648   PointerPressedOnButton(drag_and_drop_view,
649                          ShelfButtonHost::DRAG_AND_DROP,
650                          event);
651
652   // Drag the item where it really belongs.
653   Drag(location_in_screen_coordinates);
654   return true;
655 }
656
657 bool ShelfView::Drag(const gfx::Point& location_in_screen_coordinates) {
658   if (!drag_and_drop_shelf_id_ ||
659       !GetBoundsInScreen().Contains(location_in_screen_coordinates))
660     return false;
661
662   gfx::Point pt = location_in_screen_coordinates;
663   views::View* drag_and_drop_view = view_model_->view_at(
664       model_->ItemIndexByID(drag_and_drop_shelf_id_));
665   ConvertPointFromScreen(drag_and_drop_view, &pt);
666   gfx::Point point_in_root = location_in_screen_coordinates;
667   ash::wm::ConvertPointFromScreen(
668       ash::wm::GetRootWindowAt(location_in_screen_coordinates),
669       &point_in_root);
670   ui::MouseEvent event(ui::ET_MOUSE_DRAGGED, pt, point_in_root, 0, 0);
671   PointerDraggedOnButton(drag_and_drop_view,
672                          ShelfButtonHost::DRAG_AND_DROP,
673                          event);
674   return true;
675 }
676
677 void ShelfView::EndDrag(bool cancel) {
678   if (!drag_and_drop_shelf_id_)
679     return;
680
681   views::View* drag_and_drop_view = view_model_->view_at(
682       model_->ItemIndexByID(drag_and_drop_shelf_id_));
683   PointerReleasedOnButton(
684       drag_and_drop_view, ShelfButtonHost::DRAG_AND_DROP, cancel);
685
686   // Either destroy the temporarily created item - or - make the item visible.
687   if (drag_and_drop_item_pinned_ && cancel)
688     delegate_->UnpinAppWithID(drag_and_drop_app_id_);
689   else if (drag_and_drop_view) {
690     if (cancel) {
691       // When a hosted drag gets canceled, the item can remain in the same slot
692       // and it might have moved within the bounds. In that case the item need
693       // to animate back to its correct location.
694       AnimateToIdealBounds();
695     } else {
696       drag_and_drop_view->SetSize(pre_drag_and_drop_size_);
697     }
698   }
699
700   drag_and_drop_shelf_id_ = 0;
701 }
702
703 void ShelfView::LayoutToIdealBounds() {
704   if (bounds_animator_->IsAnimating()) {
705     AnimateToIdealBounds();
706     return;
707   }
708
709   IdealBounds ideal_bounds;
710   CalculateIdealBounds(&ideal_bounds);
711   views::ViewModelUtils::SetViewBoundsToIdealBounds(*view_model_);
712   overflow_button_->SetBoundsRect(ideal_bounds.overflow_bounds);
713 }
714
715 void ShelfView::UpdateAllButtonsVisibilityInOverflowMode() {
716   // The overflow button is not shown in overflow mode.
717   overflow_button_->SetVisible(false);
718   int last_button_index = model_->FirstPanelIndex() - 1;
719   DCHECK_LT(last_visible_index_, view_model_->view_size());
720   for (int i = 0; i < view_model_->view_size(); ++i) {
721     bool visible = i >= first_visible_index_ &&
722         i <= last_visible_index_;
723     if (!ash::switches::UseAlternateShelfLayout())
724       visible &= i != last_button_index;
725
726     // To track the dragging of |drag_view_| continuously, its visibility
727     // should be always true regardless of its position.
728     if (dragged_off_from_overflow_to_shelf_ &&
729         view_model_->view_at(i) == drag_view_)
730       view_model_->view_at(i)->SetVisible(true);
731     else
732       view_model_->view_at(i)->SetVisible(visible);
733   }
734 }
735
736 void ShelfView::CalculateIdealBounds(IdealBounds* bounds) {
737   int available_size = layout_manager_->PrimaryAxisValue(width(), height());
738   DCHECK(model_->item_count() == view_model_->view_size());
739   if (!available_size)
740     return;
741
742   int first_panel_index = model_->FirstPanelIndex();
743   int last_button_index = first_panel_index - 1;
744
745   // Initial x,y values account both leading_inset in primary
746   // coordinate and secondary coordinate based on the dynamic edge of the
747   // shelf (eg top edge on bottom-aligned shelf).
748   int inset = ash::switches::UseAlternateShelfLayout() ? 0 : leading_inset_;
749   int x = layout_manager_->SelectValueForShelfAlignment(inset, 0, 0, inset);
750   int y = layout_manager_->SelectValueForShelfAlignment(0, inset, inset, 0);
751
752   int button_size = GetButtonSize();
753   int button_spacing = GetButtonSpacing();
754
755   int w = layout_manager_->PrimaryAxisValue(button_size, width());
756   int h = layout_manager_->PrimaryAxisValue(height(), button_size);
757   for (int i = 0; i < view_model_->view_size(); ++i) {
758     if (i < first_visible_index_) {
759       view_model_->set_ideal_bounds(i, gfx::Rect(x, y, 0, 0));
760       continue;
761     }
762
763     view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
764     if (i != last_button_index) {
765       x = layout_manager_->PrimaryAxisValue(x + w + button_spacing, x);
766       y = layout_manager_->PrimaryAxisValue(y, y + h + button_spacing);
767     }
768   }
769
770   if (is_overflow_mode()) {
771     UpdateAllButtonsVisibilityInOverflowMode();
772     return;
773   }
774
775   // To address Fitt's law, we make the first shelf button include the
776   // leading inset (if there is one).
777   if (!ash::switches::UseAlternateShelfLayout()) {
778     if (view_model_->view_size() > 0) {
779       view_model_->set_ideal_bounds(0, gfx::Rect(gfx::Size(
780           layout_manager_->PrimaryAxisValue(inset + w, w),
781           layout_manager_->PrimaryAxisValue(h, inset + h))));
782     }
783   }
784
785   // Right aligned icons.
786   int end_position = available_size - button_spacing;
787   x = layout_manager_->PrimaryAxisValue(end_position, 0);
788   y = layout_manager_->PrimaryAxisValue(0, end_position);
789   for (int i = view_model_->view_size() - 1;
790        i >= first_panel_index; --i) {
791     x = layout_manager_->PrimaryAxisValue(x - w - button_spacing, x);
792     y = layout_manager_->PrimaryAxisValue(y, y - h - button_spacing);
793     view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
794     end_position = layout_manager_->PrimaryAxisValue(x, y);
795   }
796
797   // Icons on the left / top are guaranteed up to kLeftIconProportion of
798   // the available space.
799   int last_icon_position = layout_manager_->PrimaryAxisValue(
800       view_model_->ideal_bounds(last_button_index).right(),
801       view_model_->ideal_bounds(last_button_index).bottom())
802       + button_size + inset;
803   if (!ash::switches::UseAlternateShelfLayout())
804       last_icon_position += button_size;
805   int reserved_icon_space = available_size * kReservedNonPanelIconProportion;
806   if (last_icon_position < reserved_icon_space)
807     end_position = last_icon_position;
808   else
809     end_position = std::max(end_position, reserved_icon_space);
810
811   bounds->overflow_bounds.set_size(
812       gfx::Size(layout_manager_->PrimaryAxisValue(w, width()),
813                 layout_manager_->PrimaryAxisValue(height(), h)));
814
815   if (ash::switches::UseAlternateShelfLayout()) {
816     last_visible_index_ = DetermineLastVisibleIndex(
817         end_position - button_size);
818   } else {
819     last_visible_index_ = DetermineLastVisibleIndex(
820         end_position - inset - 2 * button_size);
821   }
822   last_hidden_index_ = DetermineFirstVisiblePanelIndex(end_position) - 1;
823   bool show_overflow =
824       ((ash::switches::UseAlternateShelfLayout() ? 0 : 1) +
825       last_visible_index_ < last_button_index ||
826       last_hidden_index_ >= first_panel_index);
827
828   // Create Space for the overflow button
829   if (show_overflow && ash::switches::UseAlternateShelfLayout() &&
830       last_visible_index_ > 0 && last_visible_index_ < last_button_index)
831     --last_visible_index_;
832   for (int i = 0; i < view_model_->view_size(); ++i) {
833     bool visible = i <= last_visible_index_ || i > last_hidden_index_;
834     // Always show the app list.
835     if (!ash::switches::UseAlternateShelfLayout())
836       visible |= (i == last_button_index);
837     // To receive drag event continously from |drag_view_| during the dragging
838     // off from the shelf, don't make |drag_view_| invisible. It will be
839     // eventually invisible and removed from the |view_model_| by
840     // FinalizeRipOffDrag().
841     if (dragged_off_shelf_ && view_model_->view_at(i) == drag_view_)
842       continue;
843     view_model_->view_at(i)->SetVisible(visible);
844   }
845
846   overflow_button_->SetVisible(show_overflow);
847   if (show_overflow) {
848     DCHECK_NE(0, view_model_->view_size());
849     if (last_visible_index_ == -1) {
850       x = layout_manager_->SelectValueForShelfAlignment(inset, 0, 0, inset);
851       y = layout_manager_->SelectValueForShelfAlignment(0, inset, inset, 0);
852     } else if (last_visible_index_ == last_button_index
853         && !ash::switches::UseAlternateShelfLayout()) {
854       x = view_model_->ideal_bounds(last_visible_index_).x();
855       y = view_model_->ideal_bounds(last_visible_index_).y();
856     } else {
857       x = layout_manager_->PrimaryAxisValue(
858           view_model_->ideal_bounds(last_visible_index_).right(),
859           view_model_->ideal_bounds(last_visible_index_).x());
860       y = layout_manager_->PrimaryAxisValue(
861           view_model_->ideal_bounds(last_visible_index_).y(),
862           view_model_->ideal_bounds(last_visible_index_).bottom());
863     }
864     // Set all hidden panel icon positions to be on the overflow button.
865     for (int i = first_panel_index; i <= last_hidden_index_; ++i)
866       view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
867
868     // Add more space between last visible item and overflow button.
869     // Without this, two buttons look too close compared with other items.
870     if (ash::switches::UseAlternateShelfLayout()) {
871       x = layout_manager_->PrimaryAxisValue(x + button_spacing, x);
872       y = layout_manager_->PrimaryAxisValue(y, y + button_spacing);
873     }
874
875     bounds->overflow_bounds.set_x(x);
876     bounds->overflow_bounds.set_y(y);
877     if (!ash::switches::UseAlternateShelfLayout()) {
878       // Position app list after overflow button.
879       gfx::Rect app_list_bounds = view_model_->ideal_bounds(last_button_index);
880
881       x = layout_manager_->PrimaryAxisValue(x + w + button_spacing, x);
882       y = layout_manager_->PrimaryAxisValue(y, y + h + button_spacing);
883       app_list_bounds.set_x(x);
884       app_list_bounds.set_y(y);
885       view_model_->set_ideal_bounds(last_button_index, app_list_bounds);
886     }
887     if (overflow_bubble_.get() && overflow_bubble_->IsShowing())
888       UpdateOverflowRange(overflow_bubble_->shelf_view());
889   } else {
890     if (overflow_bubble_)
891       overflow_bubble_->Hide();
892   }
893 }
894
895 int ShelfView::DetermineLastVisibleIndex(int max_value) const {
896   int index = model_->FirstPanelIndex() - 1;
897   while (index >= 0 &&
898          layout_manager_->PrimaryAxisValue(
899              view_model_->ideal_bounds(index).right(),
900              view_model_->ideal_bounds(index).bottom()) > max_value) {
901     index--;
902   }
903   return index;
904 }
905
906 int ShelfView::DetermineFirstVisiblePanelIndex(int min_value) const {
907   int index = model_->FirstPanelIndex();
908   while (index < view_model_->view_size() &&
909          layout_manager_->PrimaryAxisValue(
910              view_model_->ideal_bounds(index).right(),
911              view_model_->ideal_bounds(index).bottom()) < min_value) {
912     ++index;
913   }
914   return index;
915 }
916
917 void ShelfView::AddIconObserver(ShelfIconObserver* observer) {
918   observers_.AddObserver(observer);
919 }
920
921 void ShelfView::RemoveIconObserver(ShelfIconObserver* observer) {
922   observers_.RemoveObserver(observer);
923 }
924
925 void ShelfView::AnimateToIdealBounds() {
926   IdealBounds ideal_bounds;
927   CalculateIdealBounds(&ideal_bounds);
928   for (int i = 0; i < view_model_->view_size(); ++i) {
929     View* view = view_model_->view_at(i);
930     bounds_animator_->AnimateViewTo(view, view_model_->ideal_bounds(i));
931     // Now that the item animation starts, we have to make sure that the
932     // padding of the first gets properly transferred to the new first item.
933     if (i && view->border())
934       view->SetBorder(views::Border::NullBorder());
935     else if (!i && !view->border())
936       UpdateFirstButtonPadding();
937   }
938   overflow_button_->SetBoundsRect(ideal_bounds.overflow_bounds);
939 }
940
941 views::View* ShelfView::CreateViewForItem(const ShelfItem& item) {
942   views::View* view = NULL;
943   switch (item.type) {
944     case TYPE_BROWSER_SHORTCUT:
945     case TYPE_APP_SHORTCUT:
946     case TYPE_WINDOWED_APP:
947     case TYPE_PLATFORM_APP:
948     case TYPE_DIALOG:
949     case TYPE_APP_PANEL: {
950       ShelfButton* button = ShelfButton::Create(this, this, layout_manager_);
951       button->SetImage(item.image);
952       ReflectItemStatus(item, button);
953       view = button;
954       break;
955     }
956
957     case TYPE_APP_LIST: {
958       if (ash::switches::UseAlternateShelfLayout()) {
959         view = new AlternateAppListButton(this,
960                                           this,
961                                           layout_manager_->shelf_widget());
962       } else {
963         // TODO(dave): turn this into a ShelfButton too.
964         AppListButton* button = new AppListButton(this, this);
965         button->SetImageAlignment(
966             layout_manager_->SelectValueForShelfAlignment(
967                 views::ImageButton::ALIGN_CENTER,
968                 views::ImageButton::ALIGN_LEFT,
969                 views::ImageButton::ALIGN_RIGHT,
970                 views::ImageButton::ALIGN_CENTER),
971             layout_manager_->SelectValueForShelfAlignment(
972                 views::ImageButton::ALIGN_TOP,
973                 views::ImageButton::ALIGN_MIDDLE,
974                 views::ImageButton::ALIGN_MIDDLE,
975                 views::ImageButton::ALIGN_BOTTOM));
976         view = button;
977       }
978       break;
979     }
980
981     default:
982       break;
983   }
984   view->set_context_menu_controller(this);
985
986   DCHECK(view);
987   ConfigureChildView(view);
988   return view;
989 }
990
991 void ShelfView::FadeIn(views::View* view) {
992   view->SetVisible(true);
993   view->layer()->SetOpacity(0);
994   AnimateToIdealBounds();
995   bounds_animator_->SetAnimationDelegate(
996       view, new FadeInAnimationDelegate(view), true);
997 }
998
999 void ShelfView::PrepareForDrag(Pointer pointer, const ui::LocatedEvent& event) {
1000   DCHECK(!dragging());
1001   DCHECK(drag_view_);
1002   drag_pointer_ = pointer;
1003   start_drag_index_ = view_model_->GetIndexOfView(drag_view_);
1004
1005   if (start_drag_index_== -1) {
1006     CancelDrag(-1);
1007     return;
1008   }
1009
1010   // If the item is no longer draggable, bail out.
1011   ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1012       model_->items()[start_drag_index_].id);
1013   if (!item_delegate->IsDraggable()) {
1014     CancelDrag(-1);
1015     return;
1016   }
1017
1018   // Move the view to the front so that it appears on top of other views.
1019   ReorderChildView(drag_view_, -1);
1020   bounds_animator_->StopAnimatingView(drag_view_);
1021 }
1022
1023 void ShelfView::ContinueDrag(const ui::LocatedEvent& event) {
1024   // Due to a syncing operation the application might have been removed.
1025   // Bail if it is gone.
1026   int current_index = view_model_->GetIndexOfView(drag_view_);
1027   DCHECK_NE(-1, current_index);
1028
1029   ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1030       model_->items()[current_index].id);
1031   if (!item_delegate->IsDraggable()) {
1032     CancelDrag(-1);
1033     return;
1034   }
1035
1036   // If this is not a drag and drop host operation and not the app list item,
1037   // check if the item got ripped off the shelf - if it did we are done.
1038   if (!drag_and_drop_shelf_id_ && ash::switches::UseDragOffShelf() &&
1039       RemovableByRipOff(current_index) != NOT_REMOVABLE) {
1040     if (HandleRipOffDrag(event))
1041       return;
1042     // The rip off handler could have changed the location of the item.
1043     current_index = view_model_->GetIndexOfView(drag_view_);
1044   }
1045
1046   // TODO: I don't think this works correctly with RTL.
1047   gfx::Point drag_point(event.location());
1048   ConvertPointToTarget(drag_view_, this, &drag_point);
1049
1050   // Constrain the location to the range of valid indices for the type.
1051   std::pair<int, int> indices(GetDragRange(current_index));
1052   int first_drag_index = indices.first;
1053   int last_drag_index = indices.second;
1054   // If the last index isn't valid, we're overflowing. Constrain to the app list
1055   // (which is the last visible item).
1056   if (first_drag_index < model_->FirstPanelIndex() &&
1057       last_drag_index > last_visible_index_)
1058     last_drag_index = last_visible_index_;
1059   int x = 0, y = 0;
1060   if (layout_manager_->IsHorizontalAlignment()) {
1061     x = std::max(view_model_->ideal_bounds(indices.first).x(),
1062                      drag_point.x() - drag_offset_);
1063     x = std::min(view_model_->ideal_bounds(last_drag_index).right() -
1064                  view_model_->ideal_bounds(current_index).width(),
1065                  x);
1066     if (drag_view_->x() == x)
1067       return;
1068     drag_view_->SetX(x);
1069   } else {
1070     y = std::max(view_model_->ideal_bounds(indices.first).y(),
1071                      drag_point.y() - drag_offset_);
1072     y = std::min(view_model_->ideal_bounds(last_drag_index).bottom() -
1073                  view_model_->ideal_bounds(current_index).height(),
1074                  y);
1075     if (drag_view_->y() == y)
1076       return;
1077     drag_view_->SetY(y);
1078   }
1079
1080   int target_index =
1081       views::ViewModelUtils::DetermineMoveIndex(
1082           *view_model_, drag_view_,
1083           layout_manager_->IsHorizontalAlignment() ?
1084               views::ViewModelUtils::HORIZONTAL :
1085               views::ViewModelUtils::VERTICAL,
1086           x, y);
1087   target_index =
1088       std::min(indices.second, std::max(target_index, indices.first));
1089   if (target_index == current_index)
1090     return;
1091
1092   // Change the model, the ShelfItemMoved() callback will handle the
1093   // |view_model_| update.
1094   model_->Move(current_index, target_index);
1095   bounds_animator_->StopAnimatingView(drag_view_);
1096 }
1097
1098 bool ShelfView::HandleRipOffDrag(const ui::LocatedEvent& event) {
1099   int current_index = view_model_->GetIndexOfView(drag_view_);
1100   DCHECK_NE(-1, current_index);
1101   std::string dragged_app_id =
1102       delegate_->GetAppIDForShelfID(model_->items()[current_index].id);
1103
1104   gfx::Point screen_location = event.root_location();
1105   ash::wm::ConvertPointToScreen(GetWidget()->GetNativeWindow()->GetRootWindow(),
1106                                 &screen_location);
1107
1108   // To avoid ugly forwards and backwards flipping we use different constants
1109   // for ripping off / re-inserting the items.
1110   if (dragged_off_shelf_) {
1111     // If the shelf/overflow bubble bounds contains |screen_location| we insert
1112     // the item back into the shelf.
1113     if (GetBoundsForDragInsertInScreen().Contains(screen_location)) {
1114       if (dragged_off_from_overflow_to_shelf_) {
1115         // During the dragging an item from Shelf to Overflow, it can enter here
1116         // directly because both are located very closly.
1117         main_shelf_->EndDrag(true);
1118         // Stops the animation of |drag_view_| and sets its bounds explicitly
1119         // becase ContinueDrag() stops its animation. Without this, unexpected
1120         // bounds will be set.
1121         bounds_animator_->StopAnimatingView(drag_view_);
1122         int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1123         drag_view_->SetBoundsRect(view_model_->ideal_bounds(drag_view_index));
1124         dragged_off_from_overflow_to_shelf_ = false;
1125       }
1126       // Destroy our proxy view item.
1127       DestroyDragIconProxy();
1128       // Re-insert the item and return simply false since the caller will handle
1129       // the move as in any normal case.
1130       dragged_off_shelf_ = false;
1131       drag_view_->layer()->SetOpacity(1.0f);
1132       // The size of Overflow bubble should be updated immediately when an item
1133       // is re-inserted.
1134       if (is_overflow_mode())
1135         PreferredSizeChanged();
1136       return false;
1137     } else if (is_overflow_mode() &&
1138                main_shelf_->GetBoundsForDragInsertInScreen().Contains(
1139                    screen_location)) {
1140       if (!dragged_off_from_overflow_to_shelf_) {
1141         dragged_off_from_overflow_to_shelf_ = true;
1142         drag_image_->SetOpacity(1.0f);
1143         main_shelf_->StartDrag(dragged_app_id, screen_location);
1144       } else {
1145         main_shelf_->Drag(screen_location);
1146       }
1147     } else if (dragged_off_from_overflow_to_shelf_) {
1148       // Makes the |drag_image_| partially disappear again.
1149       dragged_off_from_overflow_to_shelf_ = false;
1150       drag_image_->SetOpacity(kDraggedImageOpacity);
1151       main_shelf_->EndDrag(true);
1152       bounds_animator_->StopAnimatingView(drag_view_);
1153       int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1154       drag_view_->SetBoundsRect(view_model_->ideal_bounds(drag_view_index));
1155     }
1156     // Move our proxy view item.
1157     UpdateDragIconProxy(screen_location);
1158     return true;
1159   }
1160   // Check if we are too far away from the shelf to enter the ripped off state.
1161   // Determine the distance to the shelf.
1162   int delta = CalculateShelfDistance(screen_location);
1163   if (delta > kRipOffDistance) {
1164     // Create a proxy view item which can be moved anywhere.
1165     ShelfButton* button = static_cast<ShelfButton*>(drag_view_);
1166     CreateDragIconProxy(event.root_location(),
1167                         button->GetImage(),
1168                         drag_view_,
1169                         gfx::Vector2d(0, 0),
1170                         kDragAndDropProxyScale);
1171     drag_view_->layer()->SetOpacity(0.0f);
1172     dragged_off_shelf_ = true;
1173     if (RemovableByRipOff(current_index) == REMOVABLE) {
1174       // Move the item to the front of the first panel item and hide it.
1175       // ShelfItemMoved() callback will handle the |view_model_| update and
1176       // call AnimateToIdealBounds().
1177       if (current_index != model_->FirstPanelIndex() - 1) {
1178         model_->Move(current_index, model_->FirstPanelIndex() - 1);
1179         StartFadeInLastVisibleItem();
1180       } else if (is_overflow_mode()) {
1181         // Overflow bubble should be shrunk when an item is ripped off.
1182         PreferredSizeChanged();
1183       }
1184       // Make the item partially disappear to show that it will get removed if
1185       // dropped.
1186       drag_image_->SetOpacity(kDraggedImageOpacity);
1187     }
1188     return true;
1189   }
1190   return false;
1191 }
1192
1193 void ShelfView::FinalizeRipOffDrag(bool cancel) {
1194   if (!dragged_off_shelf_)
1195     return;
1196   // Make sure we do not come in here again.
1197   dragged_off_shelf_ = false;
1198
1199   // Coming here we should always have a |drag_view_|.
1200   DCHECK(drag_view_);
1201   int current_index = view_model_->GetIndexOfView(drag_view_);
1202   // If the view isn't part of the model anymore (|current_index| == -1), a sync
1203   // operation must have removed it. In that case we shouldn't change the model
1204   // and only delete the proxy image.
1205   if (current_index == -1) {
1206     DestroyDragIconProxy();
1207     return;
1208   }
1209
1210   // Set to true when the animation should snap back to where it was before.
1211   bool snap_back = false;
1212   // Items which cannot be dragged off will be handled as a cancel.
1213   if (!cancel) {
1214     if (dragged_off_from_overflow_to_shelf_) {
1215       dragged_off_from_overflow_to_shelf_ = false;
1216       main_shelf_->EndDrag(false);
1217       drag_view_->layer()->SetOpacity(1.0f);
1218     } else if (RemovableByRipOff(current_index) != REMOVABLE) {
1219       // Make sure we do not try to remove un-removable items like items which
1220       // were not pinned or have to be always there.
1221       cancel = true;
1222       snap_back = true;
1223     } else {
1224       // Make sure the item stays invisible upon removal.
1225       drag_view_->SetVisible(false);
1226       std::string app_id =
1227           delegate_->GetAppIDForShelfID(model_->items()[current_index].id);
1228       delegate_->UnpinAppWithID(app_id);
1229     }
1230   }
1231   if (cancel || snap_back) {
1232     if (dragged_off_from_overflow_to_shelf_) {
1233       dragged_off_from_overflow_to_shelf_ = false;
1234       // Main shelf handles revert of dragged item.
1235       main_shelf_->EndDrag(true);
1236       drag_view_->layer()->SetOpacity(1.0f);
1237     } else if (!cancelling_drag_model_changed_) {
1238       // Only do something if the change did not come through a model change.
1239       gfx::Rect drag_bounds = drag_image_->GetBoundsInScreen();
1240       gfx::Point relative_to = GetBoundsInScreen().origin();
1241       gfx::Rect target(
1242           gfx::PointAtOffsetFromOrigin(drag_bounds.origin()- relative_to),
1243           drag_bounds.size());
1244       drag_view_->SetBoundsRect(target);
1245       // Hide the status from the active item since we snap it back now. Upon
1246       // animation end the flag gets cleared if |snap_back_from_rip_off_view_|
1247       // is set.
1248       snap_back_from_rip_off_view_ = drag_view_;
1249       ShelfButton* button = static_cast<ShelfButton*>(drag_view_);
1250       button->AddState(ShelfButton::STATE_HIDDEN);
1251       // When a canceling drag model is happening, the view model is diverged
1252       // from the menu model and movements / animations should not be done.
1253       model_->Move(current_index, start_drag_index_);
1254       AnimateToIdealBounds();
1255     }
1256     drag_view_->layer()->SetOpacity(1.0f);
1257   }
1258   DestroyDragIconProxy();
1259 }
1260
1261 ShelfView::RemovableState ShelfView::RemovableByRipOff(int index) {
1262   DCHECK(index >= 0 && index < model_->item_count());
1263   ShelfItemType type = model_->items()[index].type;
1264   if (type == TYPE_APP_LIST || type == TYPE_DIALOG || !delegate_->CanPin())
1265     return NOT_REMOVABLE;
1266
1267   std::string app_id = delegate_->GetAppIDForShelfID(model_->items()[index].id);
1268   // Note: Only pinned app shortcuts can be removed!
1269   return (type == TYPE_APP_SHORTCUT && delegate_->IsAppPinned(app_id)) ?
1270       REMOVABLE : DRAGGABLE;
1271 }
1272
1273 bool ShelfView::SameDragType(ShelfItemType typea, ShelfItemType typeb) const {
1274   switch (typea) {
1275     case TYPE_APP_SHORTCUT:
1276     case TYPE_BROWSER_SHORTCUT:
1277       return (typeb == TYPE_APP_SHORTCUT || typeb == TYPE_BROWSER_SHORTCUT);
1278     case TYPE_APP_LIST:
1279     case TYPE_PLATFORM_APP:
1280     case TYPE_WINDOWED_APP:
1281     case TYPE_APP_PANEL:
1282     case TYPE_DIALOG:
1283       return typeb == typea;
1284     case TYPE_UNDEFINED:
1285       NOTREACHED() << "ShelfItemType must be set.";
1286       return false;
1287   }
1288   NOTREACHED();
1289   return false;
1290 }
1291
1292 std::pair<int, int> ShelfView::GetDragRange(int index) {
1293   int min_index = -1;
1294   int max_index = -1;
1295   ShelfItemType type = model_->items()[index].type;
1296   for (int i = 0; i < model_->item_count(); ++i) {
1297     if (SameDragType(model_->items()[i].type, type)) {
1298       if (min_index == -1)
1299         min_index = i;
1300       max_index = i;
1301     }
1302   }
1303   return std::pair<int, int>(min_index, max_index);
1304 }
1305
1306 void ShelfView::ConfigureChildView(views::View* view) {
1307   view->SetPaintToLayer(true);
1308   view->layer()->SetFillsBoundsOpaquely(false);
1309 }
1310
1311 void ShelfView::ToggleOverflowBubble() {
1312   if (IsShowingOverflowBubble()) {
1313     overflow_bubble_->Hide();
1314     return;
1315   }
1316
1317   if (!overflow_bubble_)
1318     overflow_bubble_.reset(new OverflowBubble());
1319
1320   ShelfView* overflow_view =
1321       new ShelfView(model_, delegate_, layout_manager_);
1322   overflow_view->overflow_mode_ = true;
1323   overflow_view->Init();
1324   overflow_view->set_owner_overflow_bubble(overflow_bubble_.get());
1325   overflow_view->OnShelfAlignmentChanged();
1326   overflow_view->main_shelf_ = this;
1327   UpdateOverflowRange(overflow_view);
1328
1329   overflow_bubble_->Show(overflow_button_, overflow_view);
1330
1331   Shell::GetInstance()->UpdateShelfVisibility();
1332 }
1333
1334 void ShelfView::UpdateFirstButtonPadding() {
1335   if (ash::switches::UseAlternateShelfLayout())
1336     return;
1337
1338   // Creates an empty border for first shelf button to make included leading
1339   // inset act as the button's padding. This is only needed on button creation
1340   // and when shelf alignment changes.
1341   if (view_model_->view_size() > 0) {
1342     view_model_->view_at(0)->SetBorder(views::Border::CreateEmptyBorder(
1343         layout_manager_->PrimaryAxisValue(0, leading_inset_),
1344         layout_manager_->PrimaryAxisValue(leading_inset_, 0),
1345         0,
1346         0));
1347   }
1348 }
1349
1350 void ShelfView::OnFadeOutAnimationEnded() {
1351   AnimateToIdealBounds();
1352   StartFadeInLastVisibleItem();
1353 }
1354
1355 void ShelfView::StartFadeInLastVisibleItem() {
1356   // If overflow button is visible and there is a valid new last item, fading
1357   // the new last item in after sliding animation is finished.
1358   if (overflow_button_->visible() && last_visible_index_ >= 0) {
1359     views::View* last_visible_view = view_model_->view_at(last_visible_index_);
1360     last_visible_view->layer()->SetOpacity(0);
1361     bounds_animator_->SetAnimationDelegate(
1362         last_visible_view,
1363         new ShelfView::StartFadeAnimationDelegate(this, last_visible_view),
1364         true);
1365   }
1366 }
1367
1368 void ShelfView::UpdateOverflowRange(ShelfView* overflow_view) {
1369   const int first_overflow_index = last_visible_index_ + 1;
1370   const int last_overflow_index = last_hidden_index_;
1371   DCHECK_LE(first_overflow_index, last_overflow_index);
1372   DCHECK_LT(last_overflow_index, view_model_->view_size());
1373
1374   overflow_view->first_visible_index_ = first_overflow_index;
1375   overflow_view->last_visible_index_ = last_overflow_index;
1376 }
1377
1378 int ShelfView::GetButtonSize() const {
1379   return ash::switches::UseAlternateShelfLayout() ?
1380       kButtonSize : kShelfPreferredSize;
1381 }
1382
1383 int ShelfView::GetButtonSpacing() const {
1384   return ash::switches::UseAlternateShelfLayout() ?
1385       kAlternateButtonSpacing : kButtonSpacing;
1386 }
1387
1388 bool ShelfView::ShouldHideTooltip(const gfx::Point& cursor_location) {
1389   gfx::Rect active_bounds;
1390
1391   for (int i = 0; i < child_count(); ++i) {
1392     views::View* child = child_at(i);
1393     if (child == overflow_button_)
1394       continue;
1395     if (!ShouldShowTooltipForView(child))
1396       continue;
1397
1398     gfx::Rect child_bounds = child->GetMirroredBounds();
1399     active_bounds.Union(child_bounds);
1400   }
1401
1402   return !active_bounds.Contains(cursor_location);
1403 }
1404
1405 gfx::Rect ShelfView::GetVisibleItemsBoundsInScreen() {
1406   gfx::Size preferred_size = GetPreferredSize();
1407   gfx::Point origin(GetMirroredXWithWidthInView(0, preferred_size.width()), 0);
1408   ConvertPointToScreen(this, &origin);
1409   return gfx::Rect(origin, preferred_size);
1410 }
1411
1412 gfx::Rect ShelfView::GetBoundsForDragInsertInScreen() {
1413   gfx::Size preferred_size;
1414   if (is_overflow_mode()) {
1415     DCHECK(owner_overflow_bubble_);
1416     gfx::Rect bubble_bounds =
1417         owner_overflow_bubble_->bubble_view()->GetBubbleBounds();
1418     preferred_size = bubble_bounds.size();
1419   } else {
1420     const int preferred_shelf_size = layout_manager_->GetPreferredShelfSize();
1421
1422     const int last_button_index = view_model_->view_size() - 1;
1423     gfx::Rect last_button_bounds =
1424         view_model_->view_at(last_button_index)->bounds();
1425     if (overflow_button_->visible() &&
1426         model_->GetItemIndexForType(TYPE_APP_PANEL) == -1) {
1427       // When overflow button is visible and shelf has no panel items,
1428       // last_button_bounds should be overflow button's bounds.
1429       last_button_bounds = overflow_button_->bounds();
1430     }
1431
1432     if (layout_manager_->IsHorizontalAlignment()) {
1433       preferred_size = gfx::Size(last_button_bounds.right() + leading_inset_,
1434                                  preferred_shelf_size);
1435     } else {
1436       preferred_size = gfx::Size(preferred_shelf_size,
1437                                  last_button_bounds.bottom() + leading_inset_);
1438     }
1439   }
1440   gfx::Point origin(GetMirroredXWithWidthInView(0, preferred_size.width()), 0);
1441
1442   // In overflow mode, we should use OverflowBubbleView as a source for
1443   // converting |origin| to screen coordinates. When a scroll operation is
1444   // occurred in OverflowBubble, the bounds of ShelfView in OverflowBubble can
1445   // be changed.
1446   if (is_overflow_mode())
1447     ConvertPointToScreen(owner_overflow_bubble_->bubble_view(), &origin);
1448   else
1449     ConvertPointToScreen(this, &origin);
1450
1451   return gfx::Rect(origin, preferred_size);
1452 }
1453
1454 int ShelfView::CancelDrag(int modified_index) {
1455   FinalizeRipOffDrag(true);
1456   if (!drag_view_)
1457     return modified_index;
1458   bool was_dragging = dragging();
1459   int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1460   drag_pointer_ = NONE;
1461   drag_view_ = NULL;
1462   if (drag_view_index == modified_index) {
1463     // The view that was being dragged is being modified. Don't do anything.
1464     return modified_index;
1465   }
1466   if (!was_dragging)
1467     return modified_index;
1468
1469   // Restore previous position, tracking the position of the modified view.
1470   bool at_end = modified_index == view_model_->view_size();
1471   views::View* modified_view =
1472       (modified_index >= 0 && !at_end) ?
1473       view_model_->view_at(modified_index) : NULL;
1474   model_->Move(drag_view_index, start_drag_index_);
1475
1476   // If the modified view will be at the end of the list, return the new end of
1477   // the list.
1478   if (at_end)
1479     return view_model_->view_size();
1480   return modified_view ? view_model_->GetIndexOfView(modified_view) : -1;
1481 }
1482
1483 gfx::Size ShelfView::GetPreferredSize() {
1484   IdealBounds ideal_bounds;
1485   CalculateIdealBounds(&ideal_bounds);
1486
1487   const int preferred_size = layout_manager_->GetPreferredShelfSize();
1488
1489   int last_button_index = is_overflow_mode() ?
1490       last_visible_index_ : view_model_->view_size() - 1;
1491
1492   // When an item is dragged off from the overflow bubble, it is moved to last
1493   // position and and changed to invisible. Overflow bubble size should be
1494   // shrunk to fit only for visible items.
1495   // If |dragged_off_from_overflow_to_shelf_| is set, there will be no invisible
1496   // items in the shelf.
1497   if (is_overflow_mode() &&
1498       dragged_off_shelf_ &&
1499       !dragged_off_from_overflow_to_shelf_ &&
1500       RemovableByRipOff(view_model_->GetIndexOfView(drag_view_)) == REMOVABLE)
1501     last_button_index--;
1502
1503   const gfx::Rect last_button_bounds =
1504       last_button_index  >= first_visible_index_ ?
1505           view_model_->ideal_bounds(last_button_index) :
1506           gfx::Rect(gfx::Size(preferred_size, preferred_size));
1507
1508   if (layout_manager_->IsHorizontalAlignment()) {
1509     return gfx::Size(last_button_bounds.right() + leading_inset_,
1510                      preferred_size);
1511   }
1512
1513   return gfx::Size(preferred_size,
1514                    last_button_bounds.bottom() + leading_inset_);
1515 }
1516
1517 void ShelfView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1518   // This bounds change is produced by the shelf movement and all content has
1519   // to follow. Using an animation at that time would produce a time lag since
1520   // the animation of the BoundsAnimator has itself a delay before it arrives
1521   // at the required location. As such we tell the animator to go there
1522   // immediately.
1523   BoundsAnimatorDisabler disabler(bounds_animator_.get());
1524   LayoutToIdealBounds();
1525   FOR_EACH_OBSERVER(ShelfIconObserver, observers_,
1526                     OnShelfIconPositionsChanged());
1527
1528   if (IsShowingOverflowBubble())
1529     overflow_bubble_->Hide();
1530 }
1531
1532 views::FocusTraversable* ShelfView::GetPaneFocusTraversable() {
1533   return this;
1534 }
1535
1536 void ShelfView::GetAccessibleState(ui::AccessibleViewState* state) {
1537   state->role = ui::AccessibilityTypes::ROLE_TOOLBAR;
1538   state->name = l10n_util::GetStringUTF16(IDS_ASH_SHELF_ACCESSIBLE_NAME);
1539 }
1540
1541 void ShelfView::OnGestureEvent(ui::GestureEvent* event) {
1542   if (gesture_handler_.ProcessGestureEvent(*event))
1543     event->StopPropagation();
1544 }
1545
1546 void ShelfView::ShelfItemAdded(int model_index) {
1547   {
1548     base::AutoReset<bool> cancelling_drag(
1549         &cancelling_drag_model_changed_, true);
1550     model_index = CancelDrag(model_index);
1551   }
1552   views::View* view = CreateViewForItem(model_->items()[model_index]);
1553   AddChildView(view);
1554   // Hide the view, it'll be made visible when the animation is done. Using
1555   // opacity 0 here to avoid messing with CalculateIdealBounds which touches
1556   // the view's visibility.
1557   view->layer()->SetOpacity(0);
1558   view_model_->Add(view, model_index);
1559
1560   // Give the button its ideal bounds. That way if we end up animating the
1561   // button before this animation completes it doesn't appear at some random
1562   // spot (because it was in the middle of animating from 0,0 0x0 to its
1563   // target).
1564   IdealBounds ideal_bounds;
1565   CalculateIdealBounds(&ideal_bounds);
1566   view->SetBoundsRect(view_model_->ideal_bounds(model_index));
1567
1568   // The first animation moves all the views to their target position. |view|
1569   // is hidden, so it visually appears as though we are providing space for
1570   // it. When done we'll fade the view in.
1571   AnimateToIdealBounds();
1572   if (model_index <= last_visible_index_ ||
1573       model_index >= model_->FirstPanelIndex()) {
1574     bounds_animator_->SetAnimationDelegate(
1575         view, new StartFadeAnimationDelegate(this, view), true);
1576   } else {
1577     // Undo the hiding if animation does not run.
1578     view->layer()->SetOpacity(1.0f);
1579   }
1580 }
1581
1582 void ShelfView::ShelfItemRemoved(int model_index, ShelfID id) {
1583   if (id == context_menu_id_)
1584     launcher_menu_runner_.reset();
1585   {
1586     base::AutoReset<bool> cancelling_drag(
1587         &cancelling_drag_model_changed_, true);
1588     model_index = CancelDrag(model_index);
1589   }
1590   views::View* view = view_model_->view_at(model_index);
1591   view_model_->Remove(model_index);
1592
1593   // When the overflow bubble is visible, the overflow range needs to be set
1594   // before CalculateIdealBounds() gets called. Otherwise CalculateIdealBounds()
1595   // could trigger a ShelfItemChanged() by hiding the overflow bubble and
1596   // since the overflow bubble is not yet synced with the ShelfModel this
1597   // could cause a crash.
1598   if (overflow_bubble_ && overflow_bubble_->IsShowing()) {
1599     last_hidden_index_ = std::min(last_hidden_index_,
1600                                   view_model_->view_size() - 1);
1601     UpdateOverflowRange(overflow_bubble_->shelf_view());
1602   }
1603
1604   if (view->visible()) {
1605     // The first animation fades out the view. When done we'll animate the rest
1606     // of the views to their target location.
1607     bounds_animator_->AnimateViewTo(view, view->bounds());
1608     bounds_animator_->SetAnimationDelegate(
1609         view, new FadeOutAnimationDelegate(this, view), true);
1610   } else {
1611     // We don't need to show a fade out animation for invisible |view|. When an
1612     // item is ripped out from the shelf, its |view| is already invisible.
1613     AnimateToIdealBounds();
1614   }
1615
1616   // Close the tooltip because it isn't needed any longer and its anchor view
1617   // will be deleted soon.
1618   if (tooltip_->GetCurrentAnchorView() == view)
1619     tooltip_->Close();
1620 }
1621
1622 void ShelfView::ShelfItemChanged(int model_index, const ShelfItem& old_item) {
1623   const ShelfItem& item(model_->items()[model_index]);
1624   if (old_item.type != item.type) {
1625     // Type changed, swap the views.
1626     model_index = CancelDrag(model_index);
1627     scoped_ptr<views::View> old_view(view_model_->view_at(model_index));
1628     bounds_animator_->StopAnimatingView(old_view.get());
1629     // Removing and re-inserting a view in our view model will strip the ideal
1630     // bounds from the item. To avoid recalculation of everything the bounds
1631     // get remembered and restored after the insertion to the previous value.
1632     gfx::Rect old_ideal_bounds = view_model_->ideal_bounds(model_index);
1633     view_model_->Remove(model_index);
1634     views::View* new_view = CreateViewForItem(item);
1635     AddChildView(new_view);
1636     view_model_->Add(new_view, model_index);
1637     view_model_->set_ideal_bounds(model_index, old_ideal_bounds);
1638     new_view->SetBoundsRect(old_view->bounds());
1639     return;
1640   }
1641
1642   views::View* view = view_model_->view_at(model_index);
1643   switch (item.type) {
1644     case TYPE_BROWSER_SHORTCUT:
1645       // Fallthrough for the new Shelf since it needs to show the activation
1646       // change as well.
1647     case TYPE_APP_SHORTCUT:
1648     case TYPE_WINDOWED_APP:
1649     case TYPE_PLATFORM_APP:
1650     case TYPE_DIALOG:
1651     case TYPE_APP_PANEL: {
1652       ShelfButton* button = static_cast<ShelfButton*>(view);
1653       ReflectItemStatus(item, button);
1654       // The browser shortcut is currently not a "real" item and as such the
1655       // the image is bogous as well. We therefore keep the image as is for it.
1656       if (item.type != TYPE_BROWSER_SHORTCUT)
1657         button->SetImage(item.image);
1658       button->SchedulePaint();
1659       break;
1660     }
1661
1662     default:
1663       break;
1664   }
1665 }
1666
1667 void ShelfView::ShelfItemMoved(int start_index, int target_index) {
1668   view_model_->Move(start_index, target_index);
1669   // When cancelling a drag due to a shelf item being added, the currently
1670   // dragged item is moved back to its initial position. AnimateToIdealBounds
1671   // will be called again when the new item is added to the |view_model_| but
1672   // at this time the |view_model_| is inconsistent with the |model_|.
1673   if (!cancelling_drag_model_changed_)
1674     AnimateToIdealBounds();
1675 }
1676
1677 void ShelfView::ShelfStatusChanged() {
1678   if (ash::switches::UseAlternateShelfLayout())
1679     return;
1680   AppListButton* app_list_button =
1681       static_cast<AppListButton*>(GetAppListButtonView());
1682   if (model_->status() == ShelfModel::STATUS_LOADING)
1683     app_list_button->StartLoadingAnimation();
1684   else
1685     app_list_button->StopLoadingAnimation();
1686 }
1687
1688 void ShelfView::PointerPressedOnButton(views::View* view,
1689                                        Pointer pointer,
1690                                        const ui::LocatedEvent& event) {
1691   if (drag_view_)
1692     return;
1693
1694   int index = view_model_->GetIndexOfView(view);
1695   if (index == -1)
1696     return;
1697
1698   ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1699       model_->items()[index].id);
1700   if (view_model_->view_size() <= 1 || !item_delegate->IsDraggable())
1701     return;  // View is being deleted or not draggable, ignore request.
1702
1703   drag_view_ = view;
1704   drag_offset_ = layout_manager_->PrimaryAxisValue(event.x(), event.y());
1705   UMA_HISTOGRAM_ENUMERATION("Ash.ShelfAlignmentUsage",
1706       layout_manager_->SelectValueForShelfAlignment(
1707           SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM,
1708           SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT,
1709           SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT,
1710           -1),
1711       SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT);
1712 }
1713
1714 void ShelfView::PointerDraggedOnButton(views::View* view,
1715                                        Pointer pointer,
1716                                        const ui::LocatedEvent& event) {
1717   // To prepare all drag types (moving an item in the shelf and dragging off),
1718   // we should check the x-axis and y-axis offset.
1719   if (!dragging() && drag_view_ &&
1720       ((abs(event.x() - drag_offset_) >= kMinimumDragDistance) ||
1721        (abs(event.y() - drag_offset_) >= kMinimumDragDistance))) {
1722     PrepareForDrag(pointer, event);
1723   }
1724   if (drag_pointer_ == pointer)
1725     ContinueDrag(event);
1726 }
1727
1728 void ShelfView::PointerReleasedOnButton(views::View* view,
1729                                         Pointer pointer,
1730                                         bool canceled) {
1731   if (canceled) {
1732     CancelDrag(-1);
1733   } else if (drag_pointer_ == pointer) {
1734     FinalizeRipOffDrag(false);
1735     drag_pointer_ = NONE;
1736     AnimateToIdealBounds();
1737   }
1738   // If the drag pointer is NONE, no drag operation is going on and the
1739   // drag_view can be released.
1740   if (drag_pointer_ == NONE)
1741     drag_view_ = NULL;
1742 }
1743
1744 void ShelfView::MouseMovedOverButton(views::View* view) {
1745   if (!ShouldShowTooltipForView(view))
1746     return;
1747
1748   if (!tooltip_->IsVisible())
1749     tooltip_->ResetTimer();
1750 }
1751
1752 void ShelfView::MouseEnteredButton(views::View* view) {
1753   if (!ShouldShowTooltipForView(view))
1754     return;
1755
1756   if (tooltip_->IsVisible()) {
1757     tooltip_->ShowImmediately(view, GetAccessibleName(view));
1758   } else {
1759     tooltip_->ShowDelayed(view, GetAccessibleName(view));
1760   }
1761 }
1762
1763 void ShelfView::MouseExitedButton(views::View* view) {
1764   if (!tooltip_->IsVisible())
1765     tooltip_->StopTimer();
1766 }
1767
1768 base::string16 ShelfView::GetAccessibleName(const views::View* view) {
1769   int view_index = view_model_->GetIndexOfView(view);
1770   // May be -1 while in the process of animating closed.
1771   if (view_index == -1)
1772     return base::string16();
1773
1774   ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1775       model_->items()[view_index].id);
1776   return item_delegate->GetTitle();
1777 }
1778
1779 void ShelfView::ButtonPressed(views::Button* sender, const ui::Event& event) {
1780   // Do not handle mouse release during drag.
1781   if (dragging())
1782     return;
1783
1784   if (sender == overflow_button_) {
1785     ToggleOverflowBubble();
1786     return;
1787   }
1788
1789   int view_index = view_model_->GetIndexOfView(sender);
1790   // May be -1 while in the process of animating closed.
1791   if (view_index == -1)
1792     return;
1793
1794   // If the previous menu was closed by the same event as this one, we ignore
1795   // the call.
1796   if (!IsUsableEvent(event))
1797     return;
1798
1799   {
1800     ScopedTargetRootWindow scoped_target(
1801         sender->GetWidget()->GetNativeView()->GetRootWindow());
1802     // Slow down activation animations if shift key is pressed.
1803     scoped_ptr<ui::ScopedAnimationDurationScaleMode> slowing_animations;
1804     if (event.IsShiftDown()) {
1805       slowing_animations.reset(new ui::ScopedAnimationDurationScaleMode(
1806             ui::ScopedAnimationDurationScaleMode::SLOW_DURATION));
1807     }
1808
1809     // Collect usage statistics before we decide what to do with the click.
1810     switch (model_->items()[view_index].type) {
1811       case TYPE_APP_SHORTCUT:
1812       case TYPE_WINDOWED_APP:
1813       case TYPE_PLATFORM_APP:
1814       case TYPE_BROWSER_SHORTCUT:
1815         Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1816             UMA_LAUNCHER_CLICK_ON_APP);
1817         break;
1818
1819       case TYPE_APP_LIST:
1820         Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1821             UMA_LAUNCHER_CLICK_ON_APPLIST_BUTTON);
1822         break;
1823
1824       case TYPE_APP_PANEL:
1825       case TYPE_DIALOG:
1826         break;
1827
1828       case TYPE_UNDEFINED:
1829         NOTREACHED() << "ShelfItemType must be set.";
1830         break;
1831     }
1832
1833     ShelfItemDelegate* item_delegate =
1834         item_manager_->GetShelfItemDelegate(model_->items()[view_index].id);
1835     if (!item_delegate->ItemSelected(event))
1836       ShowListMenuForView(model_->items()[view_index], sender, event);
1837   }
1838 }
1839
1840 bool ShelfView::ShowListMenuForView(const ShelfItem& item,
1841                                     views::View* source,
1842                                     const ui::Event& event) {
1843   scoped_ptr<ShelfMenuModel> menu_model;
1844   ShelfItemDelegate* item_delegate =
1845       item_manager_->GetShelfItemDelegate(item.id);
1846   menu_model.reset(item_delegate->CreateApplicationMenu(event.flags()));
1847
1848   // Make sure we have a menu and it has at least two items in addition to the
1849   // application title and the 3 spacing separators.
1850   if (!menu_model.get() || menu_model->GetItemCount() <= 5)
1851     return false;
1852
1853   ShowMenu(scoped_ptr<views::MenuModelAdapter>(
1854                new ShelfMenuModelAdapter(menu_model.get())),
1855            source,
1856            gfx::Point(),
1857            false,
1858            ui::GetMenuSourceTypeForEvent(event));
1859   return true;
1860 }
1861
1862 void ShelfView::ShowContextMenuForView(views::View* source,
1863                                        const gfx::Point& point,
1864                                        ui::MenuSourceType source_type) {
1865   int view_index = view_model_->GetIndexOfView(source);
1866   if (view_index == -1) {
1867     Shell::GetInstance()->ShowContextMenu(point, source_type);
1868     return;
1869   }
1870
1871   scoped_ptr<ui::MenuModel> menu_model;
1872   ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1873       model_->items()[view_index].id);
1874   menu_model.reset(item_delegate->CreateContextMenu(
1875       source->GetWidget()->GetNativeView()->GetRootWindow()));
1876   if (!menu_model)
1877     return;
1878
1879   base::AutoReset<ShelfID> reseter(
1880       &context_menu_id_,
1881       view_index == -1 ? 0 : model_->items()[view_index].id);
1882
1883   ShowMenu(scoped_ptr<views::MenuModelAdapter>(
1884                new views::MenuModelAdapter(menu_model.get())),
1885            source,
1886            point,
1887            true,
1888            source_type);
1889 }
1890
1891 void ShelfView::ShowMenu(scoped_ptr<views::MenuModelAdapter> menu_model_adapter,
1892                          views::View* source,
1893                          const gfx::Point& click_point,
1894                          bool context_menu,
1895                          ui::MenuSourceType source_type) {
1896   closing_event_time_ = base::TimeDelta();
1897   launcher_menu_runner_.reset(
1898       new views::MenuRunner(menu_model_adapter->CreateMenu()));
1899
1900   ScopedTargetRootWindow scoped_target(
1901       source->GetWidget()->GetNativeView()->GetRootWindow());
1902
1903   // Determine the menu alignment dependent on the shelf.
1904   views::MenuItemView::AnchorPosition menu_alignment =
1905       views::MenuItemView::TOPLEFT;
1906   gfx::Rect anchor_point = gfx::Rect(click_point, gfx::Size());
1907
1908   ShelfWidget* shelf = RootWindowController::ForShelf(
1909       GetWidget()->GetNativeView())->shelf();
1910   if (!context_menu) {
1911     // Application lists use a bubble.
1912     ShelfAlignment align = shelf->GetAlignment();
1913     anchor_point = source->GetBoundsInScreen();
1914
1915     // It is possible to invoke the menu while it is sliding into view. To cover
1916     // that case, the screen coordinates are offsetted by the animation delta.
1917     gfx::Vector2d offset =
1918         source->GetWidget()->GetNativeWindow()->bounds().origin() -
1919         source->GetWidget()->GetNativeWindow()->GetTargetBounds().origin();
1920     anchor_point.set_x(anchor_point.x() - offset.x());
1921     anchor_point.set_y(anchor_point.y() - offset.y());
1922
1923     // Shelf items can have an asymmetrical border for spacing reasons.
1924     // Adjust anchor location for this.
1925     if (source->border())
1926       anchor_point.Inset(source->border()->GetInsets());
1927
1928     switch (align) {
1929       case SHELF_ALIGNMENT_BOTTOM:
1930         menu_alignment = views::MenuItemView::BUBBLE_ABOVE;
1931         break;
1932       case SHELF_ALIGNMENT_LEFT:
1933         menu_alignment = views::MenuItemView::BUBBLE_RIGHT;
1934         break;
1935       case SHELF_ALIGNMENT_RIGHT:
1936         menu_alignment = views::MenuItemView::BUBBLE_LEFT;
1937         break;
1938       case SHELF_ALIGNMENT_TOP:
1939         menu_alignment = views::MenuItemView::BUBBLE_BELOW;
1940         break;
1941     }
1942   }
1943   // If this gets deleted while we are in the menu, the shelf will be gone
1944   // as well.
1945   bool got_deleted = false;
1946   got_deleted_ = &got_deleted;
1947
1948   shelf->ForceUndimming(true);
1949   // NOTE: if you convert to HAS_MNEMONICS be sure and update menu building
1950   // code.
1951   if (launcher_menu_runner_->RunMenuAt(
1952           source->GetWidget(),
1953           NULL,
1954           anchor_point,
1955           menu_alignment,
1956           source_type,
1957           context_menu ? views::MenuRunner::CONTEXT_MENU : 0) ==
1958       views::MenuRunner::MENU_DELETED) {
1959     if (!got_deleted) {
1960       got_deleted_ = NULL;
1961       shelf->ForceUndimming(false);
1962     }
1963     return;
1964   }
1965   got_deleted_ = NULL;
1966   shelf->ForceUndimming(false);
1967
1968   // If it is a context menu and we are showing overflow bubble
1969   // we want to hide overflow bubble.
1970   if (owner_overflow_bubble_)
1971     owner_overflow_bubble_->HideBubbleAndRefreshButton();
1972
1973   // Unpinning an item will reset the |launcher_menu_runner_| before coming
1974   // here.
1975   if (launcher_menu_runner_)
1976     closing_event_time_ = launcher_menu_runner_->closing_event_time();
1977   Shell::GetInstance()->UpdateShelfVisibility();
1978 }
1979
1980 void ShelfView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) {
1981   FOR_EACH_OBSERVER(ShelfIconObserver, observers_,
1982                     OnShelfIconPositionsChanged());
1983   PreferredSizeChanged();
1984 }
1985
1986 void ShelfView::OnBoundsAnimatorDone(views::BoundsAnimator* animator) {
1987   if (snap_back_from_rip_off_view_ && animator == bounds_animator_) {
1988     if (!animator->IsAnimating(snap_back_from_rip_off_view_)) {
1989       // Coming here the animation of the ShelfButton is finished and the
1990       // previously hidden status can be shown again. Since the button itself
1991       // might have gone away or changed locations we check that the button
1992       // is still in the shelf and show its status again.
1993       for (int index = 0; index < view_model_->view_size(); index++) {
1994         views::View* view = view_model_->view_at(index);
1995         if (view == snap_back_from_rip_off_view_) {
1996           ShelfButton* button = static_cast<ShelfButton*>(view);
1997           button->ClearState(ShelfButton::STATE_HIDDEN);
1998           break;
1999         }
2000       }
2001       snap_back_from_rip_off_view_ = NULL;
2002     }
2003   }
2004 }
2005
2006 bool ShelfView::IsUsableEvent(const ui::Event& event) {
2007   if (closing_event_time_ == base::TimeDelta())
2008     return true;
2009
2010   base::TimeDelta delta =
2011       base::TimeDelta(event.time_stamp() - closing_event_time_);
2012   closing_event_time_ = base::TimeDelta();
2013   // TODO(skuhne): This time seems excessive, but it appears that the reposting
2014   // takes that long.  Need to come up with a better way of doing this.
2015   return (delta.InMilliseconds() < 0 || delta.InMilliseconds() > 130);
2016 }
2017
2018 const ShelfItem* ShelfView::ShelfItemForView(const views::View* view) const {
2019   int view_index = view_model_->GetIndexOfView(view);
2020   if (view_index == -1)
2021     return NULL;
2022   return &(model_->items()[view_index]);
2023 }
2024
2025 bool ShelfView::ShouldShowTooltipForView(const views::View* view) const {
2026   if (view == GetAppListButtonView() &&
2027       Shell::GetInstance()->GetAppListWindow())
2028     return false;
2029   const ShelfItem* item = ShelfItemForView(view);
2030   if (!item)
2031     return true;
2032   ShelfItemDelegate* item_delegate =
2033       item_manager_->GetShelfItemDelegate(item->id);
2034   return item_delegate->ShouldShowTooltip();
2035 }
2036
2037 int ShelfView::CalculateShelfDistance(const gfx::Point& coordinate) const {
2038   ShelfWidget* shelf = RootWindowController::ForShelf(
2039       GetWidget()->GetNativeView())->shelf();
2040   ShelfAlignment align = shelf->GetAlignment();
2041   const gfx::Rect bounds = GetBoundsInScreen();
2042   int distance = 0;
2043   switch (align) {
2044     case SHELF_ALIGNMENT_BOTTOM:
2045       distance = bounds.y() - coordinate.y();
2046       break;
2047     case SHELF_ALIGNMENT_LEFT:
2048       distance = coordinate.x() - bounds.right();
2049       break;
2050     case SHELF_ALIGNMENT_RIGHT:
2051       distance = bounds.x() - coordinate.x();
2052       break;
2053     case SHELF_ALIGNMENT_TOP:
2054       distance = coordinate.y() - bounds.bottom();
2055       break;
2056   }
2057   return distance > 0 ? distance : 0;
2058 }
2059
2060 }  // namespace internal
2061 }  // namespace ash