Commit 105f4e38 authored by Gauthier Ambard's avatar Gauthier Ambard Committed by Commit Bot

Remove old NTP code

This code is no longer used as ContentSuggestions is enabled.

Bug: 764720
Cq-Include-Trybots: master.tryserver.chromium.mac:ios-simulator-cronet;master.tryserver.chromium.mac:ios-simulator-full-configs
Change-Id: I1cf12abd965840c1f02c137fa4f542057842648d
Reviewed-on: https://chromium-review.googlesource.com/776653
Commit-Queue: Gauthier Ambard <gambard@chromium.org>
Reviewed-by: default avatarSylvain Defresne <sdefresne@chromium.org>
Cr-Commit-Position: refs/heads/master@{#517452}
parent 8c6f06b5
...@@ -131,11 +131,9 @@ class AppStateTest : public BlockCleanupTest { ...@@ -131,11 +131,9 @@ class AppStateTest : public BlockCleanupTest {
void SetUp() override { void SetUp() override {
BlockCleanupTest::SetUp(); BlockCleanupTest::SetUp();
TestChromeBrowserState::Builder test_cbs_builder; TestChromeBrowserState::Builder test_cbs_builder;
if (experimental_flags::IsSuggestionsUIEnabled()) { test_cbs_builder.AddTestingFactory(
test_cbs_builder.AddTestingFactory( IOSChromeContentSuggestionsServiceFactory::GetInstance(),
IOSChromeContentSuggestionsServiceFactory::GetInstance(), IOSChromeContentSuggestionsServiceFactory::GetDefaultFactory());
IOSChromeContentSuggestionsServiceFactory::GetDefaultFactory());
}
browser_state_ = test_cbs_builder.Build(); browser_state_ = test_cbs_builder.Build();
} }
......
...@@ -16,9 +16,6 @@ ...@@ -16,9 +16,6 @@
@implementation ContentSuggestionsSchedulerNotifications @implementation ContentSuggestionsSchedulerNotifications
+ (void)notifyColdStart:(ios::ChromeBrowserState*)browserState { + (void)notifyColdStart:(ios::ChromeBrowserState*)browserState {
if (!experimental_flags::IsSuggestionsUIEnabled())
return;
ntp_snippets::ContentSuggestionsService* contentSuggestionsService = ntp_snippets::ContentSuggestionsService* contentSuggestionsService =
IOSChromeContentSuggestionsServiceFactory::GetForBrowserState( IOSChromeContentSuggestionsServiceFactory::GetForBrowserState(
browserState); browserState);
...@@ -27,9 +24,6 @@ ...@@ -27,9 +24,6 @@
} }
+ (void)notifyForeground:(ios::ChromeBrowserState*)browserState { + (void)notifyForeground:(ios::ChromeBrowserState*)browserState {
if (!experimental_flags::IsSuggestionsUIEnabled())
return;
ntp_snippets::ContentSuggestionsService* contentSuggestionsService = ntp_snippets::ContentSuggestionsService* contentSuggestionsService =
IOSChromeContentSuggestionsServiceFactory::GetForBrowserState( IOSChromeContentSuggestionsServiceFactory::GetForBrowserState(
browserState); browserState);
......
...@@ -225,14 +225,6 @@ void AppendSwitchesFromExperimentalSettings(base::CommandLine* command_line) { ...@@ -225,14 +225,6 @@ void AppendSwitchesFromExperimentalSettings(base::CommandLine* command_line) {
web::BuildUserAgentFromProduct(product)); web::BuildUserAgentFromProduct(product));
} }
// Populate command line flag for Suggestions UI display.
NSString* enableSuggestions = [defaults stringForKey:@"EnableSuggestions"];
if ([enableSuggestions isEqualToString:@"Enabled"]) {
command_line->AppendSwitch(switches::kEnableSuggestionsUI);
} else if ([enableSuggestions isEqualToString:@"Disabled"]) {
command_line->AppendSwitch(switches::kDisableSuggestionsUI);
}
// Populate command line flag for fetching missing favicons for NTP tiles. // Populate command line flag for fetching missing favicons for NTP tiles.
NSString* enableMostLikelyFaviconsFromServer = NSString* enableMostLikelyFaviconsFromServer =
[defaults stringForKey:@"EnableNtpMostLikelyFaviconsFromServer"]; [defaults stringForKey:@"EnableNtpMostLikelyFaviconsFromServer"];
......
...@@ -24,9 +24,6 @@ const char kDisableIOSFeatures[] = "disable-features"; ...@@ -24,9 +24,6 @@ const char kDisableIOSFeatures[] = "disable-features";
const char kDisableIOSPasswordSuggestions[] = const char kDisableIOSPasswordSuggestions[] =
"disable-ios-password-suggestions"; "disable-ios-password-suggestions";
// Disables the Suggestions UI
const char kDisableSuggestionsUI[] = "disable-suggestions-ui";
// Disables the 3rd party keyboard omnibox workaround. // Disables the 3rd party keyboard omnibox workaround.
const char kDisableThirdPartyKeyboardWorkaround[] = const char kDisableThirdPartyKeyboardWorkaround[] =
"disable-third-party-keyboard-workaround"; "disable-third-party-keyboard-workaround";
...@@ -46,9 +43,6 @@ const char kEnableIOSHandoffToOtherDevices[] = ...@@ -46,9 +43,6 @@ const char kEnableIOSHandoffToOtherDevices[] =
// Enables the Spotlight actions. // Enables the Spotlight actions.
const char kEnableSpotlightActions[] = "enable-spotlight-actions"; const char kEnableSpotlightActions[] = "enable-spotlight-actions";
// Enables the Suggestions UI
const char kEnableSuggestionsUI[] = "enable-suggestions-ui";
// Enables the 3rd party keyboard omnibox workaround. // Enables the 3rd party keyboard omnibox workaround.
const char kEnableThirdPartyKeyboardWorkaround[] = const char kEnableThirdPartyKeyboardWorkaround[] =
"enable-third-party-keyboard-workaround"; "enable-third-party-keyboard-workaround";
......
...@@ -13,7 +13,6 @@ extern const char kDisableContextualSearch[]; ...@@ -13,7 +13,6 @@ extern const char kDisableContextualSearch[];
extern const char kDisableIOSFeatures[]; extern const char kDisableIOSFeatures[];
extern const char kDisableIOSPasswordSuggestions[]; extern const char kDisableIOSPasswordSuggestions[];
extern const char kDisableNTPFavicons[]; extern const char kDisableNTPFavicons[];
extern const char kDisableSuggestionsUI[];
extern const char kDisableThirdPartyKeyboardWorkaround[]; extern const char kDisableThirdPartyKeyboardWorkaround[];
extern const char kEnableContextualSearch[]; extern const char kEnableContextualSearch[];
...@@ -21,7 +20,6 @@ extern const char kEnableIOSFeatures[]; ...@@ -21,7 +20,6 @@ extern const char kEnableIOSFeatures[];
extern const char kEnableIOSHandoffToOtherDevices[]; extern const char kEnableIOSHandoffToOtherDevices[];
extern const char kEnableNTPFavicons[]; extern const char kEnableNTPFavicons[];
extern const char kEnableSpotlightActions[]; extern const char kEnableSpotlightActions[];
extern const char kEnableSuggestionsUI[];
extern const char kEnableThirdPartyKeyboardWorkaround[]; extern const char kEnableThirdPartyKeyboardWorkaround[];
extern const char kIOSForceVariationIds[]; extern const char kIOSForceVariationIds[];
......
...@@ -60,9 +60,6 @@ bool IsStartupCrashEnabled(); ...@@ -60,9 +60,6 @@ bool IsStartupCrashEnabled();
// Whether viewing and copying passwords is enabled. // Whether viewing and copying passwords is enabled.
bool IsViewCopyPasswordsEnabled(); bool IsViewCopyPasswordsEnabled();
// Whether the Suggestions UI is enabled.
bool IsSuggestionsUIEnabled();
// Whether a new version of FeedbackKit is the preferred feedback UI provider. // Whether a new version of FeedbackKit is the preferred feedback UI provider.
bool IsNewFeedbackKitEnabled(); bool IsNewFeedbackKitEnabled();
......
...@@ -40,9 +40,6 @@ NSString* const kWhatsNewPromoStatus = @"WhatsNewPromoStatus"; ...@@ -40,9 +40,6 @@ NSString* const kWhatsNewPromoStatus = @"WhatsNewPromoStatus";
NSString* const kClearApplicationGroup = @"ClearApplicationGroup"; NSString* const kClearApplicationGroup = @"ClearApplicationGroup";
const base::Feature kEnableThirdPartyKeyboardWorkaround{ const base::Feature kEnableThirdPartyKeyboardWorkaround{
"EnableThirdPartyKeyboardWorkaround", base::FEATURE_ENABLED_BY_DEFAULT}; "EnableThirdPartyKeyboardWorkaround", base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kIOSNTPSuggestions{"IOSNTPSuggestions",
base::FEATURE_ENABLED_BY_DEFAULT};
} // namespace } // namespace
namespace experimental_flags { namespace experimental_flags {
...@@ -144,19 +141,6 @@ bool IsViewCopyPasswordsEnabled() { ...@@ -144,19 +141,6 @@ bool IsViewCopyPasswordsEnabled() {
return ![viewCopyPasswordFlag isEqualToString:@"Disabled"]; return ![viewCopyPasswordFlag isEqualToString:@"Disabled"];
} }
bool IsSuggestionsUIEnabled() {
// Check if the experimental flag is forced on or off.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kEnableSuggestionsUI))
return true;
if (command_line->HasSwitch(switches::kDisableSuggestionsUI))
return false;
// Check if the Finch experiment is turned on.
return base::FeatureList::IsEnabled(kIOSNTPSuggestions);
}
bool IsNewFeedbackKitEnabled() { bool IsNewFeedbackKitEnabled() {
return [[NSUserDefaults standardUserDefaults] return [[NSUserDefaults standardUserDefaults]
boolForKey:@"NewFeedbackKitEnabled"]; boolForKey:@"NewFeedbackKitEnabled"];
......
...@@ -62,28 +62,6 @@ ...@@ -62,28 +62,6 @@
<key>DefaultValue</key> <key>DefaultValue</key>
<false/> <false/>
</dict> </dict>
<dict>
<key>Type</key>
<string>PSMultiValueSpecifier</string>
<key>Title</key>
<string>Enable Suggestions UI</string>
<key>Key</key>
<string>EnableSuggestions</string>
<key>DefaultValue</key>
<string></string>
<key>Values</key>
<array>
<string></string>
<string>Enabled</string>
<string>Disabled</string>
</array>
<key>Titles</key>
<array>
<string>Default</string>
<string>Enabled</string>
<string>Disabled</string>
</array>
</dict>
<dict> <dict>
<key>Type</key> <key>Type</key>
<string>PSMultiValueSpecifier</string> <string>PSMultiValueSpecifier</string>
......
...@@ -112,9 +112,7 @@ GREYElementInteraction* CellWithMatcher(id<GREYMatcher> matcher) { ...@@ -112,9 +112,7 @@ GREYElementInteraction* CellWithMatcher(id<GREYMatcher> matcher) {
#pragma mark - TestCase #pragma mark - TestCase
// Test case for the ContentSuggestion UI. // Test case for the ContentSuggestion UI.
@interface ContentSuggestionsTestCase : ChromeTestCase { @interface ContentSuggestionsTestCase : ChromeTestCase
std::unique_ptr<base::test::ScopedCommandLine> _scopedCommandLine;
}
// Current non-incognito browser state. // Current non-incognito browser state.
@property(nonatomic, assign, readonly) ios::ChromeBrowserState* browserState; @property(nonatomic, assign, readonly) ios::ChromeBrowserState* browserState;
...@@ -172,11 +170,6 @@ GREYElementInteraction* CellWithMatcher(id<GREYMatcher> matcher) { ...@@ -172,11 +170,6 @@ GREYElementInteraction* CellWithMatcher(id<GREYMatcher> matcher) {
} }
- (void)setUp { - (void)setUp {
// The command line is set up before [super setUp] in order to have the NTP
// opened with the command line already setup.
_scopedCommandLine = base::MakeUnique<base::test::ScopedCommandLine>();
base::CommandLine* commandLine = _scopedCommandLine->GetProcessCommandLine();
commandLine->AppendSwitch(switches::kEnableSuggestionsUI);
self.provider->FireCategoryStatusChanged(self.category, self.provider->FireCategoryStatusChanged(self.category,
CategoryStatus::AVAILABLE); CategoryStatus::AVAILABLE);
...@@ -196,7 +189,6 @@ GREYElementInteraction* CellWithMatcher(id<GREYMatcher> matcher) { ...@@ -196,7 +189,6 @@ GREYElementInteraction* CellWithMatcher(id<GREYMatcher> matcher) {
- (void)tearDown { - (void)tearDown {
self.provider->FireCategoryStatusChanged( self.provider->FireCategoryStatusChanged(
self.category, CategoryStatus::ALL_SUGGESTIONS_EXPLICITLY_DISABLED); self.category, CategoryStatus::ALL_SUGGESTIONS_EXPLICITLY_DISABLED);
_scopedCommandLine.reset();
chrome_test_util::ClearBrowsingHistory(); chrome_test_util::ClearBrowsingHistory();
[[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; [[GREYUIThreadExecutor sharedInstance] drainUntilIdle];
[super tearDown]; [super tearDown];
......
...@@ -69,9 +69,7 @@ std::unique_ptr<net::test_server::HttpResponse> StandardResponse( ...@@ -69,9 +69,7 @@ std::unique_ptr<net::test_server::HttpResponse> StandardResponse(
// Test case for the NTP home UI. More precisely, this tests the positions of // Test case for the NTP home UI. More precisely, this tests the positions of
// the elements after interacting with the device. // the elements after interacting with the device.
@interface NTPHomeTestCase : ChromeTestCase { @interface NTPHomeTestCase : ChromeTestCase
std::unique_ptr<base::test::ScopedCommandLine> _scopedCommandLine;
}
// Current non-incognito browser state. // Current non-incognito browser state.
@property(nonatomic, assign, readonly) ios::ChromeBrowserState* browserState; @property(nonatomic, assign, readonly) ios::ChromeBrowserState* browserState;
...@@ -136,11 +134,6 @@ std::unique_ptr<net::test_server::HttpResponse> StandardResponse( ...@@ -136,11 +134,6 @@ std::unique_ptr<net::test_server::HttpResponse> StandardResponse(
} }
- (void)setUp { - (void)setUp {
// The command line is set up before [super setUp] in order to have the NTP
// opened with the command line already setup.
_scopedCommandLine = base::MakeUnique<base::test::ScopedCommandLine>();
base::CommandLine* commandLine = _scopedCommandLine->GetProcessCommandLine();
commandLine->AppendSwitch(switches::kEnableSuggestionsUI);
self.provider->FireCategoryStatusChanged(self.category, self.provider->FireCategoryStatusChanged(self.category,
CategoryStatus::AVAILABLE); CategoryStatus::AVAILABLE);
...@@ -155,7 +148,6 @@ std::unique_ptr<net::test_server::HttpResponse> StandardResponse( ...@@ -155,7 +148,6 @@ std::unique_ptr<net::test_server::HttpResponse> StandardResponse(
self.category, CategoryStatus::ALL_SUGGESTIONS_EXPLICITLY_DISABLED); self.category, CategoryStatus::ALL_SUGGESTIONS_EXPLICITLY_DISABLED);
[EarlGrey rotateDeviceToOrientation:UIDeviceOrientationPortrait [EarlGrey rotateDeviceToOrientation:UIDeviceOrientationPortrait
errorOrNil:nil]; errorOrNil:nil];
_scopedCommandLine.reset();
[super tearDown]; [super tearDown];
} }
......
...@@ -84,18 +84,12 @@ source_set("ntp_internal") { ...@@ -84,18 +84,12 @@ source_set("ntp_internal") {
"google_landing_consumer.h", "google_landing_consumer.h",
"google_landing_mediator.h", "google_landing_mediator.h",
"google_landing_mediator.mm", "google_landing_mediator.mm",
"google_landing_view_controller.h",
"google_landing_view_controller.mm",
"incognito_view.h", "incognito_view.h",
"incognito_view.mm", "incognito_view.mm",
"incognito_view_controller.h", "incognito_view_controller.h",
"incognito_view_controller.mm", "incognito_view_controller.mm",
"metrics.h", "metrics.h",
"metrics.mm", "metrics.mm",
"most_visited_cell.h",
"most_visited_cell.mm",
"most_visited_layout.h",
"most_visited_layout.mm",
"new_tab_page_bar.h", "new_tab_page_bar.h",
"new_tab_page_bar.mm", "new_tab_page_bar.mm",
"new_tab_page_bar_button.h", "new_tab_page_bar_button.h",
...@@ -109,8 +103,6 @@ source_set("ntp_internal") { ...@@ -109,8 +103,6 @@ source_set("ntp_internal") {
"notification_promo_whats_new.mm", "notification_promo_whats_new.mm",
"ntp_tile_saver.h", "ntp_tile_saver.h",
"ntp_tile_saver.mm", "ntp_tile_saver.mm",
"whats_new_header_view.h",
"whats_new_header_view.mm",
] ]
public_deps = [ public_deps = [
":ntp_header", ":ntp_header",
...@@ -243,8 +235,6 @@ source_set("unit_tests") { ...@@ -243,8 +235,6 @@ source_set("unit_tests") {
testonly = true testonly = true
sources = [ sources = [
"centering_scrollview_unittest.mm", "centering_scrollview_unittest.mm",
"google_landing_view_controller_unittest.mm",
"most_visited_cell_unittest.mm",
"new_tab_page_bar_unittest.mm", "new_tab_page_bar_unittest.mm",
"new_tab_page_controller_unittest.mm", "new_tab_page_controller_unittest.mm",
"notification_promo_whats_new_unittest.mm", "notification_promo_whats_new_unittest.mm",
...@@ -301,7 +291,6 @@ source_set("eg_tests") { ...@@ -301,7 +291,6 @@ source_set("eg_tests") {
deps = [ deps = [
":modal_ntp", ":modal_ntp",
":ntp_controller", ":ntp_controller",
":ntp_internal",
"//components/strings", "//components/strings",
"//ios/chrome/app/strings", "//ios/chrome/app/strings",
"//ios/chrome/browser", "//ios/chrome/browser",
......
// 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.
#ifndef IOS_CHROME_BROWSER_UI_NTP_GOOGLE_LANDING_VIEW_CONTROLLER_H_
#define IOS_CHROME_BROWSER_UI_NTP_GOOGLE_LANDING_VIEW_CONTROLLER_H_
#import <UIKit/UIKit.h>
#include <memory>
#import "ios/chrome/browser/ui/ntp/google_landing_consumer.h"
#import "ios/chrome/browser/ui/ntp/new_tab_page_panel_protocol.h"
#import "ios/chrome/browser/ui/toolbar/toolbar_owner.h"
#import "ios/public/provider/chrome/browser/voice/logo_animation_controller.h"
@protocol ApplicationCommands;
@protocol BrowserCommands;
@protocol GoogleLandingDataSource;
@protocol OmniboxFocuser;
@protocol UrlLoader;
// Google centric new tab page.
@interface GoogleLandingViewController
: UIViewController<GoogleLandingConsumer,
LogoAnimationControllerOwnerOwner,
NewTabPagePanelProtocol,
ToolbarOwner>
@property(nonatomic, weak) id<GoogleLandingDataSource> dataSource;
@property(nonatomic, weak)
id<ApplicationCommands, BrowserCommands, OmniboxFocuser, UrlLoader>
dispatcher;
@end
#endif // IOS_CHROME_BROWSER_UI_NTP_GOOGLE_LANDING_VIEW_CONTROLLER_H_
// 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.
#include <memory>
#include "base/memory/ptr_util.h"
#include "components/search_engines/template_url_service.h"
#include "ios/chrome/browser/browser_state/test_chrome_browser_state.h"
#include "ios/chrome/browser/search_engines/template_url_service_factory.h"
#include "ios/chrome/browser/sessions/ios_chrome_tab_restore_service_factory.h"
#import "ios/chrome/browser/ui/ntp/google_landing_mediator.h"
#import "ios/chrome/browser/ui/ntp/google_landing_view_controller.h"
#include "ios/chrome/browser/web_state_list/fake_web_state_list_delegate.h"
#include "ios/chrome/browser/web_state_list/web_state_list.h"
#include "ios/chrome/test/block_cleanup_test.h"
#include "ios/chrome/test/ios_chrome_scoped_testing_local_state.h"
#include "ios/web/public/test/test_web_thread_bundle.h"
#include "ios/web/public/web_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest_mac.h"
#import "third_party/ocmock/OCMock/OCMock.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
namespace {
class GoogleLandingViewControllerTest : public BlockCleanupTest {
public:
GoogleLandingViewControllerTest() = default;
protected:
void SetUp() override {
DCHECK_CURRENTLY_ON(web::WebThread::UI);
TestChromeBrowserState::Builder test_cbs_builder;
test_cbs_builder.AddTestingFactory(
IOSChromeTabRestoreServiceFactory::GetInstance(),
IOSChromeTabRestoreServiceFactory::GetDefaultFactory());
test_cbs_builder.AddTestingFactory(
ios::TemplateURLServiceFactory::GetInstance(),
ios::TemplateURLServiceFactory::GetDefaultFactory());
chrome_browser_state_ = test_cbs_builder.Build();
BlockCleanupTest::SetUp();
// Set up tab restore service.
TemplateURLService* template_url_service =
ios::TemplateURLServiceFactory::GetForBrowserState(
chrome_browser_state_.get());
template_url_service->Load();
// Set up stub UrlLoader.
mockUrlLoader_ = [OCMockObject mockForProtocol:@protocol(UrlLoader)];
controller_ = [[GoogleLandingViewController alloc] init];
webStateList_ = base::MakeUnique<WebStateList>(&webStateListDelegate_);
mediator_ = [[GoogleLandingMediator alloc]
initWithBrowserState:chrome_browser_state_.get()
webStateList:webStateList_.get()];
mediator_.consumer = controller_;
[mediator_ setUp];
};
void TearDown() override { [mediator_ shutdown]; }
web::TestWebThreadBundle test_web_thread_bundle_;
IOSChromeScopedTestingLocalState local_state_;
std::unique_ptr<TestChromeBrowserState> chrome_browser_state_;
FakeWebStateListDelegate webStateListDelegate_;
std::unique_ptr<WebStateList> webStateList_;
OCMockObject* mockUrlLoader_;
GoogleLandingMediator* mediator_;
GoogleLandingViewController* controller_;
};
TEST_F(GoogleLandingViewControllerTest, TestConstructorDestructor) {
EXPECT_TRUE(controller_);
}
} // anonymous namespace
// Copyright 2016 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.
#ifndef IOS_CHROME_BROWSER_UI_NTP_MOST_VISITED_CELL_H_
#define IOS_CHROME_BROWSER_UI_NTP_MOST_VISITED_CELL_H_
#import <UIKit/UIKit.h>
#import "ios/chrome/browser/ui/favicon/favicon_attributes.h"
#include "url/gurl.h"
@protocol GoogleLandingDataSource;
// Cell showing each most visited image, favicon and title.
@interface MostVisitedCell : UICollectionViewCell
// URL of the top site.
@property(nonatomic, assign) GURL URL;
// Type of tile (icon, scrabble tile, default)
@property(nonatomic, readonly) FaviconAttributes* faviconAttributes;
// Set text of top site.
- (void)setText:(NSString*)text;
// Show the placeholder image in the cell instead of a most visited site.
- (void)showPlaceholder;
// Removes the placeholder image from the cell. Used to make a cell appear
// empty/invisible.
- (void)removePlaceholderImage;
// Setup the display state of the cell.
- (void)setupWithURL:(GURL)URL
title:(NSString*)title
dataSource:(id<GoogleLandingDataSource>)dataSource;
// Preferred maximum cell size.
+ (CGSize)maximumSize;
@end
#endif // IOS_CHROME_BROWSER_UI_NTP_MOST_VISITED_CELL_H_
// Copyright 2016 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 "ios/chrome/browser/ui/ntp/most_visited_cell.h"
#include <memory>
#include "base/mac/bind_objc_block.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/sys_string_conversions.h"
#include "components/favicon/core/fallback_url_util.h"
#import "ios/chrome/browser/ui/favicon/favicon_attributes.h"
#import "ios/chrome/browser/ui/ntp/google_landing_data_source.h"
#import "ios/chrome/browser/ui/util/constraints_ui_util.h"
#import "ios/third_party/material_components_ios/src/components/Palettes/src/MaterialPalettes.h"
#import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
const CGFloat kFaviconSize = 48;
const CGFloat kImageViewBackgroundColor = 0.941;
const CGFloat kImageViewCornerRadius = 3;
const NSInteger kLabelNumLines = 2;
const CGFloat kLabelTextColor = 0.314;
const CGFloat kMaximumWidth = 73;
const CGFloat kMaximumHeight = 100;
@interface MostVisitedCell () {
// Backs property with the same name.
GURL _URL;
// Weak reference to the relevant GoogleLandingDataSource.
__weak id<GoogleLandingDataSource> _dataSource;
// Backs property with the same name.
FaviconAttributes* _faviconAttributes;
UILabel* _label;
UILabel* _noIconLabel;
UIImageView* _imageView;
}
- (void)setFaviconAttributes:(FaviconAttributes*)attributes;
@end
@implementation MostVisitedCell
@synthesize URL = _URL;
@synthesize faviconAttributes = _faviconAttributes;
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (!self) {
return nil;
}
_label = [[UILabel alloc] initWithFrame:CGRectZero];
[_label setTextColor:[UIColor colorWithWhite:kLabelTextColor alpha:1.0]];
[_label setBackgroundColor:[UIColor clearColor]];
[_label setFont:[MDCTypography captionFont]];
[_label setTextAlignment:NSTextAlignmentCenter];
CGSize maxSize = [self.class maximumSize];
[_label setPreferredMaxLayoutWidth:maxSize.width];
[_label setNumberOfLines:kLabelNumLines];
_noIconLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[_noIconLabel setBackgroundColor:[UIColor clearColor]];
[_noIconLabel setFont:[MDCTypography headlineFont]];
[_noIconLabel setTextAlignment:NSTextAlignmentCenter];
_imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
[_imageView layer].cornerRadius = kImageViewCornerRadius;
[_imageView setClipsToBounds:YES];
[self addSubview:_imageView];
[self addSubview:_label];
[self addSubview:_noIconLabel];
[_noIconLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[_imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
[_label setTranslatesAutoresizingMaskIntoConstraints:NO];
NSDictionary* views =
@{ @"label" : _label,
@"image" : _imageView,
@"noIcon" : _noIconLabel };
NSArray* constraints = @[
@"V:|[image(==iconSize)]-10-[label]", @"V:[noIcon(==iconSize)]",
@"H:[image(==iconSize)]", @"H:|[label]|", @"H:|[noIcon]|"
];
ApplyVisualConstraintsWithMetrics(constraints, views,
@{ @"iconSize" : @(kFaviconSize) });
AddSameCenterXConstraint(self, _imageView);
AddSameCenterXConstraint(self, _noIconLabel);
[self prepareForReuse];
return self;
}
- (void)prepareForReuse {
[super prepareForReuse];
[self setFaviconAttributes:nil];
[self setText:nil];
// TODO(crbug.com/495600): -stepToVerifyAccessibilityOnCurrentScreen does not
// honor -setIsAccessibilityElement and setAccessibilityElementsHidden for
// UICollectionViewCell's, so setting the label to a single space string to
// pass tests. This string will not be read by screen readers.
[_label setText:@" "];
[self setURL:GURL()];
[_imageView
setBackgroundColor:[UIColor colorWithWhite:kImageViewBackgroundColor
alpha:1.0]];
[_noIconLabel setText:nil];
}
#pragma mark - Public Setters
- (void)setText:(NSString*)text {
[_label setText:text];
[self setAccessibilityLabel:text];
[self setIsAccessibilityElement:text != nil];
[self setAccessibilityElementsHidden:text == nil];
[self setUserInteractionEnabled:YES];
}
- (void)showPlaceholder {
[_imageView setBackgroundColor:[[MDCPalette greyPalette] tint50]];
}
- (void)setupWithURL:(GURL)URL
title:(NSString*)title
dataSource:(id<GoogleLandingDataSource>)dataSource {
_dataSource = dataSource;
[self setFaviconAttributes:nil];
[self setText:title];
[self setURL:URL];
__weak MostVisitedCell* weakSelf = self;
void (^faviconAttributesBlock)(FaviconAttributes*) =
^(FaviconAttributes* attributes) {
if (URL == [weakSelf URL]) { // Tile has not been reused.
[self setFaviconAttributes:attributes];
}
};
[_dataSource getFaviconForPageURL:URL
size:kFaviconSize
useCache:YES
callback:faviconAttributesBlock];
}
- (void)removePlaceholderImage {
[_imageView setBackgroundColor:nil];
[self setUserInteractionEnabled:NO];
}
#pragma mark - Class methods
+ (CGSize)maximumSize {
return CGSizeMake(kMaximumWidth, kMaximumHeight);
}
#pragma mark - Private methods
- (void)setFaviconAttributes:(FaviconAttributes*)attributes {
_faviconAttributes = attributes;
if (!attributes) {
[_imageView setImage:nil];
[_imageView setBackgroundColor:nil];
[_noIconLabel setText:nil];
[_noIconLabel setTextColor:nil];
} else if (!attributes.faviconImage) {
[_imageView setImage:nil];
[_imageView setBackgroundColor:attributes.backgroundColor];
[_noIconLabel setText:attributes.monogramString];
[_noIconLabel setTextColor:attributes.textColor];
} else {
[_imageView setImage:attributes.faviconImage];
[_imageView setBackgroundColor:nil];
[_noIconLabel setText:nil];
[_noIconLabel setTextColor:nil];
}
}
@end
// Copyright 2016 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 "ios/chrome/browser/ui/ntp/most_visited_cell.h"
#include "testing/gtest_mac.h"
#include "testing/platform_test.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
static NSString* title = @"Most Visited Cell Title";
const GURL URL = GURL("http://example.com");
// Fixture to test MostVisitedCell.
class MostVisitedCellTest : public PlatformTest {
protected:
MostVisitedCell* cell_;
};
TEST_F(MostVisitedCellTest, TestConstructor) {
CGRect rect = CGRectMake(0, 0, 100, 100);
cell_ = [[MostVisitedCell alloc] initWithFrame:rect];
[cell_ setURL:URL];
EXPECT_TRUE(cell_);
UIGraphicsBeginImageContext([cell_ bounds].size);
[cell_ drawRect:[cell_ bounds]];
UIGraphicsEndImageContext();
EXPECT_EQ(URL, [cell_ URL]);
}
TEST_F(MostVisitedCellTest, ValidateTitle) {
CGRect rect = CGRectMake(0, 0, 100, 100);
cell_ = [[MostVisitedCell alloc] initWithFrame:rect];
[cell_ setText:title];
EXPECT_NSEQ(title, [cell_ accessibilityLabel]);
}
// Copyright 2014 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.
#ifndef IOS_CHROME_BROWSER_UI_NTP_MOST_VISITED_LAYOUT_H_
#define IOS_CHROME_BROWSER_UI_NTP_MOST_VISITED_LAYOUT_H_
#import <UIKit/UIKit.h>
@interface MostVisitedLayout : UICollectionViewFlowLayout
@end
#endif // IOS_CHROME_BROWSER_UI_NTP_MOST_VISITED_LAYOUT_H_
// Copyright 2014 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 "ios/chrome/browser/ui/ntp/most_visited_layout.h"
#import "ios/chrome/browser/ui/ntp/new_tab_page_header_constants.h"
#include "ios/chrome/browser/ui/ui_util.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
@implementation MostVisitedLayout
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray* layoutAttributes =
[[super layoutAttributesForElementsInRect:rect] mutableCopy];
UICollectionViewLayoutAttributes* fixedHeaderAttributes = nil;
NSIndexPath* fixedHeaderIndexPath =
[NSIndexPath indexPathForItem:0 inSection:0];
for (UICollectionViewLayoutAttributes* attributes in layoutAttributes) {
if ([attributes.representedElementKind
isEqualToString:UICollectionElementKindSectionHeader] &&
attributes.indexPath.section == fixedHeaderIndexPath.section) {
fixedHeaderAttributes = [self
layoutAttributesForSupplementaryViewOfKind:
UICollectionElementKindSectionHeader
atIndexPath:fixedHeaderIndexPath];
attributes.zIndex = fixedHeaderAttributes.zIndex;
attributes.frame = fixedHeaderAttributes.frame;
}
}
// The fixed header's attributes are not updated if the header's default frame
// is far enough away from |rect|, which can occur when the NTP is scrolled
// up.
if (!fixedHeaderAttributes && !IsIPadIdiom()) {
UICollectionViewLayoutAttributes* fixedHeaderAttributes =
[self layoutAttributesForSupplementaryViewOfKind:
UICollectionElementKindSectionHeader
atIndexPath:fixedHeaderIndexPath];
[layoutAttributes addObject:fixedHeaderAttributes];
}
return layoutAttributes;
}
- (UICollectionViewLayoutAttributes*)
layoutAttributesForSupplementaryViewOfKind:(NSString*)kind
atIndexPath:(NSIndexPath*)indexPath {
UICollectionViewLayoutAttributes* attributes =
[super layoutAttributesForSupplementaryViewOfKind:kind
atIndexPath:indexPath];
if ([kind isEqualToString:UICollectionElementKindSectionHeader] &&
indexPath.section == 0) {
UICollectionView* collectionView = self.collectionView;
CGPoint contentOffset = collectionView.contentOffset;
CGFloat headerHeight = CGRectGetHeight(attributes.frame);
CGPoint origin = attributes.frame.origin;
// Keep the header in front of all other views.
attributes.zIndex = 1000;
// Prevent the fake omnibox from scrolling up off of the screen.
CGFloat minY = headerHeight - ntp_header::kMinHeaderHeight;
if (contentOffset.y > minY)
origin.y = contentOffset.y - minY;
attributes.frame = {origin, attributes.frame.size};
}
return attributes;
}
- (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:
(NSIndexPath*)indexPath {
UICollectionViewLayoutAttributes* currentItemAttributes =
[super layoutAttributesForItemAtIndexPath:indexPath];
return currentItemAttributes;
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBound {
return YES;
}
- (CGSize)collectionViewContentSize {
CGFloat collectionViewHeight = self.collectionView.bounds.size.height;
CGFloat headerHeight = [self headerReferenceSize].height;
// The minimum height for the collection view content should be the height of
// the header plus the height of the collection view minus the height of the
// NTP bottom bar. This allows the Most Visited cells to be scrolled up to the
// top of the screen.
CGFloat minimumHeight = collectionViewHeight + headerHeight -
ntp_header::kScrolledToTopOmniboxBottomMargin;
if (!IsIPadIdiom())
minimumHeight -= ntp_header::kToolbarHeight;
CGSize contentSize = [super collectionViewContentSize];
if (contentSize.height < minimumHeight) {
contentSize.height = minimumHeight;
}
return contentSize;
}
@end
...@@ -7,8 +7,6 @@ ...@@ -7,8 +7,6 @@
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#import "ios/chrome/browser/ui/ntp/google_landing_view_controller.h"
@class NewTabPageBarItem; @class NewTabPageBarItem;
@protocol NewTabPageBarDelegate @protocol NewTabPageBarDelegate
......
...@@ -114,7 +114,6 @@ std::string FragmentFromIdentifier(ntp_home::PanelIdentifier panel); ...@@ -114,7 +114,6 @@ std::string FragmentFromIdentifier(ntp_home::PanelIdentifier panel);
@interface NewTabPageController (TestSupport) @interface NewTabPageController (TestSupport)
- (id<NewTabPagePanelProtocol>)currentController; - (id<NewTabPagePanelProtocol>)currentController;
- (BookmarkHomeTabletNTPController*)bookmarkController; - (BookmarkHomeTabletNTPController*)bookmarkController;
- (GoogleLandingViewController*)googleLandingController;
- (id<NewTabPagePanelProtocol>)incognitoController; - (id<NewTabPagePanelProtocol>)incognitoController;
@end @end
......
...@@ -28,7 +28,6 @@ ...@@ -28,7 +28,6 @@
#import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/commands/browser_commands.h"
#import "ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h"
#import "ios/chrome/browser/ui/ntp/google_landing_mediator.h" #import "ios/chrome/browser/ui/ntp/google_landing_mediator.h"
#import "ios/chrome/browser/ui/ntp/google_landing_view_controller.h"
#import "ios/chrome/browser/ui/ntp/incognito_view_controller.h" #import "ios/chrome/browser/ui/ntp/incognito_view_controller.h"
#import "ios/chrome/browser/ui/ntp/modal_ntp.h" #import "ios/chrome/browser/ui/ntp/modal_ntp.h"
#import "ios/chrome/browser/ui/ntp/new_tab_page_bar_item.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_bar_item.h"
...@@ -118,13 +117,10 @@ enum { ...@@ -118,13 +117,10 @@ enum {
__weak id<UrlLoader> _loader; __weak id<UrlLoader> _loader;
__weak id<NewTabPageControllerObserver> _newTabPageObserver; __weak id<NewTabPageControllerObserver> _newTabPageObserver;
BookmarkHomeTabletNTPController* _bookmarkController; BookmarkHomeTabletNTPController* _bookmarkController;
GoogleLandingViewController* _googleLandingController;
IncognitoViewController* _incognitoController; IncognitoViewController* _incognitoController;
// The currently visible controller, one of the above. // The currently visible controller, one of the above.
__weak id<NewTabPagePanelProtocol> _currentController; __weak id<NewTabPagePanelProtocol> _currentController;
GoogleLandingMediator* _googleLandingMediator;
RecentTabsTableCoordinator* _openTabsCoordinator; RecentTabsTableCoordinator* _openTabsCoordinator;
// Has the scrollView been initialized. // Has the scrollView been initialized.
BOOL _scrollInitialized; BOOL _scrollInitialized;
...@@ -257,9 +253,7 @@ enum { ...@@ -257,9 +253,7 @@ enum {
bool isIncognito = _browserState->IsOffTheRecord(); bool isIncognito = _browserState->IsOffTheRecord();
NSString* incognito = l10n_util::GetNSString(IDS_IOS_NEW_TAB_INCOGNITO); NSString* incognito = l10n_util::GetNSString(IDS_IOS_NEW_TAB_INCOGNITO);
NSString* home = experimental_flags::IsSuggestionsUIEnabled() NSString* home = l10n_util::GetNSString(IDS_IOS_NEW_TAB_HOME);
? l10n_util::GetNSString(IDS_IOS_NEW_TAB_HOME)
: l10n_util::GetNSString(IDS_IOS_NEW_TAB_MOST_VISITED);
NSString* bookmarks = NSString* bookmarks =
l10n_util::GetNSString(IDS_IOS_NEW_TAB_BOOKMARKS_PAGE_TITLE_MOBILE); l10n_util::GetNSString(IDS_IOS_NEW_TAB_BOOKMARKS_PAGE_TITLE_MOBILE);
NSString* openTabs = l10n_util::GetNSString(IDS_IOS_NEW_TAB_RECENT_TABS); NSString* openTabs = l10n_util::GetNSString(IDS_IOS_NEW_TAB_RECENT_TABS);
...@@ -332,12 +326,9 @@ enum { ...@@ -332,12 +326,9 @@ enum {
// delegate. // delegate.
self.view.scrollView.delegate = nil; self.view.scrollView.delegate = nil;
[_googleLandingMediator shutdown];
// This is not an ideal place to put view controller contaimnent, rather a // This is not an ideal place to put view controller contaimnent, rather a
// //web -wasDismissed method on CRWNativeContent would be more accurate. If // //web -wasDismissed method on CRWNativeContent would be more accurate. If
// CRWNativeContent leaks, this will not be called. // CRWNativeContent leaks, this will not be called.
[_googleLandingController removeFromParentViewController];
[_bookmarkController removeFromParentViewController]; [_bookmarkController removeFromParentViewController];
[_incognitoController removeFromParentViewController]; [_incognitoController removeFromParentViewController];
[[self.contentSuggestionsCoordinator viewController] [[self.contentSuggestionsCoordinator viewController]
...@@ -359,7 +350,6 @@ enum { ...@@ -359,7 +350,6 @@ enum {
// This methods is called by //web immediately before |self|'s view is removed // This methods is called by //web immediately before |self|'s view is removed
// from the view hierarchy, making it an ideal spot to intiate view controller // from the view hierarchy, making it an ideal spot to intiate view controller
// containment methods. // containment methods.
[_googleLandingController willMoveToParentViewController:nil];
[_bookmarkController willMoveToParentViewController:nil]; [_bookmarkController willMoveToParentViewController:nil];
[[_openTabsCoordinator viewController] willMoveToParentViewController:nil]; [[_openTabsCoordinator viewController] willMoveToParentViewController:nil];
[[self.contentSuggestionsCoordinator viewController] [[self.contentSuggestionsCoordinator viewController]
...@@ -586,7 +576,6 @@ enum { ...@@ -586,7 +576,6 @@ enum {
panelController = _bookmarkController; panelController = _bookmarkController;
[_bookmarkController setDelegate:self]; [_bookmarkController setDelegate:self];
} else if (item.identifier == ntp_home::HOME_PANEL) { } else if (item.identifier == ntp_home::HOME_PANEL) {
if (experimental_flags::IsSuggestionsUIEnabled()) {
if (!self.contentSuggestionsCoordinator) { if (!self.contentSuggestionsCoordinator) {
self.contentSuggestionsCoordinator = self.contentSuggestionsCoordinator =
[[ContentSuggestionsCoordinator alloc] [[ContentSuggestionsCoordinator alloc]
...@@ -602,23 +591,6 @@ enum { ...@@ -602,23 +591,6 @@ enum {
} }
panelController = [self.contentSuggestionsCoordinator viewController]; panelController = [self.contentSuggestionsCoordinator viewController];
self.homePanel = self.contentSuggestionsCoordinator; self.homePanel = self.contentSuggestionsCoordinator;
} else {
if (!_googleLandingController) {
_googleLandingController = [[GoogleLandingViewController alloc] init];
[_googleLandingController setDispatcher:self.dispatcher];
_googleLandingMediator = [[GoogleLandingMediator alloc]
initWithBrowserState:_browserState
webStateList:[_tabModel webStateList]];
_googleLandingMediator.consumer = _googleLandingController;
_googleLandingMediator.dispatcher = self.dispatcher;
[_googleLandingMediator setUp];
[_googleLandingController setDataSource:_googleLandingMediator];
self.headerController = _googleLandingController;
}
panelController = _googleLandingController;
self.homePanel = _googleLandingController;
}
[self.homePanel setDelegate:self]; [self.homePanel setDelegate:self];
} else if (item.identifier == ntp_home::RECENT_TABS_PANEL) { } else if (item.identifier == ntp_home::RECENT_TABS_PANEL) {
if (!_openTabsCoordinator) { if (!_openTabsCoordinator) {
...@@ -820,10 +792,6 @@ enum { ...@@ -820,10 +792,6 @@ enum {
return _bookmarkController; return _bookmarkController;
} }
- (GoogleLandingViewController*)googleLandingController {
return _googleLandingController;
}
- (id<NewTabPagePanelProtocol>)incognitoController { - (id<NewTabPagePanelProtocol>)incognitoController {
return _incognitoController; return _incognitoController;
} }
......
...@@ -29,11 +29,6 @@ ...@@ -29,11 +29,6 @@
#error "This file requires ARC support." #error "This file requires ARC support."
#endif #endif
@interface GoogleLandingViewController (ExposedForTesting)
- (BOOL)scrolledToTop;
- (BOOL)animateHeader;
@end
namespace { namespace {
void DismissNewTabPagePanel() { void DismissNewTabPagePanel() {
...@@ -77,48 +72,13 @@ void SelectNewTabPagePanel(ntp_home::PanelIdentifier panel_type) { ...@@ -77,48 +72,13 @@ void SelectNewTabPagePanel(ntp_home::PanelIdentifier panel_type) {
[[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; [[GREYUIThreadExecutor sharedInstance] drainUntilIdle];
} }
void AssertNTPScrolledToTop(bool scrolledToTop) {
[[GREYUIThreadExecutor sharedInstance] drainUntilIdle];
NewTabPageController* ntp_controller =
chrome_test_util::GetCurrentNewTabPageController();
GoogleLandingViewController* google_landing_view_controller =
[ntp_controller googleLandingController];
[[GREYCondition
conditionWithName:@"Wait for end of animation."
block:^BOOL {
return ![google_landing_view_controller animateHeader];
}] waitWithTimeout:testing::kWaitForUIElementTimeout];
GREYAssertTrue(
[google_landing_view_controller scrolledToTop] == scrolledToTop,
@"scrolledToTop_ does not match expected value");
}
} // namespace } // namespace
@interface UIWindow (Hidden) @interface NewTabPageTestCase : ChromeTestCase
- (UIResponder*)firstResponder;
@end
@interface NewTabPageTestCase : ChromeTestCase {
std::unique_ptr<base::test::ScopedCommandLine> _scopedCommandLine;
}
@end @end
@implementation NewTabPageTestCase @implementation NewTabPageTestCase
- (void)setUp {
// The command line is set up before [super setUp] in order to have the NTP
// opened with the command line already setup.
_scopedCommandLine = std::make_unique<base::test::ScopedCommandLine>();
base::CommandLine* commandLine = _scopedCommandLine->GetProcessCommandLine();
commandLine->AppendSwitch(switches::kDisableSuggestionsUI);
[super setUp];
}
- (void)tearDown {
_scopedCommandLine.reset();
}
#pragma mark - Tests #pragma mark - Tests
// Tests that all items are accessible on the most visited page. // Tests that all items are accessible on the most visited page.
...@@ -154,183 +114,4 @@ void AssertNTPScrolledToTop(bool scrolledToTop) { ...@@ -154,183 +114,4 @@ void AssertNTPScrolledToTop(bool scrolledToTop) {
GREYAssert(chrome_test_util::CloseAllIncognitoTabs(), @"Tabs did not close"); GREYAssert(chrome_test_util::CloseAllIncognitoTabs(), @"Tabs did not close");
} }
// Tests rotating the device when the NTP's omnibox is pinned to the top of the
// screen.
- (void)testRotation {
// TODO(crbug.com/652465): Enable the test for iPad when rotation bug is
// fixed.
if (IsIPadIdiom()) {
EARL_GREY_TEST_DISABLED(@"Disabled for iPad due to device rotation bug.");
}
NSString* ntpOmniboxLabel = l10n_util::GetNSString(IDS_OMNIBOX_EMPTY_HINT);
NSString* focusedOmniboxLabel = l10n_util::GetNSString(IDS_ACCNAME_LOCATION);
SelectNewTabPagePanel(ntp_home::HOME_PANEL);
AssertNTPScrolledToTop(NO);
if (IsIPadIdiom()) {
// Tap in omnibox to scroll it to the top of the screen.
id<GREYMatcher> matcher = grey_accessibilityLabel(ntpOmniboxLabel);
[[EarlGrey selectElementWithMatcher:matcher] performAction:grey_tap()];
} else {
// Swipe up the NTP. The omnibox should be pinned at the top of the screen.
id<GREYMatcher> matcher = grey_accessibilityID(@"Google Landing");
[[EarlGrey selectElementWithMatcher:matcher]
performAction:grey_swipeFastInDirection(kGREYDirectionUp)];
}
AssertNTPScrolledToTop(YES);
// Restore the orientation of the device to portrait in Teardown.
[self setTearDownHandler:^{
if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
[EarlGrey rotateDeviceToOrientation:UIDeviceOrientationPortrait
errorOrNil:nil];
}
}];
// Rotate to landscape and check that the device and the status bar are
// rotated properly and the omnibox is still scrolled up.
[EarlGrey rotateDeviceToOrientation:UIDeviceOrientationLandscapeLeft
errorOrNil:nil];
GREYAssertTrue(
[UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft,
@"Device orientation should now be left landscape");
GREYAssertTrue([[UIApplication sharedApplication] statusBarOrientation] ==
UIInterfaceOrientationLandscapeRight,
@"Status bar orientation should now be right landscape");
AssertNTPScrolledToTop(YES);
// Tap in the omnibox.
NSString* omniboxLabel =
IsIPadIdiom() ? focusedOmniboxLabel : ntpOmniboxLabel;
id<GREYMatcher> matcher = grey_allOf(grey_accessibilityLabel(omniboxLabel),
grey_minimumVisiblePercent(0.2), nil);
[[EarlGrey selectElementWithMatcher:matcher] performAction:grey_tap()];
// Rotate to portrait and check that the device and the status bar are rotated
// properly and the omnibox is still scrolled up.
[EarlGrey rotateDeviceToOrientation:UIDeviceOrientationPortrait
errorOrNil:nil];
GREYAssertTrue(
[UIDevice currentDevice].orientation == UIDeviceOrientationPortrait,
@"Device orientation should now be portrait");
GREYAssertTrue([[UIApplication sharedApplication] statusBarOrientation] ==
UIInterfaceOrientationPortrait,
@"Status bar orientation should now be portrait");
AssertNTPScrolledToTop(YES);
// Check that omnibox is still focused.
UIResponder* firstResponder =
[[UIApplication sharedApplication].keyWindow firstResponder];
BOOL equal =
[[firstResponder accessibilityLabel] isEqualToString:focusedOmniboxLabel];
GREYAssertTrue(
equal,
@"Expected accessibility label for first responder to be '%@', got '%@'",
focusedOmniboxLabel, [firstResponder accessibilityLabel]);
}
// Tests focusing and defocusing the NTP's omnibox.
- (void)testOmnibox {
// TODO(crbug.com/782551): Rewrite this test for the new Bookmarks UI.
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndDisableFeature(kBookmarkNewGeneration);
// TODO(crbug.com/782551): Remove the following when this test is rewritten.
// Re-open tabs so that scoped_feature_list will take effect on the NTP.
chrome_test_util::CloseAllTabs();
chrome_test_util::OpenNewTab();
// Empty the pasteboard: if it contains a link the Google Landing will not be
// interactable.
[UIPasteboard generalPasteboard].string = @"";
NSString* omniboxLabel = l10n_util::GetNSString(IDS_OMNIBOX_EMPTY_HINT);
NSString* cancelLabel = l10n_util::GetNSString(IDS_CANCEL);
if (IsIPadIdiom()) {
SelectNewTabPagePanel(ntp_home::HOME_PANEL);
}
// Check that the NTP is in its normal state.
id<GREYMatcher> omnibox_matcher =
grey_allOf(grey_accessibilityLabel(omniboxLabel),
grey_minimumVisiblePercent(0.2), nil);
[[EarlGrey selectElementWithMatcher:omnibox_matcher]
assertWithMatcher:grey_notNil()];
AssertNTPScrolledToTop(NO);
// Tap in omnibox to scroll it to the top of the screen.
[[EarlGrey selectElementWithMatcher:omnibox_matcher]
performAction:grey_tap()];
// Check that the omnibox is scrolled to the top of the screen and its cancel
// button is visible.
AssertNTPScrolledToTop(YES);
if (!IsIPadIdiom()) {
[[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(cancelLabel)]
assertWithMatcher:grey_notNil()];
}
// Swipe down in the NTP to return to the normal state.
id<GREYMatcher> landing_matcher = grey_accessibilityID(@"Google Landing");
[[EarlGrey selectElementWithMatcher:landing_matcher]
performAction:grey_swipeFastInDirection(kGREYDirectionDown)];
AssertNTPScrolledToTop(NO);
if (!IsIPadIdiom()) {
[[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(cancelLabel)]
assertWithMatcher:grey_notVisible()];
}
// Tap in omnibox and check that it's scrolled to the top of the screen and
// its cancel button is visible.
[[EarlGrey selectElementWithMatcher:omnibox_matcher]
performAction:grey_tap()];
AssertNTPScrolledToTop(YES);
if (!IsIPadIdiom()) {
[[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(cancelLabel)]
assertWithMatcher:grey_sufficientlyVisible()];
}
// Tap below the omnibox to cancel editing and return to the normal state.
[[EarlGrey selectElementWithMatcher:landing_matcher]
performAction:grey_tap()];
AssertNTPScrolledToTop(NO);
if (!IsIPadIdiom()) {
[[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(cancelLabel)]
assertWithMatcher:grey_notVisible()];
}
}
// Tests that the NTP's toolbar is not visible when the NTP is scrolled up.
- (void)testScrollToolbar {
if (IsIPadIdiom()) {
EARL_GREY_TEST_SKIPPED(@"Skipped for iPad (no hidden toolbar in tablet)");
}
NSString* toolsMenuLabel = l10n_util::GetNSString(IDS_IOS_TOOLBAR_SETTINGS);
// Check that the toolbar's tab switcher and tools menu buttons are visible.
[[EarlGrey selectElementWithMatcher:chrome_test_util::ShowTabsButton()]
assertWithMatcher:grey_sufficientlyVisible()];
[[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(toolsMenuLabel)]
assertWithMatcher:grey_sufficientlyVisible()];
AssertNTPScrolledToTop(NO);
// Swipe up the NTP. The omnibox should be fixed at the top of the screen.
id<GREYMatcher> matcher = grey_accessibilityID(@"Google Landing");
[[EarlGrey selectElementWithMatcher:matcher]
performAction:grey_swipeFastInDirection(kGREYDirectionUp)];
AssertNTPScrolledToTop(YES);
// Check that tab switcher and tools menu buttons are not on screen.
[[EarlGrey selectElementWithMatcher:chrome_test_util::ShowTabsButton()]
assertWithMatcher:grey_notVisible()];
[[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(toolsMenuLabel)]
assertWithMatcher:grey_notVisible()];
}
@end @end
// Copyright 2015 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.
#ifndef IOS_CHROME_BROWSER_UI_NTP_WHATS_NEW_HEADER_VIEW_H_
#define IOS_CHROME_BROWSER_UI_NTP_WHATS_NEW_HEADER_VIEW_H_
#import <UIKit/UIKit.h>
#import "ios/chrome/browser/ui/ntp/notification_promo_whats_new.h"
#include "ios/public/provider/chrome/browser/images/whats_new_icon.h"
@protocol WhatsNewHeaderViewDelegate<NSObject>
- (void)onPromoLabelTapped;
@end
@interface WhatsNewHeaderView : UICollectionReusableView
@property(nonatomic, weak) id<WhatsNewHeaderViewDelegate> delegate;
// Sets the text for the attributed label.
- (void)setText:(NSString*)text;
// Sets the icon of the view.
- (void)setIcon:(WhatsNewIcon)icon;
// Sets the value to use for the left and right margin.
- (void)setSideMargin:(CGFloat)sideMargin forWidth:(CGFloat)width;
// Returns the minimum height required for WhatsNewHeaderView to fit in |width|,
// for a given |text|.
+ (int)heightToFitText:(NSString*)text inWidth:(CGFloat)width;
@end
#endif // IOS_CHROME_BROWSER_UI_NTP_WHATS_NEW_HEADER_VIEW_H_
// Copyright 2015 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 "ios/chrome/browser/ui/ntp/whats_new_header_view.h"
#include "base/logging.h"
#import "ios/chrome/browser/ui/uikit_ui_util.h"
#import "ios/chrome/browser/ui/util/constraints_ui_util.h"
#include "ios/chrome/common/string_util.h"
#include "ios/public/provider/chrome/browser/chrome_browser_provider.h"
#include "ios/public/provider/chrome/browser/images/branded_image_provider.h"
#import "ios/third_party/material_components_ios/src/components/Typography/src/MaterialTypography.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
namespace {
const CGFloat kLabelTopMargin = 16;
const CGFloat kLabelBottomMargin = 24;
const CGFloat kLabelLineSpacing = 4;
const CGFloat kLabelLeftMargin = 8;
const CGFloat kLabelFontSize = 14;
const CGFloat kInfoIconSize = 24;
const CGFloat kInfoIconTopMargin = 12;
const int kTextColorRgb = 0x333333;
const int kLinkColorRgb = 0x5595FE;
} // namespace
@interface WhatsNewHeaderView () {
UIImageView* _infoIconImageView;
UILabel* _promoLabel;
NSLayoutConstraint* _edgeConstraint;
UIView* _leftSpacer;
UIView* _rightSpacer;
CGFloat _sideMargin;
}
@end
@implementation WhatsNewHeaderView
@synthesize delegate = _delegate;
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.hidden = YES;
UIImage* infoIconImage = ios::GetChromeBrowserProvider()
->GetBrandedImageProvider()
->GetWhatsNewIconImage(WHATS_NEW_INFO);
_infoIconImageView = [[UIImageView alloc] initWithImage:infoIconImage];
_promoLabel = [[self class] promoLabel];
[_promoLabel setUserInteractionEnabled:YES];
UITapGestureRecognizer* promoTapRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(promoButtonPressed)];
[_promoLabel addGestureRecognizer:promoTapRecognizer];
_leftSpacer = [[UIView alloc] initWithFrame:CGRectZero];
_rightSpacer = [[UIView alloc] initWithFrame:CGRectZero];
[_leftSpacer setHidden:YES];
[_rightSpacer setHidden:YES];
[self addSubview:_infoIconImageView];
[self addSubview:_promoLabel];
[self addSubview:_leftSpacer];
[self addSubview:_rightSpacer];
[self setTranslatesAutoresizingMaskIntoConstraints:NO];
[_infoIconImageView setTranslatesAutoresizingMaskIntoConstraints:NO];
[_promoLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[_leftSpacer setTranslatesAutoresizingMaskIntoConstraints:NO];
[_rightSpacer setTranslatesAutoresizingMaskIntoConstraints:NO];
}
return self;
}
- (void)updateConstraints {
if ([[self constraints] count] == 0 && !self.hidden) {
NSString* verticalLogoVisualFormat =
@"V:|-logoTopMargin-[iconView(==iconSize)]";
NSString* verticalLabelVisualFormat = @"V:|-topMargin-[promoLabel]";
NSString* horizontalVisualFormat =
@"H:|-0-[leftSpacer]-0-[iconView(==iconSize)]-"
@"iconTextSpace-[promoLabel]-0-[rightSpacer(==leftSpacer)]-0-|";
NSNumber* topMargin = @(kLabelTopMargin);
NSNumber* iconSize = @(kInfoIconSize);
NSNumber* iconTextSpace = @(kLabelLeftMargin);
NSNumber* logoTopMargin = @(kInfoIconTopMargin);
NSDictionary* metrics = NSDictionaryOfVariableBindings(
topMargin, iconSize, iconTextSpace, logoTopMargin);
NSDictionary* views = @{
@"promoLabel" : _promoLabel,
@"iconView" : _infoIconImageView,
@"leftSpacer" : _leftSpacer,
@"rightSpacer" : _rightSpacer,
};
ApplyVisualConstraintsWithMetrics(
@[
verticalLogoVisualFormat, verticalLabelVisualFormat,
horizontalVisualFormat
],
views, metrics, self);
_edgeConstraint = [NSLayoutConstraint
constraintWithItem:_leftSpacer
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:_sideMargin];
[self addConstraint:_edgeConstraint];
}
[_edgeConstraint setConstant:_sideMargin];
[super updateConstraints];
}
- (void)setText:(NSString*)text {
[[self class] setText:text inPromoLabel:_promoLabel];
self.hidden = NO;
}
- (void)setIcon:(WhatsNewIcon)icon {
UIImage* image = ios::GetChromeBrowserProvider()
->GetBrandedImageProvider()
->GetWhatsNewIconImage(icon);
[_infoIconImageView setImage:image];
}
- (void)setSideMargin:(CGFloat)sideMargin forWidth:(CGFloat)width {
_sideMargin = sideMargin;
[self setNeedsUpdateConstraints];
CGFloat maxLabelWidth =
width - 2 * sideMargin - kInfoIconSize - kLabelLeftMargin;
[_promoLabel setPreferredMaxLayoutWidth:maxLabelWidth];
}
- (void)promoButtonPressed {
[_delegate onPromoLabelTapped];
[self removeConstraints:self.constraints];
_edgeConstraint = nil;
}
+ (void)setText:(NSString*)promoLabelText inPromoLabel:(UILabel*)promoLabel {
DCHECK(promoLabelText);
NSRange linkRange;
NSString* strippedText = ParseStringWithLink(promoLabelText, &linkRange);
DCHECK_NE(NSNotFound, static_cast<NSInteger>(linkRange.location));
DCHECK_NE(0u, linkRange.length);
NSMutableAttributedString* attributedText =
[[NSMutableAttributedString alloc] initWithString:strippedText];
// Sets the styling to mimic a link.
UIColor* linkColor = UIColorFromRGB(kLinkColorRgb, 1.0);
[attributedText addAttribute:NSForegroundColorAttributeName
value:linkColor
range:linkRange];
[attributedText addAttribute:NSUnderlineStyleAttributeName
value:@(NSUnderlineStyleSingle)
range:linkRange];
[attributedText addAttribute:NSUnderlineColorAttributeName
value:linkColor
range:linkRange];
// Sets the line spacing on the attributed string.
NSInteger strLength = [strippedText length];
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:kLabelLineSpacing];
[attributedText addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, strLength)];
[promoLabel setAttributedText:attributedText];
}
+ (UILabel*)promoLabel {
UILabel* promoLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[promoLabel
setFont:[[MDCTypography fontLoader] regularFontOfSize:kLabelFontSize]];
[promoLabel setTextColor:UIColorFromRGB(kTextColorRgb, 1.0)];
[promoLabel setNumberOfLines:0];
[promoLabel setTextAlignment:NSTextAlignmentNatural];
[promoLabel setLineBreakMode:NSLineBreakByWordWrapping];
return promoLabel;
}
+ (int)heightToFitText:(NSString*)text inWidth:(CGFloat)width {
CGFloat maxWidthForLabel = width - kInfoIconSize - kLabelLeftMargin;
UILabel* promoLabel = [self promoLabel];
[[self class] setText:text inPromoLabel:promoLabel];
CGFloat promoLabelHeight =
[promoLabel sizeThatFits:CGSizeMake(maxWidthForLabel, CGFLOAT_MAX)]
.height;
return promoLabelHeight + kLabelTopMargin + kLabelBottomMargin;
}
@end
...@@ -77,38 +77,6 @@ id<GREYMatcher> ButtonWithIdentity(ChromeIdentity* identity) { ...@@ -77,38 +77,6 @@ id<GREYMatcher> ButtonWithIdentity(ChromeIdentity* identity) {
@implementation AccountCollectionsTestCase @implementation AccountCollectionsTestCase
+ (void)setUp {
[super setUp];
[self closeAllTabs];
ios::ChromeBrowserState* browserState =
chrome_test_util::GetOriginalBrowserState();
if (experimental_flags::IsSuggestionsUIEnabled()) {
// Sets the ContentSuggestionsService associated with this browserState to a
// service with no provider registered, allowing to register fake providers
// which do not require internet connection. The previous service is
// deleted.
IOSChromeContentSuggestionsServiceFactory::GetInstance()->SetTestingFactory(
browserState, ntp_snippets::CreateChromeContentSuggestionsService);
}
}
+ (void)tearDown {
[self closeAllTabs];
ios::ChromeBrowserState* browserState =
chrome_test_util::GetOriginalBrowserState();
if (experimental_flags::IsSuggestionsUIEnabled()) {
// Resets the Service associated with this browserState to a service with
// default providers. The previous service is deleted.
IOSChromeContentSuggestionsServiceFactory::GetInstance()->SetTestingFactory(
browserState,
ntp_snippets::CreateChromeContentSuggestionsServiceWithProviders);
}
[super tearDown];
}
// Tests that the Sync and Account Settings screen are correctly popped if the // Tests that the Sync and Account Settings screen are correctly popped if the
// signed in account is removed. // signed in account is removed.
- (void)testSignInPopUpAccountOnSyncSettings { - (void)testSignInPopUpAccountOnSyncSettings {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment