summaryrefslogtreecommitdiffstats
path: root/ui/app_list/cocoa/apps_grid_controller.mm
blob: 200e853599d011397c15e45ad5d1582b6f5a1b15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "ui/app_list/cocoa/apps_grid_controller.h"

#include "base/mac/foundation_util.h"
#include "ui/app_list/app_list_model.h"
#include "ui/app_list/app_list_model_observer.h"
#include "ui/app_list/app_list_view_delegate.h"
#import "ui/app_list/cocoa/apps_collection_view_drag_manager.h"
#import "ui/app_list/cocoa/apps_grid_view_item.h"
#import "ui/app_list/cocoa/apps_pagination_model_observer.h"
#include "ui/base/models/list_model_observer.h"

namespace {

// OSX app list has hardcoded rows and columns for now.
const int kFixedRows = 4;
const int kFixedColumns = 4;
const int kItemsPerPage = kFixedRows * kFixedColumns;

// Padding space in pixels for fixed layout.
const CGFloat kGridTopPadding = 1;
const CGFloat kLeftRightPadding = 16;
const CGFloat kScrollerPadding = 16;

// Preferred tile size when showing in fixed layout. These should be even
// numbers to ensure that if they are grown 50% they remain integers.
const CGFloat kPreferredTileWidth = 88;
const CGFloat kPreferredTileHeight = 98;

const CGFloat kViewWidth =
    kFixedColumns * kPreferredTileWidth + 2 * kLeftRightPadding;
const CGFloat kViewHeight = kFixedRows * kPreferredTileHeight;

const NSTimeInterval kScrollWhileDraggingDelay = 1.0;
NSTimeInterval g_scroll_duration = 0.18;

}  // namespace

@interface AppsGridController ()

- (void)scrollToPageWithTimer:(size_t)targetPage;
- (void)onTimer:(NSTimer*)theTimer;

// Cancel a currently running scroll animation.
- (void)cancelScrollAnimation;

// Index of the page with the most content currently visible.
- (size_t)nearestPageIndex;

// Bootstrap the views this class controls.
- (void)loadAndSetView;

- (void)boundsDidChange:(NSNotification*)notification;

// Action for buttons in the grid.
- (void)onItemClicked:(id)sender;

- (AppsGridViewItem*)itemAtPageIndex:(size_t)pageIndex
                         indexInPage:(size_t)indexInPage;

// Update the model in full, and rebuild subviews.
- (void)modelUpdated;

// Return the button of the selected item.
- (NSButton*)selectedButton;

// The scroll view holding the grid pages.
- (NSScrollView*)gridScrollView;

- (NSView*)pagesContainerView;

// Create any new pages after updating |items_|.
- (void)updatePages:(size_t)startItemIndex;

- (void)updatePageContent:(size_t)pageIndex
               resetModel:(BOOL)resetModel;

// Bridged methods for ui::ListModelObserver.
- (void)listItemsAdded:(size_t)start
                 count:(size_t)count;

- (void)listItemsRemoved:(size_t)start
                   count:(size_t)count;

- (void)listItemMovedFromIndex:(size_t)fromIndex
                  toModelIndex:(size_t)toIndex;

// Moves the selection by |indexDelta| items.
- (BOOL)moveSelectionByDelta:(int)indexDelta;

@end

namespace app_list {

class AppsGridDelegateBridge : public ui::ListModelObserver {
 public:
  AppsGridDelegateBridge(AppsGridController* parent) : parent_(parent) {}

 private:
  // Overridden from ui::ListModelObserver:
  virtual void ListItemsAdded(size_t start, size_t count) OVERRIDE {
    [parent_ listItemsAdded:start
                      count:count];
  }
  virtual void ListItemsRemoved(size_t start, size_t count) OVERRIDE {
    [parent_ listItemsRemoved:start
                        count:count];
  }
  virtual void ListItemMoved(size_t index, size_t target_index) OVERRIDE {
    [parent_ listItemMovedFromIndex:index
                       toModelIndex:target_index];
  }
  virtual void ListItemsChanged(size_t start, size_t count) OVERRIDE {
    NOTREACHED();
  }

