Returning scoped_ptr instead of raw pointer in QuicInfoToValue in net/
[chromium-blink-merge.git] / ash / shelf / shelf_view.cc
blob9a22b1d51f4ef37b2f18b0486aeb9695edde55f7
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_manager.h"
24 #include "ash/shelf/shelf_layout_manager.h"
25 #include "ash/shelf/shelf_menu_model.h"
26 #include "ash/shelf/shelf_model.h"
27 #include "ash/shelf/shelf_tooltip_manager.h"
28 #include "ash/shelf/shelf_widget.h"
29 #include "ash/shell.h"
30 #include "ash/wm/coordinate_conversion.h"
31 #include "base/auto_reset.h"
32 #include "base/memory/scoped_ptr.h"
33 #include "base/metrics/histogram.h"
34 #include "grit/ash_strings.h"
35 #include "ui/accessibility/ax_view_state.h"
36 #include "ui/aura/client/screen_position_client.h"
37 #include "ui/aura/window.h"
38 #include "ui/aura/window_event_dispatcher.h"
39 #include "ui/base/l10n/l10n_util.h"
40 #include "ui/base/models/simple_menu_model.h"
41 #include "ui/base/resource/resource_bundle.h"
42 #include "ui/compositor/layer.h"
43 #include "ui/compositor/layer_animator.h"
44 #include "ui/compositor/scoped_animation_duration_scale_mode.h"
45 #include "ui/events/event_utils.h"
46 #include "ui/gfx/canvas.h"
47 #include "ui/gfx/geometry/point.h"
48 #include "ui/views/animation/bounds_animator.h"
49 #include "ui/views/border.h"
50 #include "ui/views/controls/button/image_button.h"
51 #include "ui/views/controls/menu/menu_model_adapter.h"
52 #include "ui/views/controls/menu/menu_runner.h"
53 #include "ui/views/focus/focus_search.h"
54 #include "ui/views/view_model.h"
55 #include "ui/views/view_model_utils.h"
56 #include "ui/views/widget/widget.h"
57 #include "ui/wm/core/coordinate_conversion.h"
59 using gfx::Animation;
60 using views::View;
62 namespace ash {
64 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM = 0;
65 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT = 1;
66 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT = 2;
67 const int SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT = 3;
69 // Default amount content is inset on the left edge.
70 const int kDefaultLeadingInset = 8;
72 // Minimum distance before drag starts.
73 const int kMinimumDragDistance = 8;
75 // Additional spacing for the left and right side of icons.
76 const int kHorizontalIconSpacing = 2;
78 // Inset for items which do not have an icon.
79 const int kHorizontalNoIconInsetSpacing =
80 kHorizontalIconSpacing + kDefaultLeadingInset;
82 // The proportion of the shelf space reserved for non-panel icons. Panels
83 // may flow into this space but will be put into the overflow bubble if there
84 // is contention for the space.
85 const float kReservedNonPanelIconProportion = 0.67f;
87 // This is the command id of the menu item which contains the name of the menu.
88 const int kCommandIdOfMenuName = 0;
90 // The background color of the active item in the list.
91 const SkColor kActiveListItemBackgroundColor = SkColorSetRGB(203 , 219, 241);
93 // The background color of the active & hovered item in the list.
94 const SkColor kFocusedActiveListItemBackgroundColor =
95 SkColorSetRGB(193, 211, 236);
97 // The text color of the caption item in a list.
98 const SkColor kCaptionItemForegroundColor = SK_ColorBLACK;
100 // The maximum allowable length of a menu line of an application menu in pixels.
101 const int kMaximumAppMenuItemLength = 350;
103 // The distance of the cursor from the outer rim of the shelf before it
104 // separates.
105 const int kRipOffDistance = 48;
107 // The rip off drag and drop proxy image should get scaled by this factor.
108 const float kDragAndDropProxyScale = 1.5f;
110 // The opacity represents that this partially disappeared item will get removed.
111 const float kDraggedImageOpacity = 0.5f;
113 namespace {
115 // A class to temporarily disable a given bounds animator.
116 class BoundsAnimatorDisabler {
117 public:
118 explicit BoundsAnimatorDisabler(views::BoundsAnimator* bounds_animator)
119 : old_duration_(bounds_animator->GetAnimationDuration()),
120 bounds_animator_(bounds_animator) {
121 bounds_animator_->SetAnimationDuration(1);
124 ~BoundsAnimatorDisabler() {
125 bounds_animator_->SetAnimationDuration(old_duration_);
128 private:
129 // The previous animation duration.
130 int old_duration_;
131 // The bounds animator which gets used.
132 views::BoundsAnimator* bounds_animator_;
134 DISALLOW_COPY_AND_ASSIGN(BoundsAnimatorDisabler);
137 // The MenuModelAdapter gets slightly changed to adapt the menu appearance to
138 // our requirements.
139 class ShelfMenuModelAdapter : public views::MenuModelAdapter {
140 public:
141 explicit ShelfMenuModelAdapter(ShelfMenuModel* menu_model);
143 // views::MenuModelAdapter:
144 const gfx::FontList* GetLabelFontList(int command_id) const override;
145 bool IsCommandEnabled(int id) const override;
146 void GetHorizontalIconMargins(int id,
147 int icon_size,
148 int* left_margin,
149 int* right_margin) const override;
150 bool GetForegroundColor(int command_id,
151 bool is_hovered,
152 SkColor* override_color) const override;
153 bool GetBackgroundColor(int command_id,
154 bool is_hovered,
155 SkColor* override_color) const override;
156 int GetMaxWidthForMenu(views::MenuItemView* menu) override;
157 bool ShouldReserveSpaceForSubmenuIndicator() const override;
159 private:
160 ShelfMenuModel* menu_model_;
162 DISALLOW_COPY_AND_ASSIGN(ShelfMenuModelAdapter);
165 ShelfMenuModelAdapter::ShelfMenuModelAdapter(ShelfMenuModel* menu_model)
166 : MenuModelAdapter(menu_model),
167 menu_model_(menu_model) {
170 const gfx::FontList* ShelfMenuModelAdapter::GetLabelFontList(
171 int command_id) const {
172 if (command_id != kCommandIdOfMenuName)
173 return MenuModelAdapter::GetLabelFontList(command_id);
175 ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance();
176 return &rb->GetFontList(ui::ResourceBundle::BoldFont);
179 bool ShelfMenuModelAdapter::IsCommandEnabled(int id) const {
180 return id != kCommandIdOfMenuName;
183 bool ShelfMenuModelAdapter::GetForegroundColor(int command_id,
184 bool is_hovered,
185 SkColor* override_color) const {
186 if (command_id != kCommandIdOfMenuName)
187 return false;
189 *override_color = kCaptionItemForegroundColor;
190 return true;
193 bool ShelfMenuModelAdapter::GetBackgroundColor(int command_id,
194 bool is_hovered,
195 SkColor* override_color) const {
196 if (!menu_model_->IsCommandActive(command_id))
197 return false;
199 *override_color = is_hovered ? kFocusedActiveListItemBackgroundColor :
200 kActiveListItemBackgroundColor;
201 return true;
204 void ShelfMenuModelAdapter::GetHorizontalIconMargins(int command_id,
205 int icon_size,
206 int* left_margin,
207 int* right_margin) const {
208 *left_margin = kHorizontalIconSpacing;
209 *right_margin = (command_id != kCommandIdOfMenuName) ?
210 kHorizontalIconSpacing : -(icon_size + kHorizontalNoIconInsetSpacing);
213 int ShelfMenuModelAdapter::GetMaxWidthForMenu(views::MenuItemView* menu) {
214 return kMaximumAppMenuItemLength;
217 bool ShelfMenuModelAdapter::ShouldReserveSpaceForSubmenuIndicator() const {
218 return false;
221 // Custom FocusSearch used to navigate the shelf in the order items are in
222 // the ViewModel.
223 class ShelfFocusSearch : public views::FocusSearch {
224 public:
225 explicit ShelfFocusSearch(views::ViewModel* view_model)
226 : FocusSearch(NULL, true, true),
227 view_model_(view_model) {}
228 ~ShelfFocusSearch() override {}
230 // views::FocusSearch overrides:
231 View* FindNextFocusableView(View* starting_view,
232 bool reverse,
233 Direction direction,
234 bool check_starting_view,
235 views::FocusTraversable** focus_traversable,
236 View** focus_traversable_view) override {
237 int index = view_model_->GetIndexOfView(starting_view);
238 if (index == -1)
239 return view_model_->view_at(0);
241 if (reverse) {
242 --index;
243 if (index < 0)
244 index = view_model_->view_size() - 1;
245 } else {
246 ++index;
247 if (index >= view_model_->view_size())
248 index = 0;
250 return view_model_->view_at(index);
253 private:
254 views::ViewModel* view_model_;
256 DISALLOW_COPY_AND_ASSIGN(ShelfFocusSearch);
259 // AnimationDelegate used when inserting a new item. This steadily increases the
260 // opacity of the layer as the animation progress.
261 class FadeInAnimationDelegate : public gfx::AnimationDelegate {
262 public:
263 explicit FadeInAnimationDelegate(views::View* view) : view_(view) {}
264 ~FadeInAnimationDelegate() override {}
266 // AnimationDelegate overrides:
267 void AnimationProgressed(const Animation* animation) override {
268 view_->layer()->SetOpacity(animation->GetCurrentValue());
269 view_->layer()->ScheduleDraw();
271 void AnimationEnded(const Animation* animation) override {
272 view_->layer()->SetOpacity(1.0f);
273 view_->layer()->ScheduleDraw();
275 void AnimationCanceled(const Animation* animation) override {
276 view_->layer()->SetOpacity(1.0f);
277 view_->layer()->ScheduleDraw();
280 private:
281 views::View* view_;
283 DISALLOW_COPY_AND_ASSIGN(FadeInAnimationDelegate);
286 void ReflectItemStatus(const ShelfItem& item, ShelfButton* button) {
287 switch (item.status) {
288 case STATUS_CLOSED:
289 button->ClearState(ShelfButton::STATE_ACTIVE);
290 button->ClearState(ShelfButton::STATE_RUNNING);
291 button->ClearState(ShelfButton::STATE_ATTENTION);
292 break;
293 case STATUS_RUNNING:
294 button->ClearState(ShelfButton::STATE_ACTIVE);
295 button->AddState(ShelfButton::STATE_RUNNING);
296 button->ClearState(ShelfButton::STATE_ATTENTION);
297 break;
298 case STATUS_ACTIVE:
299 button->AddState(ShelfButton::STATE_ACTIVE);
300 button->ClearState(ShelfButton::STATE_RUNNING);
301 button->ClearState(ShelfButton::STATE_ATTENTION);
302 break;
303 case STATUS_ATTENTION:
304 button->ClearState(ShelfButton::STATE_ACTIVE);
305 button->ClearState(ShelfButton::STATE_RUNNING);
306 button->AddState(ShelfButton::STATE_ATTENTION);
307 break;
311 } // namespace
313 // AnimationDelegate used when deleting an item. This steadily decreased the
314 // opacity of the layer as the animation progress.
315 class ShelfView::FadeOutAnimationDelegate : public gfx::AnimationDelegate {
316 public:
317 FadeOutAnimationDelegate(ShelfView* host, views::View* view)
318 : shelf_view_(host),
319 view_(view) {}
320 ~FadeOutAnimationDelegate() override {}
322 // AnimationDelegate overrides:
323 void AnimationProgressed(const Animation* animation) override {
324 view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
325 view_->layer()->ScheduleDraw();
327 void AnimationEnded(const Animation* animation) override {
328 shelf_view_->OnFadeOutAnimationEnded();
330 void AnimationCanceled(const Animation* animation) override {}
332 private:
333 ShelfView* shelf_view_;
334 scoped_ptr<views::View> view_;
336 DISALLOW_COPY_AND_ASSIGN(FadeOutAnimationDelegate);
339 // AnimationDelegate used to trigger fading an element in. When an item is
340 // inserted this delegate is attached to the animation that expands the size of
341 // the item. When done it kicks off another animation to fade the item in.
342 class ShelfView::StartFadeAnimationDelegate : public gfx::AnimationDelegate {
343 public:
344 StartFadeAnimationDelegate(ShelfView* host,
345 views::View* view)
346 : shelf_view_(host),
347 view_(view) {}
348 ~StartFadeAnimationDelegate() override {}
350 // AnimationDelegate overrides:
351 void AnimationEnded(const Animation* animation) override {
352 shelf_view_->FadeIn(view_);
354 void AnimationCanceled(const Animation* animation) override {
355 view_->layer()->SetOpacity(1.0f);
358 private:
359 ShelfView* shelf_view_;
360 views::View* view_;
362 DISALLOW_COPY_AND_ASSIGN(StartFadeAnimationDelegate);
365 ShelfView::ShelfView(ShelfModel* model,
366 ShelfDelegate* delegate,
367 ShelfLayoutManager* manager)
368 : model_(model),
369 delegate_(delegate),
370 view_model_(new views::ViewModel),
371 first_visible_index_(0),
372 last_visible_index_(-1),
373 overflow_button_(NULL),
374 owner_overflow_bubble_(NULL),
375 drag_pointer_(NONE),
376 drag_view_(NULL),
377 start_drag_index_(-1),
378 context_menu_id_(0),
379 leading_inset_(kDefaultLeadingInset),
380 cancelling_drag_model_changed_(false),
381 last_hidden_index_(0),
382 closing_event_time_(base::TimeDelta()),
383 got_deleted_(NULL),
384 drag_and_drop_item_pinned_(false),
385 drag_and_drop_shelf_id_(0),
386 dragged_off_shelf_(false),
387 snap_back_from_rip_off_view_(NULL),
388 item_manager_(Shell::GetInstance()->shelf_item_delegate_manager()),
389 layout_manager_(manager),
390 overflow_mode_(false),
391 main_shelf_(NULL),
392 dragged_off_from_overflow_to_shelf_(false),
393 is_repost_event_(false),
394 last_pressed_index_(-1) {
395 DCHECK(model_);
396 bounds_animator_.reset(new views::BoundsAnimator(this));
397 bounds_animator_->AddObserver(this);
398 set_context_menu_controller(this);
399 focus_search_.reset(new ShelfFocusSearch(view_model_.get()));
400 tooltip_.reset(new ShelfTooltipManager(manager, this));
403 ShelfView::~ShelfView() {
404 bounds_animator_->RemoveObserver(this);
405 model_->RemoveObserver(this);
406 // If we are inside the MenuRunner, we need to know if we were getting
407 // deleted while it was running.
408 if (got_deleted_)
409 *got_deleted_ = true;
412 void ShelfView::Init() {
413 model_->AddObserver(this);
415 const ShelfItems& items(model_->items());
416 for (ShelfItems::const_iterator i = items.begin(); i != items.end(); ++i) {
417 views::View* child = CreateViewForItem(*i);
418 child->SetPaintToLayer(true);
419 view_model_->Add(child, static_cast<int>(i - items.begin()));
420 AddChildView(child);
422 overflow_button_ = new OverflowButton(this);
423 overflow_button_->set_context_menu_controller(this);
424 ConfigureChildView(overflow_button_);
425 AddChildView(overflow_button_);
427 // We'll layout when our bounds change.
430 void ShelfView::OnShelfAlignmentChanged() {
431 overflow_button_->OnShelfAlignmentChanged();
432 LayoutToIdealBounds();
433 for (int i = 0; i < view_model_->view_size(); ++i) {
434 if (i >= first_visible_index_ && i <= last_visible_index_)
435 view_model_->view_at(i)->Layout();
437 tooltip_->Close();
438 if (overflow_bubble_)
439 overflow_bubble_->Hide();
442 void ShelfView::SchedulePaintForAllButtons() {
443 for (int i = 0; i < view_model_->view_size(); ++i) {
444 if (i >= first_visible_index_ && i <= last_visible_index_)
445 view_model_->view_at(i)->SchedulePaint();
447 if (overflow_button_ && overflow_button_->visible())
448 overflow_button_->SchedulePaint();
451 gfx::Rect ShelfView::GetIdealBoundsOfItemIcon(ShelfID id) {
452 int index = model_->ItemIndexByID(id);
453 if (index == -1)
454 return gfx::Rect();
455 // Map all items from overflow area to the overflow button. Note that the
456 // section between last_index_hidden_ and model_->FirstPanelIndex() is the
457 // list of invisible panel items. However, these items are currently nowhere
458 // represented and get dropped instead - see (crbug.com/378907). As such there
459 // is no way to address them or place them. We therefore move them over the
460 // overflow button.
461 if (index > last_visible_index_ && index < model_->FirstPanelIndex())
462 index = last_visible_index_ + 1;
463 const gfx::Rect& ideal_bounds(view_model_->ideal_bounds(index));
464 DCHECK_NE(TYPE_APP_LIST, model_->items()[index].type);
465 views::View* view = view_model_->view_at(index);
466 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
467 ShelfButton* button = static_cast<ShelfButton*>(view);
468 gfx::Rect icon_bounds = button->GetIconBounds();
469 return gfx::Rect(GetMirroredXWithWidthInView(
470 ideal_bounds.x() + icon_bounds.x(), icon_bounds.width()),
471 ideal_bounds.y() + icon_bounds.y(),
472 icon_bounds.width(),
473 icon_bounds.height());
476 void ShelfView::UpdatePanelIconPosition(ShelfID id,
477 const gfx::Point& midpoint) {
478 int current_index = model_->ItemIndexByID(id);
479 int first_panel_index = model_->FirstPanelIndex();
480 if (current_index < first_panel_index)
481 return;
483 gfx::Point midpoint_in_view(GetMirroredXInView(midpoint.x()),
484 midpoint.y());
485 int target_index = current_index;
486 while (target_index > first_panel_index &&
487 layout_manager_->PrimaryAxisValue(
488 view_model_->ideal_bounds(target_index).x(),
489 view_model_->ideal_bounds(target_index).y()) >
490 layout_manager_->PrimaryAxisValue(midpoint_in_view.x(),
491 midpoint_in_view.y())) {
492 --target_index;
494 while (target_index < view_model_->view_size() - 1 &&
495 layout_manager_->PrimaryAxisValue(
496 view_model_->ideal_bounds(target_index).right(),
497 view_model_->ideal_bounds(target_index).bottom()) <
498 layout_manager_->PrimaryAxisValue(midpoint_in_view.x(),
499 midpoint_in_view.y())) {
500 ++target_index;
502 if (current_index != target_index)
503 model_->Move(current_index, target_index);
506 bool ShelfView::IsShowingMenu() const {
507 return (launcher_menu_runner_.get() &&
508 launcher_menu_runner_->IsRunning());
511 bool ShelfView::IsShowingOverflowBubble() const {
512 return overflow_bubble_.get() && overflow_bubble_->IsShowing();
515 views::View* ShelfView::GetAppListButtonView() const {
516 for (int i = 0; i < model_->item_count(); ++i) {
517 if (model_->items()[i].type == TYPE_APP_LIST)
518 return view_model_->view_at(i);
521 NOTREACHED() << "Applist button not found";
522 return NULL;
525 ////////////////////////////////////////////////////////////////////////////////
526 // ShelfView, FocusTraversable implementation:
528 views::FocusSearch* ShelfView::GetFocusSearch() {
529 return focus_search_.get();
532 views::FocusTraversable* ShelfView::GetFocusTraversableParent() {
533 return parent()->GetFocusTraversable();
536 View* ShelfView::GetFocusTraversableParentView() {
537 return this;
540 void ShelfView::CreateDragIconProxy(
541 const gfx::Point& location_in_screen_coordinates,
542 const gfx::ImageSkia& icon,
543 views::View* replaced_view,
544 const gfx::Vector2d& cursor_offset_from_center,
545 float scale_factor) {
546 drag_replaced_view_ = replaced_view;
547 drag_image_.reset(new ash::DragImageView(
548 drag_replaced_view_->GetWidget()->GetNativeWindow()->GetRootWindow(),
549 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE));
550 drag_image_->SetImage(icon);
551 gfx::Size size = drag_image_->GetPreferredSize();
552 size.set_width(size.width() * scale_factor);
553 size.set_height(size.height() * scale_factor);
554 drag_image_offset_ = gfx::Vector2d(size.width() / 2, size.height() / 2) +
555 cursor_offset_from_center;
556 gfx::Rect drag_image_bounds(
557 location_in_screen_coordinates - drag_image_offset_,
558 size);
559 drag_image_->SetBoundsInScreen(drag_image_bounds);
560 drag_image_->SetWidgetVisible(true);
563 void ShelfView::UpdateDragIconProxy(
564 const gfx::Point& location_in_screen_coordinates) {
565 // TODO(jennyz): Investigate why drag_image_ becomes NULL at this point per
566 // crbug.com/34722, while the app list item is still being dragged around.
567 if (drag_image_) {
568 drag_image_->SetScreenPosition(
569 location_in_screen_coordinates - drag_image_offset_);
573 void ShelfView::DestroyDragIconProxy() {
574 drag_image_.reset();
575 drag_image_offset_ = gfx::Vector2d(0, 0);
578 bool ShelfView::StartDrag(const std::string& app_id,
579 const gfx::Point& location_in_screen_coordinates) {
580 // Bail if an operation is already going on - or the cursor is not inside.
581 // This could happen if mouse / touch operations overlap.
582 if (drag_and_drop_shelf_id_ ||
583 !GetBoundsInScreen().Contains(location_in_screen_coordinates))
584 return false;
586 // If the AppsGridView (which was dispatching this event) was opened by our
587 // button, ShelfView dragging operations are locked and we have to unlock.
588 CancelDrag(-1);
589 drag_and_drop_item_pinned_ = false;
590 drag_and_drop_app_id_ = app_id;
591 drag_and_drop_shelf_id_ =
592 delegate_->GetShelfIDForAppID(drag_and_drop_app_id_);
593 // Check if the application is known and pinned - if not, we have to pin it so
594 // that we can re-arrange the shelf order accordingly. Note that items have
595 // to be pinned to give them the same (order) possibilities as a shortcut.
596 // When an item is dragged from overflow to shelf, IsShowingOverflowBubble()
597 // returns true. At this time, we don't need to pin the item.
598 if (!IsShowingOverflowBubble() &&
599 (!drag_and_drop_shelf_id_ ||
600 !delegate_->IsAppPinned(app_id))) {
601 delegate_->PinAppWithID(app_id);
602 drag_and_drop_shelf_id_ =
603 delegate_->GetShelfIDForAppID(drag_and_drop_app_id_);
604 if (!drag_and_drop_shelf_id_)
605 return false;
606 drag_and_drop_item_pinned_ = true;
608 views::View* drag_and_drop_view = view_model_->view_at(
609 model_->ItemIndexByID(drag_and_drop_shelf_id_));
610 DCHECK(drag_and_drop_view);
612 // Since there is already an icon presented by the caller, we hide this item
613 // for now. That has to be done by reducing the size since the visibility will
614 // change once a regrouping animation is performed.
615 pre_drag_and_drop_size_ = drag_and_drop_view->size();
616 drag_and_drop_view->SetSize(gfx::Size());
618 // First we have to center the mouse cursor over the item.
619 gfx::Point pt = drag_and_drop_view->GetBoundsInScreen().CenterPoint();
620 views::View::ConvertPointFromScreen(drag_and_drop_view, &pt);
621 gfx::Point point_in_root = location_in_screen_coordinates;
622 ::wm::ConvertPointFromScreen(
623 ash::wm::GetRootWindowAt(location_in_screen_coordinates), &point_in_root);
624 ui::MouseEvent event(ui::ET_MOUSE_PRESSED, pt, point_in_root,
625 ui::EventTimeForNow(), 0, 0);
626 PointerPressedOnButton(drag_and_drop_view,
627 ShelfButtonHost::DRAG_AND_DROP,
628 event);
630 // Drag the item where it really belongs.
631 Drag(location_in_screen_coordinates);
632 return true;
635 bool ShelfView::Drag(const gfx::Point& location_in_screen_coordinates) {
636 if (!drag_and_drop_shelf_id_ ||
637 !GetBoundsInScreen().Contains(location_in_screen_coordinates))
638 return false;
640 gfx::Point pt = location_in_screen_coordinates;
641 views::View* drag_and_drop_view = view_model_->view_at(
642 model_->ItemIndexByID(drag_and_drop_shelf_id_));
643 ConvertPointFromScreen(drag_and_drop_view, &pt);
644 gfx::Point point_in_root = location_in_screen_coordinates;
645 ::wm::ConvertPointFromScreen(
646 ash::wm::GetRootWindowAt(location_in_screen_coordinates), &point_in_root);
647 ui::MouseEvent event(ui::ET_MOUSE_DRAGGED, pt, point_in_root,
648 ui::EventTimeForNow(), 0, 0);
649 PointerDraggedOnButton(drag_and_drop_view,
650 ShelfButtonHost::DRAG_AND_DROP,
651 event);
652 return true;
655 void ShelfView::EndDrag(bool cancel) {
656 if (!drag_and_drop_shelf_id_)
657 return;
659 views::View* drag_and_drop_view = view_model_->view_at(
660 model_->ItemIndexByID(drag_and_drop_shelf_id_));
661 PointerReleasedOnButton(
662 drag_and_drop_view, ShelfButtonHost::DRAG_AND_DROP, cancel);
664 // Either destroy the temporarily created item - or - make the item visible.
665 if (drag_and_drop_item_pinned_ && cancel) {
666 delegate_->UnpinAppWithID(drag_and_drop_app_id_);
667 } else if (drag_and_drop_view) {
668 if (cancel) {
669 // When a hosted drag gets canceled, the item can remain in the same slot
670 // and it might have moved within the bounds. In that case the item need
671 // to animate back to its correct location.
672 AnimateToIdealBounds();
673 } else {
674 drag_and_drop_view->SetSize(pre_drag_and_drop_size_);
678 drag_and_drop_shelf_id_ = 0;
681 void ShelfView::LayoutToIdealBounds() {
682 if (bounds_animator_->IsAnimating()) {
683 AnimateToIdealBounds();
684 return;
687 IdealBounds ideal_bounds;
688 CalculateIdealBounds(&ideal_bounds);
689 views::ViewModelUtils::SetViewBoundsToIdealBounds(*view_model_);
690 overflow_button_->SetBoundsRect(ideal_bounds.overflow_bounds);
693 void ShelfView::UpdateAllButtonsVisibilityInOverflowMode() {
694 // The overflow button is not shown in overflow mode.
695 overflow_button_->SetVisible(false);
696 DCHECK_LT(last_visible_index_, view_model_->view_size());
697 for (int i = 0; i < view_model_->view_size(); ++i) {
698 bool visible = i >= first_visible_index_ &&
699 i <= last_visible_index_;
700 // To track the dragging of |drag_view_| continuously, its visibility
701 // should be always true regardless of its position.
702 if (dragged_off_from_overflow_to_shelf_ &&
703 view_model_->view_at(i) == drag_view_)
704 view_model_->view_at(i)->SetVisible(true);
705 else
706 view_model_->view_at(i)->SetVisible(visible);
710 void ShelfView::CalculateIdealBounds(IdealBounds* bounds) const {
711 int available_size = layout_manager_->PrimaryAxisValue(width(), height());
712 DCHECK(model_->item_count() == view_model_->view_size());
713 if (!available_size)
714 return;
716 int first_panel_index = model_->FirstPanelIndex();
717 int last_button_index = first_panel_index - 1;
719 int x = 0;
720 int y = 0;
721 int button_size = kShelfButtonSize;
722 int button_spacing = kShelfButtonSpacing;
724 int w = layout_manager_->PrimaryAxisValue(button_size, width());
725 int h = layout_manager_->PrimaryAxisValue(height(), button_size);
726 for (int i = 0; i < view_model_->view_size(); ++i) {
727 if (i < first_visible_index_) {
728 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, 0, 0));
729 continue;
732 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
733 x = layout_manager_->PrimaryAxisValue(x + w + button_spacing, x);
734 y = layout_manager_->PrimaryAxisValue(y, y + h + button_spacing);
737 if (is_overflow_mode()) {
738 const_cast<ShelfView*>(this)->UpdateAllButtonsVisibilityInOverflowMode();
739 return;
742 // Right aligned icons.
743 int end_position = available_size - button_spacing;
744 x = layout_manager_->PrimaryAxisValue(end_position, 0);
745 y = layout_manager_->PrimaryAxisValue(0, end_position);
746 for (int i = view_model_->view_size() - 1;
747 i >= first_panel_index; --i) {
748 x = layout_manager_->PrimaryAxisValue(x - w - button_spacing, x);
749 y = layout_manager_->PrimaryAxisValue(y, y - h - button_spacing);
750 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
751 end_position = layout_manager_->PrimaryAxisValue(x, y);
754 // Icons on the left / top are guaranteed up to kLeftIconProportion of
755 // the available space.
756 int last_icon_position = layout_manager_->PrimaryAxisValue(
757 view_model_->ideal_bounds(last_button_index).right(),
758 view_model_->ideal_bounds(last_button_index).bottom()) + button_size;
759 int reserved_icon_space = available_size * kReservedNonPanelIconProportion;
760 if (last_icon_position < reserved_icon_space)
761 end_position = last_icon_position;
762 else
763 end_position = std::max(end_position, reserved_icon_space);
765 bounds->overflow_bounds.set_size(
766 gfx::Size(layout_manager_->PrimaryAxisValue(w, width()),
767 layout_manager_->PrimaryAxisValue(height(), h)));
769 last_visible_index_ = DetermineLastVisibleIndex(
770 end_position - button_size);
771 last_hidden_index_ = DetermineFirstVisiblePanelIndex(end_position) - 1;
772 bool show_overflow = last_visible_index_ < last_button_index ||
773 last_hidden_index_ >= first_panel_index;
775 // Create Space for the overflow button
776 if (show_overflow) {
777 // The following code makes sure that platform apps icons (aligned to left /
778 // top) are favored over panel apps icons (aligned to right / bottom).
779 if (last_visible_index_ > 0 && last_visible_index_ < last_button_index) {
780 // This condition means that we will take one platform app and replace it
781 // with the overflow button and put the app in the overflow bubble.
782 // This happens when the space needed for platform apps exceeds the
783 // reserved area for non-panel icons,
784 // (i.e. |last_icon_position| > |reserved_icon_space|).
785 --last_visible_index_;
786 } else if (last_hidden_index_ >= first_panel_index &&
787 last_hidden_index_ < view_model_->view_size() - 1) {
788 // This condition means that we will take a panel app icon and replace it
789 // with the overflow button.
790 // This happens when there is still room for platform apps in the reserved
791 // area for non-panel icons,
792 // (i.e. |last_icon_position| < |reserved_icon_space|).
793 ++last_hidden_index_;
797 for (int i = 0; i < view_model_->view_size(); ++i) {
798 bool visible = i <= last_visible_index_ || i > last_hidden_index_;
799 // To receive drag event continuously from |drag_view_| during the dragging
800 // off from the shelf, don't make |drag_view_| invisible. It will be
801 // eventually invisible and removed from the |view_model_| by
802 // FinalizeRipOffDrag().
803 if (dragged_off_shelf_ && view_model_->view_at(i) == drag_view_)
804 continue;
805 view_model_->view_at(i)->SetVisible(visible);
808 overflow_button_->SetVisible(show_overflow);
809 if (show_overflow) {
810 DCHECK_NE(0, view_model_->view_size());
811 if (last_visible_index_ == -1) {
812 x = 0;
813 y = 0;
814 } else {
815 x = layout_manager_->PrimaryAxisValue(
816 view_model_->ideal_bounds(last_visible_index_).right(),
817 view_model_->ideal_bounds(last_visible_index_).x());
818 y = layout_manager_->PrimaryAxisValue(
819 view_model_->ideal_bounds(last_visible_index_).y(),
820 view_model_->ideal_bounds(last_visible_index_).bottom());
822 // Set all hidden panel icon positions to be on the overflow button.
823 for (int i = first_panel_index; i <= last_hidden_index_; ++i)
824 view_model_->set_ideal_bounds(i, gfx::Rect(x, y, w, h));
826 // Add more space between last visible item and overflow button.
827 // Without this, two buttons look too close compared with other items.
828 x = layout_manager_->PrimaryAxisValue(x + button_spacing, x);
829 y = layout_manager_->PrimaryAxisValue(y, y + button_spacing);
831 bounds->overflow_bounds.set_x(x);
832 bounds->overflow_bounds.set_y(y);
833 if (overflow_bubble_.get() && overflow_bubble_->IsShowing())
834 UpdateOverflowRange(overflow_bubble_->shelf_view());
835 } else {
836 if (overflow_bubble_)
837 overflow_bubble_->Hide();
841 int ShelfView::DetermineLastVisibleIndex(int max_value) const {
842 int index = model_->FirstPanelIndex() - 1;
843 while (index >= 0 &&
844 layout_manager_->PrimaryAxisValue(
845 view_model_->ideal_bounds(index).right(),
846 view_model_->ideal_bounds(index).bottom()) > max_value) {
847 index--;
849 return index;
852 int ShelfView::DetermineFirstVisiblePanelIndex(int min_value) const {
853 int index = model_->FirstPanelIndex();
854 while (index < view_model_->view_size() &&
855 layout_manager_->PrimaryAxisValue(
856 view_model_->ideal_bounds(index).right(),
857 view_model_->ideal_bounds(index).bottom()) < min_value) {
858 ++index;
860 return index;
863 void ShelfView::AddIconObserver(ShelfIconObserver* observer) {
864 observers_.AddObserver(observer);
867 void ShelfView::RemoveIconObserver(ShelfIconObserver* observer) {
868 observers_.RemoveObserver(observer);
871 void ShelfView::AnimateToIdealBounds() {
872 IdealBounds ideal_bounds;
873 CalculateIdealBounds(&ideal_bounds);
874 for (int i = 0; i < view_model_->view_size(); ++i) {
875 View* view = view_model_->view_at(i);
876 bounds_animator_->AnimateViewTo(view, view_model_->ideal_bounds(i));
877 // Now that the item animation starts, we have to make sure that the
878 // padding of the first gets properly transferred to the new first item.
879 if (i && view->border())
880 view->SetBorder(views::Border::NullBorder());
882 overflow_button_->SetBoundsRect(ideal_bounds.overflow_bounds);
885 views::View* ShelfView::CreateViewForItem(const ShelfItem& item) {
886 views::View* view = NULL;
887 switch (item.type) {
888 case TYPE_BROWSER_SHORTCUT:
889 case TYPE_APP_SHORTCUT:
890 case TYPE_WINDOWED_APP:
891 case TYPE_PLATFORM_APP:
892 case TYPE_DIALOG:
893 case TYPE_APP_PANEL: {
894 ShelfButton* button = ShelfButton::Create(this, this, layout_manager_);
895 button->SetImage(item.image);
896 ReflectItemStatus(item, button);
897 view = button;
898 break;
901 case TYPE_APP_LIST: {
902 view = new AppListButton(this, this, layout_manager_->shelf_widget());
903 break;
906 default:
907 break;
909 view->set_context_menu_controller(this);
911 DCHECK(view);
912 ConfigureChildView(view);
913 return view;
916 void ShelfView::FadeIn(views::View* view) {
917 view->SetVisible(true);
918 view->layer()->SetOpacity(0);
919 AnimateToIdealBounds();
920 bounds_animator_->SetAnimationDelegate(
921 view,
922 scoped_ptr<gfx::AnimationDelegate>(new FadeInAnimationDelegate(view)));
925 void ShelfView::PrepareForDrag(Pointer pointer, const ui::LocatedEvent& event) {
926 DCHECK(!dragging());
927 DCHECK(drag_view_);
928 drag_pointer_ = pointer;
929 start_drag_index_ = view_model_->GetIndexOfView(drag_view_);
931 if (start_drag_index_== -1) {
932 CancelDrag(-1);
933 return;
936 // If the item is no longer draggable, bail out.
937 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
938 model_->items()[start_drag_index_].id);
939 if (!item_delegate->IsDraggable()) {
940 CancelDrag(-1);
941 return;
944 // Move the view to the front so that it appears on top of other views.
945 ReorderChildView(drag_view_, -1);
946 bounds_animator_->StopAnimatingView(drag_view_);
949 void ShelfView::ContinueDrag(const ui::LocatedEvent& event) {
950 // Due to a syncing operation the application might have been removed.
951 // Bail if it is gone.
952 int current_index = view_model_->GetIndexOfView(drag_view_);
953 DCHECK_NE(-1, current_index);
955 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
956 model_->items()[current_index].id);
957 if (!item_delegate->IsDraggable()) {
958 CancelDrag(-1);
959 return;
962 // If this is not a drag and drop host operation and not the app list item,
963 // check if the item got ripped off the shelf - if it did we are done.
964 if (!drag_and_drop_shelf_id_ &&
965 RemovableByRipOff(current_index) != NOT_REMOVABLE) {
966 if (HandleRipOffDrag(event))
967 return;
968 // The rip off handler could have changed the location of the item.
969 current_index = view_model_->GetIndexOfView(drag_view_);
972 // TODO: I don't think this works correctly with RTL.
973 gfx::Point drag_point(event.location());
974 ConvertPointToTarget(drag_view_, this, &drag_point);
976 // Constrain the location to the range of valid indices for the type.
977 std::pair<int, int> indices(GetDragRange(current_index));
978 int first_drag_index = indices.first;
979 int last_drag_index = indices.second;
980 // If the last index isn't valid, we're overflowing. Constrain to the app list
981 // (which is the last visible item).
982 if (first_drag_index < model_->FirstPanelIndex() &&
983 last_drag_index > last_visible_index_)
984 last_drag_index = last_visible_index_;
985 int x = 0, y = 0;
986 if (layout_manager_->IsHorizontalAlignment()) {
987 x = std::max(view_model_->ideal_bounds(indices.first).x(),
988 drag_point.x() - drag_origin_.x());
989 x = std::min(view_model_->ideal_bounds(last_drag_index).right() -
990 view_model_->ideal_bounds(current_index).width(),
992 if (drag_view_->x() == x)
993 return;
994 drag_view_->SetX(x);
995 } else {
996 y = std::max(view_model_->ideal_bounds(indices.first).y(),
997 drag_point.y() - drag_origin_.y());
998 y = std::min(view_model_->ideal_bounds(last_drag_index).bottom() -
999 view_model_->ideal_bounds(current_index).height(),
1001 if (drag_view_->y() == y)
1002 return;
1003 drag_view_->SetY(y);
1006 int target_index =
1007 views::ViewModelUtils::DetermineMoveIndex(
1008 *view_model_, drag_view_,
1009 layout_manager_->IsHorizontalAlignment() ?
1010 views::ViewModelUtils::HORIZONTAL :
1011 views::ViewModelUtils::VERTICAL,
1012 x, y);
1013 target_index =
1014 std::min(indices.second, std::max(target_index, indices.first));
1015 if (target_index == current_index)
1016 return;
1018 // Change the model, the ShelfItemMoved() callback will handle the
1019 // |view_model_| update.
1020 model_->Move(current_index, target_index);
1021 bounds_animator_->StopAnimatingView(drag_view_);
1024 bool ShelfView::HandleRipOffDrag(const ui::LocatedEvent& event) {
1025 int current_index = view_model_->GetIndexOfView(drag_view_);
1026 DCHECK_NE(-1, current_index);
1027 std::string dragged_app_id =
1028 delegate_->GetAppIDForShelfID(model_->items()[current_index].id);
1030 gfx::Point screen_location = event.root_location();
1031 ::wm::ConvertPointToScreen(GetWidget()->GetNativeWindow()->GetRootWindow(),
1032 &screen_location);
1034 // To avoid ugly forwards and backwards flipping we use different constants
1035 // for ripping off / re-inserting the items.
1036 if (dragged_off_shelf_) {
1037 // If the shelf/overflow bubble bounds contains |screen_location| we insert
1038 // the item back into the shelf.
1039 if (GetBoundsForDragInsertInScreen().Contains(screen_location)) {
1040 if (dragged_off_from_overflow_to_shelf_) {
1041 // During the dragging an item from Shelf to Overflow, it can enter here
1042 // directly because both are located very closly.
1043 main_shelf_->EndDrag(true);
1044 // Stops the animation of |drag_view_| and sets its bounds explicitly
1045 // becase ContinueDrag() stops its animation. Without this, unexpected
1046 // bounds will be set.
1047 bounds_animator_->StopAnimatingView(drag_view_);
1048 int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1049 drag_view_->SetBoundsRect(view_model_->ideal_bounds(drag_view_index));
1050 dragged_off_from_overflow_to_shelf_ = false;
1052 // Destroy our proxy view item.
1053 DestroyDragIconProxy();
1054 // Re-insert the item and return simply false since the caller will handle
1055 // the move as in any normal case.
1056 dragged_off_shelf_ = false;
1057 drag_view_->layer()->SetOpacity(1.0f);
1058 // The size of Overflow bubble should be updated immediately when an item
1059 // is re-inserted.
1060 if (is_overflow_mode())
1061 PreferredSizeChanged();
1062 return false;
1063 } else if (is_overflow_mode() &&
1064 main_shelf_->GetBoundsForDragInsertInScreen().Contains(
1065 screen_location)) {
1066 if (!dragged_off_from_overflow_to_shelf_) {
1067 dragged_off_from_overflow_to_shelf_ = true;
1068 drag_image_->SetOpacity(1.0f);
1069 main_shelf_->StartDrag(dragged_app_id, screen_location);
1070 } else {
1071 main_shelf_->Drag(screen_location);
1073 } else if (dragged_off_from_overflow_to_shelf_) {
1074 // Makes the |drag_image_| partially disappear again.
1075 dragged_off_from_overflow_to_shelf_ = false;
1076 drag_image_->SetOpacity(kDraggedImageOpacity);
1077 main_shelf_->EndDrag(true);
1078 bounds_animator_->StopAnimatingView(drag_view_);
1079 int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1080 drag_view_->SetBoundsRect(view_model_->ideal_bounds(drag_view_index));
1082 // Move our proxy view item.
1083 UpdateDragIconProxy(screen_location);
1084 return true;
1086 // Check if we are too far away from the shelf to enter the ripped off state.
1087 // Determine the distance to the shelf.
1088 int delta = CalculateShelfDistance(screen_location);
1089 if (delta > kRipOffDistance) {
1090 // Create a proxy view item which can be moved anywhere.
1091 CreateDragIconProxy(event.root_location(),
1092 drag_view_->GetImage(),
1093 drag_view_,
1094 gfx::Vector2d(0, 0),
1095 kDragAndDropProxyScale);
1096 drag_view_->layer()->SetOpacity(0.0f);
1097 dragged_off_shelf_ = true;
1098 if (RemovableByRipOff(current_index) == REMOVABLE) {
1099 // Move the item to the front of the first panel item and hide it.
1100 // ShelfItemMoved() callback will handle the |view_model_| update and
1101 // call AnimateToIdealBounds().
1102 if (current_index != model_->FirstPanelIndex() - 1) {
1103 model_->Move(current_index, model_->FirstPanelIndex() - 1);
1104 StartFadeInLastVisibleItem();
1105 } else if (is_overflow_mode()) {
1106 // Overflow bubble should be shrunk when an item is ripped off.
1107 PreferredSizeChanged();
1109 // Make the item partially disappear to show that it will get removed if
1110 // dropped.
1111 drag_image_->SetOpacity(kDraggedImageOpacity);
1113 return true;
1115 return false;
1118 void ShelfView::FinalizeRipOffDrag(bool cancel) {
1119 if (!dragged_off_shelf_)
1120 return;
1121 // Make sure we do not come in here again.
1122 dragged_off_shelf_ = false;
1124 // Coming here we should always have a |drag_view_|.
1125 DCHECK(drag_view_);
1126 int current_index = view_model_->GetIndexOfView(drag_view_);
1127 // If the view isn't part of the model anymore (|current_index| == -1), a sync
1128 // operation must have removed it. In that case we shouldn't change the model
1129 // and only delete the proxy image.
1130 if (current_index == -1) {
1131 DestroyDragIconProxy();
1132 return;
1135 // Set to true when the animation should snap back to where it was before.
1136 bool snap_back = false;
1137 // Items which cannot be dragged off will be handled as a cancel.
1138 if (!cancel) {
1139 if (dragged_off_from_overflow_to_shelf_) {
1140 dragged_off_from_overflow_to_shelf_ = false;
1141 main_shelf_->EndDrag(false);
1142 drag_view_->layer()->SetOpacity(1.0f);
1143 } else if (RemovableByRipOff(current_index) != REMOVABLE) {
1144 // Make sure we do not try to remove un-removable items like items which
1145 // were not pinned or have to be always there.
1146 cancel = true;
1147 snap_back = true;
1148 } else {
1149 // Make sure the item stays invisible upon removal.
1150 drag_view_->SetVisible(false);
1151 std::string app_id =
1152 delegate_->GetAppIDForShelfID(model_->items()[current_index].id);
1153 delegate_->UnpinAppWithID(app_id);
1156 if (cancel || snap_back) {
1157 if (dragged_off_from_overflow_to_shelf_) {
1158 dragged_off_from_overflow_to_shelf_ = false;
1159 // Main shelf handles revert of dragged item.
1160 main_shelf_->EndDrag(true);
1161 drag_view_->layer()->SetOpacity(1.0f);
1162 } else if (!cancelling_drag_model_changed_) {
1163 // Only do something if the change did not come through a model change.
1164 gfx::Rect drag_bounds = drag_image_->GetBoundsInScreen();
1165 gfx::Point relative_to = GetBoundsInScreen().origin();
1166 gfx::Rect target(
1167 gfx::PointAtOffsetFromOrigin(drag_bounds.origin()- relative_to),
1168 drag_bounds.size());
1169 drag_view_->SetBoundsRect(target);
1170 // Hide the status from the active item since we snap it back now. Upon
1171 // animation end the flag gets cleared if |snap_back_from_rip_off_view_|
1172 // is set.
1173 snap_back_from_rip_off_view_ = drag_view_;
1174 drag_view_->AddState(ShelfButton::STATE_HIDDEN);
1175 // When a canceling drag model is happening, the view model is diverged
1176 // from the menu model and movements / animations should not be done.
1177 model_->Move(current_index, start_drag_index_);
1178 AnimateToIdealBounds();
1180 drag_view_->layer()->SetOpacity(1.0f);
1182 DestroyDragIconProxy();
1185 ShelfView::RemovableState ShelfView::RemovableByRipOff(int index) const {
1186 DCHECK(index >= 0 && index < model_->item_count());
1187 ShelfItemType type = model_->items()[index].type;
1188 if (type == TYPE_APP_LIST || type == TYPE_DIALOG || !delegate_->CanPin())
1189 return NOT_REMOVABLE;
1191 std::string app_id = delegate_->GetAppIDForShelfID(model_->items()[index].id);
1192 // Note: Only pinned app shortcuts can be removed!
1193 return (type == TYPE_APP_SHORTCUT && delegate_->IsAppPinned(app_id)) ?
1194 REMOVABLE : DRAGGABLE;
1197 bool ShelfView::SameDragType(ShelfItemType typea, ShelfItemType typeb) const {
1198 switch (typea) {
1199 case TYPE_APP_SHORTCUT:
1200 case TYPE_BROWSER_SHORTCUT:
1201 return (typeb == TYPE_APP_SHORTCUT || typeb == TYPE_BROWSER_SHORTCUT);
1202 case TYPE_APP_LIST:
1203 case TYPE_PLATFORM_APP:
1204 case TYPE_WINDOWED_APP:
1205 case TYPE_APP_PANEL:
1206 case TYPE_DIALOG:
1207 return typeb == typea;
1208 case TYPE_UNDEFINED:
1209 NOTREACHED() << "ShelfItemType must be set.";
1210 return false;
1212 NOTREACHED();
1213 return false;
1216 std::pair<int, int> ShelfView::GetDragRange(int index) {
1217 int min_index = -1;
1218 int max_index = -1;
1219 ShelfItemType type = model_->items()[index].type;
1220 for (int i = 0; i < model_->item_count(); ++i) {
1221 if (SameDragType(model_->items()[i].type, type)) {
1222 if (min_index == -1)
1223 min_index = i;
1224 max_index = i;
1227 return std::pair<int, int>(min_index, max_index);
1230 void ShelfView::ConfigureChildView(views::View* view) {
1231 view->SetPaintToLayer(true);
1232 view->layer()->SetFillsBoundsOpaquely(false);
1235 void ShelfView::ToggleOverflowBubble() {
1236 if (IsShowingOverflowBubble()) {
1237 overflow_bubble_->Hide();
1238 return;
1241 if (!overflow_bubble_)
1242 overflow_bubble_.reset(new OverflowBubble());
1244 ShelfView* overflow_view =
1245 new ShelfView(model_, delegate_, layout_manager_);
1246 overflow_view->overflow_mode_ = true;
1247 overflow_view->Init();
1248 overflow_view->set_owner_overflow_bubble(overflow_bubble_.get());
1249 overflow_view->OnShelfAlignmentChanged();
1250 overflow_view->main_shelf_ = this;
1251 UpdateOverflowRange(overflow_view);
1253 overflow_bubble_->Show(overflow_button_, overflow_view);
1255 Shell::GetInstance()->UpdateShelfVisibility();
1258 void ShelfView::OnFadeOutAnimationEnded() {
1259 AnimateToIdealBounds();
1260 StartFadeInLastVisibleItem();
1263 void ShelfView::StartFadeInLastVisibleItem() {
1264 // If overflow button is visible and there is a valid new last item, fading
1265 // the new last item in after sliding animation is finished.
1266 if (overflow_button_->visible() && last_visible_index_ >= 0) {
1267 views::View* last_visible_view = view_model_->view_at(last_visible_index_);
1268 last_visible_view->layer()->SetOpacity(0);
1269 bounds_animator_->SetAnimationDelegate(
1270 last_visible_view,
1271 scoped_ptr<gfx::AnimationDelegate>(
1272 new StartFadeAnimationDelegate(this, last_visible_view)));
1276 void ShelfView::UpdateOverflowRange(ShelfView* overflow_view) const {
1277 const int first_overflow_index = last_visible_index_ + 1;
1278 const int last_overflow_index = last_hidden_index_;
1279 DCHECK_LE(first_overflow_index, last_overflow_index);
1280 DCHECK_LT(last_overflow_index, view_model_->view_size());
1282 overflow_view->first_visible_index_ = first_overflow_index;
1283 overflow_view->last_visible_index_ = last_overflow_index;
1286 bool ShelfView::ShouldHideTooltip(const gfx::Point& cursor_location) {
1287 gfx::Rect active_bounds;
1289 for (int i = 0; i < child_count(); ++i) {
1290 views::View* child = child_at(i);
1291 if (child == overflow_button_)
1292 continue;
1293 if (!ShouldShowTooltipForView(child))
1294 continue;
1296 gfx::Rect child_bounds = child->GetMirroredBounds();
1297 active_bounds.Union(child_bounds);
1300 return !active_bounds.Contains(cursor_location);
1303 gfx::Rect ShelfView::GetVisibleItemsBoundsInScreen() {
1304 gfx::Size preferred_size = GetPreferredSize();
1305 gfx::Point origin(GetMirroredXWithWidthInView(0, preferred_size.width()), 0);
1306 ConvertPointToScreen(this, &origin);
1307 return gfx::Rect(origin, preferred_size);
1310 gfx::Rect ShelfView::GetBoundsForDragInsertInScreen() {
1311 gfx::Size preferred_size;
1312 if (is_overflow_mode()) {
1313 DCHECK(owner_overflow_bubble_);
1314 gfx::Rect bubble_bounds =
1315 owner_overflow_bubble_->bubble_view()->GetBubbleBounds();
1316 preferred_size = bubble_bounds.size();
1317 } else {
1318 const int last_button_index = view_model_->view_size() - 1;
1319 gfx::Rect last_button_bounds =
1320 view_model_->view_at(last_button_index)->bounds();
1321 if (overflow_button_->visible() &&
1322 model_->GetItemIndexForType(TYPE_APP_PANEL) == -1) {
1323 // When overflow button is visible and shelf has no panel items,
1324 // last_button_bounds should be overflow button's bounds.
1325 last_button_bounds = overflow_button_->bounds();
1328 if (layout_manager_->IsHorizontalAlignment()) {
1329 preferred_size = gfx::Size(last_button_bounds.right() + leading_inset_,
1330 kShelfSize);
1331 } else {
1332 preferred_size = gfx::Size(kShelfSize,
1333 last_button_bounds.bottom() + leading_inset_);
1336 gfx::Point origin(GetMirroredXWithWidthInView(0, preferred_size.width()), 0);
1338 // In overflow mode, we should use OverflowBubbleView as a source for
1339 // converting |origin| to screen coordinates. When a scroll operation is
1340 // occurred in OverflowBubble, the bounds of ShelfView in OverflowBubble can
1341 // be changed.
1342 if (is_overflow_mode())
1343 ConvertPointToScreen(owner_overflow_bubble_->bubble_view(), &origin);
1344 else
1345 ConvertPointToScreen(this, &origin);
1347 return gfx::Rect(origin, preferred_size);
1350 int ShelfView::CancelDrag(int modified_index) {
1351 FinalizeRipOffDrag(true);
1352 if (!drag_view_)
1353 return modified_index;
1354 bool was_dragging = dragging();
1355 int drag_view_index = view_model_->GetIndexOfView(drag_view_);
1356 drag_pointer_ = NONE;
1357 drag_view_ = NULL;
1358 if (drag_view_index == modified_index) {
1359 // The view that was being dragged is being modified. Don't do anything.
1360 return modified_index;
1362 if (!was_dragging)
1363 return modified_index;
1365 // Restore previous position, tracking the position of the modified view.
1366 bool at_end = modified_index == view_model_->view_size();
1367 views::View* modified_view =
1368 (modified_index >= 0 && !at_end) ?
1369 view_model_->view_at(modified_index) : NULL;
1370 model_->Move(drag_view_index, start_drag_index_);
1372 // If the modified view will be at the end of the list, return the new end of
1373 // the list.
1374 if (at_end)
1375 return view_model_->view_size();
1376 return modified_view ? view_model_->GetIndexOfView(modified_view) : -1;
1379 gfx::Size ShelfView::GetPreferredSize() const {
1380 IdealBounds ideal_bounds;
1381 CalculateIdealBounds(&ideal_bounds);
1383 int last_button_index = is_overflow_mode() ?
1384 last_visible_index_ : view_model_->view_size() - 1;
1386 // When an item is dragged off from the overflow bubble, it is moved to last
1387 // position and and changed to invisible. Overflow bubble size should be
1388 // shrunk to fit only for visible items.
1389 // If |dragged_off_from_overflow_to_shelf_| is set, there will be no invisible
1390 // items in the shelf.
1391 if (is_overflow_mode() &&
1392 dragged_off_shelf_ &&
1393 !dragged_off_from_overflow_to_shelf_ &&
1394 RemovableByRipOff(view_model_->GetIndexOfView(drag_view_)) == REMOVABLE)
1395 last_button_index--;
1397 const gfx::Rect last_button_bounds =
1398 last_button_index >= first_visible_index_ ?
1399 view_model_->ideal_bounds(last_button_index) :
1400 gfx::Rect(gfx::Size(kShelfSize, kShelfSize));
1402 if (layout_manager_->IsHorizontalAlignment()) {
1403 return gfx::Size(last_button_bounds.right() + leading_inset_, kShelfSize);
1406 return gfx::Size(kShelfSize,
1407 last_button_bounds.bottom() + leading_inset_);
1410 void ShelfView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
1411 // This bounds change is produced by the shelf movement and all content has
1412 // to follow. Using an animation at that time would produce a time lag since
1413 // the animation of the BoundsAnimator has itself a delay before it arrives
1414 // at the required location. As such we tell the animator to go there
1415 // immediately.
1416 BoundsAnimatorDisabler disabler(bounds_animator_.get());
1417 LayoutToIdealBounds();
1418 FOR_EACH_OBSERVER(ShelfIconObserver, observers_,
1419 OnShelfIconPositionsChanged());
1421 if (IsShowingOverflowBubble())
1422 overflow_bubble_->Hide();
1425 views::FocusTraversable* ShelfView::GetPaneFocusTraversable() {
1426 return this;
1429 void ShelfView::GetAccessibleState(ui::AXViewState* state) {
1430 state->role = ui::AX_ROLE_TOOLBAR;
1431 state->name = l10n_util::GetStringUTF16(IDS_ASH_SHELF_ACCESSIBLE_NAME);
1434 void ShelfView::OnGestureEvent(ui::GestureEvent* event) {
1435 aura::Window* target_window = static_cast<views::View*>(event->target())
1436 ->GetWidget()
1437 ->GetNativeWindow();
1438 if (gesture_handler_.ProcessGestureEvent(*event, target_window))
1439 event->StopPropagation();
1442 void ShelfView::ShelfItemAdded(int model_index) {
1444 base::AutoReset<bool> cancelling_drag(
1445 &cancelling_drag_model_changed_, true);
1446 model_index = CancelDrag(model_index);
1448 views::View* view = CreateViewForItem(model_->items()[model_index]);
1449 AddChildView(view);
1450 // Hide the view, it'll be made visible when the animation is done. Using
1451 // opacity 0 here to avoid messing with CalculateIdealBounds which touches
1452 // the view's visibility.
1453 view->layer()->SetOpacity(0);
1454 view_model_->Add(view, model_index);
1456 // Give the button its ideal bounds. That way if we end up animating the
1457 // button before this animation completes it doesn't appear at some random
1458 // spot (because it was in the middle of animating from 0,0 0x0 to its
1459 // target).
1460 IdealBounds ideal_bounds;
1461 CalculateIdealBounds(&ideal_bounds);
1462 view->SetBoundsRect(view_model_->ideal_bounds(model_index));
1464 // The first animation moves all the views to their target position. |view|
1465 // is hidden, so it visually appears as though we are providing space for
1466 // it. When done we'll fade the view in.
1467 AnimateToIdealBounds();
1468 if (model_index <= last_visible_index_ ||
1469 model_index >= model_->FirstPanelIndex()) {
1470 bounds_animator_->SetAnimationDelegate(
1471 view,
1472 scoped_ptr<gfx::AnimationDelegate>(
1473 new StartFadeAnimationDelegate(this, view)));
1474 } else {
1475 // Undo the hiding if animation does not run.
1476 view->layer()->SetOpacity(1.0f);
1480 void ShelfView::ShelfItemRemoved(int model_index, ShelfID id) {
1481 if (id == context_menu_id_)
1482 launcher_menu_runner_.reset();
1484 base::AutoReset<bool> cancelling_drag(
1485 &cancelling_drag_model_changed_, true);
1486 model_index = CancelDrag(model_index);
1488 views::View* view = view_model_->view_at(model_index);
1489 view_model_->Remove(model_index);
1491 // When the overflow bubble is visible, the overflow range needs to be set
1492 // before CalculateIdealBounds() gets called. Otherwise CalculateIdealBounds()
1493 // could trigger a ShelfItemChanged() by hiding the overflow bubble and
1494 // since the overflow bubble is not yet synced with the ShelfModel this
1495 // could cause a crash.
1496 if (overflow_bubble_ && overflow_bubble_->IsShowing()) {
1497 last_hidden_index_ = std::min(last_hidden_index_,
1498 view_model_->view_size() - 1);
1499 UpdateOverflowRange(overflow_bubble_->shelf_view());
1502 if (view->visible()) {
1503 // The first animation fades out the view. When done we'll animate the rest
1504 // of the views to their target location.
1505 bounds_animator_->AnimateViewTo(view, view->bounds());
1506 bounds_animator_->SetAnimationDelegate(
1507 view,
1508 scoped_ptr<gfx::AnimationDelegate>(
1509 new FadeOutAnimationDelegate(this, view)));
1510 } else {
1511 // We don't need to show a fade out animation for invisible |view|. When an
1512 // item is ripped out from the shelf, its |view| is already invisible.
1513 AnimateToIdealBounds();
1516 // Close the tooltip because it isn't needed any longer and its anchor view
1517 // will be deleted soon.
1518 if (tooltip_->GetCurrentAnchorView() == view)
1519 tooltip_->Close();
1522 void ShelfView::ShelfItemChanged(int model_index, const ShelfItem& old_item) {
1523 const ShelfItem& item(model_->items()[model_index]);
1524 if (old_item.type != item.type) {
1525 // Type changed, swap the views.
1526 model_index = CancelDrag(model_index);
1527 scoped_ptr<views::View> old_view(view_model_->view_at(model_index));
1528 bounds_animator_->StopAnimatingView(old_view.get());
1529 // Removing and re-inserting a view in our view model will strip the ideal
1530 // bounds from the item. To avoid recalculation of everything the bounds
1531 // get remembered and restored after the insertion to the previous value.
1532 gfx::Rect old_ideal_bounds = view_model_->ideal_bounds(model_index);
1533 view_model_->Remove(model_index);
1534 views::View* new_view = CreateViewForItem(item);
1535 AddChildView(new_view);
1536 view_model_->Add(new_view, model_index);
1537 view_model_->set_ideal_bounds(model_index, old_ideal_bounds);
1538 new_view->SetBoundsRect(old_view->bounds());
1539 return;
1542 views::View* view = view_model_->view_at(model_index);
1543 switch (item.type) {
1544 case TYPE_BROWSER_SHORTCUT:
1545 // Fallthrough for the new Shelf since it needs to show the activation
1546 // change as well.
1547 case TYPE_APP_SHORTCUT:
1548 case TYPE_WINDOWED_APP:
1549 case TYPE_PLATFORM_APP:
1550 case TYPE_DIALOG:
1551 case TYPE_APP_PANEL: {
1552 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
1553 ShelfButton* button = static_cast<ShelfButton*>(view);
1554 ReflectItemStatus(item, button);
1555 // The browser shortcut is currently not a "real" item and as such the
1556 // the image is bogous as well. We therefore keep the image as is for it.
1557 if (item.type != TYPE_BROWSER_SHORTCUT)
1558 button->SetImage(item.image);
1559 button->SchedulePaint();
1560 break;
1563 default:
1564 break;
1568 void ShelfView::ShelfItemMoved(int start_index, int target_index) {
1569 view_model_->Move(start_index, target_index);
1570 // When cancelling a drag due to a shelf item being added, the currently
1571 // dragged item is moved back to its initial position. AnimateToIdealBounds
1572 // will be called again when the new item is added to the |view_model_| but
1573 // at this time the |view_model_| is inconsistent with the |model_|.
1574 if (!cancelling_drag_model_changed_)
1575 AnimateToIdealBounds();
1578 void ShelfView::ShelfStatusChanged() {
1579 // Nothing to do here.
1582 void ShelfView::PointerPressedOnButton(views::View* view,
1583 Pointer pointer,
1584 const ui::LocatedEvent& event) {
1585 if (drag_view_)
1586 return;
1588 int index = view_model_->GetIndexOfView(view);
1589 if (index == -1)
1590 return;
1592 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1593 model_->items()[index].id);
1594 if (view_model_->view_size() <= 1 || !item_delegate->IsDraggable())
1595 return; // View is being deleted or not draggable, ignore request.
1597 // Only when the repost event occurs on the same shelf item, we should ignore
1598 // the call in ShelfView::ButtonPressed(...).
1599 is_repost_event_ = IsRepostEvent(event) && (last_pressed_index_ == index);
1601 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
1602 drag_view_ = static_cast<ShelfButton*>(view);
1603 drag_origin_ = gfx::Point(event.x(), event.y());
1604 UMA_HISTOGRAM_ENUMERATION("Ash.ShelfAlignmentUsage",
1605 layout_manager_->SelectValueForShelfAlignment(
1606 SHELF_ALIGNMENT_UMA_ENUM_VALUE_BOTTOM,
1607 SHELF_ALIGNMENT_UMA_ENUM_VALUE_LEFT,
1608 SHELF_ALIGNMENT_UMA_ENUM_VALUE_RIGHT,
1609 -1),
1610 SHELF_ALIGNMENT_UMA_ENUM_VALUE_COUNT);
1613 void ShelfView::PointerDraggedOnButton(views::View* view,
1614 Pointer pointer,
1615 const ui::LocatedEvent& event) {
1616 // To prepare all drag types (moving an item in the shelf and dragging off),
1617 // we should check the x-axis and y-axis offset.
1618 if (!dragging() && drag_view_ &&
1619 ((std::abs(event.x() - drag_origin_.x()) >= kMinimumDragDistance) ||
1620 (std::abs(event.y() - drag_origin_.y()) >= kMinimumDragDistance))) {
1621 PrepareForDrag(pointer, event);
1623 if (drag_pointer_ == pointer)
1624 ContinueDrag(event);
1627 void ShelfView::PointerReleasedOnButton(views::View* view,
1628 Pointer pointer,
1629 bool canceled) {
1630 // Reset |is_repost_event| to false.
1631 is_repost_event_ = false;
1633 if (canceled) {
1634 CancelDrag(-1);
1635 } else if (drag_pointer_ == pointer) {
1636 FinalizeRipOffDrag(false);
1637 drag_pointer_ = NONE;
1638 AnimateToIdealBounds();
1640 // If the drag pointer is NONE, no drag operation is going on and the
1641 // drag_view can be released.
1642 if (drag_pointer_ == NONE)
1643 drag_view_ = NULL;
1646 void ShelfView::MouseMovedOverButton(views::View* view) {
1647 if (!ShouldShowTooltipForView(view))
1648 return;
1650 if (!tooltip_->IsVisible())
1651 tooltip_->ResetTimer();
1654 void ShelfView::MouseEnteredButton(views::View* view) {
1655 if (!ShouldShowTooltipForView(view))
1656 return;
1658 if (tooltip_->IsVisible()) {
1659 tooltip_->ShowImmediately(view, GetAccessibleName(view));
1660 } else {
1661 tooltip_->ShowDelayed(view, GetAccessibleName(view));
1665 void ShelfView::MouseExitedButton(views::View* view) {
1666 if (!tooltip_->IsVisible())
1667 tooltip_->StopTimer();
1670 base::string16 ShelfView::GetAccessibleName(const views::View* view) {
1671 int view_index = view_model_->GetIndexOfView(view);
1672 // May be -1 while in the process of animating closed.
1673 if (view_index == -1)
1674 return base::string16();
1676 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1677 model_->items()[view_index].id);
1678 return item_delegate->GetTitle();
1681 void ShelfView::ButtonPressed(views::Button* sender, const ui::Event& event) {
1682 // Do not handle mouse release during drag.
1683 if (dragging())
1684 return;
1686 if (sender == overflow_button_) {
1687 ToggleOverflowBubble();
1688 RecordIconActivatedSource(event);
1689 return;
1692 int view_index = view_model_->GetIndexOfView(sender);
1693 // May be -1 while in the process of animating closed.
1694 if (view_index == -1)
1695 return;
1697 // If the menu was just closed by the same event as this one, we ignore
1698 // the call and don't open the menu again. See crbug.com/343005 for more
1699 // detail.
1700 if (is_repost_event_)
1701 return;
1703 // Record the index for the last pressed shelf item.
1704 last_pressed_index_ = view_index;
1706 // Don't activate the item twice on double-click. Otherwise the window starts
1707 // animating open due to the first click, then immediately minimizes due to
1708 // the second click. The user most likely intended to open or minimize the
1709 // item once, not do both.
1710 if (event.flags() & ui::EF_IS_DOUBLE_CLICK)
1711 return;
1714 ScopedTargetRootWindow scoped_target(
1715 sender->GetWidget()->GetNativeView()->GetRootWindow());
1716 // Slow down activation animations if shift key is pressed.
1717 scoped_ptr<ui::ScopedAnimationDurationScaleMode> slowing_animations;
1718 if (event.IsShiftDown()) {
1719 slowing_animations.reset(new ui::ScopedAnimationDurationScaleMode(
1720 ui::ScopedAnimationDurationScaleMode::SLOW_DURATION));
1723 // Collect usage statistics before we decide what to do with the click.
1724 switch (model_->items()[view_index].type) {
1725 case TYPE_APP_SHORTCUT:
1726 case TYPE_WINDOWED_APP:
1727 case TYPE_PLATFORM_APP:
1728 case TYPE_BROWSER_SHORTCUT:
1729 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1730 UMA_LAUNCHER_CLICK_ON_APP);
1731 break;
1733 case TYPE_APP_LIST:
1734 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1735 UMA_LAUNCHER_CLICK_ON_APPLIST_BUTTON);
1736 break;
1738 case TYPE_APP_PANEL:
1739 case TYPE_DIALOG:
1740 break;
1742 case TYPE_UNDEFINED:
1743 NOTREACHED() << "ShelfItemType must be set.";
1744 break;
1747 RecordIconActivatedSource(event);
1749 ShelfItemDelegate::PerformedAction performed_action =
1750 item_manager_->GetShelfItemDelegate(model_->items()[view_index].id)
1751 ->ItemSelected(event);
1753 RecordIconActivatedAction(performed_action);
1755 if (performed_action != ShelfItemDelegate::kNewWindowCreated)
1756 ShowListMenuForView(model_->items()[view_index], sender, event);
1760 void ShelfView::RecordIconActivatedSource(const ui::Event& event) {
1761 if (event.IsMouseEvent()) {
1762 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1763 UMA_LAUNCHER_BUTTON_PRESSED_WITH_MOUSE);
1764 } else if (event.IsGestureEvent()) {
1765 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1766 UMA_LAUNCHER_BUTTON_PRESSED_WITH_TOUCH);
1770 void ShelfView::RecordIconActivatedAction(
1771 ShelfItemDelegate::PerformedAction performed_action) {
1772 switch (performed_action) {
1773 case ShelfItemDelegate::kNoAction:
1774 case ShelfItemDelegate::kAppListMenuShown:
1775 break;
1776 case ShelfItemDelegate::kNewWindowCreated:
1777 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1778 UMA_LAUNCHER_LAUNCH_TASK);
1779 break;
1780 case ShelfItemDelegate::kExistingWindowActivated:
1781 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1782 UMA_LAUNCHER_SWITCH_TASK);
1783 break;
1784 case ShelfItemDelegate::kExistingWindowMinimized:
1785 Shell::GetInstance()->metrics()->RecordUserMetricsAction(
1786 UMA_LAUNCHER_MINIMIZE_TASK);
1787 break;
1791 bool ShelfView::ShowListMenuForView(const ShelfItem& item,
1792 views::View* source,
1793 const ui::Event& event) {
1794 ShelfItemDelegate* item_delegate =
1795 item_manager_->GetShelfItemDelegate(item.id);
1796 scoped_ptr<ui::MenuModel> list_menu_model(
1797 item_delegate->CreateApplicationMenu(event.flags()));
1799 // Make sure we have a menu and it has at least two items in addition to the
1800 // application title and the 3 spacing separators.
1801 if (!list_menu_model.get() || list_menu_model->GetItemCount() <= 5)
1802 return false;
1804 ShowMenu(list_menu_model.get(),
1805 source,
1806 gfx::Point(),
1807 false,
1808 ui::GetMenuSourceTypeForEvent(event));
1809 return true;
1812 void ShelfView::ShowContextMenuForView(views::View* source,
1813 const gfx::Point& point,
1814 ui::MenuSourceType source_type) {
1815 int view_index = view_model_->GetIndexOfView(source);
1816 if (view_index == -1) {
1817 Shell::GetInstance()->ShowContextMenu(point, source_type);
1818 return;
1821 ShelfItemDelegate* item_delegate = item_manager_->GetShelfItemDelegate(
1822 model_->items()[view_index].id);
1823 context_menu_model_.reset(item_delegate->CreateContextMenu(
1824 source->GetWidget()->GetNativeView()->GetRootWindow()));
1825 if (!context_menu_model_)
1826 return;
1828 base::AutoReset<ShelfID> reseter(
1829 &context_menu_id_,
1830 view_index == -1 ? 0 : model_->items()[view_index].id);
1832 ShowMenu(context_menu_model_.get(),
1833 source,
1834 point,
1835 true,
1836 source_type);
1839 void ShelfView::ShowMenu(ui::MenuModel* menu_model,
1840 views::View* source,
1841 const gfx::Point& click_point,
1842 bool context_menu,
1843 ui::MenuSourceType source_type) {
1844 closing_event_time_ = base::TimeDelta();
1845 launcher_menu_runner_.reset(new views::MenuRunner(
1846 menu_model, context_menu ? views::MenuRunner::CONTEXT_MENU : 0));
1848 ScopedTargetRootWindow scoped_target(
1849 source->GetWidget()->GetNativeView()->GetRootWindow());
1851 // Determine the menu alignment dependent on the shelf.
1852 views::MenuAnchorPosition menu_alignment = views::MENU_ANCHOR_TOPLEFT;
1853 gfx::Rect anchor_point = gfx::Rect(click_point, gfx::Size());
1855 ShelfWidget* shelf = RootWindowController::ForShelf(
1856 GetWidget()->GetNativeView())->shelf();
1857 if (!context_menu) {
1858 // Application lists use a bubble.
1859 ShelfAlignment align = shelf->GetAlignment();
1860 anchor_point = source->GetBoundsInScreen();
1862 // It is possible to invoke the menu while it is sliding into view. To cover
1863 // that case, the screen coordinates are offsetted by the animation delta.
1864 gfx::Vector2d offset =
1865 source->GetWidget()->GetNativeWindow()->bounds().origin() -
1866 source->GetWidget()->GetNativeWindow()->GetTargetBounds().origin();
1867 anchor_point.set_x(anchor_point.x() - offset.x());
1868 anchor_point.set_y(anchor_point.y() - offset.y());
1870 // Shelf items can have an asymmetrical border for spacing reasons.
1871 // Adjust anchor location for this.
1872 if (source->border())
1873 anchor_point.Inset(source->border()->GetInsets());
1875 switch (align) {
1876 case SHELF_ALIGNMENT_BOTTOM:
1877 menu_alignment = views::MENU_ANCHOR_BUBBLE_ABOVE;
1878 break;
1879 case SHELF_ALIGNMENT_LEFT:
1880 menu_alignment = views::MENU_ANCHOR_BUBBLE_RIGHT;
1881 break;
1882 case SHELF_ALIGNMENT_RIGHT:
1883 menu_alignment = views::MENU_ANCHOR_BUBBLE_LEFT;
1884 break;
1885 case SHELF_ALIGNMENT_TOP:
1886 menu_alignment = views::MENU_ANCHOR_BUBBLE_BELOW;
1887 break;
1890 // If this gets deleted while we are in the menu, the shelf will be gone
1891 // as well.
1892 bool got_deleted = false;
1893 got_deleted_ = &got_deleted;
1895 shelf->ForceUndimming(true);
1896 // NOTE: if you convert to HAS_MNEMONICS be sure and update menu building
1897 // code.
1898 if (launcher_menu_runner_->RunMenuAt(source->GetWidget(),
1899 NULL,
1900 anchor_point,
1901 menu_alignment,
1902 source_type) ==
1903 views::MenuRunner::MENU_DELETED) {
1904 if (!got_deleted) {
1905 got_deleted_ = NULL;
1906 shelf->ForceUndimming(false);
1908 return;
1910 got_deleted_ = NULL;
1911 shelf->ForceUndimming(false);
1913 // If it is a context menu and we are showing overflow bubble
1914 // we want to hide overflow bubble.
1915 if (owner_overflow_bubble_)
1916 owner_overflow_bubble_->HideBubbleAndRefreshButton();
1918 // Unpinning an item will reset the |launcher_menu_runner_| before coming
1919 // here.
1920 if (launcher_menu_runner_)
1921 closing_event_time_ = launcher_menu_runner_->closing_event_time();
1922 Shell::GetInstance()->UpdateShelfVisibility();
1925 void ShelfView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) {
1926 FOR_EACH_OBSERVER(ShelfIconObserver, observers_,
1927 OnShelfIconPositionsChanged());
1928 PreferredSizeChanged();
1931 void ShelfView::OnBoundsAnimatorDone(views::BoundsAnimator* animator) {
1932 if (snap_back_from_rip_off_view_ && animator == bounds_animator_) {
1933 if (!animator->IsAnimating(snap_back_from_rip_off_view_)) {
1934 // Coming here the animation of the ShelfButton is finished and the
1935 // previously hidden status can be shown again. Since the button itself
1936 // might have gone away or changed locations we check that the button
1937 // is still in the shelf and show its status again.
1938 for (int index = 0; index < view_model_->view_size(); index++) {
1939 views::View* view = view_model_->view_at(index);
1940 if (view == snap_back_from_rip_off_view_) {
1941 CHECK_EQ(ShelfButton::kViewClassName, view->GetClassName());
1942 ShelfButton* button = static_cast<ShelfButton*>(view);
1943 button->ClearState(ShelfButton::STATE_HIDDEN);
1944 break;
1947 snap_back_from_rip_off_view_ = NULL;
1952 bool ShelfView::IsRepostEvent(const ui::Event& event) {
1953 if (closing_event_time_ == base::TimeDelta())
1954 return false;
1956 base::TimeDelta delta =
1957 base::TimeDelta(event.time_stamp() - closing_event_time_);
1958 closing_event_time_ = base::TimeDelta();
1959 // If the current (press down) event is a repost event, the time stamp of
1960 // these two events should be the same.
1961 return (delta.InMilliseconds() == 0);
1964 const ShelfItem* ShelfView::ShelfItemForView(const views::View* view) const {
1965 int view_index = view_model_->GetIndexOfView(view);
1966 if (view_index == -1)
1967 return NULL;
1968 return &(model_->items()[view_index]);
1971 bool ShelfView::ShouldShowTooltipForView(const views::View* view) const {
1972 if (view == GetAppListButtonView() &&
1973 Shell::GetInstance()->GetAppListWindow())
1974 return false;
1975 const ShelfItem* item = ShelfItemForView(view);
1976 if (!item)
1977 return true;
1978 ShelfItemDelegate* item_delegate =
1979 item_manager_->GetShelfItemDelegate(item->id);
1980 return item_delegate->ShouldShowTooltip();
1983 int ShelfView::CalculateShelfDistance(const gfx::Point& coordinate) const {
1984 ShelfWidget* shelf = RootWindowController::ForShelf(
1985 GetWidget()->GetNativeView())->shelf();
1986 ShelfAlignment align = shelf->GetAlignment();
1987 const gfx::Rect bounds = GetBoundsInScreen();
1988 int distance = 0;
1989 switch (align) {
1990 case SHELF_ALIGNMENT_BOTTOM:
1991 distance = bounds.y() - coordinate.y();
1992 break;
1993 case SHELF_ALIGNMENT_LEFT:
1994 distance = coordinate.x() - bounds.right();
1995 break;
1996 case SHELF_ALIGNMENT_RIGHT:
1997 distance = bounds.x() - coordinate.x();
1998 break;
1999 case SHELF_ALIGNMENT_TOP:
2000 distance = coordinate.y() - bounds.bottom();
2001 break;
2003 return distance > 0 ? distance : 0;
2006 } // namespace ash