Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(44)

Side by Side Diff: ios/chrome/browser/ui/ntp/google_landing_view_controller.mm

Issue 2829223004: Rename GoogleLandingController to GoogleLandingViewController.
Patch Set: Rebase Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2013 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.
4
5 #import "ios/chrome/browser/ui/ntp/google_landing_view_controller.h"
6
7 #include <algorithm>
8
9 #include "base/mac/foundation_util.h"
10 #include "base/metrics/user_metrics.h"
11 #include "base/strings/sys_string_conversions.h"
12 #include "components/strings/grit/components_strings.h"
13 #import "ios/chrome/browser/ui/commands/UIKit+ChromeExecuteCommand.h"
14 #import "ios/chrome/browser/ui/commands/generic_chrome_command.h"
15 #include "ios/chrome/browser/ui/commands/ios_command_ids.h"
16 #import "ios/chrome/browser/ui/context_menu/context_menu_coordinator.h"
17 #import "ios/chrome/browser/ui/ntp/google_landing_data_source.h"
18 #import "ios/chrome/browser/ui/ntp/most_visited_cell.h"
19 #import "ios/chrome/browser/ui/ntp/most_visited_layout.h"
20 #import "ios/chrome/browser/ui/ntp/new_tab_page_header_constants.h"
21 #import "ios/chrome/browser/ui/ntp/new_tab_page_header_view.h"
22 #import "ios/chrome/browser/ui/ntp/whats_new_header_view.h"
23 #import "ios/chrome/browser/ui/overscroll_actions/overscroll_actions_controller. h"
24 #import "ios/chrome/browser/ui/toolbar/web_toolbar_controller.h"
25 #include "ios/chrome/browser/ui/ui_util.h"
26 #import "ios/chrome/browser/ui/uikit_ui_util.h"
27 #import "ios/chrome/browser/ui/url_loader.h"
28 #include "ios/chrome/common/string_util.h"
29 #include "ios/chrome/grit/ios_strings.h"
30 #import "ios/third_party/material_components_ios/src/components/Snackbar/src/Mat erialSnackbar.h"
31 #import "ios/third_party/material_components_ios/src/components/Typography/src/M aterialTypography.h"
32 #import "ios/web/public/web_state/context_menu_params.h"
33 #import "net/base/mac/url_conversions.h"
34 #include "ui/base/l10n/l10n_util.h"
35 #include "ui/base/page_transition_types.h"
36
37 using base::UserMetricsAction;
38
39 namespace {
40
41 enum {
42 SectionWithOmnibox,
43 SectionWithMostVisited,
44 NumberOfCollectionViewSections,
45 };
46
47 enum InterfaceOrientation {
48 ALL,
49 IPHONE_LANDSCAPE,
50 };
51
52 const CGFloat kVoiceSearchButtonWidth = 48;
53 const UIEdgeInsets kSearchBoxStretchInsets = {3, 3, 3, 3};
54
55 // Height for the doodle frame when Google is not the default search engine.
56 const CGFloat kNonGoogleSearchDoodleHeight = 60;
57 // Height for the header view on tablet when Google is not the default search
58 // engine.
59 const CGFloat kNonGoogleSearchHeaderHeightIPad = 10;
60
61 const CGFloat kHintLabelSidePadding = 12;
62 const CGFloat kNTPSearchFieldBottomPadding = 16;
63 const CGFloat kWhatsNewHeaderHiddenHeight = 8;
64 const CGFloat kDoodleTopMarginIPadPortrait = 82;
65 const CGFloat kDoodleTopMarginIPadLandscape = 82;
66 const NSInteger kMaxNumMostVisitedFaviconRows = 2;
67 const CGFloat kMaxSearchFieldFrameMargin = 200;
68 const CGFloat kShiftTilesDownAnimationDuration = 0.2;
69
70 const CGFloat kMostVisitedPaddingIPhone = 16;
71 const CGFloat kMostVisitedPaddingIPadFavicon = 24;
72
73 } // namespace
74
75 @interface GoogleLandingViewController (UsedByGoogleLandingView)
76 // Update frames for subviews depending on the interface orientation.
77 - (void)updateSubviewFrames;
78 // Resets the collection view's inset to 0.
79 - (void)resetSectionInset;
80 - (void)reloadData;
81 @end
82
83 // Subclassing the main UIScrollView allows calls for setFrame.
84 @interface GoogleLandingView : UIView {
85 GoogleLandingViewController* _googleLanding;
86 }
87
88 - (void)setFrameDelegate:(GoogleLandingViewController*)delegate;
89
90 @end
91
92 @implementation GoogleLandingView
93
94 - (void)setFrameDelegate:(GoogleLandingViewController*)delegate {
95 _googleLanding = delegate;
96 }
97
98 - (void)setFrame:(CGRect)frame {
99 // On iPad and in fullscreen, the collection view's inset is very large.
100 // When Chrome enters slide over mode, the previously set inset is larger than
101 // the newly set collection view's width, which makes the collection view
102 // throw an exception.
103 // To prevent this from happening, we reset the inset to 0 before changing the
104 // frame.
105 [_googleLanding resetSectionInset];
106 [super setFrame:frame];
107 [_googleLanding updateSubviewFrames];
108 [_googleLanding reloadData];
109 }
110
111 @end
112
113 @interface GoogleLandingViewController ()<OverscrollActionsControllerDelegate,
114 UICollectionViewDataSource,
115 UICollectionViewDelegate,
116 UICollectionViewDelegateFlowLayout,
117 UIGestureRecognizerDelegate,
118 WhatsNewHeaderViewDelegate> {
119 // Fake omnibox.
120 base::scoped_nsobject<UIButton> _searchTapTarget;
121
122 // A collection view for the most visited sites.
123 base::scoped_nsobject<UICollectionView> _mostVisitedView;
124
125 // The overscroll actions controller managing accelerators over the toolbar.
126 base::scoped_nsobject<OverscrollActionsController>
127 _overscrollActionsController;
128
129 // |YES| when notifications indicate the omnibox is focused.
130 BOOL _omniboxFocused;
131
132 // Tap and swipe gesture recognizers when the omnibox is focused.
133 base::scoped_nsobject<UITapGestureRecognizer> _tapGestureRecognizer;
134 base::scoped_nsobject<UISwipeGestureRecognizer> _swipeGestureRecognizer;
135
136 // Handles displaying the context menu for all form factors.
137 base::scoped_nsobject<ContextMenuCoordinator> _contextMenuCoordinator;
138
139 // URL of the last deleted most viewed entry. If present the UI to restore it
140 // is shown.
141 base::scoped_nsobject<NSURL> _deletedUrl;
142
143 // |YES| if the view has finished its first layout. This is useful when
144 // determining if the view has sized itself for tablet.
145 BOOL _viewLoaded;
146
147 // |YES| if the fakebox header should be animated on scroll.
148 BOOL _animateHeader;
149
150 // |YES| if the collection scrollView is scrolled all the way to the top. Used
151 // to lock this position in place on various frame changes.
152 BOOL _scrolledToTop;
153
154 // |YES| if this NTP panel is visible. When set to |NO| various UI updates
155 // are ignored.
156 BOOL _isShowing;
157
158 CFTimeInterval _shiftTilesDownStartTime;
159 CGSize _mostVisitedCellSize;
160 base::scoped_nsobject<NSLayoutConstraint> _hintLabelLeadingConstraint;
161 base::scoped_nsobject<NSLayoutConstraint> _voiceTapTrailingConstraint;
162 base::scoped_nsobject<NSMutableArray> _supplementaryViews;
163 base::scoped_nsobject<NewTabPageHeaderView> _headerView;
164 base::scoped_nsobject<WhatsNewHeaderView> _promoHeaderView;
165 }
166
167 // Redeclare the |view| property to be the GoogleLandingView subclass instead of
168 // a generic UIView.
169 @property(nonatomic, readwrite, strong) GoogleLandingView* view;
170
171 // Whether the Google logo or doodle is being shown.
172 @property(nonatomic, assign) BOOL logoIsShowing;
173
174 // Exposes view and methods to drive the doodle.
175 @property(nonatomic, assign) id<LogoVendor> logoVendor;
176
177 // |YES| if this consumer is incognito.
178 @property(nonatomic, assign) BOOL isOffTheRecord;
179
180 // |YES| if this consumer is has voice search enabled.
181 @property(nonatomic, assign) BOOL voiceSearchIsEnabled;
182
183 // Gets the maximum number of sites shown.
184 @property(nonatomic, assign) NSUInteger maximumMostVisitedSitesShown;
185
186 // Gets the text of a what's new promo.
187 @property(nonatomic, retain) NSString* promoText;
188
189 // Gets the icon of a what's new promo.
190 // TODO(crbug.com/694750): This should not be WhatsNewIcon.
191 @property(nonatomic, assign) WhatsNewIcon promoIcon;
192
193 // |YES| if a what's new promo can be displayed.
194 @property(nonatomic, assign) BOOL promoCanShow;
195
196 // The number of tabs to show in the google landing fake toolbar.
197 @property(nonatomic, assign) int tabCount;
198
199 // |YES| if the google landing toolbar can show the forward arrow.
200 @property(nonatomic, assign) BOOL canGoForward;
201
202 // |YES| if the google landing toolbar can show the back arrow.
203 @property(nonatomic, assign) BOOL canGoBack;
204
205 // iPhone landscape uses a slightly different layout for the doodle and search
206 // field frame. Returns the proper frame from |frames| based on orientation,
207 // centered in the view.
208 - (CGRect)getOrientationFrame:(const CGRect[])frames;
209 // Returns the proper frame for the doodle.
210 - (CGRect)doodleFrame;
211 // Returns the proper frame for the search field.
212 - (CGRect)searchFieldFrame;
213 // Returns the height to use for the What's New promo view.
214 - (CGFloat)promoHeaderHeight;
215 // Add fake search field and voice search microphone.
216 - (void)addSearchField;
217 // Add most visited collection view.
218 - (void)addMostVisited;
219 // Update the iPhone fakebox's frame based on the current scroll view offset.
220 - (void)updateSearchField;
221 // Scrolls most visited to the top of the view when the omnibox is focused.
222 - (void)locationBarBecomesFirstResponder;
223 // Scroll the view back to 0,0 when the omnibox loses focus.
224 - (void)locationBarResignsFirstResponder;
225 // When the search field is tapped.
226 - (void)searchFieldTapped:(id)sender;
227 // Tells WebToolbarController to resign focus to the omnibox.
228 - (void)blurOmnibox;
229 // Called when a user does a long press on a most visited item.
230 - (void)handleMostVisitedLongPress:
231 (UILongPressGestureRecognizer*)longPressGesture;
232 // When the user removes a most visited a bubble pops up to undo the action.
233 - (void)showMostVisitedUndoForURL:(NSURL*)url;
234 // If Google is not the default search engine, hide the logo, doodle and
235 // fakebox.
236 - (void)updateLogoAndFakeboxDisplay;
237 // Helper method to set UICollectionViewFlowLayout insets for most visited.
238 - (void)setFlowLayoutInset:(UICollectionViewFlowLayout*)layout;
239 // Instructs the UICollectionView and UIView to reload it's data and layout.
240 - (void)reloadData;
241 // Returns the size of |self.mostVisitedData|.
242 - (NSUInteger)numberOfItems;
243 // Returns the number of non empty tiles (as opposed to the placeholder tiles).
244 - (NSInteger)numberOfNonEmptyTilesShown;
245 // Returns the URL for the mosted visited item in |self.mostVisitedData|.
246 - (GURL)urlForIndex:(NSUInteger)index;
247 // Returns the expected height of the NewTabPageHeaderView.
248 - (CGFloat)heightForSectionWithOmnibox;
249 // Returns the nearest ancestor view that is kind of |aClass|.
250 - (UIView*)nearestAncestorOfView:(UIView*)view withClass:(Class)aClass;
251 // Updates the collection view's scroll view offset for the next frame of the
252 // shiftTilesDown animation.
253 - (void)shiftTilesDownAnimationDidFire:(CADisplayLink*)link;
254 // Returns the size to use for Most Visited cells in the NTP contained in
255 // |view|.
256 - (CGSize)mostVisitedCellSizeForView;
257 // Returns the padding for use between Most Visited cells.
258 - (CGFloat)mostVisitedCellPadding;
259
260 @end
261
262 @implementation GoogleLandingViewController
263
264 @dynamic view;
265 @synthesize logoVendor = _logoVendor;
266 @synthesize dataSource = _dataSource;
267 // Property declared in NewTabPagePanelProtocol.
268 @synthesize delegate = _delegate;
269 @synthesize dispatcher = _dispatcher;
270 @synthesize isOffTheRecord = _isOffTheRecord;
271 @synthesize logoIsShowing = _logoIsShowing;
272 @synthesize promoText = _promoText;
273 @synthesize promoIcon = _promoIcon;
274 @synthesize promoCanShow = _promoCanShow;
275 @synthesize maximumMostVisitedSitesShown = _maximumMostVisitedSitesShown;
276 @synthesize tabCount = _tabCount;
277 @synthesize canGoForward = _canGoForward;
278 @synthesize canGoBack = _canGoBack;
279 @synthesize voiceSearchIsEnabled = _voiceSearchIsEnabled;
280
281 - (void)loadView {
282 self.view = [[[GoogleLandingView alloc]
283 initWithFrame:[UIScreen mainScreen].bounds] autorelease];
284 }
285
286 - (void)viewDidLoad {
287 [super viewDidLoad];
288 [self.view setAutoresizingMask:UIViewAutoresizingFlexibleHeight |
289 UIViewAutoresizingFlexibleWidth];
290 [self.view setFrameDelegate:self];
291
292 // Initialise |shiftTilesDownStartTime| to a sentinel value to indicate that
293 // the animation has not yet started.
294 _shiftTilesDownStartTime = -1;
295 _mostVisitedCellSize = [self mostVisitedCellSizeForView];
296 _isShowing = YES;
297 _scrolledToTop = NO;
298 _animateHeader = YES;
299
300 _tapGestureRecognizer.reset([[UITapGestureRecognizer alloc]
301 initWithTarget:self
302 action:@selector(blurOmnibox)]);
303 [_tapGestureRecognizer setDelegate:self];
304 _swipeGestureRecognizer.reset([[UISwipeGestureRecognizer alloc]
305 initWithTarget:self
306 action:@selector(blurOmnibox)]);
307 [_swipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionDown];
308
309 [self addSearchField];
310 [self addMostVisited];
311 [self addOverscrollActions];
312 [self reload];
313 }
314
315 - (void)viewDidLayoutSubviews {
316 [self updateSubviewFrames];
317 }
318
319 - (void)viewWillTransitionToSize:(CGSize)size
320 withTransitionCoordinator:
321 (id<UIViewControllerTransitionCoordinator>)coordinator {
322 [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
323
324 void (^alongsideBlock)(id<UIViewControllerTransitionCoordinatorContext>) = ^(
325 id<UIViewControllerTransitionCoordinatorContext> context) {
326 if (IsIPadIdiom() && _scrolledToTop) {
327 // Keep the most visited thumbnails scrolled to the top.
328 [_mostVisitedView setContentOffset:CGPointMake(0, [self pinnedOffsetY])];
329 return;
330 };
331
332 // Invalidate the layout so that the collection view's header size is reset
333 // for the new orientation.
334 if (!_scrolledToTop) {
335 [[_mostVisitedView collectionViewLayout] invalidateLayout];
336 }
337
338 // Call -scrollViewDidScroll: so that the omnibox's frame is adjusted for
339 // the scroll view's offset.
340 [self scrollViewDidScroll:_mostVisitedView];
341
342 };
343 [coordinator animateAlongsideTransition:alongsideBlock completion:nil];
344 }
345
346 - (void)dealloc {
347 [[NSNotificationCenter defaultCenter] removeObserver:self];
348 [_mostVisitedView setDelegate:nil];
349 [_mostVisitedView setDataSource:nil];
350 [_overscrollActionsController invalidate];
351 [super dealloc];
352 }
353
354 #pragma mark - Private
355
356 - (CGSize)mostVisitedCellSizeForView {
357 if (IsIPadIdiom()) {
358 // On iPads, split-screen and slide-over may require showing smaller cells.
359 CGSize maximumCellSize = [MostVisitedCell maximumSize];
360 CGSize viewSize = self.view.bounds.size;
361 CGFloat smallestDimension =
362 viewSize.height > viewSize.width ? viewSize.width : viewSize.height;
363 CGFloat cellWidth = AlignValueToPixel(
364 (smallestDimension - 3 * [self mostVisitedCellPadding]) / 2);
365 if (cellWidth < maximumCellSize.width) {
366 return CGSizeMake(cellWidth, cellWidth);
367 } else {
368 return maximumCellSize;
369 }
370 } else {
371 return [MostVisitedCell maximumSize];
372 }
373 }
374
375 - (CGFloat)mostVisitedCellPadding {
376 return IsIPadIdiom() ? kMostVisitedPaddingIPadFavicon
377 : kMostVisitedPaddingIPhone;
378 }
379
380 - (CGFloat)viewWidth {
381 return [self.view frame].size.width;
382 }
383
384 - (int)numberOfColumns {
385 CGFloat width = [self viewWidth];
386 CGFloat padding = [self mostVisitedCellPadding];
387 // Try to fit 4 columns.
388 if (width >= 5 * padding + _mostVisitedCellSize.width * 4)
389 return 4;
390 // Try to fit 3 columns.
391 if (width >= 4 * padding + _mostVisitedCellSize.width * 3)
392 return 3;
393 // Try to fit 2 columns.
394 if (width >= 3 * padding + _mostVisitedCellSize.width * 2)
395 return 2;
396 // We never want to have a layout with only one column, however: At launch,
397 // the view's size is initialized to the width of 320, which can only fit
398 // one column on iPhone 6 and 6+. TODO(crbug.com/506183): Get rid of the
399 // unecessary resize, and add a NOTREACHED() here.
400 return 1;
401 }
402
403 - (CGFloat)leftMargin {
404 int columns = [self numberOfColumns];
405 CGFloat whitespace = [self viewWidth] - columns * _mostVisitedCellSize.width -
406 (columns - 1) * [self mostVisitedCellPadding];
407 CGFloat margin = AlignValueToPixel(whitespace / 2);
408 DCHECK(margin >= [self mostVisitedCellPadding]);
409 return margin;
410 }
411
412 - (CGRect)doodleFrame {
413 const CGRect kDoodleFrame[2] = {
414 {{0, 66}, {0, 120}}, {{0, 56}, {0, 120}},
415 };
416 CGRect doodleFrame = [self getOrientationFrame:kDoodleFrame];
417 if (!IsIPadIdiom() && !self.logoIsShowing)
418 doodleFrame.size.height = kNonGoogleSearchDoodleHeight;
419 if (IsIPadIdiom()) {
420 doodleFrame.origin.y = IsPortrait() ? kDoodleTopMarginIPadPortrait
421 : kDoodleTopMarginIPadLandscape;
422 }
423 return doodleFrame;
424 }
425
426 - (CGRect)searchFieldFrame {
427 CGFloat y = CGRectGetMaxY([self doodleFrame]);
428 CGFloat leftMargin = [self leftMargin];
429 if (leftMargin > kMaxSearchFieldFrameMargin)
430 leftMargin = kMaxSearchFieldFrameMargin;
431 const CGRect kSearchFieldFrame[2] = {
432 {{leftMargin, y + 32}, {0, 50}}, {{leftMargin, y + 16}, {0, 50}},
433 };
434 CGRect searchFieldFrame = [self getOrientationFrame:kSearchFieldFrame];
435 if (IsIPadIdiom()) {
436 CGFloat iPadTopMargin = IsPortrait() ? kDoodleTopMarginIPadPortrait
437 : kDoodleTopMarginIPadLandscape;
438 searchFieldFrame.origin.y += iPadTopMargin - 32;
439 }
440 return searchFieldFrame;
441 }
442
443 - (CGRect)getOrientationFrame:(const CGRect[])frames {
444 UIInterfaceOrientation orient =
445 [[UIApplication sharedApplication] statusBarOrientation];
446 InterfaceOrientation inter_orient =
447 (IsIPadIdiom() || UIInterfaceOrientationIsPortrait(orient))
448 ? ALL
449 : IPHONE_LANDSCAPE;
450
451 // Calculate width based on screen width and origin x.
452 CGRect frame = frames[inter_orient];
453 frame.size.width = fmax(self.view.bounds.size.width - 2 * frame.origin.x, 50);
454 return frame;
455 }
456
457 - (CGFloat)promoHeaderHeight {
458 CGFloat promoMaxWidth = [self viewWidth] - 2 * [self leftMargin];
459 NSString* text = self.promoText;
460 return [WhatsNewHeaderView heightToFitText:text inWidth:promoMaxWidth];
461 }
462
463 - (void)updateLogoAndFakeboxDisplay {
464 if (self.logoVendor.showingLogo != self.logoIsShowing) {
465 self.logoVendor.showingLogo = self.logoIsShowing;
466 if (_viewLoaded) {
467 [self updateSubviewFrames];
468
469 // Adjust the height of |_headerView| to fit its content which may have
470 // been shifted due to the visibility of the doodle.
471 CGRect headerFrame = [_headerView frame];
472 headerFrame.size.height = [self heightForSectionWithOmnibox];
473 [_headerView setFrame:headerFrame];
474
475 // Adjust vertical positioning of |_promoHeaderView|.
476 CGFloat omniboxHeaderHeight =
477 [self collectionView:_mostVisitedView
478 layout:[_mostVisitedView
479 collectionViewLayout]
480 referenceSizeForHeaderInSection:0]
481 .height;
482 CGRect whatsNewFrame = [_promoHeaderView frame];
483 whatsNewFrame.origin.y = omniboxHeaderHeight;
484 [_promoHeaderView setFrame:whatsNewFrame];
485 }
486 if (IsIPadIdiom())
487 [_searchTapTarget setHidden:!self.logoIsShowing];
488 }
489 }
490
491 // Initialize and add a search field tap target and a voice search button.
492 - (void)addSearchField {
493 CGRect searchFieldFrame = [self searchFieldFrame];
494 _searchTapTarget.reset([[UIButton alloc] initWithFrame:searchFieldFrame]);
495 if (IsIPadIdiom()) {
496 UIImage* searchBoxImage = [[UIImage imageNamed:@"ntp_google_search_box"]
497 resizableImageWithCapInsets:kSearchBoxStretchInsets];
498 [_searchTapTarget setBackgroundImage:searchBoxImage
499 forState:UIControlStateNormal];
500 }
501 [_searchTapTarget setAdjustsImageWhenHighlighted:NO];
502 [_searchTapTarget addTarget:self
503 action:@selector(searchFieldTapped:)
504 forControlEvents:UIControlEventTouchUpInside];
505 [_searchTapTarget
506 setAccessibilityLabel:l10n_util::GetNSString(IDS_OMNIBOX_EMPTY_HINT)];
507 // Set isAccessibilityElement to NO so that Voice Search button is accessible.
508 [_searchTapTarget setIsAccessibilityElement:NO];
509
510 // Set up fakebox hint label.
511 CGRect hintFrame = CGRectInset([_searchTapTarget bounds], 12, 3);
512 const CGFloat kVoiceSearchOffset = 48;
513 hintFrame.size.width = searchFieldFrame.size.width - kVoiceSearchOffset;
514 base::scoped_nsobject<UILabel> searchHintLabel(
515 [[UILabel alloc] initWithFrame:hintFrame]);
516 [_searchTapTarget addSubview:searchHintLabel];
517 [searchHintLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
518 [searchHintLabel
519 addConstraint:[NSLayoutConstraint
520 constraintWithItem:searchHintLabel
521 attribute:NSLayoutAttributeHeight
522 relatedBy:NSLayoutRelationEqual
523 toItem:nil
524 attribute:NSLayoutAttributeNotAnAttribute
525 multiplier:1
526 constant:hintFrame.size.height]];
527 [_searchTapTarget
528 addConstraint:[NSLayoutConstraint
529 constraintWithItem:searchHintLabel
530 attribute:NSLayoutAttributeCenterY
531 relatedBy:NSLayoutRelationEqual
532 toItem:_searchTapTarget
533 attribute:NSLayoutAttributeCenterY
534 multiplier:1
535 constant:0]];
536 _hintLabelLeadingConstraint.reset(
537 [[NSLayoutConstraint constraintWithItem:searchHintLabel
538 attribute:NSLayoutAttributeLeading
539 relatedBy:NSLayoutRelationEqual
540 toItem:_searchTapTarget
541 attribute:NSLayoutAttributeLeading
542 multiplier:1
543 constant:kHintLabelSidePadding] retain]);
544 [_searchTapTarget addConstraint:_hintLabelLeadingConstraint];
545 [searchHintLabel setText:l10n_util::GetNSString(IDS_OMNIBOX_EMPTY_HINT)];
546 if (base::i18n::IsRTL()) {
547 [searchHintLabel setTextAlignment:NSTextAlignmentRight];
548 }
549 [searchHintLabel
550 setTextColor:[UIColor
551 colorWithWhite:kiPhoneOmniboxPlaceholderColorBrightness
552 alpha:1.0]];
553 [searchHintLabel setFont:[MDCTypography subheadFont]];
554
555 // Add a voice search button.
556 UIImage* micImage = [UIImage imageNamed:@"voice_icon"];
557 base::scoped_nsobject<UIButton> voiceTapTarget(
558 [[UIButton alloc] initWithFrame:CGRectZero]);
559 [_searchTapTarget addSubview:voiceTapTarget];
560
561 [voiceTapTarget setTranslatesAutoresizingMaskIntoConstraints:NO];
562 [_searchTapTarget
563 addConstraint:[NSLayoutConstraint
564 constraintWithItem:voiceTapTarget
565 attribute:NSLayoutAttributeCenterY
566 relatedBy:NSLayoutRelationEqual
567 toItem:_searchTapTarget
568 attribute:NSLayoutAttributeCenterY
569 multiplier:1
570 constant:0]];
571 _voiceTapTrailingConstraint.reset(
572 [[NSLayoutConstraint constraintWithItem:voiceTapTarget
573 attribute:NSLayoutAttributeTrailing
574 relatedBy:NSLayoutRelationEqual
575 toItem:_searchTapTarget
576 attribute:NSLayoutAttributeTrailing
577 multiplier:1
578 constant:0] retain]);
579 [_searchTapTarget addConstraint:_voiceTapTrailingConstraint];
580 [voiceTapTarget
581 addConstraint:[NSLayoutConstraint
582 constraintWithItem:voiceTapTarget
583 attribute:NSLayoutAttributeHeight
584 relatedBy:NSLayoutRelationEqual
585 toItem:nil
586 attribute:NSLayoutAttributeNotAnAttribute
587 multiplier:0
588 constant:kVoiceSearchButtonWidth]];
589 [voiceTapTarget
590 addConstraint:[NSLayoutConstraint
591 constraintWithItem:voiceTapTarget
592 attribute:NSLayoutAttributeWidth
593 relatedBy:NSLayoutRelationEqual
594 toItem:nil
595 attribute:NSLayoutAttributeNotAnAttribute
596 multiplier:0
597 constant:kVoiceSearchButtonWidth]];
598 [_searchTapTarget
599 addConstraint:[NSLayoutConstraint
600 constraintWithItem:searchHintLabel
601 attribute:NSLayoutAttributeTrailing
602 relatedBy:NSLayoutRelationEqual
603 toItem:voiceTapTarget
604 attribute:NSLayoutAttributeLeading
605 multiplier:1
606 constant:0]];
607 [voiceTapTarget setAdjustsImageWhenHighlighted:NO];
608 [voiceTapTarget setImage:micImage forState:UIControlStateNormal];
609 [voiceTapTarget setTag:IDC_VOICE_SEARCH];
610 [voiceTapTarget setAccessibilityLabel:l10n_util::GetNSString(
611 IDS_IOS_ACCNAME_VOICE_SEARCH)];
612 [voiceTapTarget setAccessibilityIdentifier:@"Voice Search"];
613
614 if (self.voiceSearchIsEnabled) {
615 [voiceTapTarget addTarget:self
616 action:@selector(loadVoiceSearch:)
617 forControlEvents:UIControlEventTouchUpInside];
618 [voiceTapTarget addTarget:self
619 action:@selector(preloadVoiceSearch:)
620 forControlEvents:UIControlEventTouchDown];
621 } else {
622 [voiceTapTarget setEnabled:NO];
623 }
624 }
625
626 - (void)loadVoiceSearch:(id)sender {
627 DCHECK(self.voiceSearchIsEnabled);
628 base::RecordAction(UserMetricsAction("MobileNTPMostVisitedVoiceSearch"));
629 [sender chromeExecuteCommand:sender];
630 }
631
632 - (void)preloadVoiceSearch:(id)sender {
633 DCHECK(self.voiceSearchIsEnabled);
634 [sender removeTarget:self
635 action:@selector(preloadVoiceSearch:)
636 forControlEvents:UIControlEventTouchDown];
637
638 // Use a GenericChromeCommand because |sender| already has a tag set for a
639 // different command.
640 base::scoped_nsobject<GenericChromeCommand> command(
641 [[GenericChromeCommand alloc] initWithTag:IDC_PRELOAD_VOICE_SEARCH]);
642 [sender chromeExecuteCommand:command];
643 }
644
645 - (void)setFlowLayoutInset:(UICollectionViewFlowLayout*)layout {
646 CGFloat leftMargin = [self leftMargin];
647 [layout setSectionInset:UIEdgeInsetsMake(0, leftMargin, 0, leftMargin)];
648 }
649
650 - (void)resetSectionInset {
651 UICollectionViewFlowLayout* flowLayout =
652 (UICollectionViewFlowLayout*)[_mostVisitedView collectionViewLayout];
653 [flowLayout setSectionInset:UIEdgeInsetsZero];
654 }
655
656 - (void)updateSubviewFrames {
657 _mostVisitedCellSize = [self mostVisitedCellSizeForView];
658 UICollectionViewFlowLayout* flowLayout =
659 base::mac::ObjCCastStrict<UICollectionViewFlowLayout>(
660 [_mostVisitedView collectionViewLayout]);
661 [flowLayout setItemSize:_mostVisitedCellSize];
662 self.logoVendor.view.frame = [self doodleFrame];
663
664 [self setFlowLayoutInset:flowLayout];
665 [flowLayout invalidateLayout];
666 [_promoHeaderView setSideMargin:[self leftMargin]];
667
668 // On the iPhone 6 Plus, if the app is started in landscape after a fresh
669 // install, the UICollectionViewLayout incorrectly sizes the widths of the
670 // supplementary views to the portrait width. Correct that here to ensure
671 // that the header is property laid out to the UICollectionView's width.
672 // crbug.com/491131
673 CGFloat collectionViewWidth = CGRectGetWidth([_mostVisitedView bounds]);
674 CGFloat collectionViewMinX = CGRectGetMinX([_mostVisitedView bounds]);
675 for (UIView* supplementaryView in _supplementaryViews.get()) {
676 CGRect supplementaryViewFrame = supplementaryView.frame;
677 supplementaryViewFrame.origin.x = collectionViewMinX;
678 supplementaryViewFrame.size.width = collectionViewWidth;
679 supplementaryView.frame = supplementaryViewFrame;
680 }
681
682 BOOL isScrollableNTP = !IsIPadIdiom() || IsCompactTablet();
683 if (isScrollableNTP && _scrolledToTop) {
684 // Set the scroll view's offset to the pinned offset to keep the omnibox
685 // at the top of the screen if it isn't already.
686 CGFloat pinnedOffsetY = [self pinnedOffsetY];
687 if ([_mostVisitedView contentOffset].y < pinnedOffsetY) {
688 [_mostVisitedView setContentOffset:CGPointMake(0, pinnedOffsetY)];
689 } else {
690 [self updateSearchField];
691 }
692 } else {
693 [_searchTapTarget setFrame:[self searchFieldFrame]];
694 }
695
696 if (!_viewLoaded) {
697 _viewLoaded = YES;
698 [self.logoVendor fetchDoodle];
699 }
700 [self.delegate updateNtpBarShadowForPanelController:self];
701 }
702
703 // Initialize and add a panel with most visited sites.
704 - (void)addMostVisited {
705 CGRect mostVisitedFrame = [self.view bounds];
706 base::scoped_nsobject<UICollectionViewFlowLayout> flowLayout;
707 if (IsIPadIdiom())
708 flowLayout.reset([[UICollectionViewFlowLayout alloc] init]);
709 else
710 flowLayout.reset([[MostVisitedLayout alloc] init]);
711
712 [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
713 [flowLayout setItemSize:_mostVisitedCellSize];
714 [flowLayout setMinimumInteritemSpacing:8];
715 [flowLayout setMinimumLineSpacing:[self mostVisitedCellPadding]];
716 DCHECK(!_mostVisitedView);
717 _mostVisitedView.reset([[UICollectionView alloc]
718 initWithFrame:mostVisitedFrame
719 collectionViewLayout:flowLayout]);
720 [_mostVisitedView setAutoresizingMask:UIViewAutoresizingFlexibleHeight |
721 UIViewAutoresizingFlexibleWidth];
722 [_mostVisitedView setDelegate:self];
723 [_mostVisitedView setDataSource:self];
724 [_mostVisitedView registerClass:[MostVisitedCell class]
725 forCellWithReuseIdentifier:@"classCell"];
726 [_mostVisitedView setBackgroundColor:[UIColor clearColor]];
727 [_mostVisitedView setBounces:YES];
728 [_mostVisitedView setShowsHorizontalScrollIndicator:NO];
729 [_mostVisitedView setShowsVerticalScrollIndicator:NO];
730 [_mostVisitedView registerClass:[WhatsNewHeaderView class]
731 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
732 withReuseIdentifier:@"whatsNew"];
733 [_mostVisitedView registerClass:[NewTabPageHeaderView class]
734 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
735 withReuseIdentifier:@"header"];
736 [_mostVisitedView setAccessibilityIdentifier:@"Google Landing"];
737
738 [self.view addSubview:_mostVisitedView];
739 }
740
741 - (void)updateSearchField {
742 NSArray* constraints =
743 @[ _hintLabelLeadingConstraint, _voiceTapTrailingConstraint ];
744 [_headerView updateSearchField:_searchTapTarget
745 withInitialFrame:[self searchFieldFrame]
746 subviewConstraints:constraints
747 forOffset:[_mostVisitedView contentOffset].y];
748 }
749
750 - (void)addOverscrollActions {
751 if (!IsIPadIdiom()) {
752 _overscrollActionsController.reset([[OverscrollActionsController alloc]
753 initWithScrollView:_mostVisitedView]);
754 [_overscrollActionsController setStyle:OverscrollStyle::NTP_NON_INCOGNITO];
755 [_overscrollActionsController setDelegate:self];
756 }
757 }
758
759 // Check to see if the promo label should be hidden.
760 - (void)hideWhatsNewIfNecessary {
761 if (![_promoHeaderView isHidden] && !self.promoCanShow) {
762 [_promoHeaderView setHidden:YES];
763 [self.view setNeedsLayout];
764 }
765 }
766
767 - (void)locationBarBecomesFirstResponder {
768 if (!_isShowing)
769 return;
770
771 _omniboxFocused = YES;
772 [self shiftTilesUp];
773 }
774
775 - (void)shiftTilesUp {
776 _scrolledToTop = YES;
777 // Add gesture recognizer to background |self.view| when omnibox is focused.
778 [self.view addGestureRecognizer:_tapGestureRecognizer];
779 [self.view addGestureRecognizer:_swipeGestureRecognizer];
780
781 CGFloat pinnedOffsetY = [self pinnedOffsetY];
782 _animateHeader = !IsIPadIdiom();
783
784 [UIView animateWithDuration:0.25
785 animations:^{
786 if ([_mostVisitedView contentOffset].y < pinnedOffsetY) {
787 [_mostVisitedView setContentOffset:CGPointMake(0, pinnedOffsetY)];
788 [[_mostVisitedView collectionViewLayout] invalidateLayout];
789 }
790 }
791 completion:^(BOOL finished) {
792 // Check to see if we are still scrolled to the top -- it's possible
793 // (and difficult) to resign the first responder and initiate a
794 // -shiftTilesDown before the animation here completes.
795 if (_scrolledToTop) {
796 _animateHeader = NO;
797 if (!IsIPadIdiom()) {
798 [self.dispatcher onFakeboxAnimationComplete];
799 [_headerView fadeOutShadow];
800 [_searchTapTarget setHidden:YES];
801 }
802 }
803 }];
804 }
805
806 - (void)searchFieldTapped:(id)sender {
807 [self.dispatcher focusFakebox];
808 }
809
810 - (void)blurOmnibox {
811 if (_omniboxFocused) {
812 [self.dispatcher cancelOmniboxEdit];
813 } else {
814 [self locationBarResignsFirstResponder];
815 }
816 }
817
818 - (void)locationBarResignsFirstResponder {
819 if (!_isShowing && !_scrolledToTop)
820 return;
821
822 _omniboxFocused = NO;
823 if ([_contextMenuCoordinator isVisible]) {
824 return;
825 }
826
827 [self shiftTilesDown];
828 }
829
830 - (void)shiftTilesDown {
831 _animateHeader = YES;
832 _scrolledToTop = NO;
833 if (!IsIPadIdiom()) {
834 [_searchTapTarget setHidden:NO];
835 [self.dispatcher onFakeboxBlur];
836 }
837
838 // Reload most visited sites in case the number of placeholder cells needs to
839 // be updated after an orientation change.
840 [_mostVisitedView reloadData];
841
842 // Reshow views that are within range of the most visited collection view
843 // (if necessary).
844 [self.view removeGestureRecognizer:_tapGestureRecognizer];
845 [self.view removeGestureRecognizer:_swipeGestureRecognizer];
846
847 // CADisplayLink is used for this animation instead of the standard UIView
848 // animation because the standard animation did not properly convert the
849 // fakebox from its scrolled up mode to its scrolled down mode. Specifically,
850 // calling |UICollectionView reloadData| adjacent to the standard animation
851 // caused the fakebox's views to jump incorrectly. CADisplayLink avoids this
852 // problem because it allows |shiftTilesDownAnimationDidFire| to directly
853 // control each frame.
854 CADisplayLink* link = [CADisplayLink
855 displayLinkWithTarget:self
856 selector:@selector(shiftTilesDownAnimationDidFire:)];
857 [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
858
859 // Dismisses modal UI elements if displayed. Must be called at the end of
860 // -locationBarResignsFirstResponder since it could result in -dealloc being
861 // called.
862 [self dismissModals];
863 }
864
865 - (void)shiftTilesDownAnimationDidFire:(CADisplayLink*)link {
866 // If this is the first frame of the animation, store the starting timestamp
867 // and do nothing.
868 if (_shiftTilesDownStartTime == -1) {
869 _shiftTilesDownStartTime = link.timestamp;
870 return;
871 }
872
873 CFTimeInterval timeElapsed = link.timestamp - _shiftTilesDownStartTime;
874 double percentComplete = timeElapsed / kShiftTilesDownAnimationDuration;
875 // Ensure that the percentage cannot be above 1.0.
876 if (percentComplete > 1.0)
877 percentComplete = 1.0;
878
879 // Find how much the collection view should be scrolled up in the next frame.
880 CGFloat yOffset = (1.0 - percentComplete) * [self pinnedOffsetY];
881 [_mostVisitedView setContentOffset:CGPointMake(0, yOffset)];
882
883 if (percentComplete == 1.0) {
884 [link invalidate];
885 // Reset |shiftTilesDownStartTime to its sentinal value.
886 _shiftTilesDownStartTime = -1;
887 [[_mostVisitedView collectionViewLayout] invalidateLayout];
888 }
889 }
890
891 - (void)reloadData {
892 // -reloadData updates from |self.mostVisitedData|.
893 // -invalidateLayout is necessary because sometimes the flowLayout has the
894 // wrong cached size and will throw an internal exception if the
895 // -numberOfItems shrinks. -setNeedsLayout is needed in case
896 // -numberOfItems increases enough to add a new row and change the height
897 // of _mostVisitedView.
898 [_mostVisitedView reloadData];
899 [[_mostVisitedView collectionViewLayout] invalidateLayout];
900 [self.view setNeedsLayout];
901 }
902
903 - (CGFloat)heightForSectionWithOmnibox {
904 CGFloat headerHeight =
905 CGRectGetMaxY([self searchFieldFrame]) + kNTPSearchFieldBottomPadding;
906 if (IsIPadIdiom()) {
907 if (self.logoIsShowing) {
908 if (!self.promoCanShow) {
909 UIInterfaceOrientation orient =
910 [[UIApplication sharedApplication] statusBarOrientation];
911 const CGFloat kTopSpacingMaterialPortrait = 56;
912 const CGFloat kTopSpacingMaterialLandscape = 32;
913 headerHeight += UIInterfaceOrientationIsPortrait(orient)
914 ? kTopSpacingMaterialPortrait
915 : kTopSpacingMaterialLandscape;
916 }
917 } else {
918 headerHeight = kNonGoogleSearchHeaderHeightIPad;
919 }
920 }
921 return headerHeight;
922 }
923
924 #pragma mark - ToolbarOwner
925
926 - (ToolbarController*)relinquishedToolbarController {
927 return [_headerView relinquishedToolbarController];
928 }
929
930 - (void)reparentToolbarController {
931 [_headerView reparentToolbarController];
932 }
933
934 #pragma mark - UICollectionView Methods.
935
936 - (CGSize)collectionView:(UICollectionView*)collectionView
937 layout:
938 (UICollectionViewLayout*)collectionViewLayout
939 referenceSizeForHeaderInSection:(NSInteger)section {
940 CGFloat headerHeight = 0;
941 if (section == SectionWithOmnibox) {
942 headerHeight = [self heightForSectionWithOmnibox];
943 ((UICollectionViewFlowLayout*)collectionViewLayout).headerReferenceSize =
944 CGSizeMake(0, headerHeight);
945 } else if (section == SectionWithMostVisited) {
946 if (self.promoCanShow) {
947 headerHeight = [self promoHeaderHeight];
948 } else {
949 headerHeight = kWhatsNewHeaderHiddenHeight;
950 }
951 }
952 return CGSizeMake(0, headerHeight);
953 }
954
955 #pragma mark - UICollectionViewDelegate
956
957 - (BOOL)collectionView:(UICollectionView*)collectionView
958 shouldSelectItemAtIndexPath:(NSIndexPath*)indexPath {
959 return indexPath.row < static_cast<NSInteger>([self numberOfItems]);
960 }
961
962 - (void)collectionView:(UICollectionView*)collectionView
963 didSelectItemAtIndexPath:(NSIndexPath*)indexPath {
964 MostVisitedCell* cell =
965 (MostVisitedCell*)[collectionView cellForItemAtIndexPath:indexPath];
966
967 // Keep the UICollectionView alive for one second while the screen
968 // reader does its thing.
969 // TODO(jif): This needs a radar, since it is almost certainly a
970 // UIKit accessibility bug. crbug.com/529271
971 if (UIAccessibilityIsVoiceOverRunning()) {
972 UICollectionView* blockView = [_mostVisitedView retain];
973 dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
974 static_cast<int64_t>(1 * NSEC_PER_SEC)),
975 dispatch_get_main_queue(), ^{
976 [blockView release];
977 });
978 }
979
980 const NSUInteger visitedIndex = indexPath.row;
981 [self blurOmnibox];
982 DCHECK(visitedIndex < [self numberOfItems]);
983 [self.dataSource logMostVisitedClick:visitedIndex tileType:cell.tileType];
984 [self.dispatcher loadURL:[self urlForIndex:visitedIndex]
985 referrer:web::Referrer()
986 transition:ui::PAGE_TRANSITION_AUTO_BOOKMARK
987 rendererInitiated:NO];
988 }
989
990 #pragma mark - UICollectionViewDataSource
991
992 - (UICollectionReusableView*)collectionView:(UICollectionView*)collectionView
993 viewForSupplementaryElementOfKind:(NSString*)kind
994 atIndexPath:(NSIndexPath*)indexPath {
995 DCHECK(kind == UICollectionElementKindSectionHeader);
996
997 if (!_supplementaryViews)
998 _supplementaryViews.reset([[NSMutableArray alloc] init]);
999
1000 if (indexPath.section == SectionWithOmnibox) {
1001 if (!_headerView) {
1002 _headerView.reset([[collectionView
1003 dequeueReusableSupplementaryViewOfKind:
1004 UICollectionElementKindSectionHeader
1005 withReuseIdentifier:@"header"
1006 forIndexPath:indexPath] retain]);
1007 [_headerView addSubview:[self.logoVendor view]];
1008 [_headerView addSubview:_searchTapTarget];
1009 [_headerView addViewsToSearchField:_searchTapTarget];
1010
1011 if (!IsIPadIdiom()) {
1012 // iPhone header also contains a toolbar since the normal toolbar is
1013 // hidden.
1014 [_headerView addToolbarWithDataSource:self.dataSource
1015 dispatcher:self.dispatcher];
1016 [_headerView setToolbarTabCount:self.tabCount];
1017 [_headerView setCanGoForward:self.canGoForward];
1018 [_headerView setCanGoBack:self.canGoBack];
1019 [_headerView hideToolbarViewsForNewTabPage];
1020 }
1021 [_supplementaryViews addObject:_headerView];
1022 }
1023 return _headerView;
1024 }
1025
1026 if (indexPath.section == SectionWithMostVisited) {
1027 if (!_promoHeaderView) {
1028 _promoHeaderView.reset([[collectionView
1029 dequeueReusableSupplementaryViewOfKind:
1030 UICollectionElementKindSectionHeader
1031 withReuseIdentifier:@"whatsNew"
1032 forIndexPath:indexPath] retain]);
1033 [_promoHeaderView setSideMargin:[self leftMargin]];
1034 [_promoHeaderView setDelegate:self];
1035 if (self.promoCanShow) {
1036 [_promoHeaderView setText:self.promoText];
1037 [_promoHeaderView setIcon:self.promoIcon];
1038 [self.dataSource promoViewed];
1039 }
1040 [_supplementaryViews addObject:_promoHeaderView];
1041 }
1042 return _promoHeaderView;
1043 }
1044
1045 NOTREACHED();
1046 return nil;
1047 }
1048
1049 - (NSInteger)numberOfSectionsInCollectionView:
1050 (UICollectionView*)collectionView {
1051 return NumberOfCollectionViewSections;
1052 }
1053
1054 - (NSInteger)collectionView:(UICollectionView*)collectionView
1055 numberOfItemsInSection:(NSInteger)section {
1056 // The first section only contains a header view and no items.
1057 if (section == SectionWithOmnibox)
1058 return 0;
1059
1060 // Phone always contains the maximum number of cells. Cells in excess of the
1061 // number of thumbnails are used solely for layout/sizing.
1062 if (!IsIPadIdiom())
1063 return self.maximumMostVisitedSitesShown;
1064
1065 return [self numberOfNonEmptyTilesShown];
1066 }
1067
1068 - (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView
1069 cellForItemAtIndexPath:(NSIndexPath*)indexPath {
1070 MostVisitedCell* cell = (MostVisitedCell*)[collectionView
1071 dequeueReusableCellWithReuseIdentifier:@"classCell"
1072 forIndexPath:indexPath];
1073 BOOL isPlaceholder = indexPath.row >= (int)[self numberOfItems];
1074 if (isPlaceholder) {
1075 [cell showPlaceholder];
1076 for (UIGestureRecognizer* ges in cell.gestureRecognizers) {
1077 [cell removeGestureRecognizer:ges];
1078 }
1079
1080 // When -numberOfItems is 0, always remove the placeholder.
1081 if (indexPath.row >= [self numberOfColumns] || [self numberOfItems] == 0) {
1082 // This cell is completely empty and only exists for layout/sizing
1083 // purposes.
1084 [cell removePlaceholderImage];
1085 }
1086 return cell;
1087 }
1088
1089 const ntp_tiles::NTPTile& ntpTile =
1090 [self.dataSource mostVisitedAtIndex:indexPath.row];
1091 NSString* title = base::SysUTF16ToNSString(ntpTile.title);
1092
1093 [cell setupWithURL:ntpTile.url title:title dataSource:self.dataSource];
1094
1095 base::scoped_nsobject<UILongPressGestureRecognizer> longPress(
1096 [[UILongPressGestureRecognizer alloc]
1097 initWithTarget:self
1098 action:@selector(handleMostVisitedLongPress:)]);
1099 [cell addGestureRecognizer:longPress];
1100
1101 return cell;
1102 }
1103
1104 #pragma mark - Context Menu
1105
1106 // Called when a user does a long press on a most visited item.
1107 - (void)handleMostVisitedLongPress:(UILongPressGestureRecognizer*)sender {
1108 if (sender.state == UIGestureRecognizerStateBegan) {
1109 // Only one long press at a time.
1110 if ([_contextMenuCoordinator isVisible]) {
1111 return;
1112 }
1113
1114 NSIndexPath* indexPath = [_mostVisitedView
1115 indexPathForCell:static_cast<UICollectionViewCell*>(sender.view)];
1116 const NSUInteger index = indexPath.row;
1117
1118 // A long press occured on one of the most visited button. Popup a context
1119 // menu.
1120 DCHECK(index < [self numberOfItems]);
1121
1122 web::ContextMenuParams params;
1123 // Get view coordinates in local space.
1124 params.location = [sender locationInView:self.view];
1125 params.view.reset([self.view retain]);
1126
1127 // Present sheet/popover using controller that is added to view hierarchy.
1128 UIViewController* topController = [params.view window].rootViewController;
1129 while (topController.presentedViewController)
1130 topController = topController.presentedViewController;
1131
1132 _contextMenuCoordinator.reset([[ContextMenuCoordinator alloc]
1133 initWithBaseViewController:topController
1134 params:params]);
1135
1136 ProceduralBlock action;
1137
1138 // Open In New Tab.
1139 GURL url = [self urlForIndex:index];
1140 base::WeakNSObject<GoogleLandingViewController> weakSelf(self);
1141 action = ^{
1142 base::scoped_nsobject<GoogleLandingViewController> strongSelf(
1143 [weakSelf retain]);
1144 if (!strongSelf)
1145 return;
1146 MostVisitedCell* cell = (MostVisitedCell*)sender.view;
1147 [[strongSelf dataSource] logMostVisitedClick:index
1148 tileType:cell.tileType];
1149 [[strongSelf dispatcher] webPageOrderedOpen:url
1150 referrer:web::Referrer()
1151 inBackground:YES
1152 appendTo:kCurrentTab];
1153 };
1154 [_contextMenuCoordinator
1155 addItemWithTitle:l10n_util::GetNSStringWithFixup(
1156 IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWTAB)
1157 action:action];
1158
1159 if (!self.isOffTheRecord) {
1160 // Open in Incognito Tab.
1161 action = ^{
1162 base::scoped_nsobject<GoogleLandingViewController> strongSelf(
1163 [weakSelf retain]);
1164 if (!strongSelf)
1165 return;
1166 MostVisitedCell* cell = (MostVisitedCell*)sender.view;
1167 [[strongSelf dataSource] logMostVisitedClick:index
1168 tileType:cell.tileType];
1169 [[strongSelf dispatcher] webPageOrderedOpen:url
1170 referrer:web::Referrer()
1171 inIncognito:YES
1172 inBackground:NO
1173 appendTo:kCurrentTab];
1174 };
1175 [_contextMenuCoordinator
1176 addItemWithTitle:l10n_util::GetNSStringWithFixup(
1177 IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWINCOGNITOTAB)
1178 action:action];
1179 }
1180
1181 // Remove the most visited url.
1182 NSString* title =
1183 l10n_util::GetNSStringWithFixup(IDS_BOOKMARK_BUBBLE_REMOVE_BOOKMARK);
1184 action = ^{
1185 base::scoped_nsobject<GoogleLandingViewController> strongSelf(
1186 [weakSelf retain]);
1187 // Early return if the controller has been deallocated.
1188 if (!strongSelf)
1189 return;
1190 base::RecordAction(UserMetricsAction("MostVisited_UrlBlacklisted"));
1191 [[strongSelf dataSource] addBlacklistedURL:url];
1192 [strongSelf showMostVisitedUndoForURL:net::NSURLWithGURL(url)];
1193 };
1194 [_contextMenuCoordinator addItemWithTitle:title action:action];
1195
1196 [_contextMenuCoordinator start];
1197
1198 if (IsIPadIdiom())
1199 [self blurOmnibox];
1200 }
1201 }
1202
1203 - (void)showMostVisitedUndoForURL:(NSURL*)url {
1204 _deletedUrl.reset([url retain]);
1205
1206 MDCSnackbarMessageAction* action =
1207 [[[MDCSnackbarMessageAction alloc] init] autorelease];
1208 base::WeakNSObject<GoogleLandingViewController> weakSelf(self);
1209 action.handler = ^{
1210 base::scoped_nsobject<GoogleLandingViewController> strongSelf(
1211 [weakSelf retain]);
1212 if (!strongSelf)
1213 return;
1214 [[strongSelf dataSource]
1215 removeBlacklistedURL:net::GURLWithNSURL(_deletedUrl)];
1216 };
1217 action.title = l10n_util::GetNSString(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE);
1218 action.accessibilityIdentifier = @"Undo";
1219
1220 TriggerHapticFeedbackForNotification(UINotificationFeedbackTypeSuccess);
1221 MDCSnackbarMessage* message = [MDCSnackbarMessage
1222 messageWithText:l10n_util::GetNSString(
1223 IDS_IOS_NEW_TAB_MOST_VISITED_ITEM_REMOVED)];
1224 message.action = action;
1225 message.category = @"MostVisitedUndo";
1226 [MDCSnackbarManager showMessage:message];
1227 }
1228
1229 - (void)onPromoLabelTapped {
1230 [self.dispatcher cancelOmniboxEdit];
1231 [_promoHeaderView setHidden:YES];
1232 [self.view setNeedsLayout];
1233 [self.dataSource promoTapped];
1234 }
1235
1236 // Returns the Y value to use for the scroll view's contentOffset when scrolling
1237 // the omnibox to the top of the screen.
1238 - (CGFloat)pinnedOffsetY {
1239 CGFloat headerHeight = [_headerView frame].size.height;
1240 CGFloat offsetY =
1241 headerHeight - ntp_header::kScrolledToTopOmniboxBottomMargin;
1242 if (!IsIPadIdiom())
1243 offsetY -= ntp_header::kToolbarHeight;
1244
1245 return offsetY;
1246 }
1247
1248 #pragma mark - NewTabPagePanelProtocol
1249
1250 - (void)reload {
1251 // Fetch the doodle after the view finishes laying out. Otherwise, tablet
1252 // may fetch the wrong sized doodle.
1253 if (_viewLoaded)
1254 [self.logoVendor fetchDoodle];
1255 [self updateLogoAndFakeboxDisplay];
1256 [self hideWhatsNewIfNecessary];
1257 }
1258
1259 - (void)wasShown {
1260 _isShowing = YES;
1261 [_headerView hideToolbarViewsForNewTabPage];
1262 }
1263
1264 - (void)wasHidden {
1265 _isShowing = NO;
1266 }
1267
1268 - (void)dismissModals {
1269 [_contextMenuCoordinator stop];
1270 }
1271
1272 - (void)dismissKeyboard {
1273 }
1274
1275 - (void)setScrollsToTop:(BOOL)enable {
1276 }
1277
1278 - (CGFloat)alphaForBottomShadow {
1279 // Get the frame of the bottommost cell in |self.view|'s coordinate system.
1280 NSInteger section = SectionWithMostVisited;
1281 // Account for the fact that the tableview may not yet contain
1282 // |numberOfNonEmptyTilesShown| tiles because it hasn't been updated yet.
1283 NSUInteger lastItemIndex =
1284 std::min([_mostVisitedView numberOfItemsInSection:SectionWithMostVisited],
1285 [self numberOfNonEmptyTilesShown]) -
1286 1;
1287 DCHECK(lastItemIndex >= 0);
1288 NSIndexPath* lastCellIndexPath =
1289 [NSIndexPath indexPathForItem:lastItemIndex inSection:section];
1290 UICollectionViewLayoutAttributes* attributes =
1291 [_mostVisitedView layoutAttributesForItemAtIndexPath:lastCellIndexPath];
1292 CGRect lastCellFrame = attributes.frame;
1293 CGRect cellFrameInSuperview =
1294 [_mostVisitedView convertRect:lastCellFrame toView:self.view];
1295
1296 // Calculate when the bottom of the cell passes through the bottom of
1297 // |self.view|.
1298 CGFloat maxY = CGRectGetMaxY(cellFrameInSuperview);
1299 CGFloat viewHeight = CGRectGetHeight(self.view.frame);
1300
1301 CGFloat pixelsBelowFrame = maxY - viewHeight;
1302 CGFloat alpha = pixelsBelowFrame / kNewTabPageDistanceToFadeShadow;
1303 alpha = MIN(MAX(alpha, 0), 1);
1304 return alpha;
1305 }
1306
1307 - (void)willUpdateSnapshot {
1308 [_overscrollActionsController clear];
1309 }
1310
1311 #pragma mark - LogoAnimationControllerOwnerOwner
1312
1313 - (id<LogoAnimationControllerOwner>)logoAnimationControllerOwner {
1314 return [self.logoVendor logoAnimationControllerOwner];
1315 }
1316
1317 #pragma mark - UIScrollViewDelegate Methods.
1318
1319 - (void)scrollViewDidScroll:(UIScrollView*)scrollView {
1320 [self.delegate updateNtpBarShadowForPanelController:self];
1321 [_overscrollActionsController scrollViewDidScroll:scrollView];
1322
1323 // Blur the omnibox when the scroll view is scrolled below the pinned offset.
1324 CGFloat pinnedOffsetY = [self pinnedOffsetY];
1325 if (_omniboxFocused && scrollView.dragging &&
1326 scrollView.contentOffset.y < pinnedOffsetY) {
1327 [self.dispatcher cancelOmniboxEdit];
1328 }
1329
1330 if (IsIPadIdiom()) {
1331 return;
1332 }
1333
1334 if (_animateHeader) {
1335 [self updateSearchField];
1336 }
1337 }
1338
1339 - (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView {
1340 [_overscrollActionsController scrollViewWillBeginDragging:scrollView];
1341 }
1342
1343 - (void)scrollViewDidEndDragging:(UIScrollView*)scrollView
1344 willDecelerate:(BOOL)decelerate {
1345 [_overscrollActionsController scrollViewDidEndDragging:scrollView
1346 willDecelerate:decelerate];
1347 }
1348
1349 - (void)scrollViewWillEndDragging:(UIScrollView*)scrollView
1350 withVelocity:(CGPoint)velocity
1351 targetContentOffset:(inout CGPoint*)targetContentOffset {
1352 [_overscrollActionsController scrollViewWillEndDragging:scrollView
1353 withVelocity:velocity
1354 targetContentOffset:targetContentOffset];
1355
1356 if (IsIPadIdiom() || _omniboxFocused)
1357 return;
1358
1359 CGFloat pinnedOffsetY = [self pinnedOffsetY];
1360 CGFloat offsetY = scrollView.contentOffset.y;
1361 CGFloat targetY = targetContentOffset->y;
1362 if (offsetY > 0 && offsetY < pinnedOffsetY) {
1363 // Omnibox is currently between middle and top of screen.
1364 if (velocity.y > 0) { // scrolling upwards
1365 if (targetY < pinnedOffsetY) {
1366 // Scroll the omnibox up to |pinnedOffsetY| if velocity is upwards but
1367 // scrolling will stop before reaching |pinnedOffsetY|.
1368 targetContentOffset->y = offsetY;
1369 [_mostVisitedView setContentOffset:CGPointMake(0, pinnedOffsetY)
1370 animated:YES];
1371 }
1372 _scrolledToTop = YES;
1373 } else { // scrolling downwards
1374 if (targetY > 0) {
1375 // Scroll the omnibox down to zero if velocity is downwards or 0 but
1376 // scrolling will stop before reaching 0.
1377 targetContentOffset->y = offsetY;
1378 [_mostVisitedView setContentOffset:CGPointZero animated:YES];
1379 }
1380 _scrolledToTop = NO;
1381 }
1382 } else if (offsetY > pinnedOffsetY &&
1383 targetContentOffset->y < pinnedOffsetY) {
1384 // Most visited cells are currently scrolled up past the omnibox but will
1385 // end the scroll below the omnibox. Stop the scroll at just below the
1386 // omnibox.
1387 targetContentOffset->y = offsetY;
1388 [_mostVisitedView setContentOffset:CGPointMake(0, pinnedOffsetY)
1389 animated:YES];
1390 _scrolledToTop = YES;
1391 } else if (offsetY >= pinnedOffsetY) {
1392 _scrolledToTop = YES;
1393 } else if (offsetY <= 0) {
1394 _scrolledToTop = NO;
1395 }
1396 }
1397
1398 #pragma mark - Most visited / Suggestions service wrapper methods.
1399
1400 - (NSUInteger)numberOfItems {
1401 NSUInteger numItems = [self.dataSource mostVisitedSize];
1402 NSUInteger maxItems = [self numberOfColumns] * kMaxNumMostVisitedFaviconRows;
1403 return MIN(maxItems, numItems);
1404 }
1405
1406 - (NSInteger)numberOfNonEmptyTilesShown {
1407 NSInteger numCells =
1408 MIN([self numberOfItems], self.maximumMostVisitedSitesShown);
1409 return MAX(numCells, [self numberOfColumns]);
1410 }
1411
1412 - (GURL)urlForIndex:(NSUInteger)index {
1413 return [self.dataSource mostVisitedAtIndex:index].url;
1414 }
1415
1416 #pragma mark - GoogleLandingViewController (ExposedForTesting) methods.
1417
1418 - (BOOL)scrolledToTop {
1419 return _scrolledToTop;
1420 }
1421
1422 - (BOOL)animateHeader {
1423 return _animateHeader;
1424 }
1425
1426 #pragma mark - OverscrollActionsControllerDelegate
1427
1428 - (void)overscrollActionsController:(OverscrollActionsController*)controller
1429 didTriggerAction:(OverscrollAction)action {
1430 switch (action) {
1431 case OverscrollAction::NEW_TAB: {
1432 base::scoped_nsobject<GenericChromeCommand> command(
1433 [[GenericChromeCommand alloc] initWithTag:IDC_NEW_TAB]);
1434 [[self view] chromeExecuteCommand:command];
1435 } break;
1436 case OverscrollAction::CLOSE_TAB: {
1437 base::scoped_nsobject<GenericChromeCommand> command(
1438 [[GenericChromeCommand alloc] initWithTag:IDC_CLOSE_TAB]);
1439 [[self view] chromeExecuteCommand:command];
1440 } break;
1441 case OverscrollAction::REFRESH:
1442 [self reload];
1443 break;
1444 case OverscrollAction::NONE:
1445 NOTREACHED();
1446 break;
1447 }
1448 }
1449
1450 - (BOOL)shouldAllowOverscrollActions {
1451 return YES;
1452 }
1453
1454 - (UIView*)toolbarSnapshotView {
1455 return [[_headerView toolBarView] snapshotViewAfterScreenUpdates:NO];
1456 }
1457
1458 - (UIView*)headerView {
1459 return self.view;
1460 }
1461
1462 - (CGFloat)overscrollActionsControllerHeaderInset:
1463 (OverscrollActionsController*)controller {
1464 return 0;
1465 }
1466
1467 - (CGFloat)overscrollHeaderHeight {
1468 return [_headerView toolBarView].bounds.size.height;
1469 }
1470
1471 #pragma mark - UIGestureRecognizerDelegate
1472
1473 - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
1474 shouldReceiveTouch:(UITouch*)touch {
1475 return [self nearestAncestorOfView:touch.view
1476 withClass:[MostVisitedCell class]] == nil;
1477 }
1478
1479 - (UIView*)nearestAncestorOfView:(UIView*)view withClass:(Class)aClass {
1480 if (!view) {
1481 return nil;
1482 }
1483 if ([view isKindOfClass:aClass]) {
1484 return view;
1485 }
1486 return [self nearestAncestorOfView:[view superview] withClass:aClass];
1487 }
1488
1489 #pragma mark - GoogleLandingConsumer
1490
1491 - (void)setLogoIsShowing:(BOOL)logoIsShowing {
1492 _logoIsShowing = logoIsShowing;
1493 [self updateLogoAndFakeboxDisplay];
1494 }
1495
1496 - (void)mostVisitedDataUpdated {
1497 [self reloadData];
1498 }
1499
1500 - (void)mostVisitedIconMadeAvailableAtIndex:(NSUInteger)index {
1501 if (index > [self numberOfItems])
1502 return;
1503
1504 NSIndexPath* indexPath =
1505 [NSIndexPath indexPathForRow:index inSection:SectionWithMostVisited];
1506 [_mostVisitedView reloadItemsAtIndexPaths:@[ indexPath ]];
1507 }
1508
1509 - (void)setTabCount:(int)tabCount {
1510 _tabCount = tabCount;
1511 [_headerView setToolbarTabCount:self.tabCount];
1512 }
1513
1514 - (void)setCanGoForward:(BOOL)canGoForward {
1515 _canGoForward = canGoForward;
1516 [_headerView setCanGoForward:self.canGoForward];
1517 [_headerView hideToolbarViewsForNewTabPage];
1518 }
1519
1520 - (void)setCanGoBack:(BOOL)canGoBack {
1521 _canGoBack = canGoBack;
1522 [_headerView setCanGoBack:self.canGoBack];
1523 [_headerView hideToolbarViewsForNewTabPage];
1524 }
1525 @end
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698