  AppsGridController* parent_;  // Weak, owns us.

  DISALLOW_COPY_AND_ASSIGN(AppsGridDelegateBridge);
};

}  // namespace app_list

@interface PageContainerView : NSView;
@end

// The container view needs to flip coordinates so that it is laid out
// correctly whether or not there is a horizontal scrollbar.
@implementation PageContainerView

- (BOOL)isFlipped {
  return YES;
}

@end

@implementation AppsGridController

+ (void)setScrollAnimationDuration:(NSTimeInterval)duration {
  g_scroll_duration = duration;
}

+ (CGFloat)scrollerPadding {
  return kScrollerPadding;
}

@synthesize paginationObserver = paginationObserver_;

- (id)init {
  if ((self = [super init])) {
    bridge_.reset(new app_list::AppsGridDelegateBridge(self));
    NSSize cellSize = NSMakeSize(kPreferredTileWidth, kPreferredTileHeight);
    dragManager_.reset(
        [[AppsCollectionViewDragManager alloc] initWithCellSize:cellSize
                                                           rows:kFixedRows
                                                        columns:kFixedColumns
                                                 gridController:self]);
    pages_.reset([[NSMutableArray alloc] init]);
    items_.reset([[NSMutableArray alloc] init]);
    [self loadAndSetView];
    [self updatePages:0];
  }
  return self;
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [self setModel:scoped_ptr<app_list::AppListModel>()];
  [super dealloc];
}

- (NSCollectionView*)collectionViewAtPageIndex:(size_t)pageIndex {
  return [pages_ objectAtIndex:pageIndex];
}

- (size_t)pageIndexForCollectionView:(NSCollectionView*)page {
  for (size_t pageIndex = 0; pageIndex < [pages_ count]; ++pageIndex) {
    if (page == [self collectionViewAtPageIndex:pageIndex])
      return pageIndex;
  }
  return NSNotFound;
}

- (app_list::AppListModel*)model {
  return model_.get();
}

- (void)setModel:(scoped_ptr<app_list::AppListModel>)newModel {
  if (model_) {
    model_->apps()->RemoveObserver(bridge_.get());

    // Since the model is about to be deleted, and the AppKit objects might be
    // sitting in an NSAutoreleasePool, ensure there are no references to the
    // model.
    for (size_t i = 0; i < [items_ count]; ++i)
      [[self itemAtIndex:i] setModel:NULL];
  }

  model_.reset(newModel.release());
  if (model_)
    model_->apps()->AddObserver(bridge_.get());

  [self modelUpdated];
}

- (void)setDelegate:(app_list::AppListViewDelegate*)newDelegate {
  scoped_ptr<app_list::AppListModel> newModel(new app_list::AppListModel);
  delegate_ = newDelegate;
  if (delegate_)
    delegate_->SetModel(newModel.get());  // Populates items.
  [self setModel:newModel.Pass()];
}

- (size_t)visiblePage {
  return visiblePage_;
}

- (void)activateSelection {
  [[self selectedButton] performClick:self];
}

- (size_t)pageCount {
  return [pages_ count];
}

- (size_t)itemCount {
  return [items_ count];
}

- (void)scrollToPage:(size_t)pageIndex {
  NSClipView* clipView = [[self gridScrollView] contentView];
  NSPoint newOrigin = [clipView bounds].origin;

  // Scrolling outside of this range is edge elasticity, which animates
  // automatically.
  if ((pageIndex == 0 && (newOrigin.x <= 0)) ||
      (pageIndex + 1 == [self pageCount] &&
          newOrigin.x >= pageIndex * kViewWidth)) {
    return;
  }

  // Clear any selection on the current page (unless it has been removed).
  if (visiblePage_ < [pages_ count]) {
    [[self collectionViewAtPageIndex:visiblePage_]
        setSelectionIndexes:[NSIndexSet indexSet]];
  }

  newOrigin.x = pageIndex * kViewWidth;
  [NSAnimationContext beginGrouping];
  [[NSAnimationContext currentContext] setDuration:g_scroll_duration];
  [[clipView animator] setBoundsOrigin:newOrigin];
  [NSAnimationContext endGrouping];
  animatingScroll_ = YES;
  targetScrollPage_ = pageIndex;
  [self cancelScrollTimer];
}

