[ash] drag and drop from app list to shelf is not working in secondary monitor.
[chromium-blink-merge.git] / ui / app_list / views / apps_grid_view.cc
bloba2cba7d83633f39bc609c56af41b81c86ee14f1d
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 "ui/app_list/views/apps_grid_view.h"
7 #include <algorithm>
8 #include <set>
9 #include <string>
11 #include "base/guid.h"
12 #include "content/public/browser/web_contents.h"
13 #include "ui/app_list/app_list_constants.h"
14 #include "ui/app_list/app_list_folder_item.h"
15 #include "ui/app_list/app_list_item_model.h"
16 #include "ui/app_list/app_list_switches.h"
17 #include "ui/app_list/pagination_model.h"
18 #include "ui/app_list/views/app_list_drag_and_drop_host.h"
19 #include "ui/app_list/views/app_list_item_view.h"
20 #include "ui/app_list/views/apps_grid_view_delegate.h"
21 #include "ui/app_list/views/page_switcher.h"
22 #include "ui/app_list/views/pulsing_block_view.h"
23 #include "ui/compositor/scoped_layer_animation_settings.h"
24 #include "ui/events/event.h"
25 #include "ui/gfx/animation/animation.h"
26 #include "ui/views/border.h"
27 #include "ui/views/controls/webview/webview.h"
28 #include "ui/views/view_model_utils.h"
29 #include "ui/views/widget/widget.h"
31 #if defined(USE_AURA)
32 #include "ui/aura/root_window.h"
33 #include "ui/aura/window.h"
34 #endif
36 #if defined(OS_WIN) && !defined(USE_AURA)
37 #include "base/command_line.h"
38 #include "base/files/file_path.h"
39 #include "base/win/shortcut.h"
40 #include "ui/base/dragdrop/drag_utils.h"
41 #include "ui/base/dragdrop/drop_target_win.h"
42 #include "ui/base/dragdrop/os_exchange_data.h"
43 #include "ui/base/dragdrop/os_exchange_data_provider_win.h"
44 #endif
46 namespace app_list {
48 namespace {
50 // Distance a drag needs to be from the app grid to be considered 'outside', at
51 // which point we rearrange the apps to their pre-drag configuration, as a drop
52 // then would be canceled. We have a buffer to make it easier to drag apps to
53 // other pages.
54 const int kDragBufferPx = 20;
56 // Padding space in pixels for fixed layout.
57 const int kLeftRightPadding = 20;
58 const int kTopPadding = 1;
60 // Padding space in pixels between pages.
61 const int kPagePadding = 40;
63 // Preferred tile size when showing in fixed layout.
64 const int kPreferredTileWidth = 88;
65 const int kPreferredTileHeight = 98;
67 // Width in pixels of the area on the sides that triggers a page flip.
68 const int kPageFlipZoneSize = 40;
70 // Delay in milliseconds to do the page flip.
71 const int kPageFlipDelayInMs = 1000;
73 // How many pages on either side of the selected one we prerender.
74 const int kPrerenderPages = 1;
76 // The drag and drop proxy should get scaled by this factor.
77 const float kDragAndDropProxyScale = 1.5f;
79 // Delays in milliseconds to show folder dropping preview circle.
80 const int kFolderDroppingDelay = 250;
82 // Delays in milliseconds to show re-order preview.
83 const int kReorderDelay = 50;
85 // Radius of the circle, in which if entered, show folder dropping preview
86 // UI.
87 const int kFolderDroppingCircleRadius = 15;
89 // Radius of the circle, in which if entered, show re-order preview.
90 const int kReorderDroppingCircleRadius = 30;
92 // Max items allowed in a folder.
93 size_t kMaxFolderItems = 16;
95 // RowMoveAnimationDelegate is used when moving an item into a different row.
96 // Before running the animation, the item's layer is re-created and kept in
97 // the original position, then the item is moved to just before its target
98 // position and opacity set to 0. When the animation runs, this delegate moves
99 // the layer and fades it out while fading in the item at the same time.
100 class RowMoveAnimationDelegate
101 : public views::BoundsAnimator::OwnedAnimationDelegate {
102 public:
103 RowMoveAnimationDelegate(views::View* view,
104 ui::Layer* layer,
105 const gfx::Rect& layer_target)
106 : view_(view),
107 layer_(layer),
108 layer_start_(layer ? layer->bounds() : gfx::Rect()),
109 layer_target_(layer_target) {
111 virtual ~RowMoveAnimationDelegate() {}
113 // gfx::AnimationDelegate overrides:
114 virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
115 view_->layer()->SetOpacity(animation->GetCurrentValue());
116 view_->layer()->ScheduleDraw();
118 if (layer_) {
119 layer_->SetOpacity(1 - animation->GetCurrentValue());
120 layer_->SetBounds(animation->CurrentValueBetween(layer_start_,
121 layer_target_));
122 layer_->ScheduleDraw();
125 virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
126 view_->layer()->SetOpacity(1.0f);
127 view_->layer()->ScheduleDraw();
129 virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
130 view_->layer()->SetOpacity(1.0f);
131 view_->layer()->ScheduleDraw();
134 private:
135 // The view that needs to be wrapped. Owned by views hierarchy.
136 views::View* view_;
138 scoped_ptr<ui::Layer> layer_;
139 const gfx::Rect layer_start_;
140 const gfx::Rect layer_target_;
142 DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate);
145 // ItemRemoveAnimationDelegate is used to show animation for removing an item.
146 // This happens when user drags an item into a folder. The dragged item will
147 // be removed from the original list after it is dropped into the folder.
148 class ItemRemoveAnimationDelegate
149 : public views::BoundsAnimator::OwnedAnimationDelegate {
150 public:
151 explicit ItemRemoveAnimationDelegate(views::View* view)
152 : view_(view) {
155 virtual ~ItemRemoveAnimationDelegate() {
158 // gfx::AnimationDelegate overrides:
159 virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
160 view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
161 view_->layer()->ScheduleDraw();
164 private:
165 scoped_ptr<views::View> view_;
167 DISALLOW_COPY_AND_ASSIGN(ItemRemoveAnimationDelegate);
170 // Gets the distance between the centers of the |rect_1| and |rect_2|.
171 int GetDistanceBetweenRects(gfx::Rect rect_1,
172 gfx::Rect rect_2) {
173 return (rect_1.CenterPoint() - rect_2.CenterPoint()).Length();
176 // Returns true if the |item| is an folder item.
177 bool IsFolderItem(AppListItemModel* item) {
178 return (item->GetAppType() == AppListFolderItem::kAppType);
181 // Merges |source_item| into the folder containing the target item specified
182 // by |target_item_id|. Both |source_item| and target item belongs to
183 // |item_list|.
184 // Returns the index of the target folder.
185 size_t MergeItems(AppListItemList* item_list,
186 const std::string& target_item_id,
187 AppListItemModel* source_item) {
188 scoped_ptr<AppListItemModel> source_item_ptr =
189 item_list->RemoveItem(source_item->id());
190 DCHECK_EQ(source_item, source_item_ptr.get());
191 size_t target_index;
192 bool found_target_item = item_list->FindItemIndex(target_item_id,
193 &target_index);
194 DCHECK(found_target_item);
195 AppListItemModel* target_item = item_list->item_at(target_index);
196 if (IsFolderItem(target_item)) {
197 AppListFolderItem* target_folder =
198 static_cast<AppListFolderItem*>(target_item);
199 target_folder->item_list()->AddItem(source_item_ptr.release());
200 } else {
201 scoped_ptr<AppListItemModel> target_item_ptr =
202 item_list->RemoveItemAt(target_index);
203 DCHECK_EQ(target_item, target_item_ptr.get());
204 AppListFolderItem* new_folder =
205 new AppListFolderItem(base::GenerateGUID());
206 new_folder->item_list()->AddItem(target_item_ptr.release());
207 new_folder->item_list()->AddItem(source_item_ptr.release());
208 item_list->InsertItemAt(new_folder, target_index);
211 return target_index;
214 } // namespace
216 #if defined(OS_WIN) && !defined(USE_AURA)
217 // Interprets drag events sent from Windows via the drag/drop API and forwards
218 // them to AppsGridView.
219 // On Windows, in order to have the OS perform the drag properly we need to
220 // provide it with a shortcut file which may or may not exist at the time the
221 // drag is started. Therefore while waiting for that shortcut to be located we
222 // just do a regular "internal" drag and transition into the synchronous drag
223 // when the shortcut is found/created. Hence a synchronous drag is an optional
224 // phase of a regular drag and non-Windows platforms drags are equivalent to a
225 // Windows drag that never enters the synchronous drag phase.
226 class SynchronousDrag : public ui::DragSourceWin {
227 public:
228 SynchronousDrag(AppsGridView* grid_view,
229 AppListItemView* drag_view,
230 const gfx::Point& drag_view_offset)
231 : grid_view_(grid_view),
232 drag_view_(drag_view),
233 drag_view_offset_(drag_view_offset),
234 has_shortcut_path_(false),
235 running_(false),
236 canceled_(false) {}
238 void set_shortcut_path(const base::FilePath& shortcut_path) {
239 has_shortcut_path_ = true;
240 shortcut_path_ = shortcut_path;
243 bool CanRun() {
244 return has_shortcut_path_ && !running_;
247 void Run() {
248 DCHECK(CanRun());
249 running_ = true;
251 ui::OSExchangeData data;
252 SetupExchangeData(&data);
254 // Hide the dragged view because the OS is going to create its own.
255 const gfx::Size drag_view_size = drag_view_->size();
256 drag_view_->SetSize(gfx::Size(0, 0));
258 // Blocks until the drag is finished. Calls into the ui::DragSourceWin
259 // methods.
260 DWORD effects;
261 DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
262 this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects);
264 // Restore the dragged view to its original size.
265 drag_view_->SetSize(drag_view_size);
267 grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView());
270 private:
271 // Overridden from ui::DragSourceWin.
272 virtual void OnDragSourceCancel() OVERRIDE {
273 canceled_ = true;
276 virtual void OnDragSourceDrop() OVERRIDE {
279 virtual void OnDragSourceMove() OVERRIDE {
280 grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords());
283 void SetupExchangeData(ui::OSExchangeData* data) {
284 data->SetFilename(shortcut_path_);
285 gfx::ImageSkia image(drag_view_->GetDragImage());
286 gfx::Size image_size(image.size());
287 drag_utils::SetDragImageOnDataObject(
288 image,
289 image.size(),
290 gfx::Vector2d(drag_view_offset_.x(), drag_view_offset_.y()),
291 data);
294 HWND GetGridViewHWND() {
295 return grid_view_->GetWidget()->GetTopLevelWidget()->GetNativeView();
298 bool IsCursorWithinGridView() {
299 POINT p;
300 GetCursorPos(&p);
301 return GetGridViewHWND() == WindowFromPoint(p);
304 gfx::Point GetCursorInGridViewCoords() {
305 POINT p;
306 GetCursorPos(&p);
307 ScreenToClient(GetGridViewHWND(), &p);
308 gfx::Point grid_view_pt(p.x, p.y);
309 views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt);
310 return grid_view_pt;
313 AppsGridView* grid_view_;
314 AppListItemView* drag_view_;
315 gfx::Point drag_view_offset_;
316 bool has_shortcut_path_;
317 base::FilePath shortcut_path_;
318 bool running_;
319 bool canceled_;
321 DISALLOW_COPY_AND_ASSIGN(SynchronousDrag);
323 #endif // defined(OS_WIN) && !defined(USE_AURA)
325 AppsGridView::AppsGridView(AppsGridViewDelegate* delegate,
326 PaginationModel* pagination_model,
327 content::WebContents* start_page_contents)
328 : model_(NULL),
329 item_list_(NULL),
330 delegate_(delegate),
331 pagination_model_(pagination_model),
332 page_switcher_view_(new PageSwitcher(pagination_model)),
333 start_page_view_(NULL),
334 cols_(0),
335 rows_per_page_(0),
336 selected_view_(NULL),
337 drag_view_(NULL),
338 drag_start_page_(-1),
339 drag_pointer_(NONE),
340 drop_attempt_(DROP_FOR_NONE),
341 drag_and_drop_host_(NULL),
342 forward_events_to_drag_and_drop_host_(false),
343 page_flip_target_(-1),
344 page_flip_delay_in_ms_(kPageFlipDelayInMs),
345 bounds_animator_(this),
346 is_root_level_(true) {
347 pagination_model_->AddObserver(this);
348 AddChildView(page_switcher_view_);
350 if (start_page_contents) {
351 start_page_view_ =
352 new views::WebView(start_page_contents->GetBrowserContext());
353 start_page_view_->SetWebContents(start_page_contents);
354 AddChildView(start_page_view_);
355 start_page_contents->GetWebUI()->CallJavascriptFunction(
356 "appList.startPage.onAppListShown");
360 AppsGridView::~AppsGridView() {
361 // Coming here |drag_view_| should already be canceled since otherwise the
362 // drag would disappear after the app list got animated away and closed,
363 // which would look odd.
364 DCHECK(!drag_view_);
365 if (drag_view_)
366 EndDrag(true);
368 if (model_)
369 model_->RemoveObserver(this);
370 pagination_model_->RemoveObserver(this);
372 if (item_list_)
373 item_list_->RemoveObserver(this);
375 if (start_page_view_) {
376 start_page_view_->GetWebContents()->GetWebUI()->CallJavascriptFunction(
377 "appList.startPage.onAppListHidden");
381 void AppsGridView::SetLayout(int icon_size, int cols, int rows_per_page) {
382 icon_size_.SetSize(icon_size, icon_size);
383 cols_ = cols;
384 rows_per_page_ = rows_per_page;
386 set_border(views::Border::CreateEmptyBorder(kTopPadding,
387 kLeftRightPadding,
389 kLeftRightPadding));
392 void AppsGridView::SetModel(AppListModel* model) {
393 if (model_)
394 model_->RemoveObserver(this);
396 model_ = model;
397 if (model_)
398 model_->AddObserver(this);
400 Update();
403 void AppsGridView::SetItemList(AppListItemList* item_list) {
404 if (item_list_)
405 item_list_->RemoveObserver(this);
407 item_list_ = item_list;
408 item_list_->AddObserver(this);
409 Update();
412 void AppsGridView::SetSelectedView(views::View* view) {
413 if (IsSelectedView(view) || IsDraggedView(view))
414 return;
416 Index index = GetIndexOfView(view);
417 if (IsValidIndex(index))
418 SetSelectedItemByIndex(index);
421 void AppsGridView::ClearSelectedView(views::View* view) {
422 if (view && IsSelectedView(view)) {
423 selected_view_->SchedulePaint();
424 selected_view_ = NULL;
428 void AppsGridView::ClearAnySelectedView() {
429 if (selected_view_) {
430 selected_view_->SchedulePaint();
431 selected_view_ = NULL;
435 bool AppsGridView::IsSelectedView(const views::View* view) const {
436 return selected_view_ == view;
439 void AppsGridView::EnsureViewVisible(const views::View* view) {
440 if (pagination_model_->has_transition())
441 return;
443 Index index = GetIndexOfView(view);
444 if (IsValidIndex(index))
445 pagination_model_->SelectPage(index.page, false);
448 void AppsGridView::InitiateDrag(AppListItemView* view,
449 Pointer pointer,
450 const ui::LocatedEvent& event) {
451 DCHECK(view);
452 if (drag_view_ || pulsing_blocks_model_.view_size())
453 return;
455 drag_view_ = view;
456 drag_view_offset_ = event.location();
457 drag_start_page_ = pagination_model_->selected_page();
458 ExtractDragLocation(event, &drag_start_grid_view_);
459 drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
462 void AppsGridView::OnGotShortcutPath(const base::FilePath& path) {
463 #if defined(OS_WIN) && !defined(USE_AURA)
464 // Drag may have ended before we get the shortcut path.
465 if (!synchronous_drag_)
466 return;
467 // Setting the shortcut path here means the next time we hit UpdateDrag()
468 // we'll enter the synchronous drag.
469 // NOTE we don't Run() the drag here because that causes animations not to
470 // update for some reason.
471 synchronous_drag_->set_shortcut_path(path);
472 DCHECK(synchronous_drag_->CanRun());
473 #endif
476 void AppsGridView::StartSettingUpSynchronousDrag() {
477 #if defined(OS_WIN) && !defined(USE_AURA)
478 if (!delegate_)
479 return;
481 delegate_->GetShortcutPathForApp(
482 drag_view_->model()->id(),
483 base::Bind(&AppsGridView::OnGotShortcutPath, base::Unretained(this)));
484 synchronous_drag_ = new SynchronousDrag(this, drag_view_, drag_view_offset_);
485 #endif
488 bool AppsGridView::RunSynchronousDrag() {
489 #if defined(OS_WIN) && !defined(USE_AURA)
490 if (synchronous_drag_ && synchronous_drag_->CanRun()) {
491 synchronous_drag_->Run();
492 synchronous_drag_ = NULL;
493 return true;
495 #endif
496 return false;
499 void AppsGridView::CleanUpSynchronousDrag() {
500 #if defined(OS_WIN) && !defined(USE_AURA)
501 synchronous_drag_ = NULL;
502 #endif
505 void AppsGridView::UpdateDragFromItem(Pointer pointer,
506 const ui::LocatedEvent& event) {
507 gfx::Point drag_point_in_grid_view;
508 ExtractDragLocation(event, &drag_point_in_grid_view);
509 UpdateDrag(pointer, drag_point_in_grid_view);
510 if (!dragging())
511 return;
513 // If a drag and drop host is provided, see if the drag operation needs to be
514 // forwarded.
515 gfx::Point location_in_screen = drag_point_in_grid_view;
516 views::View::ConvertPointToScreen(this, &location_in_screen);
517 DispatchDragEventToDragAndDropHost(location_in_screen);
518 if (drag_and_drop_host_)
519 drag_and_drop_host_->UpdateDragIconProxy(location_in_screen);
522 void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) {
523 // EndDrag was called before if |drag_view_| is NULL.
524 if (!drag_view_)
525 return;
527 if (RunSynchronousDrag())
528 return;
530 gfx::Vector2d drag_vector(point - drag_start_grid_view_);
531 if (!dragging() && ExceededDragThreshold(drag_vector)) {
532 drag_pointer_ = pointer;
533 // Move the view to the front so that it appears on top of other views.
534 ReorderChildView(drag_view_, -1);
535 bounds_animator_.StopAnimatingView(drag_view_);
536 StartSettingUpSynchronousDrag();
537 StartDragAndDropHostDrag(point);
540 if (drag_pointer_ != pointer)
541 return;
543 last_drag_point_ = point;
544 const Index last_drop_target = drop_target_;
545 DropAttempt last_drop_attempt = drop_attempt_;
546 CalculateDropTarget(last_drag_point_, false);
548 if (IsPointWithinDragBuffer(last_drag_point_))
549 MaybeStartPageFlipTimer(last_drag_point_);
550 else
551 StopPageFlipTimer();
553 gfx::Point page_switcher_point(last_drag_point_);
554 views::View::ConvertPointToTarget(this, page_switcher_view_,
555 &page_switcher_point);
556 page_switcher_view_->UpdateUIForDragPoint(page_switcher_point);
558 if (!EnableFolderDragDropUI()) {
559 if (last_drop_target != drop_target_)
560 AnimateToIdealBounds();
561 drag_view_->SetPosition(drag_view_start_ + drag_vector);
562 return;
565 // Update drag with folder UI enabled.
566 if (last_drop_target != drop_target_ ||
567 last_drop_attempt != drop_attempt_) {
568 if (drop_attempt_ == DROP_FOR_REORDER) {
569 folder_dropping_timer_.Stop();
570 reorder_timer_.Start(FROM_HERE,
571 base::TimeDelta::FromMilliseconds(kReorderDelay),
572 this, &AppsGridView::OnReorderTimer);
573 } else if (drop_attempt_ == DROP_FOR_FOLDER) {
574 reorder_timer_.Stop();
575 folder_dropping_timer_.Start(FROM_HERE,
576 base::TimeDelta::FromMilliseconds(kFolderDroppingDelay),
577 this, &AppsGridView::OnFolderDroppingTimer);
580 // Reset the previous drop target.
581 SetAsFolderDroppingTarget(last_drop_target, false);
584 drag_view_->SetPosition(drag_view_start_ + drag_vector);
587 void AppsGridView::EndDrag(bool cancel) {
588 // EndDrag was called before if |drag_view_| is NULL.
589 if (!drag_view_)
590 return;
591 // Coming here a drag and drop was in progress.
592 bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_;
593 if (forward_events_to_drag_and_drop_host_) {
594 forward_events_to_drag_and_drop_host_ = false;
595 drag_and_drop_host_->EndDrag(cancel);
596 } else if (!cancel && dragging()) {
597 CalculateDropTarget(last_drag_point_, true);
598 if (IsValidIndex(drop_target_)) {
599 if (!EnableFolderDragDropUI()) {
600 MoveItemInModel(drag_view_, drop_target_);
601 } else {
602 if (drop_attempt_ == DROP_FOR_REORDER)
603 MoveItemInModel(drag_view_, drop_target_);
604 else if (drop_attempt_ == DROP_FOR_FOLDER)
605 MoveItemToFolder(drag_view_, drop_target_);
610 if (drag_and_drop_host_) {
611 // If we had a drag and drop proxy icon, we delete it and make the real
612 // item visible again.
613 drag_and_drop_host_->DestroyDragIconProxy();
614 if (landed_in_drag_and_drop_host) {
615 // Move the item directly to the target location, avoiding the "zip back"
616 // animation if the user was pinning it to the shelf.
617 int i = drop_target_.slot;
618 gfx::Rect bounds = view_model_.ideal_bounds(i);
619 drag_view_->SetBoundsRect(bounds);
621 // Fade in slowly if it landed in the shelf.
622 SetViewHidden(drag_view_,
623 false /* hide */,
624 !landed_in_drag_and_drop_host /* animate */);
627 // The drag can be ended after the synchronous drag is created but before it
628 // is Run().
629 CleanUpSynchronousDrag();
631 SetAsFolderDroppingTarget(drop_target_, false);
632 drop_attempt_ = DROP_FOR_NONE;
633 drag_pointer_ = NONE;
634 drop_target_ = Index();
635 drag_view_->OnDragEnded();
636 drag_view_ = NULL;
637 drag_start_grid_view_ = gfx::Point();
638 drag_start_page_ = -1;
639 drag_view_offset_ = gfx::Point();
640 AnimateToIdealBounds();
642 StopPageFlipTimer();
645 void AppsGridView::StopPageFlipTimer() {
646 page_flip_timer_.Stop();
647 page_flip_target_ = -1;
650 bool AppsGridView::IsDraggedView(const views::View* view) const {
651 return drag_view_ == view;
654 void AppsGridView::SetDragAndDropHostOfCurrentAppList(
655 ApplicationDragAndDropHost* drag_and_drop_host) {
656 drag_and_drop_host_ = drag_and_drop_host;
659 void AppsGridView::Prerender(int page_index) {
660 Layout();
661 int start = std::max(0, (page_index - kPrerenderPages) * tiles_per_page());
662 int end = std::min(view_model_.view_size(),
663 (page_index + 1 + kPrerenderPages) * tiles_per_page());
664 for (int i = start; i < end; i++) {
665 AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i));
666 v->Prerender();
670 gfx::Size AppsGridView::GetPreferredSize() {
671 const gfx::Insets insets(GetInsets());
672 const gfx::Size tile_size = gfx::Size(kPreferredTileWidth,
673 kPreferredTileHeight);
674 const int page_switcher_height =
675 page_switcher_view_->GetPreferredSize().height();
676 return gfx::Size(
677 tile_size.width() * cols_ + insets.width(),
678 tile_size.height() * rows_per_page_ +
679 page_switcher_height + insets.height());
682 bool AppsGridView::GetDropFormats(
683 int* formats,
684 std::set<OSExchangeData::CustomFormat>* custom_formats) {
685 // TODO(koz): Only accept a specific drag type for app shortcuts.
686 *formats = OSExchangeData::FILE_NAME;
687 return true;
690 bool AppsGridView::CanDrop(const OSExchangeData& data) {
691 return true;
694 int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) {
695 return ui::DragDropTypes::DRAG_MOVE;
698 void AppsGridView::Layout() {
699 if (bounds_animator_.IsAnimating())
700 bounds_animator_.Cancel();
702 CalculateIdealBounds();
703 for (int i = 0; i < view_model_.view_size(); ++i) {
704 views::View* view = view_model_.view_at(i);
705 if (view != drag_view_)
706 view->SetBoundsRect(view_model_.ideal_bounds(i));
708 views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_);
710 const int page_switcher_height =
711 page_switcher_view_->GetPreferredSize().height();
712 gfx::Rect rect(GetContentsBounds());
713 rect.set_y(rect.bottom() - page_switcher_height);
714 rect.set_height(page_switcher_height);
715 page_switcher_view_->SetBoundsRect(rect);
717 LayoutStartPage();
720 bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) {
721 bool handled = false;
722 if (selected_view_)
723 handled = selected_view_->OnKeyPressed(event);
725 if (!handled) {
726 const int forward_dir = base::i18n::IsRTL() ? -1 : 1;
727 switch (event.key_code()) {
728 case ui::VKEY_LEFT:
729 MoveSelected(0, -forward_dir, 0);
730 return true;
731 case ui::VKEY_RIGHT:
732 MoveSelected(0, forward_dir, 0);
733 return true;
734 case ui::VKEY_UP:
735 MoveSelected(0, 0, -1);
736 return true;
737 case ui::VKEY_DOWN:
738 MoveSelected(0, 0, 1);
739 return true;
740 case ui::VKEY_PRIOR: {
741 MoveSelected(-1, 0, 0);
742 return true;
744 case ui::VKEY_NEXT: {
745 MoveSelected(1, 0, 0);
746 return true;
748 default:
749 break;
753 return handled;
756 bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) {
757 bool handled = false;
758 if (selected_view_)
759 handled = selected_view_->OnKeyReleased(event);
761 return handled;
764 void AppsGridView::ViewHierarchyChanged(
765 const ViewHierarchyChangedDetails& details) {
766 if (!details.is_add && details.parent == this) {
767 if (selected_view_ == details.child)
768 selected_view_ = NULL;
770 if (drag_view_ == details.child)
771 EndDrag(true);
773 bounds_animator_.StopAnimatingView(details.child);
777 void AppsGridView::Update() {
778 DCHECK(!selected_view_ && !drag_view_);
779 if (!item_list_)
780 return;
782 view_model_.Clear();
783 if (!item_list_->item_count())
784 return;
785 for (size_t i = 0; i < item_list_->item_count(); ++i) {
786 views::View* view = CreateViewForItemAtIndex(i);
787 view_model_.Add(view, i);
788 AddChildView(view);
790 UpdatePaging();
791 UpdatePulsingBlockViews();
792 Layout();
793 SchedulePaint();
796 void AppsGridView::UpdatePaging() {
797 int total_page = start_page_view_ ? 1 : 0;
798 if (view_model_.view_size() && tiles_per_page())
799 total_page += (view_model_.view_size() - 1) / tiles_per_page() + 1;
801 pagination_model_->SetTotalPages(total_page);
804 void AppsGridView::UpdatePulsingBlockViews() {
805 const int existing_items = item_list_ ? item_list_->item_count() : 0;
806 const int available_slots =
807 tiles_per_page() - existing_items % tiles_per_page();
808 const int desired = model_->status() == AppListModel::STATUS_SYNCING ?
809 available_slots : 0;
811 if (pulsing_blocks_model_.view_size() == desired)
812 return;
814 while (pulsing_blocks_model_.view_size() > desired) {
815 views::View* view = pulsing_blocks_model_.view_at(0);
816 pulsing_blocks_model_.Remove(0);
817 delete view;
820 while (pulsing_blocks_model_.view_size() < desired) {
821 views::View* view = new PulsingBlockView(
822 gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true);
823 pulsing_blocks_model_.Add(view, 0);
824 AddChildView(view);
828 views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) {
829 // The drag_view_ might be pending for deletion, therefore view_model_
830 // may have one more item than item_list_.
831 DCHECK_LE(index, item_list_->item_count());
832 AppListItemView* view = new AppListItemView(this,
833 item_list_->item_at(index));
834 view->SetIconSize(icon_size_);
835 #if defined(USE_AURA)
836 view->SetPaintToLayer(true);
837 view->SetFillsBoundsOpaquely(false);
838 #endif
839 return view;
842 AppsGridView::Index AppsGridView::GetIndexFromModelIndex(
843 int model_index) const {
844 int page = model_index / tiles_per_page();
845 if (start_page_view_)
846 ++page;
848 return Index(page, model_index % tiles_per_page());
851 int AppsGridView::GetModelIndexFromIndex(const Index& index) const {
852 int model_index = index.page * tiles_per_page() + index.slot;
853 if (start_page_view_)
854 model_index -= tiles_per_page();
856 return model_index;
859 void AppsGridView::SetSelectedItemByIndex(const Index& index) {
860 if (GetIndexOfView(selected_view_) == index)
861 return;
863 views::View* new_selection = GetViewAtIndex(index);
864 if (!new_selection)
865 return; // Keep current selection.
867 if (selected_view_)
868 selected_view_->SchedulePaint();
870 EnsureViewVisible(new_selection);
871 selected_view_ = new_selection;
872 selected_view_->SchedulePaint();
873 selected_view_->NotifyAccessibilityEvent(
874 ui::AccessibilityTypes::EVENT_FOCUS, true);
877 bool AppsGridView::IsValidIndex(const Index& index) const {
878 const int item_page_start = start_page_view_ ? 1 : 0;
879 return index.page >= item_page_start &&
880 index.page < pagination_model_->total_pages() &&
881 index.slot >= 0 &&
882 index.slot < tiles_per_page() &&
883 GetModelIndexFromIndex(index) < view_model_.view_size();
886 AppsGridView::Index AppsGridView::GetIndexOfView(
887 const views::View* view) const {
888 const int model_index = view_model_.GetIndexOfView(view);
889 if (model_index == -1)
890 return Index();
892 return GetIndexFromModelIndex(model_index);
895 views::View* AppsGridView::GetViewAtIndex(const Index& index) const {
896 if (!IsValidIndex(index))
897 return NULL;
899 const int model_index = GetModelIndexFromIndex(index);
900 return view_model_.view_at(model_index);
903 void AppsGridView::MoveSelected(int page_delta,
904 int slot_x_delta,
905 int slot_y_delta) {
906 if (!selected_view_)
907 return SetSelectedItemByIndex(Index(pagination_model_->selected_page(), 0));
909 const Index& selected = GetIndexOfView(selected_view_);
910 int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_;
912 if (selected.slot % cols_ == 0 && slot_x_delta == -1) {
913 if (selected.page > 0) {
914 page_delta = -1;
915 target_slot = selected.slot + cols_ - 1;
916 } else {
917 target_slot = selected.slot;
921 if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) {
922 if (selected.page < pagination_model_->total_pages() - 1) {
923 page_delta = 1;
924 target_slot = selected.slot - cols_ + 1;
925 } else {
926 target_slot = selected.slot;
930 // Clamp the target slot to the last item if we are moving to the last page
931 // but our target slot is past the end of the item list.
932 if (page_delta &&
933 selected.page + page_delta == pagination_model_->total_pages() - 1) {
934 int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page();
935 if (last_item_slot < target_slot) {
936 target_slot = last_item_slot;
940 int target_page = std::min(pagination_model_->total_pages() - 1,
941 std::max(selected.page + page_delta, 0));
942 SetSelectedItemByIndex(Index(target_page, target_slot));
945 void AppsGridView::CalculateIdealBounds() {
946 gfx::Rect rect(GetContentsBounds());
947 if (rect.IsEmpty())
948 return;
950 gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
952 gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
953 tile_size.height() * rows_per_page_));
954 grid_rect.Intersect(rect);
956 // Page width including padding pixels. A tile.x + page_width means the same
957 // tile slot in the next page.
958 const int page_width = grid_rect.width() + kPagePadding;
960 // If there is a transition, calculates offset for current and target page.
961 const int current_page = pagination_model_->selected_page();
962 const PaginationModel::Transition& transition =
963 pagination_model_->transition();
964 const bool is_valid =
965 pagination_model_->is_valid_page(transition.target_page);
967 // Transition to right means negative offset.
968 const int dir = transition.target_page > current_page ? -1 : 1;
969 const int transition_offset = is_valid ?
970 transition.progress * page_width * dir : 0;
972 const int total_views =
973 view_model_.view_size() + pulsing_blocks_model_.view_size();
974 int slot_index = 0;
975 for (int i = 0; i < total_views; ++i) {
976 if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_) {
977 if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER)
978 ++slot_index;
979 continue;
982 Index view_index = GetIndexFromModelIndex(slot_index);
984 if (drop_target_ == view_index) {
985 if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER) {
986 view_index = GetIndexFromModelIndex(slot_index);
987 } else {
988 ++slot_index;
989 view_index = GetIndexFromModelIndex(slot_index);
993 // Decides an x_offset for current item.
994 int x_offset = 0;
995 if (view_index.page < current_page)
996 x_offset = -page_width;
997 else if (view_index.page > current_page)
998 x_offset = page_width;
1000 if (is_valid) {
1001 if (view_index.page == current_page ||
1002 view_index.page == transition.target_page) {
1003 x_offset += transition_offset;
1007 const int row = view_index.slot / cols_;
1008 const int col = view_index.slot % cols_;
1009 gfx::Rect tile_slot(
1010 gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset,
1011 grid_rect.y() + row * tile_size.height()),
1012 tile_size);
1013 if (i < view_model_.view_size()) {
1014 view_model_.set_ideal_bounds(i, tile_slot);
1015 } else {
1016 pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(),
1017 tile_slot);
1020 ++slot_index;
1024 void AppsGridView::AnimateToIdealBounds() {
1025 const gfx::Rect visible_bounds(GetVisibleBounds());
1027 CalculateIdealBounds();
1028 for (int i = 0; i < view_model_.view_size(); ++i) {
1029 views::View* view = view_model_.view_at(i);
1030 if (view == drag_view_)
1031 continue;
1033 const gfx::Rect& target = view_model_.ideal_bounds(i);
1034 if (bounds_animator_.GetTargetBounds(view) == target)
1035 continue;
1037 const gfx::Rect& current = view->bounds();
1038 const bool current_visible = visible_bounds.Intersects(current);
1039 const bool target_visible = visible_bounds.Intersects(target);
1040 const bool visible = current_visible || target_visible;
1042 const int y_diff = target.y() - current.y();
1043 if (visible && y_diff && y_diff % kPreferredTileHeight == 0) {
1044 AnimationBetweenRows(view,
1045 current_visible,
1046 current,
1047 target_visible,
1048 target);
1049 } else {
1050 bounds_animator_.AnimateViewTo(view, target);
1055 void AppsGridView::AnimationBetweenRows(views::View* view,
1056 bool animate_current,
1057 const gfx::Rect& current,
1058 bool animate_target,
1059 const gfx::Rect& target) {
1060 // Determine page of |current| and |target|. -1 means in the left invisible
1061 // page, 0 is the center visible page and 1 means in the right invisible page.
1062 const int current_page = current.x() < 0 ? -1 :
1063 current.x() >= width() ? 1 : 0;
1064 const int target_page = target.x() < 0 ? -1 :
1065 target.x() >= width() ? 1 : 0;
1067 const int dir = current_page < target_page ||
1068 (current_page == target_page && current.y() < target.y()) ? 1 : -1;
1070 #if defined(USE_AURA)
1071 scoped_ptr<ui::Layer> layer;
1072 if (animate_current) {
1073 layer.reset(view->RecreateLayer());
1074 layer->SuppressPaint();
1076 view->SetFillsBoundsOpaquely(false);
1077 view->layer()->SetOpacity(0.f);
1080 gfx::Rect current_out(current);
1081 current_out.Offset(dir * kPreferredTileWidth, 0);
1082 #endif
1084 gfx::Rect target_in(target);
1085 if (animate_target)
1086 target_in.Offset(-dir * kPreferredTileWidth, 0);
1087 view->SetBoundsRect(target_in);
1088 bounds_animator_.AnimateViewTo(view, target);
1090 #if defined(USE_AURA)
1091 bounds_animator_.SetAnimationDelegate(
1092 view,
1093 new RowMoveAnimationDelegate(view, layer.release(), current_out),
1094 true);
1095 #endif
1098 void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event,
1099 gfx::Point* drag_point) {
1100 #if defined(USE_AURA)
1101 // Use root location of |event| instead of location in |drag_view_|'s
1102 // coordinates because |drag_view_| has a scale transform and location
1103 // could have integer round error and causes jitter.
1104 *drag_point = event.root_location();
1106 // GetWidget() could be NULL for tests.
1107 if (GetWidget()) {
1108 aura::Window::ConvertPointToTarget(
1109 GetWidget()->GetNativeWindow()->GetRootWindow(),
1110 GetWidget()->GetNativeWindow(),
1111 drag_point);
1114 views::View::ConvertPointFromWidget(this, drag_point);
1115 #else
1116 // For non-aura, root location is not clearly defined but |drag_view_| does
1117 // not have the scale transform. So no round error would be introduced and
1118 // it's okay to use View::ConvertPointToTarget.
1119 *drag_point = event.location();
1120 views::View::ConvertPointToTarget(drag_view_, this, drag_point);
1121 #endif
1124 void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point,
1125 bool use_page_button_hovering) {
1126 if (EnableFolderDragDropUI()) {
1127 CalculateDropTargetWithFolderEnabled(drag_point, use_page_button_hovering);
1128 return;
1131 int current_page = pagination_model_->selected_page();
1132 gfx::Point point(drag_point);
1133 if (!IsPointWithinDragBuffer(drag_point)) {
1134 point = drag_start_grid_view_;
1135 current_page = drag_start_page_;
1138 if (use_page_button_hovering &&
1139 page_switcher_view_->bounds().Contains(point)) {
1140 gfx::Point page_switcher_point(point);
1141 views::View::ConvertPointToTarget(this, page_switcher_view_,
1142 &page_switcher_point);
1143 int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
1144 if (pagination_model_->is_valid_page(page)) {
1145 drop_target_.page = page;
1146 drop_target_.slot = tiles_per_page() - 1;
1148 } else {
1149 gfx::Rect bounds(GetContentsBounds());
1150 const int drop_row = (point.y() - bounds.y()) / kPreferredTileHeight;
1151 const int drop_col = std::min(cols_ - 1,
1152 (point.x() - bounds.x()) / kPreferredTileWidth);
1154 drop_target_.page = current_page;
1155 drop_target_.slot = std::max(0, std::min(
1156 tiles_per_page() - 1,
1157 drop_row * cols_ + drop_col));
1160 // Limits to the last possible slot on last page.
1161 if (drop_target_.page == pagination_model_->total_pages() - 1) {
1162 drop_target_.slot = std::min(
1163 (view_model_.view_size() - 1) % tiles_per_page(),
1164 drop_target_.slot);
1169 void AppsGridView::CalculateDropTargetWithFolderEnabled(
1170 const gfx::Point& drag_point,
1171 bool use_page_button_hovering) {
1172 gfx::Point point(drag_point);
1173 if (!IsPointWithinDragBuffer(drag_point)) {
1174 point = drag_start_grid_view_;
1177 if (use_page_button_hovering &&
1178 page_switcher_view_->bounds().Contains(point)) {
1179 gfx::Point page_switcher_point(point);
1180 views::View::ConvertPointToTarget(this, page_switcher_view_,
1181 &page_switcher_point);
1182 int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
1183 if (pagination_model_->is_valid_page(page)) {
1184 drop_target_.page = page;
1185 drop_target_.slot = tiles_per_page() - 1;
1187 if (drop_target_.page == pagination_model_->total_pages() - 1) {
1188 drop_target_.slot = std::min(
1189 (view_model_.view_size() - 1) % tiles_per_page(),
1190 drop_target_.slot);
1192 drop_attempt_ = DROP_FOR_REORDER;
1193 } else {
1194 DCHECK(drag_view_);
1195 // Try to find the nearest target for folder dropping or re-ordering.
1196 drop_target_ = GetNearestTileForDragView();
1200 void AppsGridView::OnReorderTimer() {
1201 if (drop_attempt_ == DROP_FOR_REORDER)
1202 AnimateToIdealBounds();
1205 void AppsGridView::OnFolderDroppingTimer() {
1206 if (drop_attempt_ == DROP_FOR_FOLDER)
1207 SetAsFolderDroppingTarget(drop_target_, true);
1210 void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) {
1211 // When a drag and drop host is given, the item can be dragged out of the app
1212 // list window. In that case a proxy widget needs to be used.
1213 // Note: This code has very likely to be changed for Windows (non metro mode)
1214 // when a |drag_and_drop_host_| gets implemented.
1215 if (!drag_view_ || !drag_and_drop_host_)
1216 return;
1218 gfx::Point screen_location = grid_location;
1219 views::View::ConvertPointToScreen(this, &screen_location);
1221 // Determine the mouse offset to the center of the icon so that the drag and
1222 // drop host follows this layer.
1223 gfx::Vector2d delta = drag_view_offset_ -
1224 drag_view_->GetLocalBounds().CenterPoint();
1225 delta.set_y(delta.y() + drag_view_->title()->size().height() / 2);
1227 // We have to hide the original item since the drag and drop host will do
1228 // the OS dependent code to "lift off the dragged item".
1229 drag_and_drop_host_->CreateDragIconProxy(screen_location,
1230 drag_view_->model()->icon(),
1231 drag_view_,
1232 delta,
1233 kDragAndDropProxyScale);
1234 SetViewHidden(drag_view_,
1235 true /* hide */,
1236 true /* no animation */);
1239 void AppsGridView::DispatchDragEventToDragAndDropHost(
1240 const gfx::Point& location_in_screen_coordinates) {
1241 if (!drag_view_ || !drag_and_drop_host_)
1242 return;
1243 if (bounds().Contains(last_drag_point_)) {
1244 // The event was issued inside the app menu and we should get all events.
1245 if (forward_events_to_drag_and_drop_host_) {
1246 // The DnD host was previously called and needs to be informed that the
1247 // session returns to the owner.
1248 forward_events_to_drag_and_drop_host_ = false;
1249 drag_and_drop_host_->EndDrag(true);
1251 } else {
1252 // The event happened outside our app menu and we might need to dispatch.
1253 if (forward_events_to_drag_and_drop_host_) {
1254 // Dispatch since we have already started.
1255 if (!drag_and_drop_host_->Drag(location_in_screen_coordinates)) {
1256 // The host is not active any longer and we cancel the operation.
1257 forward_events_to_drag_and_drop_host_ = false;
1258 drag_and_drop_host_->EndDrag(true);
1260 } else {
1261 if (drag_and_drop_host_->StartDrag(drag_view_->model()->id(),
1262 location_in_screen_coordinates)) {
1263 // From now on we forward the drag events.
1264 forward_events_to_drag_and_drop_host_ = true;
1265 // Any flip operations are stopped.
1266 StopPageFlipTimer();
1272 void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) {
1273 if (!IsPointWithinDragBuffer(drag_point))
1274 StopPageFlipTimer();
1275 int new_page_flip_target = -1;
1277 if (page_switcher_view_->bounds().Contains(drag_point)) {
1278 gfx::Point page_switcher_point(drag_point);
1279 views::View::ConvertPointToTarget(this, page_switcher_view_,
1280 &page_switcher_point);
1281 new_page_flip_target =
1282 page_switcher_view_->GetPageForPoint(page_switcher_point);
1285 // TODO(xiyuan): Fix this for RTL.
1286 if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize)
1287 new_page_flip_target = pagination_model_->selected_page() - 1;
1289 if (new_page_flip_target == -1 &&
1290 drag_point.x() > width() - kPageFlipZoneSize) {
1291 new_page_flip_target = pagination_model_->selected_page() + 1;
1294 if (new_page_flip_target == page_flip_target_)
1295 return;
1297 StopPageFlipTimer();
1298 if (pagination_model_->is_valid_page(new_page_flip_target)) {
1299 page_flip_target_ = new_page_flip_target;
1301 if (page_flip_target_ != pagination_model_->selected_page()) {
1302 page_flip_timer_.Start(FROM_HERE,
1303 base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_),
1304 this, &AppsGridView::OnPageFlipTimer);
1309 void AppsGridView::OnPageFlipTimer() {
1310 DCHECK(pagination_model_->is_valid_page(page_flip_target_));
1311 pagination_model_->SelectPage(page_flip_target_, true);
1314 void AppsGridView::MoveItemInModel(views::View* item_view,
1315 const Index& target) {
1316 int current_model_index = view_model_.GetIndexOfView(item_view);
1317 DCHECK_GE(current_model_index, 0);
1319 int target_model_index = GetModelIndexFromIndex(target);
1320 if (target_model_index == current_model_index)
1321 return;
1323 item_list_->RemoveObserver(this);
1324 item_list_->MoveItem(current_model_index, target_model_index);
1325 view_model_.Move(current_model_index, target_model_index);
1326 item_list_->AddObserver(this);
1328 if (pagination_model_->selected_page() != target.page)
1329 pagination_model_->SelectPage(target.page, false);
1332 void AppsGridView::MoveItemToFolder(views::View* item_view,
1333 const Index& target) {
1334 AppListItemModel* source_item =
1335 static_cast<AppListItemView*>(item_view)->model();
1336 AppListItemView* target_view =
1337 static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot));
1338 AppListItemModel* target_item = target_view->model();
1339 bool target_is_folder = IsFolderItem(target_item);
1341 // Make change to data model.
1342 item_list_->RemoveObserver(this);
1343 int folder_index = MergeItems(item_list_, target_item->id(), source_item);
1344 item_list_->AddObserver(this);
1346 if (!target_is_folder) {
1347 // Change view_model_ to replace the old target view with new folder
1348 // item view.
1349 int target_index = view_model_.GetIndexOfView(target_view);
1350 view_model_.Remove(target_index);
1351 delete target_view;
1353 views::View* target_folder_view = CreateViewForItemAtIndex(folder_index);
1354 view_model_.Add(target_folder_view, target_index);
1355 AddChildView(target_folder_view);
1358 // Fade out the drag_view_ and delete it when animation ends.
1359 int drag_view_index = view_model_.GetIndexOfView(drag_view_);
1360 view_model_.Remove(drag_view_index);
1361 bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
1362 bounds_animator_.SetAnimationDelegate(
1363 drag_view_, new ItemRemoveAnimationDelegate(drag_view_), true);
1365 UpdatePaging();
1368 void AppsGridView::CancelContextMenusOnCurrentPage() {
1369 int start = pagination_model_->selected_page() * tiles_per_page();
1370 int end = std::min(view_model_.view_size(), start + tiles_per_page());
1371 for (int i = start; i < end; ++i) {
1372 AppListItemView* view =
1373 static_cast<AppListItemView*>(view_model_.view_at(i));
1374 view->CancelContextMenu();
1378 bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const {
1379 gfx::Rect rect(GetLocalBounds());
1380 rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx);
1381 return rect.Contains(point);
1384 void AppsGridView::ButtonPressed(views::Button* sender,
1385 const ui::Event& event) {
1386 if (dragging())
1387 return;
1389 if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName))
1390 return;
1392 if (delegate_) {
1393 delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->model(),
1394 event.flags());
1398 void AppsGridView::LayoutStartPage() {
1399 if (!start_page_view_)
1400 return;
1402 gfx::Rect start_page_bounds(GetLocalBounds());
1403 start_page_bounds.set_height(start_page_bounds.height() -
1404 page_switcher_view_->height());
1406 const int page_width = width() + kPagePadding;
1407 const int current_page = pagination_model_->selected_page();
1408 if (current_page > 0)
1409 start_page_bounds.Offset(-page_width, 0);
1411 const PaginationModel::Transition& transition =
1412 pagination_model_->transition();
1413 if (current_page == 0 || transition.target_page == 0) {
1414 const int dir = transition.target_page > current_page ? -1 : 1;
1415 start_page_bounds.Offset(transition.progress * page_width * dir, 0);
1418 start_page_view_->SetBoundsRect(start_page_bounds);
1421 void AppsGridView::OnListItemAdded(size_t index, AppListItemModel* item) {
1422 EndDrag(true);
1424 views::View* view = CreateViewForItemAtIndex(index);
1425 view_model_.Add(view, index);
1426 AddChildView(view);
1428 UpdatePaging();
1429 UpdatePulsingBlockViews();
1430 Layout();
1431 SchedulePaint();
1434 void AppsGridView::OnListItemRemoved(size_t index, AppListItemModel* item) {
1435 EndDrag(true);
1437 views::View* view = view_model_.view_at(index);
1438 view_model_.Remove(index);
1439 delete view;
1441 UpdatePaging();
1442 UpdatePulsingBlockViews();
1443 Layout();
1444 SchedulePaint();
1447 void AppsGridView::OnListItemMoved(size_t from_index,
1448 size_t to_index,
1449 AppListItemModel* item) {
1450 EndDrag(true);
1451 view_model_.Move(from_index, to_index);
1453 UpdatePaging();
1454 AnimateToIdealBounds();
1457 void AppsGridView::TotalPagesChanged() {
1460 void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) {
1461 if (dragging()) {
1462 CalculateDropTarget(last_drag_point_, true);
1463 Layout();
1464 MaybeStartPageFlipTimer(last_drag_point_);
1465 } else {
1466 ClearSelectedView(selected_view_);
1467 Layout();
1471 void AppsGridView::TransitionStarted() {
1472 CancelContextMenusOnCurrentPage();
1475 void AppsGridView::TransitionChanged() {
1476 // Update layout for valid page transition only since over-scroll no longer
1477 // animates app icons.
1478 const PaginationModel::Transition& transition =
1479 pagination_model_->transition();
1480 if (pagination_model_->is_valid_page(transition.target_page))
1481 Layout();
1484 void AppsGridView::OnAppListModelStatusChanged() {
1485 UpdatePulsingBlockViews();
1486 Layout();
1487 SchedulePaint();
1490 void AppsGridView::SetViewHidden(views::View* view, bool hide, bool immediate) {
1491 #if defined(USE_AURA)
1492 ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator());
1493 animator.SetPreemptionStrategy(
1494 immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET :
1495 ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION);
1496 view->layer()->SetOpacity(hide ? 0 : 1);
1497 #endif
1500 bool AppsGridView::EnableFolderDragDropUI() {
1501 // Enable drag and drop folder UI only if it is at the app list root level
1502 // and the switch is on and the target folder can still accept new items.
1503 return switches::IsFolderUIEnabled() && is_root_level_ &&
1504 CanDropIntoTarget(drop_target_);
1507 bool AppsGridView::CanDropIntoTarget(const Index& drop_target) {
1508 views::View* target_view = GetViewAtSlotOnCurrentPage(drop_target.slot);
1509 if (!target_view)
1510 return true;
1512 AppListItemModel* target_item =
1513 static_cast<AppListItemView*>(target_view)->model();
1514 if (!IsFolderItem(target_item))
1515 return true;
1517 return static_cast<AppListFolderItem*>(target_item)->item_list()->
1518 item_count() < kMaxFolderItems;
1521 // TODO(jennyz): Optimize the calculation for finding nearest tile.
1522 AppsGridView::Index AppsGridView::GetNearestTileForDragView() {
1523 Index nearest_tile;
1524 nearest_tile.page = -1;
1525 nearest_tile.slot = -1;
1526 int d_min = -1;
1528 // Calculate the top left tile |drag_view| intersects.
1529 gfx::Point pt = drag_view_->bounds().origin();
1530 CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
1532 // Calculate the top right tile |drag_view| intersects.
1533 pt = drag_view_->bounds().top_right();
1534 CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
1536 // Calculate the bottom left tile |drag_view| intersects.
1537 pt = drag_view_->bounds().bottom_left();
1538 CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
1540 // Calculate the bottom right tile |drag_view| intersects.
1541 pt = drag_view_->bounds().bottom_right();
1542 CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
1544 const int d_folder_dropping =
1545 kFolderDroppingCircleRadius + kPreferredIconDimension / 2;
1546 const int d_reorder =
1547 kReorderDroppingCircleRadius + kPreferredIconDimension / 2;
1549 if (IsValidIndex(nearest_tile)) {
1550 if (d_min < d_folder_dropping) {
1551 views::View* target_view = GetViewAtSlotOnCurrentPage(nearest_tile.slot);
1552 if (target_view &&
1553 !IsFolderItem(static_cast<AppListItemView*>(drag_view_)->model())) {
1554 // If a non-folder item is dragged to the target slot with an item
1555 // sitting on it, attempt to drop the dragged item into the folder
1556 // containing the item on nearest_tile.
1557 drop_attempt_ = DROP_FOR_FOLDER;
1558 return nearest_tile;
1559 } else {
1560 // If the target slot is blank, or the dragged item is a folder, attempt
1561 // to re-order.
1562 drop_attempt_ = DROP_FOR_REORDER;
1563 return nearest_tile;
1565 } else if (d_min < d_reorder) {
1566 // Entering the re-order circle of the slot.
1567 drop_attempt_ = DROP_FOR_REORDER;
1568 return nearest_tile;
1572 // If |drag_view| is not entering the re-order or fold dropping region of
1573 // any items, cancel any previous re-order or folder dropping timer, and
1574 // return itself.
1575 drop_attempt_ = DROP_FOR_NONE;
1576 reorder_timer_.Stop();
1577 folder_dropping_timer_.Stop();
1578 return GetIndexOfView(drag_view_);
1581 void AppsGridView::CalculateNearestTileForVertex(const gfx::Point& vertex,
1582 Index* nearest_tile,
1583 int* d_min) {
1584 Index target_index;
1585 gfx::Rect target_bounds = GetTileBoundsForPoint(vertex, &target_index);
1587 if (target_bounds.IsEmpty() || target_index == *nearest_tile)
1588 return;
1590 int d_center = GetDistanceBetweenRects(drag_view_->bounds(), target_bounds);
1591 if (*d_min < 0 || d_center < *d_min) {
1592 *d_min = d_center;
1593 *nearest_tile = target_index;
1597 gfx::Rect AppsGridView::GetTileBoundsForPoint(const gfx::Point& point,
1598 Index *tile_index) {
1599 // Check if |point| is outside of contents bounds.
1600 gfx::Rect bounds(GetContentsBounds());
1601 if (!bounds.Contains(point))
1602 return gfx::Rect();
1604 // Calculate which tile |point| is enclosed in.
1605 int x = point.x();
1606 int y = point.y();
1607 int col = (x - bounds.x()) / kPreferredTileWidth;
1608 int row = (y - bounds.y()) / kPreferredTileHeight;
1609 gfx::Rect tile_rect = GetTileBounds(row, col);
1611 // Check if |point| is outside a valid item's tile.
1612 Index index(pagination_model_->selected_page(), row * cols_ + col);
1613 if (!IsValidIndex(index))
1614 return gfx::Rect();
1616 // |point| is inside of the valid item's tile.
1617 *tile_index = index;
1618 return tile_rect;
1621 gfx::Rect AppsGridView::GetTileBounds(int row, int col) const {
1622 gfx::Rect bounds(GetContentsBounds());
1623 gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
1624 gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
1625 tile_size.height() * rows_per_page_));
1626 grid_rect.Intersect(bounds);
1627 gfx::Rect tile_rect(
1628 gfx::Point(grid_rect.x() + col * tile_size.width(),
1629 grid_rect.y() + row * tile_size.height()),
1630 tile_size);
1631 return tile_rect;
1634 views::View* AppsGridView::GetViewAtSlotOnCurrentPage(int slot) {
1635 if (slot < 0)
1636 return NULL;
1638 // Calculate the original bound of the tile at |index|.
1639 int row = slot / cols_;
1640 int col = slot % cols_;
1641 gfx::Rect tile_rect = GetTileBounds(row, col);
1643 for (int i = 0; i < view_model_.view_size(); ++i) {
1644 views::View* view = view_model_.view_at(i);
1645 if (view->bounds() == tile_rect)
1646 return view;
1648 return NULL;
1651 void AppsGridView::SetAsFolderDroppingTarget(const Index& target_index,
1652 bool is_target_folder) {
1653 AppListItemView* target_view =
1654 static_cast<AppListItemView*>(
1655 GetViewAtSlotOnCurrentPage(target_index.slot));
1656 if (target_view)
1657 target_view->SetAsAttemptedFolderTarget(is_target_folder);
1660 } // namespace app_list