disable two ClientCertStoreChromeOSTest.* unit_tests on Valgrind bots
[chromium-blink-merge.git] / ui / app_list / views / apps_grid_view.cc
blobeb0e80ab288e7843f6ebd19adb1e98e2c160755f
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 "ui/app_list/app_list_constants.h"
13 #include "ui/app_list/app_list_folder_item.h"
14 #include "ui/app_list/app_list_item.h"
15 #include "ui/app_list/app_list_switches.h"
16 #include "ui/app_list/pagination_controller.h"
17 #include "ui/app_list/views/app_list_drag_and_drop_host.h"
18 #include "ui/app_list/views/app_list_folder_view.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/app_list/views/top_icon_animation_view.h"
24 #include "ui/compositor/scoped_layer_animation_settings.h"
25 #include "ui/events/event.h"
26 #include "ui/gfx/animation/animation.h"
27 #include "ui/gfx/geometry/vector2d.h"
28 #include "ui/gfx/geometry/vector2d_conversions.h"
29 #include "ui/views/border.h"
30 #include "ui/views/view_model_utils.h"
31 #include "ui/views/widget/widget.h"
33 #if defined(USE_AURA)
34 #include "ui/aura/window.h"
35 #include "ui/aura/window_event_dispatcher.h"
36 #if defined(OS_WIN)
37 #include "ui/views/win/hwnd_util.h"
38 #endif // defined(OS_WIN)
39 #endif // defined(USE_AURA)
41 #if defined(OS_WIN)
42 #include "base/command_line.h"
43 #include "base/files/file_path.h"
44 #include "base/win/shortcut.h"
45 #include "ui/base/dragdrop/drag_utils.h"
46 #include "ui/base/dragdrop/drop_target_win.h"
47 #include "ui/base/dragdrop/os_exchange_data.h"
48 #include "ui/base/dragdrop/os_exchange_data_provider_win.h"
49 #include "ui/gfx/win/dpi.h"
50 #endif
52 namespace app_list {
54 namespace {
56 // Distance a drag needs to be from the app grid to be considered 'outside', at
57 // which point we rearrange the apps to their pre-drag configuration, as a drop
58 // then would be canceled. We have a buffer to make it easier to drag apps to
59 // other pages.
60 const int kDragBufferPx = 20;
62 // Padding space in pixels for fixed layout.
63 const int kBottomPadding = 2;
64 const int kLeftRightPadding = 24;
66 // Padding space in pixels between pages.
67 const int kPagePadding = 40;
69 // Preferred tile size when showing in fixed layout.
70 const int kPreferredTileWidth = 88;
71 const int kPreferredTileHeight = 98;
73 const int kExperimentalPreferredTileWidth = 100;
74 const int kExperimentalPreferredTileHeight = 100;
76 // Padding on each side of a tile.
77 const int kExperimentalTileLeftRightPadding = 10;
78 const int kExperimentalTileBottomPadding = 6;
79 const int kExperimentalTileTopPadding = 6;
81 // Width in pixels of the area on the sides that triggers a page flip.
82 const int kPageFlipZoneSize = 40;
84 // Delay in milliseconds to do the page flip.
85 const int kPageFlipDelayInMs = 1000;
87 // How many pages on either side of the selected one we prerender. Currently 0
88 // to test impact of prerendering on UI jank for http://crbug.com/440224. Was 1.
89 const int kPrerenderPages = 0;
91 // The drag and drop proxy should get scaled by this factor.
92 const float kDragAndDropProxyScale = 1.5f;
94 // Delays in milliseconds to show folder dropping preview circle.
95 const int kFolderDroppingDelay = 150;
97 // Delays in milliseconds to show re-order preview.
98 const int kReorderDelay = 120;
100 // Delays in milliseconds to show folder item reparent UI.
101 const int kFolderItemReparentDelay = 50;
103 // Radius of the circle, in which if entered, show folder dropping preview
104 // UI.
105 const int kFolderDroppingCircleRadius = 39;
107 // Returns the size of a tile view excluding its padding.
108 gfx::Size GetTileViewSize() {
109 return switches::IsExperimentalAppListEnabled()
110 ? gfx::Size(kExperimentalPreferredTileWidth,
111 kExperimentalPreferredTileHeight)
112 : gfx::Size(kPreferredTileWidth, kPreferredTileHeight);
115 // Returns the padding around a tile view.
116 gfx::Insets GetTilePadding() {
117 if (!switches::IsExperimentalAppListEnabled())
118 return gfx::Insets();
120 return gfx::Insets(
121 -kExperimentalTileTopPadding, -kExperimentalTileLeftRightPadding,
122 -kExperimentalTileBottomPadding, -kExperimentalTileLeftRightPadding);
125 // RowMoveAnimationDelegate is used when moving an item into a different row.
126 // Before running the animation, the item's layer is re-created and kept in
127 // the original position, then the item is moved to just before its target
128 // position and opacity set to 0. When the animation runs, this delegate moves
129 // the layer and fades it out while fading in the item at the same time.
130 class RowMoveAnimationDelegate : public gfx::AnimationDelegate {
131 public:
132 RowMoveAnimationDelegate(views::View* view,
133 ui::Layer* layer,
134 const gfx::Rect& layer_target)
135 : view_(view),
136 layer_(layer),
137 layer_start_(layer ? layer->bounds() : gfx::Rect()),
138 layer_target_(layer_target) {
140 ~RowMoveAnimationDelegate() override {}
142 // gfx::AnimationDelegate overrides:
143 void AnimationProgressed(const gfx::Animation* animation) override {
144 view_->layer()->SetOpacity(animation->GetCurrentValue());
145 view_->layer()->ScheduleDraw();
147 if (layer_) {
148 layer_->SetOpacity(1 - animation->GetCurrentValue());
149 layer_->SetBounds(animation->CurrentValueBetween(layer_start_,
150 layer_target_));
151 layer_->ScheduleDraw();
154 void AnimationEnded(const gfx::Animation* animation) override {
155 view_->layer()->SetOpacity(1.0f);
156 view_->SchedulePaint();
158 void AnimationCanceled(const gfx::Animation* animation) override {
159 view_->layer()->SetOpacity(1.0f);
160 view_->SchedulePaint();
163 private:
164 // The view that needs to be wrapped. Owned by views hierarchy.
165 views::View* view_;
167 scoped_ptr<ui::Layer> layer_;
168 const gfx::Rect layer_start_;
169 const gfx::Rect layer_target_;
171 DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate);
174 // ItemRemoveAnimationDelegate is used to show animation for removing an item.
175 // This happens when user drags an item into a folder. The dragged item will
176 // be removed from the original list after it is dropped into the folder.
177 class ItemRemoveAnimationDelegate : public gfx::AnimationDelegate {
178 public:
179 explicit ItemRemoveAnimationDelegate(views::View* view)
180 : view_(view) {
183 ~ItemRemoveAnimationDelegate() override {}
185 // gfx::AnimationDelegate overrides:
186 void AnimationProgressed(const gfx::Animation* animation) override {
187 view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
188 view_->layer()->ScheduleDraw();
191 private:
192 scoped_ptr<views::View> view_;
194 DISALLOW_COPY_AND_ASSIGN(ItemRemoveAnimationDelegate);
197 // ItemMoveAnimationDelegate observes when an item finishes animating when it is
198 // not moving between rows. This is to ensure an item is repainted for the
199 // "zoom out" case when releasing an item being dragged.
200 class ItemMoveAnimationDelegate : public gfx::AnimationDelegate {
201 public:
202 explicit ItemMoveAnimationDelegate(views::View* view) : view_(view) {}
204 void AnimationEnded(const gfx::Animation* animation) override {
205 view_->SchedulePaint();
207 void AnimationCanceled(const gfx::Animation* animation) override {
208 view_->SchedulePaint();
211 private:
212 views::View* view_;
214 DISALLOW_COPY_AND_ASSIGN(ItemMoveAnimationDelegate);
217 // Returns true if the |item| is a folder item.
218 bool IsFolderItem(AppListItem* item) {
219 return (item->GetItemType() == AppListFolderItem::kItemType);
222 bool IsOEMFolderItem(AppListItem* item) {
223 return IsFolderItem(item) &&
224 (static_cast<AppListFolderItem*>(item))->folder_type() ==
225 AppListFolderItem::FOLDER_TYPE_OEM;
228 int ClampToRange(int value, int min, int max) {
229 return std::min(std::max(value, min), max);
232 } // namespace
234 #if defined(OS_WIN)
235 // Interprets drag events sent from Windows via the drag/drop API and forwards
236 // them to AppsGridView.
237 // On Windows, in order to have the OS perform the drag properly we need to
238 // provide it with a shortcut file which may or may not exist at the time the
239 // drag is started. Therefore while waiting for that shortcut to be located we
240 // just do a regular "internal" drag and transition into the synchronous drag
241 // when the shortcut is found/created. Hence a synchronous drag is an optional
242 // phase of a regular drag and non-Windows platforms drags are equivalent to a
243 // Windows drag that never enters the synchronous drag phase.
244 class SynchronousDrag : public ui::DragSourceWin {
245 public:
246 SynchronousDrag(AppsGridView* grid_view,
247 AppListItemView* drag_view,
248 const gfx::Point& drag_view_offset)
249 : grid_view_(grid_view),
250 drag_view_(drag_view),
251 drag_view_offset_(drag_view_offset),
252 has_shortcut_path_(false),
253 running_(false),
254 canceled_(false) {}
256 void set_shortcut_path(const base::FilePath& shortcut_path) {
257 has_shortcut_path_ = true;
258 shortcut_path_ = shortcut_path;
261 bool running() { return running_; }
263 bool CanRun() {
264 return has_shortcut_path_ && !running_;
267 void Run() {
268 DCHECK(CanRun());
270 // Prevent the synchronous dragger being destroyed while the drag is
271 // running.
272 Microsoft::WRL::ComPtr<SynchronousDrag> this_ref = this;
273 running_ = true;
275 ui::OSExchangeData data;
276 SetupExchangeData(&data);
278 // Hide the dragged view because the OS is going to create its own.
279 drag_view_->SetVisible(false);
281 // Blocks until the drag is finished. Calls into the ui::DragSourceWin
282 // methods.
283 DWORD effects;
284 DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
285 this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects);
287 // If |drag_view_| is NULL the drag was ended by some reentrant code.
288 if (drag_view_) {
289 // Make the drag view visible again.
290 drag_view_->SetVisible(true);
291 drag_view_->OnSyncDragEnd();
293 grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView());
297 void EndDragExternally() {
298 CancelDrag();
299 DCHECK(drag_view_);
300 drag_view_->SetVisible(true);
301 drag_view_ = NULL;
304 private:
305 // Overridden from ui::DragSourceWin.
306 void OnDragSourceCancel() override { canceled_ = true; }
308 void OnDragSourceDrop() override {}
310 void OnDragSourceMove() override {
311 grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords());
314 void SetupExchangeData(ui::OSExchangeData* data) {
315 data->SetFilename(shortcut_path_);
316 gfx::ImageSkia image(drag_view_->GetDragImage());
317 gfx::Size image_size(image.size());
318 drag_utils::SetDragImageOnDataObject(
319 image,
320 drag_view_offset_ - drag_view_->GetDragImageOffset(),
321 data);
324 HWND GetGridViewHWND() {
325 return views::HWNDForView(grid_view_);
328 bool IsCursorWithinGridView() {
329 POINT p;
330 GetCursorPos(&p);
331 return GetGridViewHWND() == WindowFromPoint(p);
334 gfx::Point GetCursorInGridViewCoords() {
335 POINT p;
336 GetCursorPos(&p);
337 ScreenToClient(GetGridViewHWND(), &p);
338 gfx::Point grid_view_pt(p.x, p.y);
339 grid_view_pt = gfx::win::ScreenToDIPPoint(grid_view_pt);
340 views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt);
341 return grid_view_pt;
344 AppsGridView* grid_view_;
345 AppListItemView* drag_view_;
346 gfx::Point drag_view_offset_;
347 bool has_shortcut_path_;
348 base::FilePath shortcut_path_;
349 bool running_;
350 bool canceled_;
352 DISALLOW_COPY_AND_ASSIGN(SynchronousDrag);
354 #endif // defined(OS_WIN)
356 AppsGridView::AppsGridView(AppsGridViewDelegate* delegate)
357 : model_(NULL),
358 item_list_(NULL),
359 delegate_(delegate),
360 folder_delegate_(NULL),
361 page_switcher_view_(NULL),
362 cols_(0),
363 rows_per_page_(0),
364 selected_view_(NULL),
365 drag_view_(NULL),
366 drag_start_page_(-1),
367 #if defined(OS_WIN)
368 use_synchronous_drag_(true),
369 #endif
370 drag_pointer_(NONE),
371 drop_attempt_(DROP_FOR_NONE),
372 drag_and_drop_host_(NULL),
373 forward_events_to_drag_and_drop_host_(false),
374 page_flip_target_(-1),
375 page_flip_delay_in_ms_(kPageFlipDelayInMs),
376 bounds_animator_(this),
377 activated_folder_item_view_(NULL),
378 dragging_for_reparent_item_(false) {
379 SetPaintToLayer(true);
380 // Clip any icons that are outside the grid view's bounds. These icons would
381 // otherwise be visible to the user when the grid view is off screen.
382 layer()->SetMasksToBounds(true);
383 SetFillsBoundsOpaquely(false);
385 pagination_model_.SetTransitionDurations(kPageTransitionDurationInMs,
386 kOverscrollPageTransitionDurationMs);
388 pagination_model_.AddObserver(this);
389 pagination_controller_.reset(new PaginationController(
390 &pagination_model_, PaginationController::SCROLL_AXIS_HORIZONTAL));
391 page_switcher_view_ = new PageSwitcher(&pagination_model_);
392 AddChildView(page_switcher_view_);
395 AppsGridView::~AppsGridView() {
396 // Coming here |drag_view_| should already be canceled since otherwise the
397 // drag would disappear after the app list got animated away and closed,
398 // which would look odd.
399 DCHECK(!drag_view_);
400 if (drag_view_)
401 EndDrag(true);
403 if (model_)
404 model_->RemoveObserver(this);
405 pagination_model_.RemoveObserver(this);
407 if (item_list_)
408 item_list_->RemoveObserver(this);
410 // Make sure |page_switcher_view_| is deleted before |pagination_model_|.
411 view_model_.Clear();
412 RemoveAllChildViews(true);
415 void AppsGridView::SetLayout(int cols, int rows_per_page) {
416 cols_ = cols;
417 rows_per_page_ = rows_per_page;
419 if (switches::IsExperimentalAppListEnabled()) {
420 SetBorder(views::Border::CreateEmptyBorder(
421 0, kExperimentalAppsGridPadding, 0, kExperimentalAppsGridPadding));
422 } else {
423 SetBorder(views::Border::CreateEmptyBorder(
424 0, kLeftRightPadding, kBottomPadding, kLeftRightPadding));
428 // static
429 gfx::Size AppsGridView::GetTotalTileSize() {
430 gfx::Rect rect(GetTileViewSize());
431 rect.Inset(GetTilePadding());
432 return rect.size();
435 void AppsGridView::ResetForShowApps() {
436 activated_folder_item_view_ = NULL;
437 ClearDragState();
438 layer()->SetOpacity(1.0f);
439 SetVisible(true);
440 // Set all views to visible in case they weren't made visible again by an
441 // incomplete animation.
442 for (int i = 0; i < view_model_.view_size(); ++i) {
443 view_model_.view_at(i)->SetVisible(true);
445 CHECK_EQ(item_list_->item_count(),
446 static_cast<size_t>(view_model_.view_size()));
449 void AppsGridView::SetModel(AppListModel* model) {
450 if (model_)
451 model_->RemoveObserver(this);
453 model_ = model;
454 if (model_)
455 model_->AddObserver(this);
457 Update();
460 void AppsGridView::SetItemList(AppListItemList* item_list) {
461 if (item_list_)
462 item_list_->RemoveObserver(this);
463 item_list_ = item_list;
464 if (item_list_)
465 item_list_->AddObserver(this);
466 Update();
469 void AppsGridView::SetSelectedView(AppListItemView* view) {
470 if (IsSelectedView(view) || IsDraggedView(view))
471 return;
473 Index index = GetIndexOfView(view);
474 if (IsValidIndex(index))
475 SetSelectedItemByIndex(index);
478 void AppsGridView::ClearSelectedView(AppListItemView* view) {
479 if (view && IsSelectedView(view)) {
480 selected_view_->SchedulePaint();
481 selected_view_ = NULL;
485 void AppsGridView::ClearAnySelectedView() {
486 if (selected_view_) {
487 selected_view_->SchedulePaint();
488 selected_view_ = NULL;
492 bool AppsGridView::IsSelectedView(const AppListItemView* view) const {
493 return selected_view_ == view;
496 void AppsGridView::InitiateDrag(AppListItemView* view,
497 Pointer pointer,
498 const ui::LocatedEvent& event) {
499 DCHECK(view);
500 if (drag_view_ || pulsing_blocks_model_.view_size())
501 return;
503 drag_view_ = view;
504 drag_view_init_index_ = GetIndexOfView(drag_view_);
505 drag_view_offset_ = event.location();
506 drag_start_page_ = pagination_model_.selected_page();
507 reorder_placeholder_ = drag_view_init_index_;
508 ExtractDragLocation(event, &drag_start_grid_view_);
509 drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
512 void AppsGridView::StartSettingUpSynchronousDrag() {
513 #if defined(OS_WIN)
514 if (!delegate_ || !use_synchronous_drag_)
515 return;
517 // Folders and downloading items can't be integrated with the OS.
518 if (IsFolderItem(drag_view_->item()) || drag_view_->item()->is_installing())
519 return;
521 // Favor the drag and drop host over native win32 drag. For the Win8/ash
522 // launcher we want to have ashes drag and drop over win32's.
523 if (drag_and_drop_host_)
524 return;
526 // Never create a second synchronous drag if the drag started in a folder.
527 if (IsDraggingForReparentInRootLevelGridView())
528 return;
530 synchronous_drag_ = Microsoft::WRL::Make<SynchronousDrag>(this, drag_view_,
531 drag_view_offset_);
532 delegate_->GetShortcutPathForApp(drag_view_->item()->id(),
533 base::Bind(&AppsGridView::OnGotShortcutPath,
534 base::Unretained(this),
535 synchronous_drag_));
536 #endif
539 bool AppsGridView::RunSynchronousDrag() {
540 #if defined(OS_WIN)
541 if (!synchronous_drag_.Get())
542 return false;
544 if (synchronous_drag_->CanRun()) {
545 if (IsDraggingForReparentInHiddenGridView())
546 folder_delegate_->SetRootLevelDragViewVisible(false);
547 synchronous_drag_->Run();
548 synchronous_drag_ = nullptr;
549 return true;
550 } else if (!synchronous_drag_->running()) {
551 // The OS drag is not ready yet. If the root grid has a drag view because
552 // a reparent has started, ensure it is visible.
553 if (IsDraggingForReparentInHiddenGridView())
554 folder_delegate_->SetRootLevelDragViewVisible(true);
556 #endif
557 return false;
560 void AppsGridView::CleanUpSynchronousDrag() {
561 #if defined(OS_WIN)
562 if (synchronous_drag_.Get())
563 synchronous_drag_->EndDragExternally();
565 synchronous_drag_ = nullptr;
566 #endif
569 #if defined(OS_WIN)
570 void AppsGridView::OnGotShortcutPath(
571 Microsoft::WRL::ComPtr<SynchronousDrag> synchronous_drag,
572 const base::FilePath& path) {
573 // Drag may have ended before we get the shortcut path or a new drag may have
574 // begun.
575 if (synchronous_drag_ != synchronous_drag)
576 return;
577 // Setting the shortcut path here means the next time we hit UpdateDrag()
578 // we'll enter the synchronous drag.
579 // NOTE we don't Run() the drag here because that causes animations not to
580 // update for some reason.
581 synchronous_drag_->set_shortcut_path(path);
582 DCHECK(synchronous_drag_->CanRun());
584 #endif
586 bool AppsGridView::UpdateDragFromItem(Pointer pointer,
587 const ui::LocatedEvent& event) {
588 if (!drag_view_)
589 return false; // Drag canceled.
591 gfx::Point drag_point_in_grid_view;
592 ExtractDragLocation(event, &drag_point_in_grid_view);
593 UpdateDrag(pointer, drag_point_in_grid_view);
594 if (!dragging())
595 return false;
597 // If a drag and drop host is provided, see if the drag operation needs to be
598 // forwarded.
599 gfx::Point location_in_screen = drag_point_in_grid_view;
600 views::View::ConvertPointToScreen(this, &location_in_screen);
601 DispatchDragEventToDragAndDropHost(location_in_screen);
602 if (drag_and_drop_host_)
603 drag_and_drop_host_->UpdateDragIconProxy(location_in_screen);
604 return true;
607 void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) {
608 if (folder_delegate_)
609 UpdateDragStateInsideFolder(pointer, point);
611 if (!drag_view_)
612 return; // Drag canceled.
614 if (RunSynchronousDrag())
615 return;
617 gfx::Vector2d drag_vector(point - drag_start_grid_view_);
618 if (!dragging() && ExceededDragThreshold(drag_vector)) {
619 drag_pointer_ = pointer;
620 // Move the view to the front so that it appears on top of other views.
621 ReorderChildView(drag_view_, -1);
622 bounds_animator_.StopAnimatingView(drag_view_);
623 // Stopping the animation may have invalidated our drag view due to the
624 // view hierarchy changing.
625 if (!drag_view_)
626 return;
628 StartSettingUpSynchronousDrag();
629 if (!dragging_for_reparent_item_)
630 StartDragAndDropHostDrag(point);
633 if (drag_pointer_ != pointer)
634 return;
636 drag_view_->SetPosition(drag_view_start_ + drag_vector);
638 last_drag_point_ = point;
639 const Index last_reorder_drop_target = reorder_drop_target_;
640 const Index last_folder_drop_target = folder_drop_target_;
641 DropAttempt last_drop_attempt = drop_attempt_;
642 CalculateDropTarget();
644 MaybeStartPageFlipTimer(last_drag_point_);
646 gfx::Point page_switcher_point(last_drag_point_);
647 views::View::ConvertPointToTarget(this, page_switcher_view_,
648 &page_switcher_point);
649 page_switcher_view_->UpdateUIForDragPoint(page_switcher_point);
651 if (last_folder_drop_target != folder_drop_target_ ||
652 last_reorder_drop_target != reorder_drop_target_ ||
653 last_drop_attempt != drop_attempt_) {
654 if (drop_attempt_ == DROP_FOR_REORDER) {
655 folder_dropping_timer_.Stop();
656 reorder_timer_.Start(FROM_HERE,
657 base::TimeDelta::FromMilliseconds(kReorderDelay),
658 this, &AppsGridView::OnReorderTimer);
659 } else if (drop_attempt_ == DROP_FOR_FOLDER) {
660 reorder_timer_.Stop();
661 folder_dropping_timer_.Start(FROM_HERE,
662 base::TimeDelta::FromMilliseconds(kFolderDroppingDelay),
663 this, &AppsGridView::OnFolderDroppingTimer);
666 // Reset the previous drop target.
667 SetAsFolderDroppingTarget(last_folder_drop_target, false);
671 void AppsGridView::EndDrag(bool cancel) {
672 // EndDrag was called before if |drag_view_| is NULL.
673 if (!drag_view_)
674 return;
676 // Coming here a drag and drop was in progress.
677 bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_;
678 if (forward_events_to_drag_and_drop_host_) {
679 DCHECK(!IsDraggingForReparentInRootLevelGridView());
680 forward_events_to_drag_and_drop_host_ = false;
681 drag_and_drop_host_->EndDrag(cancel);
682 if (IsDraggingForReparentInHiddenGridView()) {
683 folder_delegate_->DispatchEndDragEventForReparent(
684 true /* events_forwarded_to_drag_drop_host */,
685 cancel /* cancel_drag */);
687 } else {
688 if (IsDraggingForReparentInHiddenGridView()) {
689 // Forward the EndDrag event to the root level grid view.
690 folder_delegate_->DispatchEndDragEventForReparent(
691 false /* events_forwarded_to_drag_drop_host */,
692 cancel /* cancel_drag */);
693 EndDragForReparentInHiddenFolderGridView();
694 return;
697 if (IsDraggingForReparentInRootLevelGridView()) {
698 // An EndDrag can be received during a reparent via a model change. This
699 // is always a cancel and needs to be forwarded to the folder.
700 DCHECK(cancel);
701 delegate_->CancelDragInActiveFolder();
702 return;
705 if (!cancel && dragging()) {
706 // Regular drag ending path, ie, not for reparenting.
707 CalculateDropTarget();
708 if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER &&
709 IsValidIndex(folder_drop_target_)) {
710 MoveItemToFolder(drag_view_, folder_drop_target_);
711 } else if (IsValidIndex(reorder_drop_target_)) {
712 MoveItemInModel(drag_view_, reorder_drop_target_);
717 if (drag_and_drop_host_) {
718 // If we had a drag and drop proxy icon, we delete it and make the real
719 // item visible again.
720 drag_and_drop_host_->DestroyDragIconProxy();
721 // Issue 439055: MoveItemToFolder() can sometimes delete |drag_view_|
722 if (drag_view_) {
723 if (landed_in_drag_and_drop_host) {
724 // Move the item directly to the target location, avoiding the
725 // "zip back" animation if the user was pinning it to the shelf.
726 int i = reorder_drop_target_.slot;
727 gfx::Rect bounds = view_model_.ideal_bounds(i);
728 drag_view_->SetBoundsRect(bounds);
730 // Fade in slowly if it landed in the shelf.
731 SetViewHidden(drag_view_, false /* show */,
732 !landed_in_drag_and_drop_host /* animate */);
736 // The drag can be ended after the synchronous drag is created but before it
737 // is Run().
738 CleanUpSynchronousDrag();
740 SetAsFolderDroppingTarget(folder_drop_target_, false);
741 ClearDragState();
742 AnimateToIdealBounds();
744 StopPageFlipTimer();
746 // If user releases mouse inside a folder's grid view, burst the folder
747 // container ink bubble.
748 if (folder_delegate_ && !IsDraggingForReparentInHiddenGridView())
749 folder_delegate_->UpdateFolderViewBackground(false);
752 void AppsGridView::StopPageFlipTimer() {
753 page_flip_timer_.Stop();
754 page_flip_target_ = -1;
757 AppListItemView* AppsGridView::GetItemViewAt(int index) const {
758 return view_model_.view_at(index);
761 void AppsGridView::SetTopItemViewsVisible(bool visible) {
762 int top_item_count = std::min(static_cast<int>(kNumFolderTopItems),
763 view_model_.view_size());
764 for (int i = 0; i < top_item_count; ++i)
765 GetItemViewAt(i)->icon()->SetVisible(visible);
768 void AppsGridView::ScheduleShowHideAnimation(bool show) {
769 // Stop any previous animation.
770 layer()->GetAnimator()->StopAnimating();
772 // Set initial state.
773 SetVisible(true);
774 layer()->SetOpacity(show ? 0.0f : 1.0f);
776 ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator());
777 animation.AddObserver(this);
778 animation.SetTweenType(
779 show ? kFolderFadeInTweenType : kFolderFadeOutTweenType);
780 animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
781 show ? kFolderTransitionInDurationMs : kFolderTransitionOutDurationMs));
783 layer()->SetOpacity(show ? 1.0f : 0.0f);
786 void AppsGridView::InitiateDragFromReparentItemInRootLevelGridView(
787 AppListItemView* original_drag_view,
788 const gfx::Rect& drag_view_rect,
789 const gfx::Point& drag_point,
790 bool has_native_drag) {
791 DCHECK(original_drag_view && !drag_view_);
792 DCHECK(!dragging_for_reparent_item_);
794 // Since the item is new, its placeholder is conceptually at the back of the
795 // entire apps grid.
796 reorder_placeholder_ = GetLastViewIndex();
798 // Create a new AppListItemView to duplicate the original_drag_view in the
799 // folder's grid view.
800 AppListItemView* view = new AppListItemView(this, original_drag_view->item());
801 AddChildView(view);
802 drag_view_ = view;
803 drag_view_->SetPaintToLayer(true);
804 // Note: For testing purpose, SetFillsBoundsOpaquely can be set to true to
805 // show the gray background.
806 drag_view_->SetFillsBoundsOpaquely(false);
807 drag_view_->SetBoundsRect(drag_view_rect);
808 drag_view_->SetDragUIState(); // Hide the title of the drag_view_.
810 // Hide the drag_view_ for drag icon proxy when a native drag is responsible
811 // for showing the icon.
812 if (has_native_drag)
813 SetViewHidden(drag_view_, true /* hide */, true /* no animate */);
815 // Add drag_view_ to the end of the view_model_.
816 view_model_.Add(drag_view_, view_model_.view_size());
818 drag_start_page_ = pagination_model_.selected_page();
819 drag_start_grid_view_ = drag_point;
821 drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
823 // Set the flag in root level grid view.
824 dragging_for_reparent_item_ = true;
827 void AppsGridView::UpdateDragFromReparentItem(Pointer pointer,
828 const gfx::Point& drag_point) {
829 // Note that if a cancel ocurrs while reparenting, the |drag_view_| in both
830 // root and folder grid views is cleared, so the check in UpdateDragFromItem()
831 // for |drag_view_| being NULL (in the folder grid) is sufficient.
832 DCHECK(drag_view_);
833 DCHECK(IsDraggingForReparentInRootLevelGridView());
835 UpdateDrag(pointer, drag_point);
838 bool AppsGridView::IsDraggedView(const AppListItemView* view) const {
839 return drag_view_ == view;
842 void AppsGridView::ClearDragState() {
843 drop_attempt_ = DROP_FOR_NONE;
844 drag_pointer_ = NONE;
845 reorder_drop_target_ = Index();
846 folder_drop_target_ = Index();
847 reorder_placeholder_ = Index();
848 drag_start_grid_view_ = gfx::Point();
849 drag_start_page_ = -1;
850 drag_view_offset_ = gfx::Point();
852 if (drag_view_) {
853 drag_view_->OnDragEnded();
854 if (IsDraggingForReparentInRootLevelGridView()) {
855 const int drag_view_index = view_model_.GetIndexOfView(drag_view_);
856 CHECK_EQ(view_model_.view_size() - 1, drag_view_index);
857 DeleteItemViewAtIndex(drag_view_index);
860 drag_view_ = NULL;
861 dragging_for_reparent_item_ = false;
864 void AppsGridView::SetDragViewVisible(bool visible) {
865 DCHECK(drag_view_);
866 SetViewHidden(drag_view_, !visible, true);
869 void AppsGridView::SetDragAndDropHostOfCurrentAppList(
870 ApplicationDragAndDropHost* drag_and_drop_host) {
871 drag_and_drop_host_ = drag_and_drop_host;
874 void AppsGridView::Prerender() {
875 Layout();
876 int selected_page = std::max(0, pagination_model_.selected_page());
877 int start = std::max(0, (selected_page - kPrerenderPages) * tiles_per_page());
878 int end = std::min(view_model_.view_size(),
879 (selected_page + 1 + kPrerenderPages) * tiles_per_page());
880 for (int i = start; i < end; i++)
881 GetItemViewAt(i)->Prerender();
884 bool AppsGridView::IsAnimatingView(AppListItemView* view) {
885 return bounds_animator_.IsAnimating(view);
888 gfx::Size AppsGridView::GetPreferredSize() const {
889 const gfx::Insets insets(GetInsets());
890 int page_switcher_height = page_switcher_view_->GetPreferredSize().height();
891 gfx::Size size = GetTileGridSize();
892 size.Enlarge(insets.width(), insets.height() + page_switcher_height);
893 return size;
896 bool AppsGridView::GetDropFormats(
897 int* formats,
898 std::set<OSExchangeData::CustomFormat>* custom_formats) {
899 // TODO(koz): Only accept a specific drag type for app shortcuts.
900 *formats = OSExchangeData::FILE_NAME;
901 return true;
904 bool AppsGridView::CanDrop(const OSExchangeData& data) {
905 return true;
908 int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) {
909 return ui::DragDropTypes::DRAG_MOVE;
912 void AppsGridView::Layout() {
913 if (bounds_animator_.IsAnimating())
914 bounds_animator_.Cancel();
916 CalculateIdealBounds();
917 for (int i = 0; i < view_model_.view_size(); ++i) {
918 AppListItemView* view = GetItemViewAt(i);
919 if (view != drag_view_)
920 view->SetBoundsRect(view_model_.ideal_bounds(i));
922 views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_);
924 const int page_switcher_height =
925 page_switcher_view_->GetPreferredSize().height();
926 gfx::Rect rect(GetContentsBounds());
927 rect.set_y(rect.bottom() - page_switcher_height);
928 rect.set_height(page_switcher_height);
929 page_switcher_view_->SetBoundsRect(rect);
932 bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) {
933 bool handled = false;
934 if (selected_view_)
935 handled = static_cast<views::View*>(selected_view_)->OnKeyPressed(event);
937 if (!handled) {
938 const int forward_dir = base::i18n::IsRTL() ? -1 : 1;
939 switch (event.key_code()) {
940 case ui::VKEY_LEFT:
941 MoveSelected(0, -forward_dir, 0);
942 return true;
943 case ui::VKEY_RIGHT:
944 MoveSelected(0, forward_dir, 0);
945 return true;
946 case ui::VKEY_UP:
947 if (selected_view_) // Don't initiate selection with UP
948 MoveSelected(0, 0, -1);
949 return true;
950 case ui::VKEY_DOWN:
951 MoveSelected(0, 0, 1);
952 return true;
953 case ui::VKEY_PRIOR: {
954 MoveSelected(-1, 0, 0);
955 return true;
957 case ui::VKEY_NEXT: {
958 MoveSelected(1, 0, 0);
959 return true;
961 case ui::VKEY_TAB: {
962 if (event.IsShiftDown()) {
963 ClearAnySelectedView(); // ContentsView will move focus back.
964 } else {
965 MoveSelected(0, 0, 0); // Ensure but don't change selection.
966 handled = true; // TABing internally doesn't move focus.
968 break;
970 default:
971 break;
975 return handled;
978 bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) {
979 bool handled = false;
980 if (selected_view_)
981 handled = selected_view_->OnKeyReleased(event);
983 return handled;
986 bool AppsGridView::OnMouseWheel(const ui::MouseWheelEvent& event) {
987 return pagination_controller_->OnScroll(
988 gfx::Vector2d(event.x_offset(), event.y_offset()),
989 PaginationController::SCROLL_MOUSE_WHEEL);
992 void AppsGridView::ViewHierarchyChanged(
993 const ViewHierarchyChangedDetails& details) {
994 if (!details.is_add && details.parent == this) {
995 // The view being delete should not have reference in |view_model_|.
996 CHECK_EQ(-1, view_model_.GetIndexOfView(details.child));
998 if (selected_view_ == details.child)
999 selected_view_ = NULL;
1000 if (activated_folder_item_view_ == details.child)
1001 activated_folder_item_view_ = NULL;
1003 if (drag_view_ == details.child)
1004 EndDrag(true);
1006 bounds_animator_.StopAnimatingView(details.child);
1010 void AppsGridView::OnGestureEvent(ui::GestureEvent* event) {
1011 if (pagination_controller_->OnGestureEvent(*event, GetContentsBounds()))
1012 event->SetHandled();
1015 void AppsGridView::OnScrollEvent(ui::ScrollEvent* event) {
1016 if (event->type() == ui::ET_SCROLL_FLING_CANCEL)
1017 return;
1019 gfx::Vector2dF offset(event->x_offset(), event->y_offset());
1020 if (pagination_controller_->OnScroll(gfx::ToFlooredVector2d(offset),
1021 PaginationController::SCROLL_TOUCHPAD)) {
1022 event->SetHandled();
1023 event->StopPropagation();
1027 void AppsGridView::Update() {
1028 DCHECK(!selected_view_ && !drag_view_);
1029 view_model_.Clear();
1030 if (!item_list_ || !item_list_->item_count())
1031 return;
1032 for (size_t i = 0; i < item_list_->item_count(); ++i) {
1033 AppListItemView* view = CreateViewForItemAtIndex(i);
1034 view_model_.Add(view, i);
1035 AddChildView(view);
1037 UpdatePaging();
1038 UpdatePulsingBlockViews();
1039 Layout();
1040 SchedulePaint();
1043 void AppsGridView::UpdatePaging() {
1044 int total_page = view_model_.view_size() && tiles_per_page()
1045 ? (view_model_.view_size() - 1) / tiles_per_page() + 1
1046 : 0;
1048 pagination_model_.SetTotalPages(total_page);
1051 void AppsGridView::UpdatePulsingBlockViews() {
1052 const int existing_items = item_list_ ? item_list_->item_count() : 0;
1053 const int available_slots =
1054 tiles_per_page() - existing_items % tiles_per_page();
1055 const int desired = model_->status() == AppListModel::STATUS_SYNCING ?
1056 available_slots : 0;
1058 if (pulsing_blocks_model_.view_size() == desired)
1059 return;
1061 while (pulsing_blocks_model_.view_size() > desired) {
1062 PulsingBlockView* view = pulsing_blocks_model_.view_at(0);
1063 pulsing_blocks_model_.Remove(0);
1064 delete view;
1067 while (pulsing_blocks_model_.view_size() < desired) {
1068 PulsingBlockView* view = new PulsingBlockView(GetTotalTileSize(), true);
1069 pulsing_blocks_model_.Add(view, 0);
1070 AddChildView(view);
1074 AppListItemView* AppsGridView::CreateViewForItemAtIndex(size_t index) {
1075 // The drag_view_ might be pending for deletion, therefore view_model_
1076 // may have one more item than item_list_.
1077 DCHECK_LE(index, item_list_->item_count());
1078 AppListItemView* view = new AppListItemView(this,
1079 item_list_->item_at(index));
1080 view->SetPaintToLayer(true);
1081 view->SetFillsBoundsOpaquely(false);
1082 return view;
1085 AppsGridView::Index AppsGridView::GetIndexFromModelIndex(
1086 int model_index) const {
1087 return Index(model_index / tiles_per_page(), model_index % tiles_per_page());
1090 int AppsGridView::GetModelIndexFromIndex(const Index& index) const {
1091 return index.page * tiles_per_page() + index.slot;
1094 void AppsGridView::EnsureViewVisible(const Index& index) {
1095 if (pagination_model_.has_transition())
1096 return;
1098 if (IsValidIndex(index))
1099 pagination_model_.SelectPage(index.page, false);
1102 void AppsGridView::SetSelectedItemByIndex(const Index& index) {
1103 if (GetIndexOfView(selected_view_) == index)
1104 return;
1106 AppListItemView* new_selection = GetViewAtIndex(index);
1107 if (!new_selection)
1108 return; // Keep current selection.
1110 if (selected_view_)
1111 selected_view_->SchedulePaint();
1113 EnsureViewVisible(index);
1114 selected_view_ = new_selection;
1115 selected_view_->SetTitleSubpixelAA();
1116 selected_view_->SchedulePaint();
1117 selected_view_->NotifyAccessibilityEvent(
1118 ui::AX_EVENT_FOCUS, true);
1121 bool AppsGridView::IsValidIndex(const Index& index) const {
1122 return index.page >= 0 && index.page < pagination_model_.total_pages() &&
1123 index.slot >= 0 && index.slot < tiles_per_page() &&
1124 GetModelIndexFromIndex(index) < view_model_.view_size();
1127 AppsGridView::Index AppsGridView::GetIndexOfView(
1128 const AppListItemView* view) const {
1129 const int model_index = view_model_.GetIndexOfView(view);
1130 if (model_index == -1)
1131 return Index();
1133 return GetIndexFromModelIndex(model_index);
1136 AppListItemView* AppsGridView::GetViewAtIndex(const Index& index) const {
1137 if (!IsValidIndex(index))
1138 return NULL;
1140 const int model_index = GetModelIndexFromIndex(index);
1141 return GetItemViewAt(model_index);
1144 AppsGridView::Index AppsGridView::GetLastViewIndex() const {
1145 DCHECK_LT(0, view_model_.view_size());
1146 int view_index = view_model_.view_size() - 1;
1147 return Index(view_index / tiles_per_page(), view_index % tiles_per_page());
1150 void AppsGridView::MoveSelected(int page_delta,
1151 int slot_x_delta,
1152 int slot_y_delta) {
1153 if (!selected_view_)
1154 return SetSelectedItemByIndex(Index(pagination_model_.selected_page(), 0));
1156 const Index& selected = GetIndexOfView(selected_view_);
1157 int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_;
1159 if (selected.slot % cols_ == 0 && slot_x_delta == -1) {
1160 if (selected.page > 0) {
1161 page_delta = -1;
1162 target_slot = selected.slot + cols_ - 1;
1163 } else {
1164 target_slot = selected.slot;
1168 if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) {
1169 if (selected.page < pagination_model_.total_pages() - 1) {
1170 page_delta = 1;
1171 target_slot = selected.slot - cols_ + 1;
1172 } else {
1173 target_slot = selected.slot;
1177 // Clamp the target slot to the last item if we are moving to the last page
1178 // but our target slot is past the end of the item list.
1179 if (page_delta &&
1180 selected.page + page_delta == pagination_model_.total_pages() - 1) {
1181 int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page();
1182 if (last_item_slot < target_slot) {
1183 target_slot = last_item_slot;
1187 int target_page = std::min(pagination_model_.total_pages() - 1,
1188 std::max(selected.page + page_delta, 0));
1189 SetSelectedItemByIndex(Index(target_page, target_slot));
1192 void AppsGridView::CalculateIdealBounds() {
1193 gfx::Size grid_size = GetTileGridSize();
1195 // Page size including padding pixels. A tile.x + page_width means the same
1196 // tile slot in the next page; similarly for tile.y + page_height.
1197 const int page_width = grid_size.width() + kPagePadding;
1198 const int page_height = grid_size.height() + kPagePadding;
1200 // If there is a transition, calculates offset for current and target page.
1201 const int current_page = pagination_model_.selected_page();
1202 const PaginationModel::Transition& transition =
1203 pagination_model_.transition();
1204 const bool is_valid = pagination_model_.is_valid_page(transition.target_page);
1206 // Transition to previous page means negative offset.
1207 const int dir = transition.target_page > current_page ? -1 : 1;
1209 const int total_views =
1210 view_model_.view_size() + pulsing_blocks_model_.view_size();
1211 int slot_index = 0;
1212 for (int i = 0; i < total_views; ++i) {
1213 if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_)
1214 continue;
1216 Index view_index = GetIndexFromModelIndex(slot_index);
1218 // Leaves a blank space in the grid for the current reorder placeholder.
1219 if (reorder_placeholder_ == view_index) {
1220 ++slot_index;
1221 view_index = GetIndexFromModelIndex(slot_index);
1224 // Decide the x or y offset for current item.
1225 int x_offset = 0;
1226 int y_offset = 0;
1228 if (pagination_controller_->scroll_axis() ==
1229 PaginationController::SCROLL_AXIS_HORIZONTAL) {
1230 if (view_index.page < current_page)
1231 x_offset = -page_width;
1232 else if (view_index.page > current_page)
1233 x_offset = page_width;
1235 if (is_valid) {
1236 if (view_index.page == current_page ||
1237 view_index.page == transition.target_page) {
1238 x_offset += transition.progress * page_width * dir;
1241 } else {
1242 if (view_index.page < current_page)
1243 y_offset = -page_height;
1244 else if (view_index.page > current_page)
1245 y_offset = page_height;
1247 if (is_valid) {
1248 if (view_index.page == current_page ||
1249 view_index.page == transition.target_page) {
1250 y_offset += transition.progress * page_height * dir;
1255 const int row = view_index.slot / cols_;
1256 const int col = view_index.slot % cols_;
1257 gfx::Rect tile_slot = GetExpectedTileBounds(row, col);
1258 tile_slot.Offset(x_offset, y_offset);
1259 if (i < view_model_.view_size()) {
1260 view_model_.set_ideal_bounds(i, tile_slot);
1261 } else {
1262 pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(),
1263 tile_slot);
1266 ++slot_index;
1270 void AppsGridView::AnimateToIdealBounds() {
1271 const gfx::Rect visible_bounds(GetVisibleBounds());
1273 CalculateIdealBounds();
1274 for (int i = 0; i < view_model_.view_size(); ++i) {
1275 AppListItemView* view = GetItemViewAt(i);
1276 if (view == drag_view_)
1277 continue;
1279 const gfx::Rect& target = view_model_.ideal_bounds(i);
1280 if (bounds_animator_.GetTargetBounds(view) == target)
1281 continue;
1283 const gfx::Rect& current = view->bounds();
1284 const bool current_visible = visible_bounds.Intersects(current);
1285 const bool target_visible = visible_bounds.Intersects(target);
1286 const bool visible = current_visible || target_visible;
1288 const int y_diff = target.y() - current.y();
1289 if (visible && y_diff && y_diff % GetTotalTileSize().height() == 0) {
1290 AnimationBetweenRows(view,
1291 current_visible,
1292 current,
1293 target_visible,
1294 target);
1295 } else if (visible || bounds_animator_.IsAnimating(view)) {
1296 bounds_animator_.AnimateViewTo(view, target);
1297 bounds_animator_.SetAnimationDelegate(
1298 view,
1299 scoped_ptr<gfx::AnimationDelegate>(
1300 new ItemMoveAnimationDelegate(view)));
1301 } else {
1302 view->SetBoundsRect(target);
1307 void AppsGridView::AnimationBetweenRows(AppListItemView* view,
1308 bool animate_current,
1309 const gfx::Rect& current,
1310 bool animate_target,
1311 const gfx::Rect& target) {
1312 // Determine page of |current| and |target|. -1 means in the left invisible
1313 // page, 0 is the center visible page and 1 means in the right invisible page.
1314 const int current_page = current.x() < 0 ? -1 :
1315 current.x() >= width() ? 1 : 0;
1316 const int target_page = target.x() < 0 ? -1 :
1317 target.x() >= width() ? 1 : 0;
1319 const int dir = current_page < target_page ||
1320 (current_page == target_page && current.y() < target.y()) ? 1 : -1;
1322 scoped_ptr<ui::Layer> layer;
1323 if (animate_current) {
1324 layer = view->RecreateLayer();
1325 layer->SuppressPaint();
1327 view->SetFillsBoundsOpaquely(false);
1328 view->layer()->SetOpacity(0.f);
1331 gfx::Size total_tile_size = GetTotalTileSize();
1332 gfx::Rect current_out(current);
1333 current_out.Offset(dir * total_tile_size.width(), 0);
1335 gfx::Rect target_in(target);
1336 if (animate_target)
1337 target_in.Offset(-dir * total_tile_size.width(), 0);
1338 view->SetBoundsRect(target_in);
1339 bounds_animator_.AnimateViewTo(view, target);
1341 bounds_animator_.SetAnimationDelegate(
1342 view,
1343 scoped_ptr<gfx::AnimationDelegate>(
1344 new RowMoveAnimationDelegate(view, layer.release(), current_out)));
1347 void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event,
1348 gfx::Point* drag_point) {
1349 // Use root location of |event| instead of location in |drag_view_|'s
1350 // coordinates because |drag_view_| has a scale transform and location
1351 // could have integer round error and causes jitter.
1352 *drag_point = event.root_location();
1354 #if defined(USE_AURA)
1355 // GetWidget() could be NULL for tests.
1356 if (GetWidget()) {
1357 aura::Window::ConvertPointToTarget(
1358 GetWidget()->GetNativeWindow()->GetRootWindow(),
1359 GetWidget()->GetNativeWindow(),
1360 drag_point);
1362 #endif
1364 views::View::ConvertPointFromWidget(this, drag_point);
1367 void AppsGridView::CalculateDropTarget() {
1368 DCHECK(drag_view_);
1370 gfx::Point point = drag_view_->icon()->bounds().CenterPoint();
1371 views::View::ConvertPointToTarget(drag_view_, this, &point);
1372 if (!IsPointWithinDragBuffer(point)) {
1373 // Reset the reorder target to the original position if the cursor is
1374 // outside the drag buffer.
1375 if (IsDraggingForReparentInRootLevelGridView()) {
1376 drop_attempt_ = DROP_FOR_NONE;
1377 return;
1380 reorder_drop_target_ = drag_view_init_index_;
1381 drop_attempt_ = DROP_FOR_REORDER;
1382 return;
1385 if (EnableFolderDragDropUI() &&
1386 CalculateFolderDropTarget(point, &folder_drop_target_)) {
1387 drop_attempt_ = DROP_FOR_FOLDER;
1388 return;
1391 drop_attempt_ = DROP_FOR_REORDER;
1392 CalculateReorderDropTarget(point, &reorder_drop_target_);
1395 bool AppsGridView::CalculateFolderDropTarget(const gfx::Point& point,
1396 Index* drop_target) const {
1397 // Folders can't be dropped into other folders.
1398 if (IsFolderItem(drag_view_->item()))
1399 return false;
1401 // A folder drop shouldn't happen on the reorder placeholder since that would
1402 // be merging an item with itself.
1403 Index nearest_tile_index(GetNearestTileIndexForPoint(point));
1404 if (!IsValidIndex(nearest_tile_index) ||
1405 nearest_tile_index == reorder_placeholder_) {
1406 return false;
1409 int distance_to_tile_center =
1410 (point - GetExpectedTileBounds(nearest_tile_index.slot).CenterPoint())
1411 .Length();
1412 if (distance_to_tile_center > kFolderDroppingCircleRadius)
1413 return false;
1415 AppListItemView* target_view =
1416 GetViewDisplayedAtSlotOnCurrentPage(nearest_tile_index.slot);
1417 if (!target_view)
1418 return false;
1420 AppListItem* target_item = target_view->item();
1422 // Items can only be dropped into non-folders (which have no children) or
1423 // folders that have fewer than the max allowed items.
1424 // The OEM folder does not allow drag/drop of other items into it.
1425 if (target_item->ChildItemCount() >= kMaxFolderItems ||
1426 IsOEMFolderItem(target_item)) {
1427 return false;
1430 *drop_target = nearest_tile_index;
1431 DCHECK(IsValidIndex(*drop_target));
1432 return true;
1435 void AppsGridView::CalculateReorderDropTarget(const gfx::Point& point,
1436 Index* drop_target) const {
1437 gfx::Rect bounds = GetContentsBounds();
1438 Index grid_index = GetNearestTileIndexForPoint(point);
1439 gfx::Point reorder_placeholder_center =
1440 GetExpectedTileBounds(reorder_placeholder_.slot).CenterPoint();
1442 int x_offset_direction = 0;
1443 if (grid_index == reorder_placeholder_) {
1444 x_offset_direction = reorder_placeholder_center.x() < point.x() ? -1 : 1;
1445 } else {
1446 x_offset_direction = reorder_placeholder_ < grid_index ? -1 : 1;
1449 gfx::Size total_tile_size = GetTotalTileSize();
1450 int row = grid_index.slot / cols_;
1452 // Offset the target column based on the direction of the target. This will
1453 // result in earlier targets getting their reorder zone shifted backwards
1454 // and later targets getting their reorder zones shifted forwards.
1456 // This makes eordering feel like the user is slotting items into the spaces
1457 // between apps.
1458 int x_offset = x_offset_direction *
1459 (total_tile_size.width() - kFolderDroppingCircleRadius) / 2;
1460 int col = (point.x() - bounds.x() + x_offset) / total_tile_size.width();
1461 col = ClampToRange(col, 0, cols_ - 1);
1462 *drop_target =
1463 std::min(Index(pagination_model_.selected_page(), row * cols_ + col),
1464 GetLastViewIndex());
1465 DCHECK(IsValidIndex(*drop_target));
1468 void AppsGridView::OnReorderTimer() {
1469 if (drop_attempt_ == DROP_FOR_REORDER) {
1470 reorder_placeholder_ = reorder_drop_target_;
1471 AnimateToIdealBounds();
1475 void AppsGridView::OnFolderItemReparentTimer() {
1476 DCHECK(folder_delegate_);
1477 if (drag_out_of_folder_container_ && drag_view_) {
1478 bool has_native_drag = drag_and_drop_host_ != nullptr;
1479 #if defined(OS_WIN)
1480 has_native_drag = has_native_drag || synchronous_drag_.Get();
1481 #endif
1482 folder_delegate_->ReparentItem(
1483 drag_view_, last_drag_point_, has_native_drag);
1485 // Set the flag in the folder's grid view.
1486 dragging_for_reparent_item_ = true;
1488 // Do not observe any data change since it is going to be hidden.
1489 item_list_->RemoveObserver(this);
1490 item_list_ = NULL;
1494 void AppsGridView::OnFolderDroppingTimer() {
1495 if (drop_attempt_ == DROP_FOR_FOLDER)
1496 SetAsFolderDroppingTarget(folder_drop_target_, true);
1499 void AppsGridView::UpdateDragStateInsideFolder(Pointer pointer,
1500 const gfx::Point& drag_point) {
1501 if (IsUnderOEMFolder())
1502 return;
1504 if (IsDraggingForReparentInHiddenGridView()) {
1505 // Dispatch drag event to root level grid view for re-parenting folder
1506 // folder item purpose.
1507 DispatchDragEventForReparent(pointer, drag_point);
1508 return;
1511 // Regular drag and drop in a folder's grid view.
1512 folder_delegate_->UpdateFolderViewBackground(true);
1514 // Calculate if the drag_view_ is dragged out of the folder's container
1515 // ink bubble.
1516 gfx::Rect bounds_to_folder_view = ConvertRectToParent(drag_view_->bounds());
1517 gfx::Point pt = bounds_to_folder_view.CenterPoint();
1518 bool is_item_dragged_out_of_folder =
1519 folder_delegate_->IsPointOutsideOfFolderBoundary(pt);
1520 if (is_item_dragged_out_of_folder) {
1521 if (!drag_out_of_folder_container_) {
1522 folder_item_reparent_timer_.Start(
1523 FROM_HERE,
1524 base::TimeDelta::FromMilliseconds(kFolderItemReparentDelay),
1525 this,
1526 &AppsGridView::OnFolderItemReparentTimer);
1527 drag_out_of_folder_container_ = true;
1529 } else {
1530 folder_item_reparent_timer_.Stop();
1531 drag_out_of_folder_container_ = false;
1535 bool AppsGridView::IsDraggingForReparentInRootLevelGridView() const {
1536 return (!folder_delegate_ && dragging_for_reparent_item_);
1539 bool AppsGridView::IsDraggingForReparentInHiddenGridView() const {
1540 return (folder_delegate_ && dragging_for_reparent_item_);
1543 gfx::Rect AppsGridView::GetTargetIconRectInFolder(
1544 AppListItemView* drag_item_view,
1545 AppListItemView* folder_item_view) {
1546 gfx::Rect view_ideal_bounds = view_model_.ideal_bounds(
1547 view_model_.GetIndexOfView(folder_item_view));
1548 gfx::Rect icon_ideal_bounds =
1549 folder_item_view->GetIconBoundsForTargetViewBounds(view_ideal_bounds);
1550 AppListFolderItem* folder_item =
1551 static_cast<AppListFolderItem*>(folder_item_view->item());
1552 return folder_item->GetTargetIconRectInFolderForItem(
1553 drag_item_view->item(), icon_ideal_bounds);
1556 bool AppsGridView::IsUnderOEMFolder() {
1557 if (!folder_delegate_)
1558 return false;
1560 return folder_delegate_->IsOEMFolder();
1563 void AppsGridView::DispatchDragEventForReparent(Pointer pointer,
1564 const gfx::Point& drag_point) {
1565 folder_delegate_->DispatchDragEventForReparent(pointer, drag_point);
1568 void AppsGridView::EndDragFromReparentItemInRootLevel(
1569 bool events_forwarded_to_drag_drop_host,
1570 bool cancel_drag) {
1571 // EndDrag was called before if |drag_view_| is NULL.
1572 if (!drag_view_)
1573 return;
1575 DCHECK(IsDraggingForReparentInRootLevelGridView());
1576 bool cancel_reparent = cancel_drag || drop_attempt_ == DROP_FOR_NONE;
1577 if (!events_forwarded_to_drag_drop_host && !cancel_reparent) {
1578 CalculateDropTarget();
1579 if (drop_attempt_ == DROP_FOR_REORDER &&
1580 IsValidIndex(reorder_drop_target_)) {
1581 ReparentItemForReorder(drag_view_, reorder_drop_target_);
1582 } else if (drop_attempt_ == DROP_FOR_FOLDER &&
1583 IsValidIndex(folder_drop_target_)) {
1584 cancel_reparent =
1585 !ReparentItemToAnotherFolder(drag_view_, folder_drop_target_);
1586 } else {
1587 NOTREACHED();
1589 SetViewHidden(drag_view_, false /* show */, true /* no animate */);
1592 // The drag can be ended after the synchronous drag is created but before it
1593 // is Run().
1594 CleanUpSynchronousDrag();
1596 SetAsFolderDroppingTarget(folder_drop_target_, false);
1597 if (cancel_reparent) {
1598 CancelFolderItemReparent(drag_view_);
1599 } else {
1600 // By setting |drag_view_| to NULL here, we prevent ClearDragState() from
1601 // cleaning up the newly created AppListItemView, effectively claiming
1602 // ownership of the newly created drag view.
1603 drag_view_->OnDragEnded();
1604 drag_view_ = NULL;
1606 ClearDragState();
1607 AnimateToIdealBounds();
1609 StopPageFlipTimer();
1612 void AppsGridView::EndDragForReparentInHiddenFolderGridView() {
1613 if (drag_and_drop_host_) {
1614 // If we had a drag and drop proxy icon, we delete it and make the real
1615 // item visible again.
1616 drag_and_drop_host_->DestroyDragIconProxy();
1619 // The drag can be ended after the synchronous drag is created but before it
1620 // is Run().
1621 CleanUpSynchronousDrag();
1623 SetAsFolderDroppingTarget(folder_drop_target_, false);
1624 ClearDragState();
1627 void AppsGridView::OnFolderItemRemoved() {
1628 DCHECK(folder_delegate_);
1629 if (item_list_)
1630 item_list_->RemoveObserver(this);
1631 item_list_ = nullptr;
1634 void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) {
1635 // When a drag and drop host is given, the item can be dragged out of the app
1636 // list window. In that case a proxy widget needs to be used.
1637 // Note: This code has very likely to be changed for Windows (non metro mode)
1638 // when a |drag_and_drop_host_| gets implemented.
1639 if (!drag_view_ || !drag_and_drop_host_)
1640 return;
1642 gfx::Point screen_location = grid_location;
1643 views::View::ConvertPointToScreen(this, &screen_location);
1645 // Determine the mouse offset to the center of the icon so that the drag and
1646 // drop host follows this layer.
1647 gfx::Vector2d delta = drag_view_offset_ -
1648 drag_view_->GetLocalBounds().CenterPoint();
1649 delta.set_y(delta.y() + drag_view_->title()->size().height() / 2);
1651 // We have to hide the original item since the drag and drop host will do
1652 // the OS dependent code to "lift off the dragged item".
1653 DCHECK(!IsDraggingForReparentInRootLevelGridView());
1654 drag_and_drop_host_->CreateDragIconProxy(screen_location,
1655 drag_view_->item()->icon(),
1656 drag_view_,
1657 delta,
1658 kDragAndDropProxyScale);
1659 SetViewHidden(drag_view_,
1660 true /* hide */,
1661 true /* no animation */);
1664 void AppsGridView::DispatchDragEventToDragAndDropHost(
1665 const gfx::Point& location_in_screen_coordinates) {
1666 if (!drag_view_ || !drag_and_drop_host_)
1667 return;
1669 if (GetLocalBounds().Contains(last_drag_point_)) {
1670 // The event was issued inside the app menu and we should get all events.
1671 if (forward_events_to_drag_and_drop_host_) {
1672 // The DnD host was previously called and needs to be informed that the
1673 // session returns to the owner.
1674 forward_events_to_drag_and_drop_host_ = false;
1675 drag_and_drop_host_->EndDrag(true);
1677 } else {
1678 if (IsFolderItem(drag_view_->item()))
1679 return;
1681 // The event happened outside our app menu and we might need to dispatch.
1682 if (forward_events_to_drag_and_drop_host_) {
1683 // Dispatch since we have already started.
1684 if (!drag_and_drop_host_->Drag(location_in_screen_coordinates)) {
1685 // The host is not active any longer and we cancel the operation.
1686 forward_events_to_drag_and_drop_host_ = false;
1687 drag_and_drop_host_->EndDrag(true);
1689 } else {
1690 if (drag_and_drop_host_->StartDrag(drag_view_->item()->id(),
1691 location_in_screen_coordinates)) {
1692 // From now on we forward the drag events.
1693 forward_events_to_drag_and_drop_host_ = true;
1694 // Any flip operations are stopped.
1695 StopPageFlipTimer();
1701 void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) {
1702 if (!IsPointWithinDragBuffer(drag_point))
1703 StopPageFlipTimer();
1704 int new_page_flip_target = -1;
1706 // Drag zones are at the edges of the scroll axis.
1707 if (pagination_controller_->scroll_axis() ==
1708 PaginationController::SCROLL_AXIS_VERTICAL) {
1709 if (drag_point.y() < kPageFlipZoneSize)
1710 new_page_flip_target = pagination_model_.selected_page() - 1;
1711 else if (drag_point.y() > height() - kPageFlipZoneSize)
1712 new_page_flip_target = pagination_model_.selected_page() + 1;
1713 } else {
1714 if (page_switcher_view_->bounds().Contains(drag_point)) {
1715 gfx::Point page_switcher_point(drag_point);
1716 views::View::ConvertPointToTarget(
1717 this, page_switcher_view_, &page_switcher_point);
1718 new_page_flip_target =
1719 page_switcher_view_->GetPageForPoint(page_switcher_point);
1722 // TODO(xiyuan): Fix this for RTL.
1723 if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize)
1724 new_page_flip_target = pagination_model_.selected_page() - 1;
1726 if (new_page_flip_target == -1 &&
1727 drag_point.x() > width() - kPageFlipZoneSize) {
1728 new_page_flip_target = pagination_model_.selected_page() + 1;
1732 if (new_page_flip_target == page_flip_target_)
1733 return;
1735 StopPageFlipTimer();
1736 if (pagination_model_.is_valid_page(new_page_flip_target)) {
1737 page_flip_target_ = new_page_flip_target;
1739 if (page_flip_target_ != pagination_model_.selected_page()) {
1740 page_flip_timer_.Start(FROM_HERE,
1741 base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_),
1742 this, &AppsGridView::OnPageFlipTimer);
1747 void AppsGridView::OnPageFlipTimer() {
1748 DCHECK(pagination_model_.is_valid_page(page_flip_target_));
1749 pagination_model_.SelectPage(page_flip_target_, true);
1752 void AppsGridView::MoveItemInModel(AppListItemView* item_view,
1753 const Index& target) {
1754 int current_model_index = view_model_.GetIndexOfView(item_view);
1755 DCHECK_GE(current_model_index, 0);
1757 int target_model_index = GetModelIndexFromIndex(target);
1758 if (target_model_index == current_model_index)
1759 return;
1761 item_list_->RemoveObserver(this);
1762 item_list_->MoveItem(current_model_index, target_model_index);
1763 view_model_.Move(current_model_index, target_model_index);
1764 item_list_->AddObserver(this);
1766 if (pagination_model_.selected_page() != target.page)
1767 pagination_model_.SelectPage(target.page, false);
1770 void AppsGridView::MoveItemToFolder(AppListItemView* item_view,
1771 const Index& target) {
1772 const std::string& source_item_id = item_view->item()->id();
1773 AppListItemView* target_view =
1774 GetViewDisplayedAtSlotOnCurrentPage(target.slot);
1775 DCHECK(target_view);
1776 const std::string& target_view_item_id = target_view->item()->id();
1778 // Check that the item is not being dropped onto itself; this should not
1779 // happen, but it can if something allows multiple views to share an
1780 // item (e.g., if a folder drop does not clean up properly).
1781 DCHECK_NE(source_item_id, target_view_item_id);
1783 // Make change to data model.
1784 item_list_->RemoveObserver(this);
1785 std::string folder_item_id =
1786 model_->MergeItems(target_view_item_id, source_item_id);
1787 item_list_->AddObserver(this);
1788 if (folder_item_id.empty()) {
1789 LOG(ERROR) << "Unable to merge into item id: " << target_view_item_id;
1790 return;
1792 if (folder_item_id != target_view_item_id) {
1793 // New folder was created, change the view model to replace the old target
1794 // view with the new folder item view.
1795 size_t folder_item_index;
1796 if (item_list_->FindItemIndex(folder_item_id, &folder_item_index)) {
1797 int target_view_index = view_model_.GetIndexOfView(target_view);
1798 gfx::Rect target_view_bounds = target_view->bounds();
1799 DeleteItemViewAtIndex(target_view_index);
1800 AppListItemView* target_folder_view =
1801 CreateViewForItemAtIndex(folder_item_index);
1802 target_folder_view->SetBoundsRect(target_view_bounds);
1803 view_model_.Add(target_folder_view, target_view_index);
1804 AddChildView(target_folder_view);
1805 } else {
1806 LOG(ERROR) << "Folder no longer in item_list: " << folder_item_id;
1810 // Fade out the drag_view_ and delete it when animation ends.
1811 int drag_view_index = view_model_.GetIndexOfView(drag_view_);
1812 view_model_.Remove(drag_view_index);
1813 bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
1814 bounds_animator_.SetAnimationDelegate(
1815 drag_view_,
1816 scoped_ptr<gfx::AnimationDelegate>(
1817 new ItemRemoveAnimationDelegate(drag_view_)));
1818 UpdatePaging();
1821 void AppsGridView::ReparentItemForReorder(AppListItemView* item_view,
1822 const Index& target) {
1823 item_list_->RemoveObserver(this);
1824 model_->RemoveObserver(this);
1826 AppListItem* reparent_item = item_view->item();
1827 DCHECK(reparent_item->IsInFolder());
1828 const std::string source_folder_id = reparent_item->folder_id();
1829 AppListFolderItem* source_folder =
1830 static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
1832 int target_model_index = GetModelIndexFromIndex(target);
1834 // Remove the source folder view if there is only 1 item in it, since the
1835 // source folder will be deleted after its only child item removed from it.
1836 if (source_folder->ChildItemCount() == 1u) {
1837 const int deleted_folder_index =
1838 view_model_.GetIndexOfView(activated_folder_item_view());
1839 DeleteItemViewAtIndex(deleted_folder_index);
1841 // Adjust |target_model_index| if it is beyond the deleted folder index.
1842 if (target_model_index > deleted_folder_index)
1843 --target_model_index;
1846 // Move the item from its parent folder to top level item list.
1847 // Must move to target_model_index, the location we expect the target item
1848 // to be, not the item location we want to insert before.
1849 int current_model_index = view_model_.GetIndexOfView(item_view);
1850 syncer::StringOrdinal target_position;
1851 if (target_model_index < static_cast<int>(item_list_->item_count()))
1852 target_position = item_list_->item_at(target_model_index)->position();
1853 model_->MoveItemToFolderAt(reparent_item, "", target_position);
1854 view_model_.Move(current_model_index, target_model_index);
1856 RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
1858 item_list_->AddObserver(this);
1859 model_->AddObserver(this);
1860 UpdatePaging();
1863 bool AppsGridView::ReparentItemToAnotherFolder(AppListItemView* item_view,
1864 const Index& target) {
1865 DCHECK(IsDraggingForReparentInRootLevelGridView());
1867 AppListItemView* target_view =
1868 GetViewDisplayedAtSlotOnCurrentPage(target.slot);
1869 if (!target_view)
1870 return false;
1872 AppListItem* reparent_item = item_view->item();
1873 DCHECK(reparent_item->IsInFolder());
1874 const std::string source_folder_id = reparent_item->folder_id();
1875 AppListFolderItem* source_folder =
1876 static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
1878 AppListItem* target_item = target_view->item();
1880 // An app is being reparented to its original folder. Just cancel the
1881 // reparent.
1882 if (target_item->id() == reparent_item->folder_id())
1883 return false;
1885 // Make change to data model.
1886 item_list_->RemoveObserver(this);
1888 // Remove the source folder view if there is only 1 item in it, since the
1889 // source folder will be deleted after its only child item merged into the
1890 // target item.
1891 if (source_folder->ChildItemCount() == 1u)
1892 DeleteItemViewAtIndex(
1893 view_model_.GetIndexOfView(activated_folder_item_view()));
1895 // Move item to the target folder.
1896 std::string target_id_after_merge =
1897 model_->MergeItems(target_item->id(), reparent_item->id());
1898 if (target_id_after_merge.empty()) {
1899 LOG(ERROR) << "Unable to reparent to item id: " << target_item->id();
1900 item_list_->AddObserver(this);
1901 return false;
1904 if (target_id_after_merge != target_item->id()) {
1905 // New folder was created, change the view model to replace the old target
1906 // view with the new folder item view.
1907 const std::string& new_folder_id = reparent_item->folder_id();
1908 size_t new_folder_index;
1909 if (item_list_->FindItemIndex(new_folder_id, &new_folder_index)) {
1910 int target_view_index = view_model_.GetIndexOfView(target_view);
1911 DeleteItemViewAtIndex(target_view_index);
1912 AppListItemView* new_folder_view =
1913 CreateViewForItemAtIndex(new_folder_index);
1914 view_model_.Add(new_folder_view, target_view_index);
1915 AddChildView(new_folder_view);
1916 } else {
1917 LOG(ERROR) << "Folder no longer in item_list: " << new_folder_id;
1921 RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
1923 item_list_->AddObserver(this);
1925 // Fade out the drag_view_ and delete it when animation ends.
1926 int drag_view_index = view_model_.GetIndexOfView(drag_view_);
1927 view_model_.Remove(drag_view_index);
1928 bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
1929 bounds_animator_.SetAnimationDelegate(
1930 drag_view_,
1931 scoped_ptr<gfx::AnimationDelegate>(
1932 new ItemRemoveAnimationDelegate(drag_view_)));
1933 UpdatePaging();
1935 return true;
1938 // After moving the re-parenting item out of the folder, if there is only 1 item
1939 // left, remove the last item out of the folder, delete the folder and insert it
1940 // to the data model at the same position. Make the same change to view_model_
1941 // accordingly.
1942 void AppsGridView::RemoveLastItemFromReparentItemFolderIfNecessary(
1943 const std::string& source_folder_id) {
1944 AppListFolderItem* source_folder =
1945 static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
1946 if (!source_folder || source_folder->ChildItemCount() != 1u)
1947 return;
1949 // Delete view associated with the folder item to be removed.
1950 DeleteItemViewAtIndex(
1951 view_model_.GetIndexOfView(activated_folder_item_view()));
1953 // Now make the data change to remove the folder item in model.
1954 AppListItem* last_item = source_folder->item_list()->item_at(0);
1955 model_->MoveItemToFolderAt(last_item, "", source_folder->position());
1957 // Create a new item view for the last item in folder.
1958 size_t last_item_index;
1959 if (!item_list_->FindItemIndex(last_item->id(), &last_item_index) ||
1960 last_item_index > static_cast<size_t>(view_model_.view_size())) {
1961 NOTREACHED();
1962 return;
1964 AppListItemView* last_item_view = CreateViewForItemAtIndex(last_item_index);
1965 view_model_.Add(last_item_view, last_item_index);
1966 AddChildView(last_item_view);
1969 void AppsGridView::CancelFolderItemReparent(AppListItemView* drag_item_view) {
1970 // The icon of the dragged item must target to its final ideal bounds after
1971 // the animation completes.
1972 CalculateIdealBounds();
1974 gfx::Rect target_icon_rect =
1975 GetTargetIconRectInFolder(drag_item_view, activated_folder_item_view_);
1977 gfx::Rect drag_view_icon_to_grid =
1978 drag_item_view->ConvertRectToParent(drag_item_view->GetIconBounds());
1979 drag_view_icon_to_grid.ClampToCenteredSize(
1980 gfx::Size(kGridIconDimension, kGridIconDimension));
1981 TopIconAnimationView* icon_view = new TopIconAnimationView(
1982 drag_item_view->item()->icon(),
1983 target_icon_rect,
1984 false); /* animate like closing folder */
1985 AddChildView(icon_view);
1986 icon_view->SetBoundsRect(drag_view_icon_to_grid);
1987 icon_view->TransformView();
1990 void AppsGridView::CancelContextMenusOnCurrentPage() {
1991 int start = pagination_model_.selected_page() * tiles_per_page();
1992 int end = std::min(view_model_.view_size(), start + tiles_per_page());
1993 for (int i = start; i < end; ++i)
1994 GetItemViewAt(i)->CancelContextMenu();
1997 void AppsGridView::DeleteItemViewAtIndex(int index) {
1998 AppListItemView* item_view = GetItemViewAt(index);
1999 view_model_.Remove(index);
2000 if (item_view == drag_view_)
2001 drag_view_ = NULL;
2002 delete item_view;
2005 bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const {
2006 gfx::Rect rect(GetLocalBounds());
2007 rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx);
2008 return rect.Contains(point);
2011 void AppsGridView::ButtonPressed(views::Button* sender,
2012 const ui::Event& event) {
2013 if (dragging())
2014 return;
2016 if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName))
2017 return;
2018 AppListItemView* pressed_item_view = static_cast<AppListItemView*>(sender);
2020 if (delegate_) {
2021 // Always set the previous activated_folder_item_view_ to be visible. This
2022 // prevents a case where the item would remain hidden due the
2023 // |activated_folder_item_view_| changing during the animation. We only
2024 // need to track |activated_folder_item_view_| in the root level grid view.
2025 if (!folder_delegate_) {
2026 if (activated_folder_item_view_)
2027 activated_folder_item_view_->SetVisible(true);
2028 if (IsFolderItem(pressed_item_view->item()))
2029 activated_folder_item_view_ = pressed_item_view;
2030 else
2031 activated_folder_item_view_ = NULL;
2033 delegate_->ActivateApp(pressed_item_view->item(), event.flags());
2037 void AppsGridView::OnListItemAdded(size_t index, AppListItem* item) {
2038 EndDrag(true);
2040 AppListItemView* view = CreateViewForItemAtIndex(index);
2041 view_model_.Add(view, index);
2042 AddChildView(view);
2044 UpdatePaging();
2045 UpdatePulsingBlockViews();
2046 Layout();
2047 SchedulePaint();
2050 void AppsGridView::OnListItemRemoved(size_t index, AppListItem* item) {
2051 EndDrag(true);
2053 DeleteItemViewAtIndex(index);
2055 UpdatePaging();
2056 UpdatePulsingBlockViews();
2057 Layout();
2058 SchedulePaint();
2061 void AppsGridView::OnListItemMoved(size_t from_index,
2062 size_t to_index,
2063 AppListItem* item) {
2064 EndDrag(true);
2065 view_model_.Move(from_index, to_index);
2067 UpdatePaging();
2068 AnimateToIdealBounds();
2071 void AppsGridView::OnAppListItemHighlight(size_t index, bool highlight) {
2072 AppListItemView* view = GetItemViewAt(index);
2073 view->SetItemIsHighlighted(highlight);
2074 if (highlight)
2075 EnsureViewVisible(GetIndexFromModelIndex(index));
2078 void AppsGridView::TotalPagesChanged() {
2081 void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) {
2082 if (dragging()) {
2083 CalculateDropTarget();
2084 Layout();
2085 MaybeStartPageFlipTimer(last_drag_point_);
2086 } else {
2087 ClearSelectedView(selected_view_);
2088 Layout();
2092 void AppsGridView::TransitionStarted() {
2093 CancelContextMenusOnCurrentPage();
2096 void AppsGridView::TransitionChanged() {
2097 // Update layout for valid page transition only since over-scroll no longer
2098 // animates app icons.
2099 const PaginationModel::Transition& transition =
2100 pagination_model_.transition();
2101 if (pagination_model_.is_valid_page(transition.target_page))
2102 Layout();
2105 void AppsGridView::OnAppListModelStatusChanged() {
2106 UpdatePulsingBlockViews();
2107 Layout();
2108 SchedulePaint();
2111 void AppsGridView::SetViewHidden(AppListItemView* view,
2112 bool hide,
2113 bool immediate) {
2114 ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator());
2115 animator.SetPreemptionStrategy(
2116 immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET :
2117 ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION);
2118 view->layer()->SetOpacity(hide ? 0 : 1);
2121 void AppsGridView::OnImplicitAnimationsCompleted() {
2122 if (layer()->opacity() == 0.0f)
2123 SetVisible(false);
2126 bool AppsGridView::EnableFolderDragDropUI() {
2127 // Enable drag and drop folder UI only if it is at the app list root level
2128 // and the switch is on.
2129 return model_->folders_enabled() && !folder_delegate_;
2132 AppsGridView::Index AppsGridView::GetNearestTileIndexForPoint(
2133 const gfx::Point& point) const {
2134 gfx::Rect bounds = GetContentsBounds();
2135 gfx::Size total_tile_size = GetTotalTileSize();
2136 int col = ClampToRange(
2137 (point.x() - bounds.x()) / total_tile_size.width(), 0, cols_ - 1);
2138 int row = ClampToRange((point.y() - bounds.y()) / total_tile_size.height(),
2140 rows_per_page_ - 1);
2141 return Index(pagination_model_.selected_page(), row * cols_ + col);
2144 gfx::Size AppsGridView::GetTileGridSize() const {
2145 gfx::Rect bounds = GetExpectedTileBounds(0, 0);
2146 bounds.Union(GetExpectedTileBounds(rows_per_page_ - 1, cols_ - 1));
2147 bounds.Inset(GetTilePadding());
2148 return bounds.size();
2151 gfx::Rect AppsGridView::GetExpectedTileBounds(int slot) const {
2152 return GetExpectedTileBounds(slot / cols_, slot % cols_);
2155 gfx::Rect AppsGridView::GetExpectedTileBounds(int row, int col) const {
2156 gfx::Rect bounds(GetContentsBounds());
2157 gfx::Size total_tile_size = GetTotalTileSize();
2158 gfx::Rect tile_bounds(gfx::Point(bounds.x() + col * total_tile_size.width(),
2159 bounds.y() + row * total_tile_size.height()),
2160 total_tile_size);
2161 tile_bounds.Inset(-GetTilePadding());
2162 return tile_bounds;
2165 AppListItemView* AppsGridView::GetViewDisplayedAtSlotOnCurrentPage(
2166 int slot) const {
2167 if (slot < 0)
2168 return NULL;
2170 // Calculate the original bound of the tile at |index|.
2171 int row = slot / cols_;
2172 int col = slot % cols_;
2173 gfx::Rect tile_rect = GetExpectedTileBounds(row, col);
2175 for (int i = 0; i < view_model_.view_size(); ++i) {
2176 AppListItemView* view = GetItemViewAt(i);
2177 if (view->bounds() == tile_rect && view != drag_view_)
2178 return view;
2180 return NULL;
2183 void AppsGridView::SetAsFolderDroppingTarget(const Index& target_index,
2184 bool is_target_folder) {
2185 AppListItemView* target_view =
2186 GetViewDisplayedAtSlotOnCurrentPage(target_index.slot);
2187 if (target_view)
2188 target_view->SetAsAttemptedFolderTarget(is_target_folder);
2191 } // namespace app_list