- (void)maybeChangePageForPoint:(NSPoint)locationInWindow {
  NSPoint pointInView = [[self view] convertPoint:locationInWindow
                                         fromView:nil];
  // Check if the point is outside the view on the left or right.
  if (pointInView.x <= 0 || pointInView.x >= NSWidth([[self view] bounds])) {
    size_t targetPage = visiblePage_;
    if (pointInView.x <= 0)
      targetPage -= targetPage != 0 ? 1 : 0;
    else
      targetPage += targetPage < [pages_ count] - 1 ? 1 : 0;
    [self scrollToPageWithTimer:targetPage];
    return;
  }

  if (paginationObserver_) {
    NSInteger segment =
        [paginationObserver_ pagerSegmentAtLocation:locationInWindow];
    if (segment >= 0 && static_cast<size_t>(segment) != targetScrollPage_) {
      [self scrollToPageWithTimer:segment];
      return;
    }
  }

  // Otherwise the point may have moved back into the view.
  [self cancelScrollTimer];
}

- (void)cancelScrollTimer {
  scheduledScrollPage_ = targetScrollPage_;
  [scrollWhileDraggingTimer_ invalidate];
}

- (void)scrollToPageWithTimer:(size_t)targetPage {
  if (targetPage == targetScrollPage_) {
    [self cancelScrollTimer];
    return;
  }

  if (targetPage == scheduledScrollPage_)
    return;

  scheduledScrollPage_ = targetPage;
  [scrollWhileDraggingTimer_ invalidate];
  scrollWhileDraggingTimer_.reset(
      [[NSTimer scheduledTimerWithTimeInterval:kScrollWhileDraggingDelay
                                        target:self
                                      selector:@selector(onTimer:)
                                      userInfo:nil
                                       repeats:NO] retain]);
}

- (void)onTimer:(NSTimer*)theTimer {
  if (scheduledScrollPage_ == targetScrollPage_)
    return;  // Already animating scroll.

  [self scrollToPage:scheduledScrollPage_];
}

- (void)cancelScrollAnimation {
  NSClipView* clipView = [[self gridScrollView] contentView];
  [NSAnimationContext beginGrouping];
  [[NSAnimationContext currentContext] setDuration:0];
  [[clipView animator] setBoundsOrigin:[clipView bounds].origin];
  [NSAnimationContext endGrouping];
  animatingScroll_ = NO;
}

- (size_t)nearestPageIndex {
  return lround(
      NSMinX([[[self gridScrollView] contentView] bounds]) / kViewWidth);
}

- (void)userScrolling:(BOOL)isScrolling {
  if (isScrolling) {
    if (animatingScroll_)
      [self cancelScrollAnimation];
  } else {
    [self scrollToPage:[self nearestPageIndex]];
  }
}

- (void)loadAndSetView {
  base::scoped_nsobject<PageContainerView> pagesContainer(
      [[PageContainerView alloc] initWithFrame:NSZeroRect]);

  NSRect scrollFrame = NSMakeRect(0, kGridTopPadding, kViewWidth,
                                  kViewHeight + kScrollerPadding);
  base::scoped_nsobject<ScrollViewWithNoScrollbars> scrollView(
      [[ScrollViewWithNoScrollbars alloc] initWithFrame:scrollFrame]);
  [scrollView setBorderType:NSNoBorder];
  [scrollView setLineScroll:kViewWidth];
  [scrollView setPageScroll:kViewWidth];
  [scrollView setDelegate:self];
  [scrollView setDocumentView:pagesContainer];
  [scrollView setDrawsBackground:NO];

  [[NSNotificationCenter defaultCenter]
      addObserver:self
         selector:@selector(boundsDidChange:)
             name:NSViewBoundsDidChangeNotification
           object:[scrollView contentView]];

  [self setView:scrollView];
}

