Roll src/third_party/WebKit f36d5e0:68b67cd (svn 193299:193303)
[chromium-blink-merge.git] / ash / shelf / shelf_view.cc
blobb4a3b72c3d1f43c28c4f53c84125c4ef8369824d
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ash/shelf/shelf_view.h"
7 #include <algorithm>
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/app_list_button.h"
16 #include "ash/shelf/overflow_bubble.h"
17 #include "ash/shelf/overflow_bubble_view.h"
18 #include "ash/shelf/overflow_button.h"
19 #include "ash/shelf/shelf_button.h"
20 #include "ash/shelf/shelf_constants.h"
21 #include "ash/shelf/shelf_delegate.h"
22 #include "ash/shelf/shelf_icon_observer.h"
23 #include "ash/shelf/shelf_item_delegate.h"
24 #include "ash/shelf/shelf_item_delegate_manager.h"
25 #include "ash/shelf/shelf_layout_manager.h"
26 #include "ash/shelf/shelf_menu_model.h"
27 #include "ash/shelf/shelf_model.h"
28 #include "ash/shelf/shelf_tooltip_manager.h"
29 #include "ash/shelf/shelf_widget.h"
30 #include "ash/shell.h"
31 #include "ash/wm/coordinate_conversion.h"
32 #include "base/auto_reset.h"
33 #include "base/memory/scoped_ptr.h"
34 #include "base/metrics/histogram.h"
35 #include "grit/ash_strings.h"
36 #include "ui/accessibility/ax_view_state.h"
37 #include "ui/aura/client/screen_position_client.h"
38 #include "ui/aura/window.h"
39 #include "ui/aura/window_event_dispatcher.h"
40 #include "ui/base/l10n/l10n_util.h"
41 #include "ui/base/models/simple_menu_model.h"
42 #include "ui/base/resource/resource_bundle.h"
43 #include "ui/compositor/layer.h"
44 #include "ui/compositor/layer_animator.h"
45 #include "ui/compositor/scoped_animation_duration_scale_mode.h"
46 #include "ui/events/event_utils.h"
47 #include "ui/gfx/canvas.h"
48 #include "ui/gfx/geometry/point.h"
49 #include "ui/views/animation/bounds_animator.h"
50 #include "ui/views/border.h"
51 #include "ui/views/controls/button/image_button.h"
52 #include "ui/views/controls/menu/menu_model_adapter.h"
53 #include "ui/views/controls/menu/menu_runner.h"
54 #include "ui/views/focus/focus_search.h"
55 #include "ui/views/view_model.h"
56 #include "ui/views/view_model_utils.h"
57 #include "ui/views/widget/widget.h"
58 #include "ui/wm/core/coordinate_conversion.h"
60 using gfx::Animation;
61 using views::View;
63 namespace ash {
65 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM = 0;
66 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT = 1;
67 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT = 2;
68 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT = 3;
70 // Default amount content is inset on the left edge.
71 const int kDefaultLeadingInset = 8;
73 // Minimum distance before drag starts.
74 const int kMinimumDragDistance = 8;
76 // Additional spacing for the left and right side of icons.
77 const int kHorizontalIconSpacing = 2;
79 // Inset for items which do not have an icon.
80 const int kHorizontalNoIconInsetSpacing =
81 kHorizontalIconSpacing + kDefaultLeadingInset;
83 // The proportion of the shelf space reserved for non-panel icons. Panels
84 // may flow into this space but will be put into the overflow bubble if there
85 // is contention for the space.
86 const float kReservedNonPanelIconProportion = 0.67f;
88 // This is the command id of the menu item which contains the name of the menu.
89 const int kCommandIdOfMenuName = 0;
91 // The background color of the active item in the list.
92 const SkColor kActiveListItemBackgroundColor = SkColorSetRGB(203 , 219, 241);
94 // The background color of the active & hovered item in the list.
95 const SkColor kFocusedActiveListItemBackgroundColor =
96 SkColorSetRGB(193, 211, 236);
98 // The text color of the caption item in a list.
99 const SkColor kCaptionItemForegroundColor = SK_ColorBLACK;
101 // The maximum allowable length of a menu line of an application menu in pixels.
102 const int kMaximumAppMenuItemLength = 350;
104 // The distance of the cursor from the outer rim of the shelf before it
105 // separates.
106 const int kRipOffDistance = 48;
108 // The rip off drag and drop proxy image should get scaled by this factor.
109 const float kDragAndDropProxyScale = 1.5f;
111 // The opacity represents that this partially disappeared item will get removed.
112 const float kDraggedImageOpacity = 0.5f;
114 namespace {
116 // A class to temporarily disable a given bounds animator.
117 class BoundsAnimatorDisabler {
118 public:
119 explicit BoundsAnimatorDisabler(views::BoundsAnimator* bounds_animator)
120 : old_duration_(bounds_animator->GetAnimationDuration()),
121 bounds_animator_(bounds_animator) {
122 bounds_animator_->SetAnimationDuration(1);
125 ~BoundsAnimatorDisabler() {
126 bounds_animator_->SetAnimationDuration(old_duration_);
129 private:
130 // The previous animation duration.
131 int old_duration_;
132 // The bounds animator which gets used.
133 views::BoundsAnimator* bounds_animator_;
135 DISALLOW_COPY_AND_ASSIGN(BoundsAnimatorDisabler);
138 // The MenuModelAdapter gets slightly changed to adapt the menu appearance to
139 // our requirements.
140 class ShelfMenuModelAdapter : public views::MenuModelAdapter {
141 public:
142 explicit ShelfMenuModelAdapter(ShelfMenuModel* menu_model);
144 // views::MenuModelAdapter:
145 const gfx::FontList* GetLabelFontList(int command_id) const override;
146 bool IsCommandEnabled(int id) const override;
147 void GetHorizontalIconMargins(int id,
148 int icon_size,
149 int* left_margin,
150 int* right_margin) const override;
151 bool GetForegroundColor(int command_id,
152 bool is_hovered,
153 SkColor* override_color) const override;
154 bool GetBackgroundColor(int command_id,
155 bool is_hovered,
156 SkColor* override_color) const override;
157 int GetMaxWidthForMenu(views::MenuItemView* menu) override;
158 bool ShouldReserveSpaceForSubmenuIndicator() const override;
160 private:
161 ShelfMenuModel* menu_model_;
163 DISALLOW_COPY_AND_ASSIGN(ShelfMenuModelAdapter);
166 ShelfMenuModelAdapter::ShelfMenuModelAdapter(ShelfMenuModel* menu_model)
167 : MenuModelAdapter(menu_model),
168 menu_model_(menu_model) {
171 const gfx::FontList* ShelfMenuModelAdapter::GetLabelFontList(
172 int command_id) const {
173 if (command_id != kCommandIdOfMenuName)
174 return MenuModelAdapter::GetLabelFontList(command_id);
176 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
177 return &rb.GetFontList(ui::ResourceBundle::BoldFont);
180 bool ShelfMenuModelAdapter::IsCommandEnabled(int id) const {
181 return id != kCommandIdOfMenuName;
184 bool ShelfMenuModelAdapter::GetForegroundColor(int command_id,
185 bool is_hovered,
186 SkColor* override_color) const {
187 if (command_id != kCommandIdOfMenuName)
188 return false;
190 *override_color = kCaptionItemForegroundColor;
191 return true;
194 bool ShelfMenuModelAdapter::GetBackgroundColor(int command_id,
195 bool is_hovered,
196 SkColor* override_color) const {
197 if (!menu_model_->IsCommandActive(command_id))
198 return false;
200 *override_color = is_hovered ? kFocusedActiveListItemBackgroundColor :
201 kActiveListItemBackgroundColor;
202 return true;
205 void ShelfMenuModelAdapter::GetHorizontalIconMargins(int command_id,
206 int icon_size,
207 int* left_margin,
208 int* right_margin) const {
209 *left_margin = kHorizontalIconSpacing;
210 *right_margin = (command_id != kCommandIdOfMenuName) ?
211 kHorizontalIconSpacing : -(icon_size + kHorizontalNoIconInsetSpacing);
214 int ShelfMenuModelAdapter::GetMaxWidthForMenu(views::MenuItemView* menu) {
215 return kMaximumAppMenuItemLength;
218 bool ShelfMenuModelAdapter::ShouldReserveSpaceForSubmenuIndicator() const {
219 return false;
222 // Custom FocusSearch used to navigate the shelf in the order items are in
223 // the ViewModel.
224 class ShelfFocusSearch : public views::FocusSearch {
225 public:
226 explicit ShelfFocusSearch(views::ViewModel* view_model)
227 : FocusSearch(NULL, true, true),
228 view_model_(view_model) {}
229 ~ShelfFocusSearch() override {}
231 // views::FocusSearch overrides:
232 View* FindNextFocusableView(View* starting_view,
233 bool reverse,
234 Direction direction,
235 bool check_starting_view,
236 views::FocusTraversable** focus_traversable,
237 View** focus_traversable_view) override {
238 int index = view_model_->GetIndexOfView(starting_view);
239 if (index == -1)
240 return view_model_->view_at(0);
242 if (reverse) {
243 --index;
244 if (index < 0)
245 index = view_model_->view_size() - 1;
246 } else {
247 ++index;
248 if (index >= view_model_->view_size())
249 index = 0;
251 return view_model_->view_at(index);
254 private:
255 views::ViewModel* view_model_;
257 DISALLOW_COPY_AND_ASSIGN(ShelfFocusSearch);
260 // AnimationDelegate used when inserting a new item. This steadily increases the
261 // opacity of the layer as the animation progress.
262 class FadeInAnimationDelegate : public gfx::AnimationDelegate {
263 public:
264 explicit FadeInAnimationDelegate(views::View* view) : view_(view) {}
265 ~FadeInAnimationDelegate() override {}
267 // AnimationDelegate overrides:
268 void AnimationProgressed(const Animation* animation) override {
269 view_->layer()->SetOpacity(animation->GetCurrentValue());
270 view_->layer()->ScheduleDraw();
272 void AnimationEnded(const Animation* animation) override {
273 view_->layer()->SetOpacity(1.0f);
274 view_->layer()->ScheduleDraw();
276 void AnimationCanceled(const Animation* animation) override {
277 view_->layer()->SetOpacity(1.0f);
278 view_->layer()->ScheduleDraw();
281 private:
282 views::View* view_;
284 DISALLOW_COPY_AND_ASSIGN(FadeInAnimationDelegate);
287 void ReflectItemStatus(const ShelfItem& item, ShelfButton* button) {
288 switch (item.status) {
289 case STATUS_CLOSED:
290 button->ClearState(ShelfButton::STATE_ACTIVE);
291 button->ClearState(ShelfButton::STATE_RUNNING);
292 button->ClearState(ShelfButton::STATE_ATTENTION);
293 break;
294 case STATUS_RUNNING:
295 button->ClearState(ShelfButton::STATE_ACTIVE);
296 button->AddState(ShelfButton::STATE_RUNNING);
297 button->ClearState(ShelfButton::STATE_ATTENTION);
298 break;
299 case STATUS_ACTIVE:
300 button->AddState(ShelfButton::STATE_ACTIVE);
301 button->ClearState(ShelfButton::STATE_RUNNING);
302 button->ClearState(ShelfButton::STATE_ATTENTION);
303 break;
304 case STATUS_ATTENTION:
305 button->ClearState(ShelfButton::STATE_ACTIVE);
306 button->ClearState(ShelfButton::STATE_RUNNING);
307 button->AddState(ShelfButton::STATE_ATTENTION);
308 break;
312 void RecordIconActivatedAction(const ui::Event& event) {
313 if (event.IsMouseEvent()) {
314 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
315 UMA_LAUNCHER_BUTTON_PRESSED_WITH_MOUSE);
316 } else if (event.IsGestureEvent()) {
317 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
318 UMA_LAUNCHER_BUTTON_PRESSED_WITH_TOUCH);
322 } // namespace
324 // AnimationDelegate used when deleting an item. This steadily decreased the
325 // opacity of the layer as the animation progress.
326 class ShelfView::FadeOutAnimationDelegate : public gfx::AnimationDelegate {
327 public:
328 FadeOutAnimationDelegate(ShelfView* host, views::View* view)
329 : shelf_view_(host),
330 view_(view) {}
331 ~FadeOutAnimationDelegate() override {}
333 // AnimationDelegate overrides:
334 void AnimationProgressed(const Animation* animation) override {
335 view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
336 view_->layer()->ScheduleDraw();
338 void AnimationEnded(const Animation* animation) override {
339 shelf_view_->OnFadeOutAnimationEnded();
341 void AnimationCanceled(const Animation* animation) override {}
343 private:
344 ShelfView* shelf_view_;
345 scoped_ptr<views::View> view_;
347 DISALLOW_COPY_AND_ASSIGN(FadeOutAnimationDelegate);
350 // AnimationDelegate used to trigger fading an element in. When an item is
351 // inserted this delegate is attached to the animation that expands the size of
352 // the item. When done it kicks off another animation to fade the item in.
353 class ShelfView::StartFadeAnimationDelegate : public gfx::AnimationDelegate {
354 public:
355 StartFadeAnimationDelegate(ShelfView* host,
356 views::View* view)
357 : shelf_view_(host),
358 view_(view) {}
359 ~StartFadeAnimationDelegate() override {}
361 // AnimationDelegate overrides:
362 void AnimationEnded(const Animation* animation) override {
363 shelf_view_->FadeIn(view_);
365 void AnimationCanceled(const Animation* animation) override {
366 view_->layer()->SetOpacity(1.0f);
369 private:
370 ShelfView* shelf_view_;
371 views::View* view_;
373 DISALLOW_COPY_AND_ASSIGN(StartFadeAnimationDelegate);
376 ShelfView::ShelfView(ShelfModel* model,
377 ShelfDelegate* delegate,
378 ShelfLayoutManager* manager)
379 : model_(model),
380 delegate_(delegate),
381 view_model_(new views::ViewModel),
382 first_visible_index_(0),
383 last_visible_index_(-1),
384 overflow_button_(NULL),
385 owner_overflow_bubble_(NULL),
386 drag_pointer_(NONE),
387 drag_view_(NULL),
388 start_drag_index_(-1),
389 context_menu_id_(0),
390 leading_inset_(kDefaultLeadingInset),
391 cancelling_drag_model_changed_(false),
392 last_hidden_index_(0),
393 closing_event_time_(base::TimeDelta()),
394 got_deleted_(NULL),
395 drag_and_drop_item_pinned_(false),
396 drag_and_drop_shelf_id_(0),
397 dragged_off_shelf_(false),
398 snap_back_from_rip_off_view_(NULL),
399 item_manager_(Shell::GetInstance()->shelf_item_delegate_manager()),
400 layout_manager_(manager),
401 overflow_mode_(false),
402 main_shelf_(NULL),
403 dragged_off_from_overflow_to_shelf_(false),
404 is_repost_event_(false),
405 last_pressed_index_(-1) {
406 DCHECK(model_);
407 bounds_animator_.reset(new views::BoundsAnimator(this));
408 bounds_animator_->AddObserver(this);
409 set_context_menu_controller(this);
410 focus_search_.reset(new ShelfFocusSearch(view_model_.get()));
411 tooltip_.reset(new ShelfTooltipManager(manager, this));
414 ShelfView::~ShelfView() {
415 bounds_animator_->RemoveObserver(this);
416 model_->RemoveObserver(this);
417 // If we are inside the MenuRunner, we need to know if we were getting
418 // deleted while it was running.
419 if (got_deleted_)
420 *got_deleted_ = true;
423 void ShelfView::Init() {
424 model_->AddObserver(this);
426 const ShelfItems& items(model_->items());
427 for (ShelfItems::const_iterator i = items.begin(); i != items.end(); ++i) {
428 views::View* child = CreateViewForItem(*i);
429 child->SetPaintToLayer(true);
430 view_model_->Add(child, static_cast<int>(i - items.begin()));
431 AddChildView(child);
433 overflow_button_ = new OverflowButton(this);
434 overflow_button_->set_context_menu_controller(this);
435 ConfigureChildView(overflow_button_);
436 AddChildView(overflow_button_);
438 // We'll layout when our bounds change.
441 void ShelfView::OnShelfAlignmentChanged() {
442 overflow_button_->OnShelfAlignmentChanged();
443 LayoutToIdealBounds();
444 for (int i = 0; i < view_model_->view_size(); ++i) {
445 if (i >= first_visible_index_ && i <= last_visible_index_)
446 view_model_->view_at(i)->Layout();
448 tooltip_->Close();
449 if (overflow_bubble_)
450 overflow_bubble_->Hide();
453 void ShelfView::SchedulePaintForAllButtons() {
454 for (int i = 0; i < view_model_->view_size(); ++i) {
455 if (i >= first_visible_index_ && i <= last_visible_index_)
456 view_model_->view_at(i)->SchedulePaint();
458 if (overflow_button_ && overflow_button_->visible())
459 overflow_button_->SchedulePaint();
462 gfx::Rect ShelfView::GetIdealBoundsOfItemIcon(ShelfID id) {
463 int index = model_->ItemIndexByID(id);
464 if (index == -1)
465 return gfx::Rect();
466 // Map all items from overflow area to the overflow button. Note that the
467 // section between last_index_hidden_ and model_->FirstPanelIndex() is the
468 // list of invisible panel items. However, these items are currently nowhere
469 // represented and get dropped instead - see (crbug.com/378907). As such there
470 // is no way to address them or place them. We therefore move them over the
471 // overflow button.
472 if (index > last_visible_index_ && index < model_->FirstPanelIndex())
473 index = last_visible_index_ + 1;
474 const gfx::Rect& ideal_bounds(view_model_->ideal_bounds(index));
475 DCHECK_NE(TYPE_APP_LIST, model_->items()[index].type);
476 views::View* view = view_model_->view_at(index);
477 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
478 ShelfButton* button = static_cast<ShelfButton*>(view);
479 gfx::Rect icon_bounds = button->GetIconBounds();
480 return gfx::Rect(GetMirroredXWithWidthInView(
481 ideal_bounds.x() + icon_bounds.x(), icon_bounds.width()),
482 ideal_bounds.y() + icon_bounds.y(),
483 icon_bounds.width(),
484 icon_bounds.height());
487 void ShelfView::UpdatePanelIconPosition(ShelfID id,
488 const gfx::Point& midpoint) {
489 int current_index = model_->ItemIndexByID(id);
490 int first_panel_index = model_->FirstPanelIndex();
491 if (current_index < first_panel_index)
492 return;
494 gfx::Point midpoint_in_view(GetMirroredXInView(midpoint.x()),
495 midpoint.y());
496 int target_index = current_index;
497 while (target_index > first_panel_index &&
498 layout_manager_->PrimaryAxisValue(
499 view_model_->ideal_bounds(target_index).x(),
500 view_model_->ideal_bounds(target_index).y()) >
501 layout_manager_->PrimaryAxisValue(midpoint_in_view.x(),
502 midpoint_in_view.y())) {
503 --target_index;
505 while (target_index < view_model_->view_size() - 1 &&
506 layout_manager_->PrimaryAxisValue(
507 view_model_->ideal_bounds(target_index).right(),
508 view_model_->ideal_bounds(target_index).bottom()) <
509 layout_manager_->PrimaryAxisValue(midpoint_in_view.x(),
510 midpoint_in_view.y())) {
511 ++target_index;
513 if (current_index != target_index)
514 model_->Move(current_index, target_index);
517 bool ShelfView::IsShowingMenu() const {
518 return (launcher_menu_runner_.get() &&
519 launcher_menu_runner_->IsRunning());
522 bool ShelfView::IsShowingOverflowBubble() const {
523 return overflow_bubble_.get() && overflow_bubble_->IsShowing();
526 views::View* ShelfView::GetAppListButtonView() const {
527 for (int i = 0; i < model_->item_count(); ++i) {
528 if (model_->items()[i].type == TYPE_APP_LIST)
529 return view_model_->view_at(i);
532 NOTREACHED() << "Applist button not found";
533 return NULL;
536 ////////////////////////////////////////////////////////////////////////////////
537 // ShelfView, FocusTraversable implementation:
539 views::FocusSearch* ShelfView::GetFocusSearch() {
540 return focus_search_.get();
543 views::FocusTraversable* ShelfView::GetFocusTraversableParent() {
544 return parent()->GetFocusTraversable();
547 View* ShelfView::GetFocusTraversableParentView() {
548 return this;
551 void ShelfView::CreateDragIconProxy(
552 const gfx::Point& location_in_screen_coordinates,
553 const gfx::ImageSkia& icon,
554 views::View* replaced_view,
555 const gfx::Vector2d& cursor_offset_from_center,
556 float scale_factor) {
557 drag_replaced_view_ = replaced_view;
558 drag_image_.reset(new ash::DragImageView(
559 drag_replaced_view_->GetWidget()->GetNativeWindow()->GetRootWindow(),
560 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE));
561 drag_image_->SetImage(icon);
562 gfx::Size size = drag_image_->GetPreferredSize();
563 size.set_width(size.width() * scale_factor);
564 size.set_height(size.height() * scale_factor);
565 drag_image_offset_ = gfx::Vector2d(size.width() / 2, size.height() / 2) +
566 cursor_offset_from_center;
567 gfx::Rect drag_image_bounds(
568 location_in_screen_coordinates - drag_image_offset_,
569 size);
570 drag_image_->SetBoundsInScreen(drag_image_bounds);
571 drag_image_->SetWidgetVisible(true);
574 void ShelfView::UpdateDragIconProxy(
575 const gfx::Point& location_in_screen_coordinates) {
576 // TODO(jennyz): Investigate why drag_image_ becomes NULL at this point per
577 // crbug.com/34722, while the app list item is still being dragged around.
578 if (drag_image_) {
579 drag_image_->SetScreenPosition(
580 location_in_screen_coordinates - drag_image_offset_);
584 void ShelfView::DestroyDragIconProxy() {
585 drag_image_.reset();
586 drag_image_offset_ = gfx::Vector2d(0, 0);
589 bool ShelfView::StartDrag(const std::string& app_id,
590 const gfx::Point& location_in_screen_coordinates) {
591 // Bail if an operation is already going on - or the cursor is not inside.
592 // This could happen if mouse / touch operations overlap.
593 if (drag_and_drop_shelf_id_ ||
594 !GetBoundsInScreen().Contains(location_in_screen_coordinates))
595 return false;
597 // If the AppsGridView (which was dispatching this event) was opened by our
598 // button, ShelfView dragging operations are locked and we have to unlock.
599 CancelDrag(-1);
600 drag_and_drop_item_pinned_ = false;
601 drag_and_drop_app_id_ = app_id;
602 drag_and_drop_shelf_id_ =
603 delegate_->GetShelfIDForAppID(drag_and_drop_app_id_);
604 // Check if the application is known and pinned - if not, we have to pin it so
605 // that we can re-arrange the shelf order accordingly. Note that items have
606 // to be pinned to give them the same (order) possibilities as a shortcut.
607 // When an item is dragged from overflow to shelf, IsShowingOverflowBubble()
608 // returns true. At this time, we don't need to pin the item.
609 if (!IsShowingOverflowBubble() &&
610 (!drag_and_drop_shelf_id_ ||
611 !delegate_->IsAppPinned(app_id))) {
612 delegate_->PinAppWithID(app_id);
613 drag_and_drop_shelf_id_ =
614 delegate_->GetShelfIDForAppID(drag_and_drop_app_id_);
615 if (!drag_and_drop_shelf_id_)
616 return false;
617 drag_and_drop_item_pinned_ = true;
619 views::View* drag_and_drop_view = view_model_->view_at(
620 model_->ItemIndexByID(drag_and_drop_shelf_id_));
621 DCHECK(drag_and_drop_view);
623 // Since there is already an icon presented by the caller, we hide this item
624 // for now. That has to be done by reducing the size since the visibility will
625 // change once a regrouping animation is performed.
626 pre_drag_and_drop_size_ = drag_and_drop_view->size();
627 drag_and_drop_view->SetSize(gfx::Size());
629 // First we have to center the mouse cursor over the item.
630 gfx::Point pt = drag_and_drop_view->GetBoundsInScreen().CenterPoint();
631 views::View::ConvertPointFromScreen(drag_and_drop_view, &pt);
632 gfx::Point point_in_root = location_in_screen_coordinates;
633 ::wm::ConvertPointFromScreen(
634 ash::wm::GetRootWindowAt(location_in_screen_coordinates), &point_in_root);
635 ui::MouseEvent event(ui::ET_MOUSE_PRESSED, pt, point_in_root,
636 ui::EventTimeForNow(), 0, 0);
637 PointerPressedOnButton(drag_and_drop_view,
638 ShelfButtonHost::DRAG_AND_DROP,
639 event);
641 // Drag the item where it really belongs.
642 Drag(location_in_screen_coordinates);
643 return true;
646 bool ShelfView::Drag(const gfx::Point& location_in_screen_coordinates) {
647 if (!drag_and_drop_shelf_id_ ||
648 !GetBoundsInScreen().Contains(location_in_screen_coordinates))
649 return false;
651 gfx::Point pt = location_in_screen_coordinates;
652 views::View* drag_and_drop_view = view_model_->view_at(
653 model_->ItemIndexByID(drag_and_drop_shelf_id_));
654 ConvertPointFromScreen(drag_and_drop_view, &pt);
655 gfx::Point point_in_root = location_in_screen_coordinates;
656 ::wm::ConvertPointFromScreen(
657 ash::wm::GetRootWindowAt(location_in_screen_coordinates), &point_in_root);
658 ui::MouseEvent event(ui::ET_MOUSE_DRAGGED, pt, point_in_root,
659 ui::EventTimeForNow(), 0, 0);
660 PointerDraggedOnButton(drag_and_drop_view,
661 ShelfButtonHost::DRAG_AND_DROP,
662 event);
663 return true;
666 void ShelfView::EndDrag(bool cancel) {
667 if (!drag_and_drop_shelf_id_)
668 return;
670 views::View* drag_and_drop_view = view_model_->view_at(
671 model_->ItemIndexByID(drag_and_drop_shelf_id_));
672 PointerReleasedOnButton(
673 drag_and_drop_view, ShelfButtonHost::DRAG_AND_DROP, cancel);
675 // Either destroy the temporarily created item - or - make the item visible.
676 if (drag_and_drop_item_pinned_ && cancel) {
677 delegate_->UnpinAppWithID(drag_and_drop_app_id_);
678 } else if (drag_and_drop_view) {
679 if (cancel) {
680 // When a hosted drag gets canceled, the item can remain in the same slot
681 // and it might have moved within the bounds. In that case the item need
682 // to animate back to its correct location.
683 AnimateToIdealBounds();
684 } else {
685 drag_and_drop_view->SetSize(pre_drag_and_drop_size_);
689 drag_and_drop_shelf_id_ = 0;
692 void ShelfView::LayoutToIdealBounds() {
693 if (bounds_animator_->IsAnimating()) {
694 AnimateToIdealBounds();
695 return;
698 IdealBounds ideal_bounds;
699 CalculateIdealBounds(&ideal_bounds);
700 views::ViewModelUtils::SetViewBoundsToIdealBounds(*view_model_);
701 overflow_button_->SetBoundsRect(ideal_bounds.overflow_bounds);
704 void ShelfView::UpdateAllButtonsVisibilityInOverflowMode() {
705 // The overflow button is not shown in overflow mode.
706 overflow_button_->SetVisible(false);
707 DCHECK_LT(last_visible_index_, view_model_->view_size());
708 for (int i = 0; i < view_model_->view_size(); ++i) {
709 bool visible = i >= first_visible_index_ &&
710 i <= last_visible_index_;
711 // To track the dragging of |drag_view_| continuously, its visibility
712 // should be always true regardless of its position.
713 if (dragged_off_from_overflow_to_shelf_ &&
714 view_model_->view_at(i) == drag_view_)
715 view_model_->view_at(i)->SetVisible(true);
716 else
717 view_model_->view_at(i)->SetVisible(visible);
721 void ShelfView::CalculateIdealBounds(IdealBounds* bounds) const {
722 int available_size = layout_manager_->PrimaryAxisValue(width(), height());
723 DCHECK(model_->item_count() == view_model_->view_size());
724 if (!available_size)
725 return;
727 int first_panel_index = model_->FirstPanelIndex();
728 int last_button_index = first_panel_index - 1;
730 int x = 0;
731 int y = 0;
732 int button_size = kShelfButtonSize;
733 int button_spacing = kShelfButtonSpacing;
735 int w = layout_manager_->PrimaryAxisValue(button_size, width());
736 int h = layout_manager_->PrimaryAxisValue(height(), button_size);
737 for (int i = 0; i < view_model_->view_size(); ++i) {
738 if (i < first_visible_index_) {
739 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, 0, 0));
740 continue;
743 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
744 x = layout_manager_->PrimaryAxisValue(x + w + button_spacing, x);
745 y = layout_manager_->PrimaryAxisValue(y, y + h + button_spacing);
748 if (is_overflow_mode()) {
749 const_cast<ShelfView*>(this)->UpdateAllButtonsVisibilityInOverflowMode();
750 return;
753 // Right aligned icons.
754 int end_position = available_size - button_spacing;
755 x = layout_manager_->PrimaryAxisValue(end_position, 0);
756 y = layout_manager_->PrimaryAxisValue(0, end_position);
757 for (int i = view_model_->view_size() - 1;
758 i >= first_panel_index; --i) {
759 x = layout_manager_->PrimaryAxisValue(x - w - button_spacing, x);
760 y = layout_manager_->PrimaryAxisValue(y, y - h - button_spacing);
761 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
762 end_position = layout_manager_->PrimaryAxisValue(x, y);
765 // Icons on the left / top are guaranteed up to kLeftIconProportion of
766 // the available space.
767 int last_icon_position = layout_manager_->PrimaryAxisValue(
768 view_model_->ideal_bounds(last_button_index).right(),
769 view_model_->ideal_bounds(last_button_index).bottom()) + button_size;
770 int reserved_icon_space = available_size * kReservedNonPanelIconProportion;
771 if (last_icon_position < reserved_icon_space)
772 end_position = last_icon_position;
773 else
774 end_position = std::max(end_position, reserved_icon_space);
776 bounds->overflow_bounds.set_size(
777 gfx::Size(layout_manager_->PrimaryAxisValue(w, width()),
778 layout_manager_->PrimaryAxisValue(height(), h)));
780 last_visible_index_ = DetermineLastVisibleIndex(
781 end_position - button_size);
782 last_hidden_index_ = DetermineFirstVisiblePanelIndex(end_position) - 1;
783 bool show_overflow = last_visible_index_ < last_button_index ||
784 last_hidden_index_ >= first_panel_index;
786 // Create Space for the overflow button
787 if (show_overflow) {
788 // The following code makes sure that platform apps icons (aligned to left /
789 // top) are favored over panel apps icons (aligned to right / bottom).
790 if (last_visible_index_ > 0 && last_visible_index_ < last_button_index) {
791 // This condition means that we will take one platform app and replace it
792 // with the overflow button and put the app in the overflow bubble.
793 // This happens when the space needed for platform apps exceeds the
794 // reserved area for non-panel icons,
795 // (i.e. |last_icon_position| > |reserved_icon_space|).
796 --last_visible_index_;
797 } else if (last_hidden_index_ >= first_panel_index &&
798 last_hidden_index_ < view_model_->view_size() - 1) {
799 // This condition means that we will take a panel app icon and replace it
800 // with the overflow button.
801 // This happens when there is still room for platform apps in the reserved
802 // area for non-panel icons,
803 // (i.e. |last_icon_position| < |reserved_icon_space|).
804 ++last_hidden_index_;
808 for (int i = 0; i < view_model_->view_size(); ++i) {
809 bool visible = i <= last_visible_index_ || i > last_hidden_index_;
810 // To receive drag event continuously from |drag_view_| during the dragging
811 // off from the shelf, don't make |drag_view_| invisible. It will be
812 // eventually invisible and removed from the |view_model_| by
813 // FinalizeRipOffDrag().
814 if (dragged_off_shelf_ && view_model_->view_at(i) == drag_view_)
815 continue;
816 view_model_->view_at(i)->SetVisible(visible);
819 overflow_button_->SetVisible(show_overflow);
820 if (show_overflow) {
821 DCHECK_NE(0, view_model_->view_size());
822 if (last_visible_index_ == -1) {
823 x = 0;
824 y = 0;
825 } else {
826 x = layout_manager_->PrimaryAxisValue(
827 view_model_->ideal_bounds(last_visible_index_).right(),
828 view_model_->ideal_bounds(last_visible_index_).x());
829 y = layout_manager_->PrimaryAxisValue(
830 view_model_->ideal_bounds(last_visible_index_).y(),
831 view_model_->ideal_bounds(last_visible_index_).bottom());
833 // Set all hidden panel icon positions to be on the overflow button.
834 for (int i = first_panel_index; i <= last_hidden_index_; ++i)
835 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
837 // Add more space between last visible item and overflow button.
838 // Without this, two buttons look too close compared with other items.
839 x = layout_manager_->PrimaryAxisValue(x + button_spacing, x);
840 y = layout_manager_->PrimaryAxisValue(y, y + button_spacing);
842 bounds->overflow_bounds.set_x(x);
843 bounds->overflow_bounds.set_y(y);
844 if (overflow_bubble_.get() && overflow_bubble_->IsShowing())
845 UpdateOverflowRange(overflow_bubble_->shelf_view());
846 } else {
847 if (overflow_bubble_)
848 overflow_bubble_->Hide();
852 int ShelfView::DetermineLastVisibleIndex(int max_value) const {
853 int index = model_->FirstPanelIndex() - 1;
854 while (index >= 0 &&
855 layout_manager_->PrimaryAxisValue(
856 view_model_->ideal_bounds(index).right(),
857 view_model_->ideal_bounds(index).bottom()) > max_value) {
858 index--;
860 return index;
863 int ShelfView::DetermineFirstVisiblePanelIndex(int min_value) const {
864 int index = model_->FirstPanelIndex();
865 while (index < view_model_->view_size() &&
866 layout_manager_->PrimaryAxisValue(
867 view_model_->ideal_bounds(index).right(),
868 view_model_->ideal_bounds(index).bottom()) < min_value) {
869 ++index;
871 return index;
874 void ShelfView::AddIconObserver(ShelfIconObserver* observer) {
875 observers_.AddObserver(observer);
878 void ShelfView::RemoveIconObserver(ShelfIconObserver* observer) {
879 observers_.RemoveObserver(observer);
882 void ShelfView::AnimateToIdealBounds() {
883 IdealBounds ideal_bounds;
884 CalculateIdealBounds(&ideal_bounds);
885 for (int i = 0; i < view_model_->view_size(); ++i) {
886 View* view = view_model_->view_at(i);
887 bounds_animator_->AnimateViewTo(view, view_model_->ideal_bounds(i));
888 // Now that the item animation starts, we have to make sure that the
889 // padding of the first gets properly transferred to the new first item.
890 if (i && view->border())
891 view->SetBorder(views::Border::NullBorder());
893 overflow_button_->SetBoundsRect(ideal_bounds.overflow_bounds);
896 views::View* ShelfView::CreateViewForItem(const ShelfItem& item) {
897 views::View* view = NULL;
898 switch (item.type) {
899 case TYPE_BROWSER_SHORTCUT:
900 case TYPE_APP_SHORTCUT:
901 case TYPE_WINDOWED_APP:
902 case TYPE_PLATFORM_APP:
903 case TYPE_DIALOG:
904 case TYPE_APP_PANEL: {
905 ShelfButton* button = ShelfButton::Create(this, this, layout_manager_);
906 button->SetImage(item.image);
907 ReflectItemStatus(item, button);
908 view = button;
909 break;
912 case TYPE_APP_LIST: {
913 view = new AppListButton(this, this, layout_manager_->shelf_widget());
914 break;
917 default:
918 break;
920 view->set_context_menu_controller(this);
922 DCHECK(view);
923 ConfigureChildView(view);
924 return view;
927 void ShelfView::FadeIn(views::View* view) {
928 view->SetVisible(true);
929 view->layer()->SetOpacity(0);
930 AnimateToIdealBounds();
931 bounds_animator_->SetAnimationDelegate(
932 view,
933 scoped_ptr<gfx::AnimationDelegate>(new FadeInAnimationDelegate(view)));
936 void ShelfView::PrepareForDrag(Pointer pointer, const ui::LocatedEvent& event) {
937 DCHECK(!dragging());
938 DCHECK(drag_view_);
939 drag_pointer_ = pointer;
940 start_drag_index_ = view_model_->GetIndexOfView(drag_view_);
942 if (start_drag_index_== -1) {
943 CancelDrag(-1);
944 return;
947 // If the item is no longer draggable, bail out.
948 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
949 model_->items()[start_drag_index_].id);
950 if (!item_delegate->IsDraggable()) {
951 CancelDrag(-1);
952 return;
955 // Move the view to the front so that it appears on top of other views.
956 ReorderChildView(drag_view_, -1);
957 bounds_animator_->StopAnimatingView(drag_view_);
960 void ShelfView::ContinueDrag(const ui::LocatedEvent& event) {
961 // Due to a syncing operation the application might have been removed.
962 // Bail if it is gone.
963 int current_index = view_model_->GetIndexOfView(drag_view_);
964 DCHECK_NE(-1, current_index);
966 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
967 model_->items()[current_index].id);
968 if (!item_delegate->IsDraggable()) {
969 CancelDrag(-1);
970 return;
973 // If this is not a drag and drop host operation and not the app list item,
974 // check if the item got ripped off the shelf - if it did we are done.
975 if (!drag_and_drop_shelf_id_ &&
976 RemovableByRipOff(current_index) != NOT_REMOVABLE) {
977 if (HandleRipOffDrag(event))
978 return;
979 // The rip off handler could have changed the location of the item.
980 current_index = view_model_->GetIndexOfView(drag_view_);
983 // TODO: I don't think this works correctly with RTL.
984 gfx::Point drag_point(event.location());
985 ConvertPointToTarget(drag_view_, this, &drag_point);
987 // Constrain the location to the range of valid indices for the type.
988 std::pair<int, int> indices(GetDragRange(current_index));
989 int first_drag_index = indices.first;
990 int last_drag_index = indices.second;
991 // If the last index isn't valid, we're overflowing. Constrain to the app list
992 // (which is the last visible item).
993 if (first_drag_index < model_->FirstPanelIndex() &&
994 last_drag_index > last_visible_index_)
995 last_drag_index = last_visible_index_;
996 int x = 0, y = 0;
997 if (layout_manager_->IsHorizontalAlignment()) {
998 x = std::max(view_model_->ideal_bounds(indices.first).x(),
999 drag_point.x() - drag_origin_.x());
1000 x = std::min(view_model_->ideal_bounds(last_drag_index).right() -
1001 view_model_->ideal_bounds(current_index).width(),
1003 if (drag_view_->x() == x)
1004 return;
1005 drag_view_->SetX(x);
1006 } else {
1007 y = std::max(view_model_->ideal_bounds(indices.first).y(),
1008 drag_point.y() - drag_origin_.y());
1009 y = std::min(view_model_->ideal_bounds(last_drag_index).bottom() -
1010 view_model_->ideal_bounds(current_index).height(),
1012 if (drag_view_->y() == y)
1013 return;
1014 drag_view_->SetY(y);
1017 int target_index =
1018 views::ViewModelUtils::DetermineMoveIndex(
1019 *view_model_, drag_view_,
1020 layout_manager_->IsHorizontalAlignment() ?
1021 views::ViewModelUtils::HORIZONTAL :
1022 views::ViewModelUtils::VERTICAL,
1023 x, y);
1024 target_index =
1025 std::min(indices.second, std::max(target_index, indices.first));
1026 if (target_index == current_index)
1027 return;
1029 // Change the model, the ShelfItemMoved() callback will handle the
1030 // |view_model_| update.
1031 model_->Move(current_index, target_index);
1032 bounds_animator_->StopAnimatingView(drag_view_);
1035 bool ShelfView::HandleRipOffDrag(const ui::LocatedEvent& event) {
1036 int current_index = view_model_->GetIndexOfView(drag_view_);
1037 DCHECK_NE(-1, current_index);
1038 std::string dragged_app_id =
1039 delegate_->GetAppIDForShelfID(model_->items()[current_index].id);
1041 gfx::Point screen_location = event.root_location();
1042 ::wm::ConvertPointToScreen(GetWidget()->GetNativeWindow()->GetRootWindow(),
1043 &screen_location);
1045 // To avoid ugly forwards and backwards flipping we use different constants
1046 // for ripping off / re-inserting the items.
1047 if (dragged_off_shelf_) {
1048 // If the shelf/overflow bubble bounds contains |screen_location| we insert
1049 // the item back into the shelf.
1050 if (GetBoundsForDragInsertInScreen().Contains(screen_location)) {
1051 if (dragged_off_from_overflow_to_shelf_) {
1052 // During the dragging an item from Shelf to Overflow, it can enter here
1053 // directly because both are located very closly.
1054 main_shelf_->EndDrag(true);
1055 // Stops the animation of |drag_view_| and sets its bounds explicitly
1056 // becase ContinueDrag() stops its animation. Without this, unexpected
1057 // bounds will be set.
1058 bounds_animator_->StopAnimatingView(drag_view_);
1059 int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1060 drag_view_->SetBoundsRect(view_model_->ideal_bounds(drag_view_index));
1061 dragged_off_from_overflow_to_shelf_ = false;
1063 // Destroy our proxy view item.
1064 DestroyDragIconProxy();
1065 // Re-insert the item and return simply false since the caller will handle
1066 // the move as in any normal case.
1067 dragged_off_shelf_ = false;
1068 drag_view_->layer()->SetOpacity(1.0f);
1069 // The size of Overflow bubble should be updated immediately when an item
1070 // is re-inserted.
1071 if (is_overflow_mode())
1072 PreferredSizeChanged();
1073 return false;
1074 } else if (is_overflow_mode() &&
1075 main_shelf_->GetBoundsForDragInsertInScreen().Contains(
1076 screen_location)) {
1077 if (!dragged_off_from_overflow_to_shelf_) {
1078 dragged_off_from_overflow_to_shelf_ = true;
1079 drag_image_->SetOpacity(1.0f);
1080 main_shelf_->StartDrag(dragged_app_id, screen_location);
1081 } else {
1082 main_shelf_->Drag(screen_location);
1084 } else if (dragged_off_from_overflow_to_shelf_) {
1085 // Makes the |drag_image_| partially disappear again.
1086 dragged_off_from_overflow_to_shelf_ = false;
1087 drag_image_->SetOpacity(kDraggedImageOpacity);
1088 main_shelf_->EndDrag(true);
1089 bounds_animator_->StopAnimatingView(drag_view_);
1090 int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1091 drag_view_->SetBoundsRect(view_model_->ideal_bounds(drag_view_index));
1093 // Move our proxy view item.
1094 UpdateDragIconProxy(screen_location);
1095 return true;
1097 // Check if we are too far away from the shelf to enter the ripped off state.
1098 // Determine the distance to the shelf.
1099 int delta = CalculateShelfDistance(screen_location);
1100 if (delta > kRipOffDistance) {
1101 // Create a proxy view item which can be moved anywhere.
1102 CreateDragIconProxy(event.root_location(),
1103 drag_view_->GetImage(),
1104 drag_view_,
1105 gfx::Vector2d(0, 0),
1106 kDragAndDropProxyScale);
1107 drag_view_->layer()->SetOpacity(0.0f);
1108 dragged_off_shelf_ = true;
1109 if (RemovableByRipOff(current_index) == REMOVABLE) {
1110 // Move the item to the front of the first panel item and hide it.
1111 // ShelfItemMoved() callback will handle the |view_model_| update and
1112 // call AnimateToIdealBounds().
1113 if (current_index != model_->FirstPanelIndex() - 1) {
1114 model_->Move(current_index, model_->FirstPanelIndex() - 1);
1115 StartFadeInLastVisibleItem();
1116 } else if (is_overflow_mode()) {
1117 // Overflow bubble should be shrunk when an item is ripped off.
1118 PreferredSizeChanged();
1120 // Make the item partially disappear to show that it will get removed if
1121 // dropped.
1122 drag_image_->SetOpacity(kDraggedImageOpacity);
1124 return true;
1126 return false;
1129 void ShelfView::FinalizeRipOffDrag(bool cancel) {
1130 if (!dragged_off_shelf_)
1131 return;
1132 // Make sure we do not come in here again.
1133 dragged_off_shelf_ = false;
1135 // Coming here we should always have a |drag_view_|.
1136 DCHECK(drag_view_);
1137 int current_index = view_model_->GetIndexOfView(drag_view_);
1138 // If the view isn't part of the model anymore (|current_index| == -1), a sync
1139 // operation must have removed it. In that case we shouldn't change the model
1140 // and only delete the proxy image.
1141 if (current_index == -1) {
1142 DestroyDragIconProxy();
1143 return;
1146 // Set to true when the animation should snap back to where it was before.
1147 bool snap_back = false;
1148 // Items which cannot be dragged off will be handled as a cancel.
1149 if (!cancel) {
1150 if (dragged_off_from_overflow_to_shelf_) {
1151 dragged_off_from_overflow_to_shelf_ = false;
1152 main_shelf_->EndDrag(false);
1153 drag_view_->layer()->SetOpacity(1.0f);
1154 } else if (RemovableByRipOff(current_index) != REMOVABLE) {
1155 // Make sure we do not try to remove un-removable items like items which
1156 // were not pinned or have to be always there.
1157 cancel = true;
1158 snap_back = true;
1159 } else {
1160 // Make sure the item stays invisible upon removal.
1161 drag_view_->SetVisible(false);
1162 std::string app_id =
1163 delegate_->GetAppIDForShelfID(model_->items()[current_index].id);
1164 delegate_->UnpinAppWithID(app_id);
1167 if (cancel || snap_back) {
1168 if (dragged_off_from_overflow_to_shelf_) {
1169 dragged_off_from_overflow_to_shelf_ = false;
1170 // Main shelf handles revert of dragged item.
1171 main_shelf_->EndDrag(true);
1172 drag_view_->layer()->SetOpacity(1.0f);
1173 } else if (!cancelling_drag_model_changed_) {
1174 // Only do something if the change did not come through a model change.
1175 gfx::Rect drag_bounds = drag_image_->GetBoundsInScreen();
1176 gfx::Point relative_to = GetBoundsInScreen().origin();
1177 gfx::Rect target(
1178 gfx::PointAtOffsetFromOrigin(drag_bounds.origin()- relative_to),
1179 drag_bounds.size());
1180 drag_view_->SetBoundsRect(target);
1181 // Hide the status from the active item since we snap it back now. Upon
1182 // animation end the flag gets cleared if |snap_back_from_rip_off_view_|
1183 // is set.
1184 snap_back_from_rip_off_view_ = drag_view_;
1185 drag_view_->AddState(ShelfButton::STATE_HIDDEN);
1186 // When a canceling drag model is happening, the view model is diverged
1187 // from the menu model and movements / animations should not be done.
1188 model_->Move(current_index, start_drag_index_);
1189 AnimateToIdealBounds();
1191 drag_view_->layer()->SetOpacity(1.0f);
1193 DestroyDragIconProxy();
1196 ShelfView::RemovableState ShelfView::RemovableByRipOff(int index) const {
1197 DCHECK(index >= 0 && index < model_->item_count());
1198 ShelfItemType type = model_->items()[index].type;
1199 if (type == TYPE_APP_LIST || type == TYPE_DIALOG || !delegate_->CanPin())
1200 return NOT_REMOVABLE;
1202 std::string app_id = delegate_->GetAppIDForShelfID(model_->items()[index].id);
1203 // Note: Only pinned app shortcuts can be removed!
1204 return (type == TYPE_APP_SHORTCUT && delegate_->IsAppPinned(app_id)) ?
1205 REMOVABLE : DRAGGABLE;
1208 bool ShelfView::SameDragType(ShelfItemType typea, ShelfItemType typeb) const {
1209 switch (typea) {
1210 case TYPE_APP_SHORTCUT:
1211 case TYPE_BROWSER_SHORTCUT:
1212 return (typeb == TYPE_APP_SHORTCUT || typeb == TYPE_BROWSER_SHORTCUT);
1213 case TYPE_APP_LIST:
1214 case TYPE_PLATFORM_APP:
1215 case TYPE_WINDOWED_APP:
1216 case TYPE_APP_PANEL:
1217 case TYPE_DIALOG:
1218 return typeb == typea;
1219 case TYPE_UNDEFINED:
1220 NOTREACHED() << "ShelfItemType must be set.";
1221 return false;
1223 NOTREACHED();
1224 return false;
1227 std::pair<int, int> ShelfView::GetDragRange(int index) {
1228 int min_index = -1;
1229 int max_index = -1;
1230 ShelfItemType type = model_->items()[index].type;
1231 for (int i = 0; i < model_->item_count(); ++i) {
1232 if (SameDragType(model_->items()[i].type, type)) {
1233 if (min_index == -1)
1234 min_index = i;
1235 max_index = i;
1238 return std::pair<int, int>(min_index, max_index);
1241 void ShelfView::ConfigureChildView(views::View* view) {
1242 view->SetPaintToLayer(true);
1243 view->layer()->SetFillsBoundsOpaquely(false);
1246 void ShelfView::ToggleOverflowBubble() {
1247 if (IsShowingOverflowBubble()) {
1248 overflow_bubble_->Hide();
1249 return;
1252 if (!overflow_bubble_)
1253 overflow_bubble_.reset(new OverflowBubble());
1255 ShelfView* overflow_view =
1256 new ShelfView(model_, delegate_, layout_manager_);
1257 overflow_view->overflow_mode_ = true;
1258 overflow_view->Init();
1259 overflow_view->set_owner_overflow_bubble(overflow_bubble_.get());
1260 overflow_view->OnShelfAlignmentChanged();
1261 overflow_view->main_shelf_ = this;
1262 UpdateOverflowRange(overflow_view);
1264 overflow_bubble_->Show(overflow_button_, overflow_view);
1266 Shell::GetInstance()->UpdateShelfVisibility();
1269 void ShelfView::OnFadeOutAnimationEnded() {
1270 AnimateToIdealBounds();
1271 StartFadeInLastVisibleItem();
1274 void ShelfView::StartFadeInLastVisibleItem() {
1275 // If overflow button is visible and there is a valid new last item, fading
1276 // the new last item in after sliding animation is finished.
1277 if (overflow_button_->visible() && last_visible_index_ >= 0) {
1278 views::View* last_visible_view = view_model_->view_at(last_visible_index_);
1279 last_visible_view->layer()->SetOpacity(0);
1280 bounds_animator_->SetAnimationDelegate(
1281 last_visible_view,
1282 scoped_ptr<gfx::AnimationDelegate>(
1283 new StartFadeAnimationDelegate(this, last_visible_view)));
1287 void ShelfView::UpdateOverflowRange(ShelfView* overflow_view) const {
1288 const int first_overflow_index = last_visible_index_ + 1;
1289 const int last_overflow_index = last_hidden_index_;
1290 DCHECK_LE(first_overflow_index, last_overflow_index);
1291 DCHECK_LT(last_overflow_index, view_model_->view_size());
1293 overflow_view->first_visible_index_ = first_overflow_index;
1294 overflow_view->last_visible_index_ = last_overflow_index;
1297 bool ShelfView::ShouldHideTooltip(const gfx::Point& cursor_location) {
1298 gfx::Rect active_bounds;
1300 for (int i = 0; i < child_count(); ++i) {
1301 views::View* child = child_at(i);
1302 if (child == overflow_button_)
1303 continue;
1304 if (!ShouldShowTooltipForView(child))
1305 continue;
1307 gfx::Rect child_bounds = child->GetMirroredBounds();
1308 active_bounds.Union(child_bounds);
1311 return !active_bounds.Contains(cursor_location);
1314 gfx::Rect ShelfView::GetVisibleItemsBoundsInScreen() {
1315 gfx::Size preferred_size = GetPreferredSize();
1316 gfx::Point origin(GetMirroredXWithWidthInView(0, preferred_size.width()), 0);
1317 ConvertPointToScreen(this, &origin);
1318 return gfx::Rect(origin, preferred_size);
1321 gfx::Rect ShelfView::GetBoundsForDragInsertInScreen() {
1322 gfx::Size preferred_size;
1323 if (is_overflow_mode()) {
1324 DCHECK(owner_overflow_bubble_);
1325 gfx::Rect bubble_bounds =
1326 owner_overflow_bubble_->bubble_view()->GetBubbleBounds();
1327 preferred_size = bubble_bounds.size();
1328 } else {
1329 const int last_button_index = view_model_->view_size() - 1;
1330 gfx::Rect last_button_bounds =
1331 view_model_->view_at(last_button_index)->bounds();
1332 if (overflow_button_->visible() &&
1333 model_->GetItemIndexForType(TYPE_APP_PANEL) == -1) {
1334 // When overflow button is visible and shelf has no panel items,
1335 // last_button_bounds should be overflow button's bounds.
1336 last_button_bounds = overflow_button_->bounds();
1339 if (layout_manager_->IsHorizontalAlignment()) {
1340 preferred_size = gfx::Size(last_button_bounds.right() + leading_inset_,
1341 kShelfSize);
1342 } else {
1343 preferred_size = gfx::Size(kShelfSize,
1344 last_button_bounds.bottom() + leading_inset_);
1347 gfx::Point origin(GetMirroredXWithWidthInView(0, preferred_size.width()), 0);
1349 // In overflow mode, we should use OverflowBubbleView as a source for
1350 // converting |origin| to screen coordinates. When a scroll operation is
1351 // occurred in OverflowBubble, the bounds of ShelfView in OverflowBubble can
1352 // be changed.
1353 if (is_overflow_mode())
1354 ConvertPointToScreen(owner_overflow_bubble_->bubble_view(), &origin);
1355 else
1356 ConvertPointToScreen(this, &origin);
1358 return gfx::Rect(origin, preferred_size);
1361 int ShelfView::CancelDrag(int modified_index) {
1362 FinalizeRipOffDrag(true);
1363 if (!drag_view_)
1364 return modified_index;
1365 bool was_dragging = dragging();
1366 int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1367 drag_pointer_ = NONE;
1368 drag_view_ = NULL;
1369 if (drag_view_index == modified_index) {
1370 // The view that was being dragged is being modified. Don't do anything.
1371 return modified_index;
1373 if (!was_dragging)
1374 return modified_index;
1376 // Restore previous position, tracking the position of the modified view.
1377 bool at_end = modified_index == view_model_->view_size();
1378 views::View* modified_view =
1379 (modified_index >= 0 && !at_end) ?
1380 view_model_->view_at(modified_index) : NULL;
1381 model_->Move(drag_view_index, start_drag_index_);
1383 // If the modified view will be at the end of the list, return the new end of
1384 // the list.
1385 if (at_end)
1386 return view_model_->view_size();
1387 return modified_view ? view_model_->GetIndexOfView(modified_view) : -1;
1390 gfx::Size ShelfView::GetPreferredSize() const {
1391 IdealBounds ideal_bounds;
1392 CalculateIdealBounds(&ideal_bounds);
1394 int last_button_index = is_overflow_mode() ?
1395 last_visible_index_ : view_model_->view_size() - 1;
1397 // When an item is dragged off from the overflow bubble, it is moved to last
1398 // position and and changed to invisible. Overflow bubble size should be
1399 // shrunk to fit only for visible items.
1400 // If |dragged_off_from_overflow_to_shelf_| is set, there will be no invisible
1401 // items in the shelf.
1402 if (is_overflow_mode() &&
1403 dragged_off_shelf_ &&
1404 !dragged_off_from_overflow_to_shelf_ &&
1405 RemovableByRipOff(view_model_->GetIndexOfView(drag_view_)) == REMOVABLE)
1406 last_button_index--;
1408 const gfx::Rect last_button_bounds =
1409 last_button_index >= first_visible_index_ ?
1410 view_model_->ideal_bounds(last_button_index) :
1411 gfx::Rect(gfx::Size(kShelfSize, kShelfSize));
1413 if (layout_manager_->IsHorizontalAlignment()) {
1414 return gfx::Size(last_button_bounds.right() + leading_inset_, kShelfSize);
1417 return gfx::Size(kShelfSize,
1418 last_button_bounds.bottom() + leading_inset_);
1421 void ShelfView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1422 // This bounds change is produced by the shelf movement and all content has
1423 // to follow. Using an animation at that time would produce a time lag since
1424 // the animation of the BoundsAnimator has itself a delay before it arrives
1425 // at the required location. As such we tell the animator to go there
1426 // immediately.
1427 BoundsAnimatorDisabler disabler(bounds_animator_.get());
1428 LayoutToIdealBounds();
1429 FOR_EACH_OBSERVER(ShelfIconObserver, observers_,
1430 OnShelfIconPositionsChanged());
1432 if (IsShowingOverflowBubble())
1433 overflow_bubble_->Hide();
1436 views::FocusTraversable* ShelfView::GetPaneFocusTraversable() {
1437 return this;
1440 void ShelfView::GetAccessibleState(ui::AXViewState* state) {
1441 state->role = ui::AX_ROLE_TOOLBAR;
1442 state->name = l10n_util::GetStringUTF16(IDS_ASH_SHELF_ACCESSIBLE_NAME);
1445 void ShelfView::OnGestureEvent(ui::GestureEvent* event) {
1446 if (gesture_handler_.ProcessGestureEvent(*event))
1447 event->StopPropagation();
1450 void ShelfView::ShelfItemAdded(int model_index) {
1452 base::AutoReset<bool> cancelling_drag(
1453 &cancelling_drag_model_changed_, true);
1454 model_index = CancelDrag(model_index);
1456 views::View* view = CreateViewForItem(model_->items()[model_index]);
1457 AddChildView(view);
1458 // Hide the view, it'll be made visible when the animation is done. Using
1459 // opacity 0 here to avoid messing with CalculateIdealBounds which touches
1460 // the view's visibility.
1461 view->layer()->SetOpacity(0);
1462 view_model_->Add(view, model_index);
1464 // Give the button its ideal bounds. That way if we end up animating the
1465 // button before this animation completes it doesn't appear at some random
1466 // spot (because it was in the middle of animating from 0,0 0x0 to its
1467 // target).
1468 IdealBounds ideal_bounds;
1469 CalculateIdealBounds(&ideal_bounds);
1470 view->SetBoundsRect(view_model_->ideal_bounds(model_index));
1472 // The first animation moves all the views to their target position. |view|
1473 // is hidden, so it visually appears as though we are providing space for
1474 // it. When done we'll fade the view in.
1475 AnimateToIdealBounds();
1476 if (model_index <= last_visible_index_ ||
1477 model_index >= model_->FirstPanelIndex()) {
1478 bounds_animator_->SetAnimationDelegate(
1479 view,
1480 scoped_ptr<gfx::AnimationDelegate>(
1481 new StartFadeAnimationDelegate(this, view)));
1482 } else {
1483 // Undo the hiding if animation does not run.
1484 view->layer()->SetOpacity(1.0f);
1488 void ShelfView::ShelfItemRemoved(int model_index, ShelfID id) {
1489 if (id == context_menu_id_)
1490 launcher_menu_runner_.reset();
1492 base::AutoReset<bool> cancelling_drag(
1493 &cancelling_drag_model_changed_, true);
1494 model_index = CancelDrag(model_index);
1496 views::View* view = view_model_->view_at(model_index);
1497 view_model_->Remove(model_index);
1499 // When the overflow bubble is visible, the overflow range needs to be set
1500 // before CalculateIdealBounds() gets called. Otherwise CalculateIdealBounds()
1501 // could trigger a ShelfItemChanged() by hiding the overflow bubble and
1502 // since the overflow bubble is not yet synced with the ShelfModel this
1503 // could cause a crash.
1504 if (overflow_bubble_ && overflow_bubble_->IsShowing()) {
1505 last_hidden_index_ = std::min(last_hidden_index_,
1506 view_model_->view_size() - 1);
1507 UpdateOverflowRange(overflow_bubble_->shelf_view());
1510 if (view->visible()) {
1511 // The first animation fades out the view. When done we'll animate the rest
1512 // of the views to their target location.
1513 bounds_animator_->AnimateViewTo(view, view->bounds());
1514 bounds_animator_->SetAnimationDelegate(
1515 view,
1516 scoped_ptr<gfx::AnimationDelegate>(
1517 new FadeOutAnimationDelegate(this, view)));
1518 } else {
1519 // We don't need to show a fade out animation for invisible |view|. When an
1520 // item is ripped out from the shelf, its |view| is already invisible.
1521 AnimateToIdealBounds();
1524 // Close the tooltip because it isn't needed any longer and its anchor view
1525 // will be deleted soon.
1526 if (tooltip_->GetCurrentAnchorView() == view)
1527 tooltip_->Close();
1530 void ShelfView::ShelfItemChanged(int model_index, const ShelfItem& old_item) {
1531 const ShelfItem& item(model_->items()[model_index]);
1532 if (old_item.type != item.type) {
1533 // Type changed, swap the views.
1534 model_index = CancelDrag(model_index);
1535 scoped_ptr<views::View> old_view(view_model_->view_at(model_index));
1536 bounds_animator_->StopAnimatingView(old_view.get());
1537 // Removing and re-inserting a view in our view model will strip the ideal
1538 // bounds from the item. To avoid recalculation of everything the bounds
1539 // get remembered and restored after the insertion to the previous value.
1540 gfx::Rect old_ideal_bounds = view_model_->ideal_bounds(model_index);
1541 view_model_->Remove(model_index);
1542 views::View* new_view = CreateViewForItem(item);
1543 AddChildView(new_view);
1544 view_model_->Add(new_view, model_index);
1545 view_model_->set_ideal_bounds(model_index, old_ideal_bounds);
1546 new_view->SetBoundsRect(old_view->bounds());
1547 return;
1550 views::View* view = view_model_->view_at(model_index);
1551 switch (item.type) {
1552 case TYPE_BROWSER_SHORTCUT:
1553 // Fallthrough for the new Shelf since it needs to show the activation
1554 // change as well.
1555 case TYPE_APP_SHORTCUT:
1556 case TYPE_WINDOWED_APP:
1557 case TYPE_PLATFORM_APP:
1558 case TYPE_DIALOG:
1559 case TYPE_APP_PANEL: {
1560 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
1561 ShelfButton* button = static_cast<ShelfButton*>(view);
1562 ReflectItemStatus(item, button);
1563 // The browser shortcut is currently not a "real" item and as such the
1564 // the image is bogous as well. We therefore keep the image as is for it.
1565 if (item.type != TYPE_BROWSER_SHORTCUT)
1566 button->SetImage(item.image);
1567 button->SchedulePaint();
1568 break;
1571 default:
1572 break;
1576 void ShelfView::ShelfItemMoved(int start_index, int target_index) {
1577 view_model_->Move(start_index, target_index);
1578 // When cancelling a drag due to a shelf item being added, the currently
1579 // dragged item is moved back to its initial position. AnimateToIdealBounds
1580 // will be called again when the new item is added to the |view_model_| but
1581 // at this time the |view_model_| is inconsistent with the |model_|.
1582 if (!cancelling_drag_model_changed_)
1583 AnimateToIdealBounds();
1586 void ShelfView::ShelfStatusChanged() {
1587 // Nothing to do here.
1590 void ShelfView::PointerPressedOnButton(views::View* view,
1591 Pointer pointer,
1592 const ui::LocatedEvent& event) {
1593 if (drag_view_)
1594 return;
1596 int index = view_model_->GetIndexOfView(view);
1597 if (index == -1)
1598 return;
1600 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1601 model_->items()[index].id);
1602 if (view_model_->view_size() <= 1 || !item_delegate->IsDraggable())
1603 return; // View is being deleted or not draggable, ignore request.
1605 // Only when the repost event occurs on the same shelf item, we should ignore
1606 // the call in ShelfView::ButtonPressed(...).
1607 is_repost_event_ = IsRepostEvent(event) && (last_pressed_index_ == index);
1609 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
1610 drag_view_ = static_cast<ShelfButton*>(view);
1611 drag_origin_ = gfx::Point(event.x(), event.y());
1612 UMA_HISTOGRAM_ENUMERATION("Ash.ShelfAlignmentUsage",
1613 layout_manager_->SelectValueForShelfAlignment(
1614 SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM,
1615 SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT,
1616 SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT,
1617 -1),
1618 SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT);
1621 void ShelfView::PointerDraggedOnButton(views::View* view,
1622 Pointer pointer,
1623 const ui::LocatedEvent& event) {
1624 // To prepare all drag types (moving an item in the shelf and dragging off),
1625 // we should check the x-axis and y-axis offset.
1626 if (!dragging() && drag_view_ &&
1627 ((std::abs(event.x() - drag_origin_.x()) >= kMinimumDragDistance) ||
1628 (std::abs(event.y() - drag_origin_.y()) >= kMinimumDragDistance))) {
1629 PrepareForDrag(pointer, event);
1631 if (drag_pointer_ == pointer)
1632 ContinueDrag(event);
1635 void ShelfView::PointerReleasedOnButton(views::View* view,
1636 Pointer pointer,
1637 bool canceled) {
1638 // Reset |is_repost_event| to false.
1639 is_repost_event_ = false;
1641 if (canceled) {
1642 CancelDrag(-1);
1643 } else if (drag_pointer_ == pointer) {
1644 FinalizeRipOffDrag(false);
1645 drag_pointer_ = NONE;
1646 AnimateToIdealBounds();
1648 // If the drag pointer is NONE, no drag operation is going on and the
1649 // drag_view can be released.
1650 if (drag_pointer_ == NONE)
1651 drag_view_ = NULL;
1654 void ShelfView::MouseMovedOverButton(views::View* view) {
1655 if (!ShouldShowTooltipForView(view))
1656 return;
1658 if (!tooltip_->IsVisible())
1659 tooltip_->ResetTimer();
1662 void ShelfView::MouseEnteredButton(views::View* view) {
1663 if (!ShouldShowTooltipForView(view))
1664 return;
1666 if (tooltip_->IsVisible()) {
1667 tooltip_->ShowImmediately(view, GetAccessibleName(view));
1668 } else {
1669 tooltip_->ShowDelayed(view, GetAccessibleName(view));
1673 void ShelfView::MouseExitedButton(views::View* view) {
1674 if (!tooltip_->IsVisible())
1675 tooltip_->StopTimer();
1678 base::string16 ShelfView::GetAccessibleName(const views::View* view) {
1679 int view_index = view_model_->GetIndexOfView(view);
1680 // May be -1 while in the process of animating closed.
1681 if (view_index == -1)
1682 return base::string16();
1684 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1685 model_->items()[view_index].id);
1686 return item_delegate->GetTitle();
1689 void ShelfView::ButtonPressed(views::Button* sender, const ui::Event& event) {
1690 // Do not handle mouse release during drag.
1691 if (dragging())
1692 return;
1694 if (sender == overflow_button_) {
1695 ToggleOverflowBubble();
1696 RecordIconActivatedAction(event);
1697 return;
1700 int view_index = view_model_->GetIndexOfView(sender);
1701 // May be -1 while in the process of animating closed.
1702 if (view_index == -1)
1703 return;
1705 // If the menu was just closed by the same event as this one, we ignore
1706 // the call and don't open the menu again. See crbug.com/343005 for more
1707 // detail.
1708 if (is_repost_event_)
1709 return;
1711 // Record the index for the last pressed shelf item.
1712 last_pressed_index_ = view_index;
1714 // Don't activate the item twice on double-click. Otherwise the window starts
1715 // animating open due to the first click, then immediately minimizes due to
1716 // the second click. The user most likely intended to open or minimize the
1717 // item once, not do both.
1718 if (event.flags() & ui::EF_IS_DOUBLE_CLICK)
1719 return;
1722 ScopedTargetRootWindow scoped_target(
1723 sender->GetWidget()->GetNativeView()->GetRootWindow());
1724 // Slow down activation animations if shift key is pressed.
1725 scoped_ptr<ui::ScopedAnimationDurationScaleMode> slowing_animations;
1726 if (event.IsShiftDown()) {
1727 slowing_animations.reset(new ui::ScopedAnimationDurationScaleMode(
1728 ui::ScopedAnimationDurationScaleMode::SLOW_DURATION));
1731 // Collect usage statistics before we decide what to do with the click.
1732 switch (model_->items()[view_index].type) {
1733 case TYPE_APP_SHORTCUT:
1734 case TYPE_WINDOWED_APP:
1735 case TYPE_PLATFORM_APP:
1736 case TYPE_BROWSER_SHORTCUT:
1737 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1738 UMA_LAUNCHER_CLICK_ON_APP);
1739 break;
1741 case TYPE_APP_LIST:
1742 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1743 UMA_LAUNCHER_CLICK_ON_APPLIST_BUTTON);
1744 break;
1746 case TYPE_APP_PANEL:
1747 case TYPE_DIALOG:
1748 break;
1750 case TYPE_UNDEFINED:
1751 NOTREACHED() << "ShelfItemType must be set.";
1752 break;
1755 RecordIconActivatedAction(event);
1757 ShelfItemDelegate* item_delegate =
1758 item_manager_->GetShelfItemDelegate(model_->items()[view_index].id);
1759 if (!item_delegate->ItemSelected(event)) {
1760 ShowListMenuForView(model_->items()[view_index], sender, event);
1761 } else {
1762 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1763 UMA_LAUNCHER_LAUNCH_TASK);
1768 bool ShelfView::ShowListMenuForView(const ShelfItem& item,
1769 views::View* source,
1770 const ui::Event& event) {
1771 ShelfItemDelegate* item_delegate =
1772 item_manager_->GetShelfItemDelegate(item.id);
1773 scoped_ptr<ui::MenuModel> list_menu_model(
1774 item_delegate->CreateApplicationMenu(event.flags()));
1776 // Make sure we have a menu and it has at least two items in addition to the
1777 // application title and the 3 spacing separators.
1778 if (!list_menu_model.get() || list_menu_model->GetItemCount() <= 5)
1779 return false;
1781 ShowMenu(list_menu_model.get(),
1782 source,
1783 gfx::Point(),
1784 false,
1785 ui::GetMenuSourceTypeForEvent(event));
1786 return true;
1789 void ShelfView::ShowContextMenuForView(views::View* source,
1790 const gfx::Point& point,
1791 ui::MenuSourceType source_type) {
1792 int view_index = view_model_->GetIndexOfView(source);
1793 if (view_index == -1) {
1794 Shell::GetInstance()->ShowContextMenu(point, source_type);
1795 return;
1798 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1799 model_->items()[view_index].id);
1800 context_menu_model_.reset(item_delegate->CreateContextMenu(
1801 source->GetWidget()->GetNativeView()->GetRootWindow()));
1802 if (!context_menu_model_)
1803 return;
1805 base::AutoReset<ShelfID> reseter(
1806 &context_menu_id_,
1807 view_index == -1 ? 0 : model_->items()[view_index].id);
1809 ShowMenu(context_menu_model_.get(),
1810 source,
1811 point,
1812 true,
1813 source_type);
1816 void ShelfView::ShowMenu(ui::MenuModel* menu_model,
1817 views::View* source,
1818 const gfx::Point& click_point,
1819 bool context_menu,
1820 ui::MenuSourceType source_type) {
1821 closing_event_time_ = base::TimeDelta();
1822 launcher_menu_runner_.reset(new views::MenuRunner(
1823 menu_model, context_menu ? views::MenuRunner::CONTEXT_MENU : 0));
1825 ScopedTargetRootWindow scoped_target(
1826 source->GetWidget()->GetNativeView()->GetRootWindow());
1828 // Determine the menu alignment dependent on the shelf.
1829 views::MenuAnchorPosition menu_alignment = views::MENU_ANCHOR_TOPLEFT;
1830 gfx::Rect anchor_point = gfx::Rect(click_point, gfx::Size());
1832 ShelfWidget* shelf = RootWindowController::ForShelf(
1833 GetWidget()->GetNativeView())->shelf();
1834 if (!context_menu) {
1835 // Application lists use a bubble.
1836 ShelfAlignment align = shelf->GetAlignment();
1837 anchor_point = source->GetBoundsInScreen();
1839 // It is possible to invoke the menu while it is sliding into view. To cover
1840 // that case, the screen coordinates are offsetted by the animation delta.
1841 gfx::Vector2d offset =
1842 source->GetWidget()->GetNativeWindow()->bounds().origin() -
1843 source->GetWidget()->GetNativeWindow()->GetTargetBounds().origin();
1844 anchor_point.set_x(anchor_point.x() - offset.x());
1845 anchor_point.set_y(anchor_point.y() - offset.y());
1847 // Shelf items can have an asymmetrical border for spacing reasons.
1848 // Adjust anchor location for this.
1849 if (source->border())
1850 anchor_point.Inset(source->border()->GetInsets());
1852 switch (align) {
1853 case SHELF_ALIGNMENT_BOTTOM:
1854 menu_alignment = views::MENU_ANCHOR_BUBBLE_ABOVE;
1855 break;
1856 case SHELF_ALIGNMENT_LEFT:
1857 menu_alignment = views::MENU_ANCHOR_BUBBLE_RIGHT;
1858 break;
1859 case SHELF_ALIGNMENT_RIGHT:
1860 menu_alignment = views::MENU_ANCHOR_BUBBLE_LEFT;
1861 break;
1862 case SHELF_ALIGNMENT_TOP:
1863 menu_alignment = views::MENU_ANCHOR_BUBBLE_BELOW;
1864 break;
1867 // If this gets deleted while we are in the menu, the shelf will be gone
1868 // as well.
1869 bool got_deleted = false;
1870 got_deleted_ = &got_deleted;
1872 shelf->ForceUndimming(true);
1873 // NOTE: if you convert to HAS_MNEMONICS be sure and update menu building
1874 // code.
1875 if (launcher_menu_runner_->RunMenuAt(source->GetWidget(),
1876 NULL,
1877 anchor_point,
1878 menu_alignment,
1879 source_type) ==
1880 views::MenuRunner::MENU_DELETED) {
1881 if (!got_deleted) {
1882 got_deleted_ = NULL;
1883 shelf->ForceUndimming(false);
1885 return;
1887 got_deleted_ = NULL;
1888 shelf->ForceUndimming(false);
1890 // If it is a context menu and we are showing overflow bubble
1891 // we want to hide overflow bubble.
1892 if (owner_overflow_bubble_)
1893 owner_overflow_bubble_->HideBubbleAndRefreshButton();
1895 // Unpinning an item will reset the |launcher_menu_runner_| before coming
1896 // here.
1897 if (launcher_menu_runner_)
1898 closing_event_time_ = launcher_menu_runner_->closing_event_time();
1899 Shell::GetInstance()->UpdateShelfVisibility();
1902 void ShelfView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) {
1903 FOR_EACH_OBSERVER(ShelfIconObserver, observers_,
1904 OnShelfIconPositionsChanged());
1905 PreferredSizeChanged();
1908 void ShelfView::OnBoundsAnimatorDone(views::BoundsAnimator* animator) {
1909 if (snap_back_from_rip_off_view_ && animator == bounds_animator_) {
1910 if (!animator->IsAnimating(snap_back_from_rip_off_view_)) {
1911 // Coming here the animation of the ShelfButton is finished and the
1912 // previously hidden status can be shown again. Since the button itself
1913 // might have gone away or changed locations we check that the button
1914 // is still in the shelf and show its status again.
1915 for (int index = 0; index < view_model_->view_size(); index++) {
1916 views::View* view = view_model_->view_at(index);
1917 if (view == snap_back_from_rip_off_view_) {
1918 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
1919 ShelfButton* button = static_cast<ShelfButton*>(view);
1920 button->ClearState(ShelfButton::STATE_HIDDEN);
1921 break;
1924 snap_back_from_rip_off_view_ = NULL;
1929 bool ShelfView::IsRepostEvent(const ui::Event& event) {
1930 if (closing_event_time_ == base::TimeDelta())
1931 return false;
1933 base::TimeDelta delta =
1934 base::TimeDelta(event.time_stamp() - closing_event_time_);
1935 closing_event_time_ = base::TimeDelta();
1936 // If the current (press down) event is a repost event, the time stamp of
1937 // these two events should be the same.
1938 return (delta.InMilliseconds() == 0);
1941 const ShelfItem* ShelfView::ShelfItemForView(const views::View* view) const {
1942 int view_index = view_model_->GetIndexOfView(view);
1943 if (view_index == -1)
1944 return NULL;
1945 return &(model_->items()[view_index]);
1948 bool ShelfView::ShouldShowTooltipForView(const views::View* view) const {
1949 if (view == GetAppListButtonView() &&
1950 Shell::GetInstance()->GetAppListWindow())
1951 return false;
1952 const ShelfItem* item = ShelfItemForView(view);
1953 if (!item)
1954 return true;
1955 ShelfItemDelegate* item_delegate =
1956 item_manager_->GetShelfItemDelegate(item->id);
1957 return item_delegate->ShouldShowTooltip();
1960 int ShelfView::CalculateShelfDistance(const gfx::Point& coordinate) const {
1961 ShelfWidget* shelf = RootWindowController::ForShelf(
1962 GetWidget()->GetNativeView())->shelf();
1963 ShelfAlignment align = shelf->GetAlignment();
1964 const gfx::Rect bounds = GetBoundsInScreen();
1965 int distance = 0;
1966 switch (align) {
1967 case SHELF_ALIGNMENT_BOTTOM:
1968 distance = bounds.y() - coordinate.y();
1969 break;
1970 case SHELF_ALIGNMENT_LEFT:
1971 distance = coordinate.x() - bounds.right();
1972 break;
1973 case SHELF_ALIGNMENT_RIGHT:
1974 distance = bounds.x() - coordinate.x();
1975 break;
1976 case SHELF_ALIGNMENT_TOP:
1977 distance = coordinate.y() - bounds.bottom();
1978 break;
1980 return distance > 0 ? distance : 0;
1983 } // namespace ash