- (void)boundsDidChange:(NSNotification*)notification {
  size_t newPage = [self nearestPageIndex];
  if (newPage == visiblePage_) {
    [paginationObserver_ pageVisibilityChanged];
    return;
  }

  visiblePage_ = newPage;
  [paginationObserver_ selectedPageChanged:newPage];
  [paginationObserver_ pageVisibilityChanged];
}

- (void)onItemClicked:(id)sender {
  for (size_t i = 0; i < [items_ count]; ++i) {
    AppsGridViewItem* item = [self itemAtIndex:i];
    if ([[item button] isEqual:sender])
      delegate_->ActivateAppListItem([item model], 0);
  }
}

- (AppsGridViewItem*)itemAtPageIndex:(size_t)pageIndex
                         indexInPage:(size_t)indexInPage {
  return base::mac::ObjCCastStrict<AppsGridViewItem>(
      [[self collectionViewAtPageIndex:pageIndex] itemAtIndex:indexInPage]);
}

- (AppsGridViewItem*)itemAtIndex:(size_t)itemIndex {
  const size_t pageIndex = itemIndex / kItemsPerPage;
  return [self itemAtPageIndex:pageIndex
                   indexInPage:itemIndex - pageIndex * kItemsPerPage];
}

- (void)modelUpdated {
  [items_ removeAllObjects];
  if (model_ && model_->apps()->item_count()) {
    [self listItemsAdded:0
                   count:model_->apps()->item_count()];
  } else {
    [self updatePages:0];
  }
  [self scrollToPage:0];
}

- (NSUInteger)selectedItemIndex {
  NSCollectionView* page = [self collectionViewAtPageIndex:visiblePage_];
  NSUInteger indexOnPage = [[page selectionIndexes] firstIndex];
  if (indexOnPage == NSNotFound)
    return NSNotFound;

  return indexOnPage + visiblePage_ * kItemsPerPage;
}

- (NSButton*)selectedButton {
  NSUInteger index = [self selectedItemIndex];
  if (index == NSNotFound)
    return nil;

  return [[self itemAtIndex:index] button];
}

- (NSScrollView*)gridScrollView {
  return base::mac::ObjCCastStrict<NSScrollView>([self view]);
}

- (NSView*)pagesContainerView {
  return [[self gridScrollView] documentView];
}

- (void)updatePages:(size_t)startItemIndex {
  // Note there is always at least one page.
  size_t targetPages = 1;
  if ([items_ count] != 0)
    targetPages = ([items_ count] - 1) / kItemsPerPage + 1;

  const size_t currentPages = [self pageCount];
  // First see if the number of pages have changed.
  if (targetPages != currentPages) {
    if (targetPages < currentPages) {
      // Pages need to be removed.
      [pages_ removeObjectsInRange:NSMakeRange(targetPages,
                                               currentPages - targetPages)];
    } else {
      // Pages need to be added.
      for (size_t i = currentPages; i < targetPages; ++i) {
        NSRect pageFrame = NSMakeRect(
            kLeftRightPadding + kViewWidth * i, 0,
            kViewWidth, kViewHeight);
        [pages_ addObject:[dragManager_ makePageWithFrame:pageFrame]];
      }
    }

    [[self pagesContainerView] setSubviews:pages_];
    NSSize pagesSize = NSMakeSize(kViewWidth * targetPages, kViewHeight);
    [[self pagesContainerView] setFrameSize:pagesSize];
    [paginationObserver_ totalPagesChanged];
  }

  const size_t startPage = startItemIndex / kItemsPerPage;
  // All pages on or after |startPage| may need items added or removed.
  for (size_t pageIndex = startPage; pageIndex < targetPages; ++pageIndex) {
    [self updatePageContent:pageIndex
                 resetModel:YES];
  }
}

- (void)updatePageContent:(size_t)pageIndex
               resetModel:(BOOL)resetModel {
  NSCollectionView* pageView = [self collectionViewAtPageIndex:pageIndex];
  if (resetModel) {
    // Clear the models first, otherwise removed items could be autoreleased at
    // an unknown point in the future, when the model owner may have gone away.
    for (size_t i = 0; i < [[pageView content] count]; ++i) {
      AppsGridViewItem* item = base::mac::ObjCCastStrict<AppsGridViewItem>(
          [pageView itemAtIndex:i]);
      [item setModel:NULL];
    }
  }

  NSRange inPageRange = NSIntersectionRange(
      NSMakeRange(pageIndex * kItemsPerPage, kItemsPerPage),
      NSMakeRange(0, [items_ count]));
  NSArray* pageContent = [items_ subarrayWithRange:inPageRange];
  [pageView setContent:pageContent];
  if (!resetModel)
    return;

  for (size_t i = 0; i < [pageContent count]; ++i) {
    AppsGridViewItem* item = base::mac::ObjCCastStrict<AppsGridViewItem>(
        [pageView itemAtIndex:i]);
    [item setModel:static_cast<app_list::AppListItemModel*>(
        [[pageContent objectAtIndex:i] pointerValue])];
  }
}

- (void)moveItemInView:(size_t)fromIndex
           toItemIndex:(size_t)toIndex {
  base::scoped_nsobject<NSValue> item(
      [[items_ objectAtIndex:fromIndex] retain]);
  [items_ removeObjectAtIndex:fromIndex];
  [items_ insertObject:item
               atIndex:toIndex];

  size_t fromPageIndex = fromIndex / kItemsPerPage;
  size_t toPageIndex = toIndex / kItemsPerPage;
  if (fromPageIndex == toPageIndex) {
    [self updatePageContent:fromPageIndex
                 resetModel:NO];  // Just reorder items.
    return;
  }

  if (fromPageIndex > toPageIndex)
    std::swap(fromPageIndex, toPageIndex);

  for (size_t i = fromPageIndex; i <= toPageIndex; ++i) {
    [self updatePageContent:i
                 resetModel:YES];
  }
}

// Compare with views implementation in AppsGridView::MoveItemInModel().
- (void)moveItemWithIndex:(size_t)itemIndex
             toModelIndex:(size_t)modelIndex {
  // Ingore no-op moves. Note that this is always the case when canceled.
  if (itemIndex == modelIndex)
    return;

  model_->apps()->RemoveObserver(bridge_.get());
  model_->apps()->Move(itemIndex, modelIndex);
  model_->apps()->AddObserver(bridge_.get());
}

- (AppsCollectionViewDragManager*)dragManager {
  return dragManager_;
}

- (size_t)scheduledScrollPage {
  return scheduledScrollPage_;
}

- (void)listItemsAdded:(size_t)start
                 count:(size_t)count {
  // Cancel any drag, to ensure the model stays consistent.
  [dragManager_ cancelDrag];

  for (size_t i = start; i < start + count; ++i) {
    app_list::AppListItemModel* itemModel = model_->apps()->GetItemAt(i);
    [items_ insertObject:[NSValue valueWithPointer:itemModel]
                 atIndex:i];
  }

  [self updatePages:start];
}

- (void)listItemsRemoved:(size_t)start
                   count:(size_t)count {
  [dragManager_ cancelDrag];

  // Clear the models explicitly to avoid surprises from autorelease.
  for (size_t i = start; i < start + count; ++i)
    [[self itemAtIndex:i] setModel:NULL];

  [items_ removeObjectsInRange:NSMakeRange(start, count)];
  [self updatePages:start];
}

- (void)listItemMovedFromIndex:(size_t)fromIndex
                  toModelIndex:(size_t)toIndex {
  [dragManager_ cancelDrag];
  [self moveItemInView:fromIndex
           toItemIndex:toIndex];
}

- (CGFloat)visiblePortionOfPage:(int)page {
  CGFloat scrollOffsetOfPage =
      NSMinX([[[self gridScrollView] contentView] bounds]) / kViewWidth - page;
  if (scrollOffsetOfPage <= -1.0 || scrollOffsetOfPage >= 1.0)
    return 0.0;

  if (scrollOffsetOfPage <= 0.0)
    return scrollOffsetOfPage + 1.0;

  return -1.0 + scrollOffsetOfPage;
}

- (void)onPagerClicked:(AppListPagerView*)sender {
  int selectedSegment = [sender selectedSegment];
  if (selectedSegment < 0)
    return;  // No selection.

  int pageIndex = [[sender cell] tagForSegment:selectedSegment];
  if (pageIndex >= 0)
    [self scrollToPage:pageIndex];
}

- (BOOL)moveSelectionByDelta:(int)indexDelta {
  if (indexDelta == 0)
    return NO;

  NSUInteger oldIndex = [self selectedItemIndex];

  // If nothing is currently selected, select the first item on the page.
  if (oldIndex == NSNotFound) {
    [self selectItemAtIndex:visiblePage_ * kItemsPerPage];
    return YES;
  }

  // Can't select a negative index.
  if (indexDelta < 0 && static_cast<NSUInteger>(-indexDelta) > oldIndex)
    return NO;

  // Can't select an index greater or equal to the number of items.
  if (oldIndex + indexDelta >= [items_ count]) {
    if (visiblePage_ == [pages_ count] - 1)
      return NO;

    // If we're not on the last page, then select the last item.
    [self selectItemAtIndex:[items_ count] - 1];
    return YES;
  }

  [self selectItemAtIndex:oldIndex + indexDelta];
  return YES;
}

- (void)selectItemAtIndex:(NSUInteger)index {
  if (index >= [items_ count])
    return;

  if (index / kItemsPerPage != visiblePage_)
    [self scrollToPage:index / kItemsPerPage];

  [[self itemAtIndex:index] setSelected:YES];
}

- (BOOL)handleCommandBySelector:(SEL)command {
  if (command == @selector(insertNewline:) ||
      command == @selector(insertLineBreak:)) {
    [self activateSelection];
    return YES;
  }

  NSUInteger oldIndex = [self selectedItemIndex];
  // If nothing is currently selected, select the first item on the page.
  if (oldIndex == NSNotFound) {
    [self selectItemAtIndex:visiblePage_ * kItemsPerPage];
    return YES;
  }

  if (command == @selector(moveLeft:)) {
    return oldIndex % kFixedColumns == 0 ?
        [self moveSelectionByDelta:-kItemsPerPage + kFixedColumns - 1] :
        [self moveSelectionByDelta:-1];
  }

  if (command == @selector(moveRight:)) {
    return oldIndex % kFixedColumns == kFixedColumns - 1 ?
        [self moveSelectionByDelta:+kItemsPerPage - kFixedColumns + 1] :
        [self moveSelectionByDelta:1];
  }

  if (command == @selector(moveUp:)) {
    return oldIndex / kFixedColumns % kFixedRows == 0 ?
        NO : [self moveSelectionByDelta:-kFixedColumns];
  }

  if (command == @selector(moveDown:)) {
    return oldIndex / kFixedColumns % kFixedRows == kFixedRows - 1 ?
        NO : [self moveSelectionByDelta:kFixedColumns];
  }

  if (command == @selector(pageUp:) ||
      command == @selector(scrollPageUp:))
    return [self moveSelectionByDelta:-kItemsPerPage];

  if (command == @selector(pageDown:) ||
      command == @selector(scrollPageDown:))
    return [self moveSelectionByDelta:kItemsPerPage];

  return NO;
}

@end