diff --git a/DEPS b/DEPS index 593e66f..9b01b13 100644 --- a/DEPS +++ b/DEPS
@@ -133,7 +133,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '49d1e6f9b11ed9a1a2e7b6855ae26907ec119713', + 'v8_revision': 'ab1a9efefbbd2a95a35a74a5ef699cc20581c137', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -252,7 +252,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '7aad9653f9a36afa69bb54665a30591f5977881e', + 'spv_tools_revision': '07c4dd4b9ecb13f3a6d3bea1f51be6c9563c45ec', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -805,7 +805,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '13cb24c76e7e78937b214949cb9df894173bfcad', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'de445983dd9293d55cbad16f18b78334f7223a68', 'condition': 'checkout_linux', }, @@ -820,7 +820,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + 'a2b1d754558c4e0b6dab30866bdb60e80b1c8795', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '3a78fde2f31448ec30a807f8cba7c6cf7059b9d1', 'condition': 'checkout_linux', }, @@ -1183,7 +1183,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '7fa9a66b28ac0a93dda975e4d3aa23231129d8cc', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '22219acb4b586534155702c4fcac9f95a2d45a09', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1395,7 +1395,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@7a8bbc22887c3e2b12d310bba92937d788ef5394', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@11c47f6e5f74a5ea96d0f553e9c44e687a3b7a79', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/tools/remove_preinstalled_webview.py b/android_webview/tools/remove_preinstalled_webview.py index a2784e8c..2e96fd20 100755 --- a/android_webview/tools/remove_preinstalled_webview.py +++ b/android_webview/tools/remove_preinstalled_webview.py
@@ -44,11 +44,6 @@ from devil.android.tools import system_app # pylint: disable=import-error from devil.utils import logging_common # pylint: disable=import-error -WEBVIEW_SYSTEM_IMAGE_PATHS = [ - '/system/app/webview/webview.apk', - '/system/app/WebViewGoogle/WebViewGoogle.apk', - '/system/app/WebViewStub/WebViewStub.apk' -] WEBVIEW_PACKAGES = ['com.android.webview', 'com.google.android.webview'] @@ -67,14 +62,13 @@ """Uninstalls updates for WebView packages, if updates exist.""" print('Uninstalling updates from %s...' % device.serial) for webview_package in WEBVIEW_PACKAGES: - paths = device.GetApplicationPaths(webview_package) - if not paths: - continue # Package isn't installed, nothing to do - if set(paths) <= set(WEBVIEW_SYSTEM_IMAGE_PATHS): - # If we only have preinstalled paths, don't try to uninstall updates - # (necessary, otherwise we will raise an exception on some devices). - continue - device.Uninstall(webview_package) + try: + device.Uninstall(webview_package) + except device_errors.AdbCommandFailedError: + # This can happen if the app is on the system image but there are no + # updates installed on top of that. + logging.info('No update to uninstall for %s on %s', webview_package, + device.serial) def CheckWebViewIsUninstalled(device):
diff --git a/ash/autoclick/autoclick_controller.cc b/ash/autoclick/autoclick_controller.cc index 3ab1aca6..b6dab61 100644 --- a/ash/autoclick/autoclick_controller.cc +++ b/ash/autoclick/autoclick_controller.cc
@@ -432,16 +432,9 @@ autoclick_ring_handler_->SetGestureCenter(point_in_screen, widget_.get()); } } else if (event->type() == ui::ET_MOUSE_PRESSED || - event->type() == ui::ET_MOUSE_RELEASED) { + event->type() == ui::ET_MOUSE_RELEASED || + event->type() == ui::ET_MOUSEWHEEL) { CancelAutoclickAction(); - } else if (event->type() == ui::ET_MOUSEWHEEL) { - anchor_location_ = point_in_screen; - gesture_anchor_location_ = point_in_screen; - start_gesture_timer_->Reset(); - if (autoclick_timer_) { - autoclick_timer_->Stop(); - } - autoclick_ring_handler_->StopGesture(); } }
diff --git a/ash/autoclick/autoclick_unittest.cc b/ash/autoclick/autoclick_unittest.cc index ab87cfe..508186e 100644 --- a/ash/autoclick/autoclick_unittest.cc +++ b/ash/autoclick/autoclick_unittest.cc
@@ -379,6 +379,12 @@ events = WaitForMouseEvents(); EXPECT_EQ(2u, events.size()); + // Mouse-wheel scroll events should cancel the autoclick. + GetEventGenerator()->MoveMouseTo(300, 300); + GetEventGenerator()->MoveMouseWheel(0, 20); + events = WaitForMouseEvents(); + EXPECT_EQ(0u, events.size()); + // Performing a gesture should cancel the autoclick. GetEventGenerator()->MoveMouseTo(200, 200); GetEventGenerator()->GestureTapDownAndUp(gfx::Point(100, 100));
diff --git a/ash/components/shortcut_viewer/views/ksv_search_box_view.h b/ash/components/shortcut_viewer/views/ksv_search_box_view.h index dc44d80..8634cc4 100644 --- a/ash/components/shortcut_viewer/views/ksv_search_box_view.h +++ b/ash/components/shortcut_viewer/views/ksv_search_box_view.h
@@ -34,12 +34,7 @@ private: // search_box::SearchBoxViewBase: void UpdateBackgroundColor(SkColor color) override; - void ModelChanged() override {} - void UpdateKeyboardVisibility() override {} - void UpdateModel(bool initiated_by_user) override {} - void UpdateSearchIcon() override {} void UpdateSearchBoxBorder() override; - void SetupAssistantButton() override {} void SetupCloseButton() override; void SetupBackButton() override;
diff --git a/ash/login/ui/login_pin_view.cc b/ash/login/ui/login_pin_view.cc index 3405bae5..3b335aca 100644 --- a/ash/login/ui/login_pin_view.cc +++ b/ash/login/ui/login_pin_view.cc
@@ -253,9 +253,7 @@ : BasePinButton(size, l10n_util::GetStringUTF16( IDS_ASH_PIN_KEYBOARD_DELETE_ACCESSIBLE_NAME), - on_press), - delay_timer_(std::make_unique<base::OneShotTimer>()), - repeat_timer_(std::make_unique<base::RepeatingTimer>()) { + on_press) { image_ = new views::ImageView(); image_->SetImage(gfx::CreateVectorIcon( kLockScreenBackspaceIcon, login_constants::kButtonEnabledColor)); @@ -271,8 +269,7 @@ repeat_timer_ = std::move(repeat_timer); } - // BasePinButton: - void OnEnabledChanged() override { + void OnEnabledChanged() { SkColor color = login_constants::kButtonEnabledColor; if (!enabled()) { color = SkColorSetA(color, login_constants::kButtonDisabledAlpha); @@ -281,6 +278,8 @@ image_->SetImage(gfx::CreateVectorIcon(kLockScreenBackspaceIcon, color)); } + + // BasePinButton: void OnEvent(ui::Event* event) override { BasePinButton::OnEvent(event); if (event->handled()) @@ -357,10 +356,16 @@ } bool is_held_ = false; - std::unique_ptr<base::OneShotTimer> delay_timer_; - std::unique_ptr<base::RepeatingTimer> repeat_timer_; + std::unique_ptr<base::OneShotTimer> delay_timer_ = + std::make_unique<base::OneShotTimer>(); + std::unique_ptr<base::RepeatingTimer> repeat_timer_ = + std::make_unique<base::RepeatingTimer>(); views::ImageView* image_ = nullptr; + views::PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback(base::BindRepeating( + &LoginPinView::BackspacePinButton::OnEnabledChanged, + base::Unretained(this))); DISALLOW_COPY_AND_ASSIGN(BackspacePinButton); };
diff --git a/ash/media/media_notification_controller.cc b/ash/media/media_notification_controller.cc index d27a2517..da418448 100644 --- a/ash/media/media_notification_controller.cc +++ b/ash/media/media_notification_controller.cc
@@ -6,12 +6,16 @@ #include "ash/media/media_notification_constants.h" #include "ash/media/media_notification_view.h" +#include "ash/session/session_controller.h" +#include "ash/session/session_observer.h" +#include "ash/shell.h" #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" #include "services/media_session/public/mojom/constants.mojom.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/message_center/message_center.h" +#include "ui/message_center/notification_blocker.h" #include "ui/message_center/views/message_view_factory.h" namespace ash { @@ -30,6 +34,64 @@ // unlikely to see a user with 20+ things playing at once. const int kMediaNotificationCountHistogramMax = 20; +// MediaNotificationBlocker will block media notifications if the screen is +// locked. +class MediaNotificationBlocker : public message_center::NotificationBlocker, + public SessionObserver { + public: + MediaNotificationBlocker(message_center::MessageCenter* message_center, + SessionController* session_controller) + : message_center::NotificationBlocker(message_center), + locked_(session_controller->IsScreenLocked()), + session_controller_(session_controller) { + message_center->AddNotificationBlocker(this); + session_controller->AddObserver(this); + + NotifyBlockingStateChanged(); + } + + ~MediaNotificationBlocker() override { + message_center()->RemoveNotificationBlocker(this); + session_controller_->RemoveObserver(this); + } + + void CheckState() override { + OnLockStateChanged(session_controller_->IsScreenLocked()); + } + + bool ShouldShowNotification( + const message_center::Notification& notification) const override { + if (notification.notifier_id() == + message_center::NotifierId( + message_center::NotifierType::SYSTEM_COMPONENT, + kMediaSessionNotifierId)) { + return !locked_; + } + + return true; + } + + bool ShouldShowNotificationAsPopup( + const message_center::Notification& notification) const override { + return ShouldShowNotification(notification); + } + + void OnLockStateChanged(bool locked) override { + if (locked == locked_) + return; + + locked_ = locked; + NotifyBlockingStateChanged(); + } + + private: + bool locked_; + + SessionController* const session_controller_; + + DISALLOW_COPY_AND_ASSIGN(MediaNotificationBlocker); +}; + } // namespace // static @@ -37,7 +99,10 @@ "Media.Notification.Count"; MediaNotificationController::MediaNotificationController( - service_manager::Connector* connector) { + service_manager::Connector* connector) + : blocker_(std::make_unique<MediaNotificationBlocker>( + message_center::MessageCenter::Get(), + Shell::Get()->session_controller())) { if (!message_center::MessageViewFactory::HasCustomNotificationViewFactory( kMediaSessionNotificationCustomViewType)) { message_center::MessageViewFactory::SetCustomNotificationViewFactory(
diff --git a/ash/media/media_notification_controller.h b/ash/media/media_notification_controller.h index 6aed283..f3b16cb 100644 --- a/ash/media/media_notification_controller.h +++ b/ash/media/media_notification_controller.h
@@ -22,6 +22,10 @@ namespace ash { +namespace { +class MediaNotificationBlocker; +} // namespace + class MediaNotificationItem; class MediaNotificationView; @@ -67,6 +71,8 @@ // |request_id| in string format. std::map<const std::string, MediaNotificationItem> notifications_; + std::unique_ptr<MediaNotificationBlocker> blocker_; + DISALLOW_COPY_AND_ASSIGN(MediaNotificationController); };
diff --git a/ash/media/media_notification_controller_unittest.cc b/ash/media/media_notification_controller_unittest.cc index ec514ac..b30915d 100644 --- a/ash/media/media_notification_controller_unittest.cc +++ b/ash/media/media_notification_controller_unittest.cc
@@ -9,6 +9,8 @@ #include "ash/media/media_notification_constants.h" #include "ash/media/media_notification_item.h" #include "ash/public/cpp/ash_features.h" +#include "ash/public/cpp/notification_utils.h" +#include "ash/session/session_controller.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "base/macros.h" @@ -84,6 +86,13 @@ static_cast<base::HistogramBase::Sample>(source), 1); } + void SimulateSessionLock(bool locked) { + mojom::SessionInfoPtr info_ptr = mojom::SessionInfo::New(); + info_ptr->state = locked ? session_manager::SessionState::LOCKED + : session_manager::SessionState::ACTIVE; + Shell::Get()->session_controller()->SetSessionInfo(std::move(info_ptr)); + } + private: base::test::ScopedFeatureList scoped_feature_list_; @@ -419,4 +428,45 @@ ExpectHistogramSourceRecorded(MediaNotificationItem::Source::kArc); } +// Test that locking the screen will hide the media notifications. Unlocking the +// screen should re-show the notifications. +TEST_F(MediaNotificationControllerTest, HideWhenScreenLocked) { + message_center::MessageCenter* message_center = + message_center::MessageCenter::Get(); + + base::UnguessableToken id = base::UnguessableToken::Create(); + + ExpectNotificationCount(0); + + Shell::Get()->media_notification_controller()->OnFocusGained( + GetRequestStateWithId(id)); + + Shell::Get() + ->media_notification_controller() + ->GetItem(id.ToString()) + ->MediaSessionMetadataChanged(BuildMediaMetadata()); + + ExpectNotificationCount(1); + + // Show a non-media notification that should still be displayed. + message_center->AddNotification( + ash::CreateSystemNotification("test", base::string16(), base::string16(), + "test", base::BindRepeating([]() {}))); + + EXPECT_EQ(2u, message_center->GetVisibleNotifications().size()); + + // Lock the screen and only the non-media notification should be visible. + SimulateSessionLock(true); + + { + auto notifications = message_center->GetVisibleNotifications(); + EXPECT_EQ(1u, notifications.size()); + EXPECT_EQ("test", (*notifications.begin())->id()); + } + + // Unlock the screen and both notifications should be visible again. + SimulateSessionLock(false); + EXPECT_EQ(2u, message_center->GetVisibleNotifications().size()); +} + } // namespace ash
diff --git a/ash/public/cpp/ash_features.cc b/ash/public/cpp/ash_features.cc index 3a53c68..a8acaa3 100644 --- a/ash/public/cpp/ash_features.cc +++ b/ash/public/cpp/ash_features.cc
@@ -30,10 +30,10 @@ base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kHideArcMediaNotifications{ - "HideArcMediaNotifications", base::FEATURE_DISABLED_BY_DEFAULT}; + "HideArcMediaNotifications", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kMediaSessionNotification{ - "MediaSessionNotification", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kMediaSessionNotification{"MediaSessionNotification", + base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kNightLight{"NightLight", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/ash/system/tray/detailed_view_delegate.cc b/ash/system/tray/detailed_view_delegate.cc index 0abb2c3e..52a0e03 100644 --- a/ash/system/tray/detailed_view_delegate.cc +++ b/ash/system/tray/detailed_view_delegate.cc
@@ -21,6 +21,7 @@ #include "ui/views/controls/label.h" #include "ui/views/controls/separator.h" #include "ui/views/layout/box_layout.h" +#include "ui/views/view_class_properties.h" namespace ash { @@ -69,6 +70,10 @@ l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_PREVIOUS_MENU)); SetBorder(views::CreateEmptyBorder( gfx::Insets((kTrayItemSize - image.width()) / 2))); + + auto path = std::make_unique<SkPath>( + CreateCustomShapePath(gfx::Rect(CalculatePreferredSize()))); + SetProperty(views::kHighlightPathKey, path.release()); } ~BackButton() override = default;
diff --git a/ash/system/tray/hover_highlight_view.cc b/ash/system/tray/hover_highlight_view.cc index 587326d..d5b751c 100644 --- a/ash/system/tray/hover_highlight_view.cc +++ b/ash/system/tray/hover_highlight_view.cc
@@ -242,6 +242,11 @@ return GetPreferredSize().height(); } +void HoverHighlightView::OnFocus() { + ScrollRectToVisible(gfx::Rect(gfx::Point(), size())); + ActionableView::OnFocus(); +} + void HoverHighlightView::OnEnabledChanged() { if (left_icon_) left_icon_->SetEnabled(enabled()); @@ -251,9 +256,4 @@ right_view_->SetEnabled(enabled()); } -void HoverHighlightView::OnFocus() { - ScrollRectToVisible(gfx::Rect(gfx::Point(), size())); - ActionableView::OnFocus(); -} - } // namespace ash
diff --git a/ash/system/tray/hover_highlight_view.h b/ash/system/tray/hover_highlight_view.h index e775ab9..d24a0329 100644 --- a/ash/system/tray/hover_highlight_view.h +++ b/ash/system/tray/hover_highlight_view.h
@@ -9,6 +9,7 @@ #include "ash/system/tray/actionable_view.h" #include "ash/system/tray/tray_popup_item_style.h" +#include "base/bind.h" #include "base/macros.h" #include "ui/gfx/font.h" #include "ui/gfx/text_constants.h" @@ -128,9 +129,10 @@ // views::View: gfx::Size CalculatePreferredSize() const override; int GetHeightForWidth(int width) const override; - void OnEnabledChanged() override; void OnFocus() override; + void OnEnabledChanged(); + // Determines whether the view is populated or not. If it is, Reset() should // be called before re-populating the view. bool is_populated_ = false; @@ -144,6 +146,10 @@ bool expandable_ = false; const bool use_unified_theme_; AccessibilityState accessibility_state_ = AccessibilityState::DEFAULT; + views::PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&HoverHighlightView::OnEnabledChanged, + base::Unretained(this))); DISALLOW_COPY_AND_ASSIGN(HoverHighlightView); };
diff --git a/ash/system/unified/collapse_button.cc b/ash/system/unified/collapse_button.cc index 31ac219..9d2d662 100644 --- a/ash/system/unified/collapse_button.cc +++ b/ash/system/unified/collapse_button.cc
@@ -122,14 +122,6 @@ SchedulePaint(); } -void CollapseButton::OnEnabledChanged() { - SetImage(views::Button::STATE_NORMAL, - gfx::CreateVectorIcon(kUnifiedMenuExpandIcon, - enabled() ? kUnifiedMenuIconColor - : kUnifiedMenuIconColorDisabled)); - SchedulePaint(); -} - gfx::Size CollapseButton::CalculatePreferredSize() const { return gfx::Size(kTrayItemSize, kTrayItemSize * 3 / 2); } @@ -153,4 +145,11 @@ canvas->DrawImageInt(image, -image.width() / 2, -image.height() / 2); } +void CollapseButton::OnEnabledChanged() { + SetImage(views::Button::STATE_NORMAL, + gfx::CreateVectorIcon(kUnifiedMenuExpandIcon, + enabled() ? kUnifiedMenuIconColor + : kUnifiedMenuIconColorDisabled)); +} + } // namespace ash
diff --git a/ash/system/unified/collapse_button.h b/ash/system/unified/collapse_button.h index c2997e10..cde34a2a 100644 --- a/ash/system/unified/collapse_button.h +++ b/ash/system/unified/collapse_button.h
@@ -5,6 +5,7 @@ #ifndef ASH_SYSTEM_UNIFIED_COLLAPSE_BUTTON_H_ #define ASH_SYSTEM_UNIFIED_COLLAPSE_BUTTON_H_ +#include "base/bind.h" #include "ui/views/controls/button/image_button.h" namespace ash { @@ -47,13 +48,18 @@ void SetExpandedAmount(double expanded_amount); // CustomShapeButton: - void OnEnabledChanged() override; gfx::Size CalculatePreferredSize() const override; SkPath CreateCustomShapePath(const gfx::Rect& bounds) const override; void PaintButtonContents(gfx::Canvas* canvas) override; private: + void OnEnabledChanged(); + double expanded_amount_ = 1.0; + views::PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&CollapseButton::OnEnabledChanged, + base::Unretained(this))); DISALLOW_COPY_AND_ASSIGN(CollapseButton); };
diff --git a/ash/system/unified/feature_pod_button.cc b/ash/system/unified/feature_pod_button.cc index 64e30584..b6e460b 100644 --- a/ash/system/unified/feature_pod_button.cc +++ b/ash/system/unified/feature_pod_button.cc
@@ -153,17 +153,6 @@ arrow_size)); } -void FeaturePodLabelButton::OnEnabledChanged() { - label_->SetEnabledColor(enabled() ? kUnifiedMenuTextColor - : kUnifiedMenuTextColorDisabled); - sub_label_->SetEnabledColor(enabled() ? kUnifiedMenuSecondaryTextColor - : kUnifiedMenuTextColorDisabled); - detailed_view_arrow_->SetImage(gfx::CreateVectorIcon( - kUnifiedMenuMoreIcon, - enabled() ? kUnifiedMenuIconColor : kUnifiedMenuIconColorDisabled)); - SchedulePaint(); -} - gfx::Size FeaturePodLabelButton::CalculatePreferredSize() const { // Minimum width of the button int width = kUnifiedFeaturePodLabelWidth + GetInsets().width(); @@ -226,6 +215,16 @@ InvalidateLayout(); } +void FeaturePodLabelButton::OnEnabledChanged() { + label_->SetEnabledColor(enabled() ? kUnifiedMenuTextColor + : kUnifiedMenuTextColorDisabled); + sub_label_->SetEnabledColor(enabled() ? kUnifiedMenuSecondaryTextColor + : kUnifiedMenuTextColorDisabled); + detailed_view_arrow_->SetImage(gfx::CreateVectorIcon( + kUnifiedMenuMoreIcon, + enabled() ? kUnifiedMenuIconColor : kUnifiedMenuIconColorDisabled)); +} + void FeaturePodLabelButton::LayoutInCenter(views::View* child, int y) { gfx::Rect contents_bounds = GetContentsBounds(); gfx::Size preferred_size = child->GetPreferredSize(); @@ -327,7 +326,6 @@ void FeaturePodButton::OnEnabledChanged() { icon_button_->SetEnabled(enabled()); label_button_->SetEnabled(enabled()); - SchedulePaint(); } void FeaturePodButton::ButtonPressed(views::Button* sender,
diff --git a/ash/system/unified/feature_pod_button.h b/ash/system/unified/feature_pod_button.h index fd42abb..2b747f2 100644 --- a/ash/system/unified/feature_pod_button.h +++ b/ash/system/unified/feature_pod_button.h
@@ -6,6 +6,7 @@ #define ASH_SYSTEM_UNIFIED_FEATURE_POD_BUTTON_H_ #include "ash/ash_export.h" +#include "base/bind.h" #include "ui/gfx/vector_icon_types.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/view.h" @@ -65,7 +66,6 @@ // views::Button: void Layout() override; - void OnEnabledChanged() override; gfx::Size CalculatePreferredSize() const override; std::unique_ptr<views::InkDrop> CreateInkDrop() override; std::unique_ptr<views::InkDropRipple> CreateInkDropRipple() const override; @@ -77,10 +77,16 @@ // Layout |child| in horizontal center with its vertical origin set to |y|. void LayoutInCenter(views::View* child, int y); + void OnEnabledChanged(); + // Owned by views hierarchy. views::Label* const label_; views::Label* const sub_label_; views::ImageView* const detailed_view_arrow_; + views::PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&FeaturePodLabelButton::OnEnabledChanged, + base::Unretained(this))); DISALLOW_COPY_AND_ASSIGN(FeaturePodLabelButton); }; @@ -139,7 +145,6 @@ void SetVisible(bool visible) override; bool HasFocus() const override; void RequestFocus() override; - void OnEnabledChanged() override; // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; @@ -150,6 +155,8 @@ FeaturePodIconButton* icon_button() const { return icon_button_; } private: + void OnEnabledChanged(); + // Unowned. FeaturePodControllerBase* const controller_; @@ -164,6 +171,11 @@ // expanded. bool visible_preferred_ = true; + views::PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&FeaturePodButton::OnEnabledChanged, + base::Unretained(this))); + DISALLOW_COPY_AND_ASSIGN(FeaturePodButton); };
diff --git a/ash/wallpaper/wallpaper_controller.cc b/ash/wallpaper/wallpaper_controller.cc index 35e2079..78c692c3 100644 --- a/ash/wallpaper/wallpaper_controller.cc +++ b/ash/wallpaper/wallpaper_controller.cc
@@ -318,7 +318,7 @@ void SaveCustomWallpaper(const std::string& wallpaper_files_id, const base::FilePath& original_path, WallpaperLayout layout, - std::unique_ptr<gfx::ImageSkia> image) { + gfx::ImageSkia image) { base::DeleteFile(WallpaperController::GetCustomWallpaperDir( WallpaperController::kOriginalWallpaperSubDir) .Append(wallpaper_files_id), @@ -345,11 +345,11 @@ // Re-encode orginal file to jpeg format and saves the result in case that // resized wallpaper is not generated (i.e. chrome shutdown before resized // wallpaper is saved). - ResizeAndSaveWallpaper(*image, original_path, WALLPAPER_LAYOUT_STRETCH, - image->width(), image->height()); - ResizeAndSaveWallpaper(*image, small_wallpaper_path, layout, + ResizeAndSaveWallpaper(image, original_path, WALLPAPER_LAYOUT_STRETCH, + image.width(), image.height()); + ResizeAndSaveWallpaper(image, small_wallpaper_path, layout, kSmallWallpaperMaxWidth, kSmallWallpaperMaxHeight); - ResizeAndSaveWallpaper(*image, large_wallpaper_path, layout, + ResizeAndSaveWallpaper(image, large_wallpaper_path, layout, kLargeWallpaperMaxWidth, kLargeWallpaperMaxHeight); } @@ -395,19 +395,19 @@ // system. void SaveOnlineWallpaper(const std::string& url, WallpaperLayout layout, - std::unique_ptr<gfx::ImageSkia> image) { + gfx::ImageSkia image) { DCHECK(!GlobalChromeOSWallpapersDir().empty()); if (!base::DirectoryExists(GlobalChromeOSWallpapersDir()) && !base::CreateDirectory(GlobalChromeOSWallpapersDir())) { return; } ResizeAndSaveWallpaper( - *image, + image, GetOnlineWallpaperPath(url, WallpaperController::WALLPAPER_RESOLUTION_LARGE), - layout, image->width(), image->height()); + layout, image.width(), image.height()); ResizeAndSaveWallpaper( - *image, + image, GetOnlineWallpaperPath(url, WallpaperController::WALLPAPER_RESOLUTION_SMALL), WALLPAPER_LAYOUT_CENTER_CROPPED, kSmallWallpaperMaxWidth, @@ -1729,11 +1729,10 @@ if (save_file) { image.EnsureRepsForSupportedScales(); - std::unique_ptr<gfx::ImageSkia> deep_copy(image.DeepCopy()); + gfx::ImageSkia deep_copy(image.DeepCopy()); sequenced_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&SaveOnlineWallpaper, params.url, params.layout, - base::Passed(std::move(deep_copy)))); + FROM_HERE, base::BindOnce(&SaveOnlineWallpaper, params.url, + params.layout, deep_copy)); } const bool is_active_user = IsActiveUser(params.account_id); @@ -1895,7 +1894,7 @@ if (should_save_to_disk) { image.EnsureRepsForSupportedScales(); - std::unique_ptr<gfx::ImageSkia> deep_copy(image.DeepCopy()); + gfx::ImageSkia deep_copy(image.DeepCopy()); // Block shutdown on this task. Otherwise, we may lose the custom wallpaper // that the user selected. scoped_refptr<base::SequencedTaskRunner> blocking_task_runner = @@ -1903,9 +1902,8 @@ {base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); blocking_task_runner->PostTask( - FROM_HERE, - base::BindOnce(&SaveCustomWallpaper, wallpaper_files_id, wallpaper_path, - layout, base::Passed(std::move(deep_copy)))); + FROM_HERE, base::BindOnce(&SaveCustomWallpaper, wallpaper_files_id, + wallpaper_path, layout, deep_copy)); } if (show_wallpaper) {
diff --git a/base/BUILD.gn b/base/BUILD.gn index 20ca6fd0..3e9a1208 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -3158,6 +3158,7 @@ "android/java/src/org/chromium/base/task/AsyncTask.java", "android/java/src/org/chromium/base/task/BackgroundOnlyAsyncTask.java", "android/java/src/org/chromium/base/task/DefaultTaskExecutor.java", + "android/java/src/org/chromium/base/task/ChoreographerTaskRunner.java", "android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java", "android/java/src/org/chromium/base/task/PostTask.java", "android/java/src/org/chromium/base/task/SequencedTaskRunner.java",
diff --git a/base/android/java/src/org/chromium/base/task/ChoreographerTaskRunner.java b/base/android/java/src/org/chromium/base/task/ChoreographerTaskRunner.java new file mode 100644 index 0000000..d44ef4e --- /dev/null +++ b/base/android/java/src/org/chromium/base/task/ChoreographerTaskRunner.java
@@ -0,0 +1,63 @@ +// Copyright 2018 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. + +package org.chromium.base.task; + +import android.view.Choreographer; + +/** + * An adapter that allows PostTask to submit Choreographer frame callbacks which + * run after the next vsync. + */ +final class ChoreographerTaskRunner implements SingleThreadTaskRunner { + private final Choreographer mChoreographer; + + ChoreographerTaskRunner(Choreographer choreographer) { + mChoreographer = choreographer; + } + + @Override + public boolean belongsToCurrentThread() { + try { + return mChoreographer == Choreographer.getInstance(); + } catch (IllegalStateException e) { + return false; + } + } + + @Override + public void postTask(Runnable task) { + mChoreographer.postFrameCallback(new Choreographer.FrameCallback() { + @Override + public void doFrame(long frameTimeNanos) { + task.run(); + } + }); + } + + @Override + public void destroy() { + // NOP + } + + @Override + public void disableLifetimeCheck() { + // NOP + } + + @Override + public void postDelayedTask(Runnable task, long delayMillis) { + mChoreographer.postFrameCallbackDelayed(new Choreographer.FrameCallback() { + @Override + public void doFrame(long frameTimeNanos) { + task.run(); + } + }, delayMillis); + } + + @Override + public void initNativeTaskRunner() { + // NOP + } +}
diff --git a/base/android/java/src/org/chromium/base/task/DefaultTaskExecutor.java b/base/android/java/src/org/chromium/base/task/DefaultTaskExecutor.java index 0613e38..9952c42 100644 --- a/base/android/java/src/org/chromium/base/task/DefaultTaskExecutor.java +++ b/base/android/java/src/org/chromium/base/task/DefaultTaskExecutor.java
@@ -4,6 +4,10 @@ package org.chromium.base.task; +import android.view.Choreographer; + +import org.chromium.base.ThreadUtils; + import java.util.HashMap; import java.util.Map; @@ -11,15 +15,18 @@ * The default {@link TaskExecutor} which maps directly to base::ThreadPool. */ class DefaultTaskExecutor implements TaskExecutor { - Map<TaskTraits, TaskRunner> mTraitsToRunnerMap = new HashMap<>(); + private final Map<TaskTraits, TaskRunner> mTraitsToRunnerMap = new HashMap<>(); + private ChoreographerTaskRunner mChoreographerTaskRunner; @Override public TaskRunner createTaskRunner(TaskTraits taskTraits) { + if (taskTraits.mIsChoreographerFrame) return getChoreographerTaskRunner(); return new TaskRunnerImpl(taskTraits); } @Override public SequencedTaskRunner createSequencedTaskRunner(TaskTraits taskTraits) { + if (taskTraits.mIsChoreographerFrame) return getChoreographerTaskRunner(); return new SequencedTaskRunnerImpl(taskTraits); } @@ -29,12 +36,13 @@ */ @Override public SingleThreadTaskRunner createSingleThreadTaskRunner(TaskTraits taskTraits) { + if (taskTraits.mIsChoreographerFrame) return getChoreographerTaskRunner(); // Tasks posted via this API will not execute until after native has started. return new SingleThreadTaskRunnerImpl(null, taskTraits); } @Override - public void postDelayedTask(TaskTraits taskTraits, Runnable task, long delay) { + public synchronized void postDelayedTask(TaskTraits taskTraits, Runnable task, long delay) { if (taskTraits.hasExtension()) { TaskRunner runner = createTaskRunner(taskTraits); runner.postDelayedTask(task, delay); @@ -57,4 +65,14 @@ public boolean canRunTaskImmediately(TaskTraits traits) { return false; } + + private synchronized ChoreographerTaskRunner getChoreographerTaskRunner() { + // TODO(alexclarke): Migrate to the new Android UI thread trait when available. + ChoreographerTaskRunner choreographerTaskRunner = + ThreadUtils.runOnUiThreadBlockingNoException( + () -> { return new ChoreographerTaskRunner(Choreographer.getInstance()); }); + + mTraitsToRunnerMap.put(TaskTraits.CHOREOGRAPHER_FRAME, choreographerTaskRunner); + return choreographerTaskRunner; + } }
diff --git a/base/android/java/src/org/chromium/base/task/TaskTraits.java b/base/android/java/src/org/chromium/base/task/TaskTraits.java index 4b91a323..0633fc78 100644 --- a/base/android/java/src/org/chromium/base/task/TaskTraits.java +++ b/base/android/java/src/org/chromium/base/task/TaskTraits.java
@@ -54,6 +54,11 @@ public static final TaskTraits USER_BLOCKING = new TaskTraits().taskPriority(TaskPriority.USER_BLOCKING); + // A bit like requestAnimationFrame, this task will be posted onto the Choreographer + // and will be run on the android main thread after the next vsync. + public static final TaskTraits CHOREOGRAPHER_FRAME = + new TaskTraits().setIsChoreographerFrame(true); + public TaskTraits() {} private TaskTraits(TaskTraits other) { @@ -89,6 +94,11 @@ return taskTraits; } + private TaskTraits setIsChoreographerFrame(boolean isChoreographerFrame) { + mIsChoreographerFrame = isChoreographerFrame; + return this; + } + // For convenience of the JNI code, we use primitive types only. // Note shutdown behavior is not supported on android. boolean mPrioritySetExplicitly; @@ -96,6 +106,7 @@ boolean mMayBlock; byte mExtensionId = INVALID_EXTENSION_ID; byte mExtensionData[]; + boolean mIsChoreographerFrame; /** * @return true if this task is using some TaskTraits extension. @@ -152,6 +163,7 @@ hash = 37 * hash + (mMayBlock ? 0 : 1); hash = 37 * hash + (int) mExtensionId; hash = 37 * hash + Arrays.hashCode(mExtensionData); + hash = 37 * hash + (mIsChoreographerFrame ? 0 : 1); return hash; } }
diff --git a/base/android/javatests/src/org/chromium/base/task/PostTaskTest.java b/base/android/javatests/src/org/chromium/base/task/PostTaskTest.java index 022013b..c7ad98c 100644 --- a/base/android/javatests/src/org/chromium/base/task/PostTaskTest.java +++ b/base/android/javatests/src/org/chromium/base/task/PostTaskTest.java
@@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -95,4 +96,34 @@ taskQueue.destroy(); } } + + @Test + @SmallTest + public void testChoreographerFrameTrait() throws Exception { + List<Integer> orderList = new ArrayList<>(); + CountDownLatch latch = new CountDownLatch(2); + PostTask.postTask(TaskTraits.CHOREOGRAPHER_FRAME, new Runnable() { + @Override + public void run() { + synchronized (orderList) { + orderList.add(1); + latch.countDown(); + } + } + }); + + PostTask.postTask(TaskTraits.CHOREOGRAPHER_FRAME, new Runnable() { + @Override + public void run() { + synchronized (orderList) { + orderList.add(2); + latch.countDown(); + } + } + }); + + latch.await(); + + assertThat(orderList, contains(1, 2)); + } }
diff --git a/base/profiler/stack_sampling_profiler_unittest.cc b/base/profiler/stack_sampling_profiler_unittest.cc index 0f2cdc3..93a94c88 100644 --- a/base/profiler/stack_sampling_profiler_unittest.cc +++ b/base/profiler/stack_sampling_profiler_unittest.cc
@@ -8,6 +8,7 @@ #include <algorithm> #include <cstdlib> #include <memory> +#include <set> #include <utility> #include <vector> @@ -88,213 +89,271 @@ NativeLibrary library; }; -// Signature for a target function that is expected to appear in the stack. See -// SignalAndWaitUntilSignaled() below. The return value should be a program -// counter pointer near the end of the function. -using TargetFunction = const void* (*)(WaitableEvent*, - WaitableEvent*, - const StackConfiguration*); +// Addresses near the start and end of a function. +struct FunctionAddressRange { + const void* start; + const void* end; +}; + +// Disable inlining for this function so that it gets its own stack frame. +NOINLINE const void* GetProgramCounter() { + // Saving to a volatile prevents clang from assuming it can reuse the return + // value across multiple calls to GetProgramCounter(). +#if defined(OS_WIN) + const void* volatile program_counter = _ReturnAddress(); +#else + const void* volatile program_counter = __builtin_return_address(0); +#endif + return program_counter; +} + +// Represents a stack unwind scenario to be sampled by the +// StackSamplingProfiler. +class UnwindScenario { + public: + // A callback provided by the caller that sets up the unwind scenario, then + // calls into the passed closure to wait for a sample to be taken. Returns the + // address range of the function that sets up the unwind scenario. The passed + // closure will be null when invoked solely to obtain the address range. + using SetupFunction = RepeatingCallback<FunctionAddressRange(const Closure&)>; + + // Events to coordinate the sampling. + struct SampleEvents { + WaitableEvent ready_for_sample; + WaitableEvent sample_finished; + }; + + explicit UnwindScenario(const SetupFunction& setup_function) + : setup_function_(setup_function) {} + + UnwindScenario(const UnwindScenario&) = delete; + UnwindScenario& operator=(const UnwindScenario&) = delete; + + FunctionAddressRange GetWaitForSampleAddressRange() const; + FunctionAddressRange GetSetupFunctionAddressRange() const; + FunctionAddressRange GetOuterFunctionAddressRange() const; + + void Execute(SampleEvents* events); + + private: + static FunctionAddressRange InvokeSetupFunction( + const SetupFunction& setup_function, + SampleEvents* events); + + static FunctionAddressRange WaitForSample(SampleEvents* events); + + const SetupFunction setup_function_; +}; + +FunctionAddressRange UnwindScenario::GetWaitForSampleAddressRange() const { + return WaitForSample(nullptr); +} + +FunctionAddressRange UnwindScenario::GetSetupFunctionAddressRange() const { + return setup_function_.Run(Closure()); +} + +FunctionAddressRange UnwindScenario::GetOuterFunctionAddressRange() const { + return InvokeSetupFunction(SetupFunction(), nullptr); +} + +void UnwindScenario::Execute(SampleEvents* events) { + InvokeSetupFunction(setup_function_, events); +} + +// static +// Disable inlining for this function so that it gets its own stack frame. +NOINLINE FunctionAddressRange +UnwindScenario::InvokeSetupFunction(const SetupFunction& setup_function, + SampleEvents* events) { + const void* start_program_counter = GetProgramCounter(); + + if (!setup_function.is_null()) { + const auto wait_for_sample_closure = + BindLambdaForTesting([&]() { UnwindScenario::WaitForSample(events); }); + setup_function.Run(wait_for_sample_closure); + } + + // Volatile to prevent a tail call to GetProgramCounter(). + const void* volatile end_program_counter = GetProgramCounter(); + return {start_program_counter, end_program_counter}; +} + +// static +// Disable inlining for this function so that it gets its own stack frame. +NOINLINE FunctionAddressRange +UnwindScenario::WaitForSample(SampleEvents* events) { + const void* start_program_counter = GetProgramCounter(); + + if (events) { + events->ready_for_sample.Signal(); + events->sample_finished.Wait(); + } + + // Volatile to prevent a tail call to GetProgramCounter(). + const void* volatile end_program_counter = GetProgramCounter(); + return {start_program_counter, end_program_counter}; +} // A thread to target for profiling, whose stack is guaranteed to contain // SignalAndWaitUntilSignaled() when coordinated with the main thread. class TargetThread : public PlatformThread::Delegate { public: - explicit TargetThread(const StackConfiguration& stack_config); + TargetThread(const Closure& to_run); // PlatformThread::Delegate: void ThreadMain() override; - // Waits for the thread to have started and be executing in - // SignalAndWaitUntilSignaled(). - void WaitForThreadStart(); - - // Allows the thread to return from SignalAndWaitUntilSignaled() and finish - // execution. - void SignalThreadToFinish(); - - // A function which invokes one of the stack setup functions below. This is - // used to place a frame on the stack that we can identify before those calls, - // so that we can check that unwinds from them have succeeded. - // - // This and the following functions return a program counter value near the - // end of the function. They can be invoked with null parameters to just - // return the program counter. The functions are static so that we can get a - // straightforward address for them in the tests below, rather than dealing - // with the complexity of a member function pointer representation. - static const void* InvokeSetupFunction( - WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config); - - // This function is guaranteed to be executing between calls to - // WaitForThreadStart() and SignalThreadToFinish() when invoked with - // |thread_started_event_| and |finish_event_|. - static const void* SignalAndWaitUntilSignaled( - WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config); - - // Calls into SignalAndWaitUntilSignaled() after allocating memory on the - // stack with alloca. - static const void* CallWithAlloca(WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config); - - // Calls into SignalAndWaitUntilSignaled() via a function in - // base_profiler_test_support_library. - static const void* CallThroughOtherLibrary( - WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config); - PlatformThreadId id() const { return id_; } private: - struct TargetFunctionArgs { - WaitableEvent* thread_started_event; - WaitableEvent* finish_event; - const StackConfiguration* stack_config; - }; - - // Callback function to be provided when calling through the other library. - static void OtherLibraryCallback(void* arg); - - // Returns the current program counter, or a value very close to it. - static const void* GetProgramCounter(); - - WaitableEvent thread_started_event_; - WaitableEvent finish_event_; - PlatformThreadId id_; - const StackConfiguration stack_config_; + PlatformThreadId id_ = 0; + Closure to_run_; DISALLOW_COPY_AND_ASSIGN(TargetThread); }; -TargetThread::TargetThread(const StackConfiguration& stack_config) - : thread_started_event_(WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED), - finish_event_(WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED), - id_(0), - stack_config_(stack_config) {} +TargetThread::TargetThread(const Closure& to_run) : to_run_(to_run) {} void TargetThread::ThreadMain() { id_ = PlatformThread::CurrentId(); - InvokeSetupFunction(&thread_started_event_, &finish_event_, &stack_config_); + to_run_.Run(); } -void TargetThread::WaitForThreadStart() { - thread_started_event_.Wait(); -} - -void TargetThread::SignalThreadToFinish() { - finish_event_.Signal(); -} - -// static +// Calls into |wait_for_sample| without doing any special unwinding setup, to +// test the "normal" unwind scenario. // Disable inlining for this function so that it gets its own stack frame. -NOINLINE const void* TargetThread::InvokeSetupFunction( - WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config) { - if (stack_config) { - switch (stack_config->config) { - case StackConfiguration::NORMAL: - SignalAndWaitUntilSignaled(thread_started_event, finish_event, - stack_config); - break; +NOINLINE FunctionAddressRange +CallWithPlainFunction(const Closure& wait_for_sample) { + const void* start_program_counter = GetProgramCounter(); - case StackConfiguration::WITH_ALLOCA: - CallWithAlloca(thread_started_event, finish_event, stack_config); - break; - - case StackConfiguration::WITH_OTHER_LIBRARY: - CallThroughOtherLibrary(thread_started_event, finish_event, - stack_config); - break; - } - } + if (!wait_for_sample.is_null()) + wait_for_sample.Run(); // Volatile to prevent a tail call to GetProgramCounter(). - const void* volatile program_counter = GetProgramCounter(); - return program_counter; + const void* volatile end_program_counter = GetProgramCounter(); + return {start_program_counter, end_program_counter}; } -// static +// Calls into |wait_for_sample| after using alloca(), to test unwinding with a +// frame pointer. // Disable inlining for this function so that it gets its own stack frame. -NOINLINE const void* TargetThread::SignalAndWaitUntilSignaled( - WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config) { - if (thread_started_event && finish_event) { - thread_started_event->Signal(); - finish_event->Wait(); - } +NOINLINE FunctionAddressRange CallWithAlloca(const Closure& wait_for_sample) { + const void* start_program_counter = GetProgramCounter(); - // Volatile to prevent a tail call to GetProgramCounter(). - const void* volatile program_counter = GetProgramCounter(); - return program_counter; -} - -// static -// Disable inlining for this function so that it gets its own stack frame. -NOINLINE const void* TargetThread::CallWithAlloca( - WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config) { const size_t alloca_size = 100; // Memset to 0 to generate a clean failure. std::memset(alloca(alloca_size), 0, alloca_size); - SignalAndWaitUntilSignaled(thread_started_event, finish_event, stack_config); + if (!wait_for_sample.is_null()) + wait_for_sample.Run(); // Volatile to prevent a tail call to GetProgramCounter(). - const void* volatile program_counter = GetProgramCounter(); - return program_counter; + const void* volatile end_program_counter = GetProgramCounter(); + return {start_program_counter, end_program_counter}; } -// static -NOINLINE const void* TargetThread::CallThroughOtherLibrary( - WaitableEvent* thread_started_event, - WaitableEvent* finish_event, - const StackConfiguration* stack_config) { - if (stack_config) { - // A function whose arguments are a function accepting void*, and a void*. - using InvokeCallbackFunction = void (*)(void (*)(void*), void*); - EXPECT_TRUE(stack_config->library); - InvokeCallbackFunction function = reinterpret_cast<InvokeCallbackFunction>( - GetFunctionPointerFromNativeLibrary(stack_config->library, - "InvokeCallbackFunction")); - EXPECT_TRUE(function); +// The function to be executed by the code in the other library. +void OtherLibraryCallback(void* arg) { + const Closure* wait_for_sample = static_cast<const Closure*>(arg); - TargetFunctionArgs args = {thread_started_event, finish_event, - stack_config}; - (*function)(&OtherLibraryCallback, &args); - } + wait_for_sample->Run(); - // Volatile to prevent a tail call to GetProgramCounter(). - const void* volatile program_counter = GetProgramCounter(); - return program_counter; -} - -// static -void TargetThread::OtherLibraryCallback(void* arg) { - const TargetFunctionArgs* args = static_cast<TargetFunctionArgs*>(arg); - SignalAndWaitUntilSignaled(args->thread_started_event, args->finish_event, - args->stack_config); // Prevent tail call. volatile int i = 0; ALLOW_UNUSED_LOCAL(i); } -// static +// Calls into |wait_for_sample| through a function within another library, to +// test unwinding through multiple modules and scenarios involving unloaded +// modules. // Disable inlining for this function so that it gets its own stack frame. -NOINLINE const void* TargetThread::GetProgramCounter() { -#if defined(OS_WIN) - return _ReturnAddress(); -#else - return __builtin_return_address(0); -#endif +NOINLINE FunctionAddressRange +CallThroughOtherLibrary(NativeLibrary library, const Closure& wait_for_sample) { + const void* start_program_counter = GetProgramCounter(); + + if (!wait_for_sample.is_null()) { + // A function whose arguments are a function accepting void*, and a void*. + using InvokeCallbackFunction = void (*)(void (*)(void*), void*); + EXPECT_TRUE(library); + InvokeCallbackFunction function = reinterpret_cast<InvokeCallbackFunction>( + GetFunctionPointerFromNativeLibrary(library, "InvokeCallbackFunction")); + EXPECT_TRUE(function); + + // This copy avoids the need for a const_cast. + Closure wait_for_sample_copy = wait_for_sample; + (*function)(&OtherLibraryCallback, &wait_for_sample_copy); + } + + // Volatile to prevent a tail call to GetProgramCounter(). + const void* volatile end_program_counter = GetProgramCounter(); + return {start_program_counter, end_program_counter}; +} + +// Formats a sample into a string that can be output for test diagnostics. +std::string FormatSampleForDiagnosticOutput(const Frames& frames) { + std::string output; + for (const auto& frame : frames) { + output += StringPrintf( + "0x%p %s\n", reinterpret_cast<const void*>(frame.instruction_pointer), + frame.module ? frame.module->GetDebugBasename().AsUTF8Unsafe().c_str() + : "null module"); + } + return output; +} + +// Expects that the stack contains the functions with the specified address +// ranges, in the specified order. +void ExpectStackContains(const Frames& stack, + const std::vector<FunctionAddressRange>& functions) { + auto frame_it = stack.begin(); + auto function_it = functions.begin(); + for (; frame_it != stack.end() && function_it != functions.end(); + ++frame_it) { + if (frame_it->instruction_pointer >= + reinterpret_cast<uintptr_t>(function_it->start) && + frame_it->instruction_pointer <= + reinterpret_cast<uintptr_t>(function_it->end)) { + ++function_it; + } + } + + EXPECT_EQ(function_it, functions.end()) + << "Function in position " << function_it - functions.begin() << " at " + << function_it->start << " was not found in stack " + << "(or did not appear in the expected order):\n" + << FormatSampleForDiagnosticOutput(stack); +} + +// Expects that the stack does not contain the functions with the specified +// address ranges. +void ExpectStackDoesNotContain( + const Frames& stack, + const std::vector<FunctionAddressRange>& functions) { + struct FunctionAddressRangeCompare { + bool operator()(const FunctionAddressRange& a, + const FunctionAddressRange& b) const { + return std::make_pair(a.start, a.end) < std::make_pair(b.start, b.end); + } + }; + + std::set<FunctionAddressRange, FunctionAddressRangeCompare> seen_functions; + for (const auto frame : stack) { + for (const auto function : functions) { + if (frame.instruction_pointer >= + reinterpret_cast<uintptr_t>(function.start) && + frame.instruction_pointer <= + reinterpret_cast<uintptr_t>(function.end)) { + seen_functions.insert(function); + } + } + } + + for (const auto function : seen_functions) { + ADD_FAILURE() << "Function at " << function.start + << " was unexpectedly found in stack:\n" + << FormatSampleForDiagnosticOutput(stack); + } } // Profile consists of a set of frame sets and other sampling information. @@ -437,28 +496,32 @@ #endif } -// Executes the function with the target thread running and executing within -// SignalAndWaitUntilSignaled(). Performs all necessary target thread startup -// and shutdown work before and afterward. -template <class Function> -void WithTargetThread(Function function, - const StackConfiguration& stack_config) { - TargetThread target_thread(stack_config); +// Executes ProfileFunction while ThreadFunction is running on the target +// thread. Performs all necessary target thread startup and shutdown work before +// and afterward. +template <class ProfileFunction> +void WithTargetThread(UnwindScenario* scenario, + ProfileFunction profile_function) { + UnwindScenario::SampleEvents events; + TargetThread target_thread( + BindLambdaForTesting([&]() { scenario->Execute(&events); })); + PlatformThreadHandle target_thread_handle; EXPECT_TRUE(PlatformThread::Create(0, &target_thread, &target_thread_handle)); - target_thread.WaitForThreadStart(); + events.ready_for_sample.Wait(); - function(target_thread.id()); + profile_function(target_thread.id()); - target_thread.SignalThreadToFinish(); + events.sample_finished.Signal(); PlatformThread::Join(target_thread_handle); } -template <class Function> -void WithTargetThread(Function function) { - WithTargetThread(function, StackConfiguration(StackConfiguration::NORMAL)); +template <class ProfileFunction> +void WithTargetThread(ProfileFunction profile_function) { + UnwindScenario scenario(BindRepeating(&CallWithPlainFunction)); + WithTargetThread(&scenario, profile_function); } struct TestProfilerInfo { @@ -536,60 +599,6 @@ sampling_completed_rawptrs.size()); } -// If this executable was linked with /INCREMENTAL (the default for non-official -// debug and release builds on Windows), function addresses do not correspond to -// function code itself, but instead to instructions in the Incremental Link -// Table that jump to the functions. Checks for a jump instruction and if -// present does a little decompilation to find the function's actual starting -// address. -const void* MaybeFixupFunctionAddressForILT(const void* function_address) { -#if defined(_WIN64) - const unsigned char* opcode = - reinterpret_cast<const unsigned char*>(function_address); - if (*opcode == 0xe9) { - // This is a relative jump instruction. Assume we're in the ILT and compute - // the function start address from the instruction offset. - const int32_t* offset = reinterpret_cast<const int32_t*>(opcode + 1); - const unsigned char* next_instruction = - reinterpret_cast<const unsigned char*>(offset + 1); - return next_instruction + *offset; - } -#endif - return function_address; -} - -// Searches through the frames in |sample|, returning an iterator to the first -// frame that has an instruction pointer within |target_function|. Returns -// sample.end() if no such frames are found. -Frames::const_iterator FindFirstFrameWithinFunction( - const Frames& frames, - TargetFunction target_function) { - uintptr_t function_start = - reinterpret_cast<uintptr_t>(MaybeFixupFunctionAddressForILT( - reinterpret_cast<const void*>(target_function))); - uintptr_t function_end = - reinterpret_cast<uintptr_t>(target_function(nullptr, nullptr, nullptr)); - for (auto it = frames.begin(); it != frames.end(); ++it) { - if (it->instruction_pointer >= function_start && - it->instruction_pointer <= function_end) { - return it; - } - } - return frames.end(); -} - -// Formats a sample into a string that can be output for test diagnostics. -std::string FormatSampleForDiagnosticOutput(const Frames& frames) { - std::string output; - for (const auto& frame : frames) { - output += StringPrintf( - "0x%p %s\n", reinterpret_cast<const void*>(frame.instruction_pointer), - frame.module ? frame.module->GetDebugBasename().AsUTF8Unsafe().c_str() - : "null module"); - } - return output; -} - // Returns a duration that is longer than the test timeout. We would use // TimeDelta::Max() but https://crbug.com/465948. TimeDelta AVeryLongTimeDelta() { @@ -629,13 +638,18 @@ params.samples_per_profile = 1; NativeLibrary other_library = LoadOtherLibrary(); - TargetThread target_thread(StackConfiguration( - StackConfiguration::WITH_OTHER_LIBRARY, other_library)); + + UnwindScenario scenario( + BindRepeating(&CallThroughOtherLibrary, Unretained(other_library))); + + UnwindScenario::SampleEvents events; + TargetThread target_thread( + BindLambdaForTesting([&]() { scenario.Execute(&events); })); PlatformThreadHandle target_thread_handle; EXPECT_TRUE(PlatformThread::Create(0, &target_thread, &target_thread_handle)); - target_thread.WaitForThreadStart(); + events.ready_for_sample.Wait(); WaitableEvent sampling_thread_completed( WaitableEvent::ResetPolicy::MANUAL, @@ -666,7 +680,7 @@ // Cause the target thread to finish, so that it's no longer executing code in // the library we're about to unload. - target_thread.SignalThreadToFinish(); + events.sample_finished.Signal(); PlatformThread::Join(target_thread_handle); // Unload the library now that it's not being used. @@ -686,80 +700,40 @@ ASSERT_EQ(1u, profile.frame_sets.size()); const Frames& frames = profile.frame_sets[0]; - // Check that the stack contains a frame for - // TargetThread::SignalAndWaitUntilSignaled(). - auto end_frame = FindFirstFrameWithinFunction( - frames, &TargetThread::SignalAndWaitUntilSignaled); - ASSERT_TRUE(end_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT(reinterpret_cast<const void*>( - &TargetThread::SignalAndWaitUntilSignaled)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - if (wait_until_unloaded) { - // The stack should look like this, resulting one frame after - // SignalAndWaitUntilSignaled. The frame in the now-unloaded library should - // have a null module. + // We expect the stack to look something like this, with the frame in the + // now-unloaded library having a null module. // // ... WaitableEvent and system frames ... - // TargetThread::SignalAndWaitUntilSignaled + // WaitForSample() // TargetThread::OtherLibraryCallback // <frame in unloaded library> - EXPECT_EQ(3, frames.end() - end_frame) - << "Stack:\n" - << FormatSampleForDiagnosticOutput(frames); EXPECT_EQ(nullptr, frames.back().module) << "Stack:\n" << FormatSampleForDiagnosticOutput(frames); + + ExpectStackContains(frames, {scenario.GetWaitForSampleAddressRange()}); + ExpectStackDoesNotContain(frames, + {scenario.GetSetupFunctionAddressRange(), + scenario.GetOuterFunctionAddressRange()}); } else { // We didn't wait for the asynchronous unloading to complete, so the results // are non-deterministic: if the library finished unloading we should have // the same stack as |wait_until_unloaded|, if not we should have the full // stack. The important thing is that we should not crash. - if (frames.end() - end_frame == 3) { + if (!frames.back().module) { // This is the same case as |wait_until_unloaded|. + ExpectStackContains(frames, {scenario.GetWaitForSampleAddressRange()}); + ExpectStackDoesNotContain(frames, + {scenario.GetSetupFunctionAddressRange(), + scenario.GetOuterFunctionAddressRange()}); return; } - // Check that the stack contains a frame for - // TargetThread::CallThroughOtherLibrary(). - auto other_library_frame = FindFirstFrameWithinFunction( - frames, &TargetThread::CallThroughOtherLibrary); - ASSERT_TRUE(other_library_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT(reinterpret_cast<const void*>( - &TargetThread::CallThroughOtherLibrary)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // Check that the stack contains a frame for - // TargetThread::InvokeSetupFunction(). - auto invoker_frame = FindFirstFrameWithinFunction( - frames, &TargetThread::InvokeSetupFunction); - ASSERT_TRUE(invoker_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT(reinterpret_cast<const void*>( - &TargetThread::InvokeSetupFunction)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // The stack should look like this, resulting in three frames between - // SignalAndWaitUntilSignaled and CallThroughOtherLibrary: - // - // ... WaitableEvent and system frames ... - // TargetThread::SignalAndWaitUntilSignaled - // TargetThread::OtherLibraryCallback - // InvokeCallbackFunction (in other library) - // TargetThread::CallThroughOtherLibrary - // TargetThread::InvokeSetupFunction - EXPECT_EQ(4, invoker_frame - end_frame) - << "Stack:\n" - << FormatSampleForDiagnosticOutput(frames); - EXPECT_EQ(1, invoker_frame - other_library_frame) - << "Stack:\n" - << FormatSampleForDiagnosticOutput(frames); + ExpectStackContains(frames, {scenario.GetWaitForSampleAddressRange(), + scenario.GetSetupFunctionAddressRange(), + scenario.GetOuterFunctionAddressRange()}); } } @@ -803,38 +777,38 @@ params.sampling_interval = TimeDelta::FromMilliseconds(0); params.samples_per_profile = 1; - FrameSets frame_sets = - CaptureFrameSets(params, AVeryLongTimeDelta(), module_cache()); + UnwindScenario scenario(BindRepeating(&CallWithPlainFunction)); + + Profile profile; + WithTargetThread(&scenario, [&](PlatformThreadId target_thread_id) { + WaitableEvent sampling_thread_completed( + WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + StackSamplingProfiler profiler( + target_thread_id, params, + std::make_unique<TestProfileBuilder>( + module_cache(), + BindLambdaForTesting( + [&profile, &sampling_thread_completed](Profile result_profile) { + profile = std::move(result_profile); + sampling_thread_completed.Signal(); + }))); + profiler.Start(); + sampling_thread_completed.Wait(); + }); // Check that the size of the frame sets are correct. - ASSERT_EQ(1u, frame_sets.size()); - const Frames& frames = frame_sets[0]; + ASSERT_EQ(1u, profile.frame_sets.size()); + const Frames& frames = profile.frame_sets[0]; // Check that all the modules are valid. for (const auto& frame : frames) EXPECT_NE(nullptr, frame.module); - // Check that the stack contains a frame for - // TargetThread::SignalAndWaitUntilSignaled(). - auto end_frame = FindFirstFrameWithinFunction( - frames, &TargetThread::SignalAndWaitUntilSignaled); - ASSERT_TRUE(end_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT(reinterpret_cast<const void*>( - &TargetThread::SignalAndWaitUntilSignaled)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // Check that the stack contains a frame for - // TargetThread::InvokeSetupFunction(). - auto invoker_frame = - FindFirstFrameWithinFunction(frames, &TargetThread::InvokeSetupFunction); - ASSERT_TRUE(invoker_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT( - reinterpret_cast<const void*>(&TargetThread::InvokeSetupFunction)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); + // The stack should contain a full unwind. + ExpectStackContains(frames, {scenario.GetWaitForSampleAddressRange(), + scenario.GetSetupFunctionAddressRange(), + scenario.GetOuterFunctionAddressRange()}); } // Checks that the profiler handles stacks containing dynamically-allocated @@ -850,9 +824,11 @@ params.sampling_interval = TimeDelta::FromMilliseconds(0); params.samples_per_profile = 1; + UnwindScenario scenario(BindRepeating(&CallWithAlloca)); + Profile profile; WithTargetThread( - [&](PlatformThreadId target_thread_id) { + &scenario, [&](PlatformThreadId target_thread_id) { WaitableEvent sampling_thread_completed( WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); @@ -867,52 +843,16 @@ }))); profiler.Start(); sampling_thread_completed.Wait(); - }, - StackConfiguration(StackConfiguration::WITH_ALLOCA)); + }); // Look up the frames. ASSERT_EQ(1u, profile.frame_sets.size()); const Frames& frames = profile.frame_sets[0]; - // Check that the stack contains a frame for - // TargetThread::SignalAndWaitUntilSignaled(). - auto end_frame = FindFirstFrameWithinFunction( - frames, &TargetThread::SignalAndWaitUntilSignaled); - ASSERT_TRUE(end_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT(reinterpret_cast<const void*>( - &TargetThread::SignalAndWaitUntilSignaled)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // Check that the stack contains a frame for TargetThread::CallWithAlloca(). - auto alloca_frame = - FindFirstFrameWithinFunction(frames, &TargetThread::CallWithAlloca); - ASSERT_TRUE(alloca_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT( - reinterpret_cast<const void*>(&TargetThread::CallWithAlloca)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // Check that the stack contains a frame for - // TargetThread::InvokeSetupFunction(). - auto invoker_frame = - FindFirstFrameWithinFunction(frames, &TargetThread::InvokeSetupFunction); - ASSERT_TRUE(invoker_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT( - reinterpret_cast<const void*>(&TargetThread::InvokeSetupFunction)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // These frames should be adjacent on the stack. - EXPECT_EQ(1, alloca_frame - end_frame) - << "Stack:\n" - << FormatSampleForDiagnosticOutput(frames); - EXPECT_EQ(1, invoker_frame - alloca_frame) - << "Stack:\n" - << FormatSampleForDiagnosticOutput(frames); + // The stack should contain a full unwind. + ExpectStackContains(frames, {scenario.GetWaitForSampleAddressRange(), + scenario.GetSetupFunctionAddressRange(), + scenario.GetOuterFunctionAddressRange()}); } // Checks that a profiler can stop/destruct without ever having started. @@ -1383,81 +1323,36 @@ params.samples_per_profile = 1; Profile profile; - { - ScopedNativeLibrary other_library(LoadOtherLibrary()); - WithTargetThread( - [&, this](PlatformThreadId target_thread_id) { - WaitableEvent sampling_thread_completed( - WaitableEvent::ResetPolicy::MANUAL, - WaitableEvent::InitialState::NOT_SIGNALED); - StackSamplingProfiler profiler( - target_thread_id, params, - std::make_unique<TestProfileBuilder>( - module_cache(), - BindLambdaForTesting([&profile, &sampling_thread_completed]( - Profile result_profile) { - profile = std::move(result_profile); - sampling_thread_completed.Signal(); - }))); - profiler.Start(); - sampling_thread_completed.Wait(); - }, - StackConfiguration(StackConfiguration::WITH_OTHER_LIBRARY, - other_library.get())); - } + + ScopedNativeLibrary other_library(LoadOtherLibrary()); + UnwindScenario scenario( + BindRepeating(&CallThroughOtherLibrary, Unretained(other_library.get()))); + + WithTargetThread(&scenario, [&, this](PlatformThreadId target_thread_id) { + WaitableEvent sampling_thread_completed( + WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + StackSamplingProfiler profiler( + target_thread_id, params, + std::make_unique<TestProfileBuilder>( + module_cache(), + BindLambdaForTesting( + [&profile, &sampling_thread_completed](Profile result_profile) { + profile = std::move(result_profile); + sampling_thread_completed.Signal(); + }))); + profiler.Start(); + sampling_thread_completed.Wait(); + }); // Look up the frames. ASSERT_EQ(1u, profile.frame_sets.size()); const Frames& frames = profile.frame_sets[0]; - // Check that the stack contains a frame for - // TargetThread::CallThroughOtherLibrary(). - auto other_library_frame = FindFirstFrameWithinFunction( - frames, &TargetThread::CallThroughOtherLibrary); - ASSERT_TRUE(other_library_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT(reinterpret_cast<const void*>( - &TargetThread::CallThroughOtherLibrary)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // Check that the stack contains a frame for - // TargetThread::SignalAndWaitUntilSignaled(). - auto end_frame = FindFirstFrameWithinFunction( - frames, &TargetThread::SignalAndWaitUntilSignaled); - ASSERT_TRUE(end_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT(reinterpret_cast<const void*>( - &TargetThread::SignalAndWaitUntilSignaled)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // Check that the stack contains a frame for - // TargetThread::InvokeSetupFunction(). - auto invoker_frame = - FindFirstFrameWithinFunction(frames, &TargetThread::InvokeSetupFunction); - ASSERT_TRUE(invoker_frame != frames.end()) - << "Function at " - << MaybeFixupFunctionAddressForILT( - reinterpret_cast<const void*>(&TargetThread::InvokeSetupFunction)) - << " was not found in stack:\n" - << FormatSampleForDiagnosticOutput(frames); - - // The stack should look like this, resulting in three frames between - // SignalAndWaitUntilSignaled and CallThroughOtherLibrary: - // - // ... WaitableEvent and system frames ... - // TargetThread::SignalAndWaitUntilSignaled - // TargetThread::OtherLibraryCallback - // InvokeCallbackFunction (in other library) - // TargetThread::CallThroughOtherLibrary - // TargetThread::InvokeSetupFunction - EXPECT_EQ(3, other_library_frame - end_frame) - << "Stack:\n" - << FormatSampleForDiagnosticOutput(frames); - EXPECT_EQ(1, invoker_frame - other_library_frame) - << "Stack:\n" - << FormatSampleForDiagnosticOutput(frames); + // The stack should contain a full unwind. + ExpectStackContains(frames, {scenario.GetWaitForSampleAddressRange(), + scenario.GetSetupFunctionAddressRange(), + scenario.GetOuterFunctionAddressRange()}); } // Checks that a stack that runs through a library that is unloading produces a @@ -1486,17 +1381,24 @@ // Checks that different threads can be sampled in parallel. PROFILER_TEST_F(StackSamplingProfilerTest, MultipleSampledThreads) { - // Create target threads. The extra parethesis around the StackConfiguration - // call are to avoid the most-vexing-parse problem. - TargetThread target_thread1((StackConfiguration(StackConfiguration::NORMAL))); - TargetThread target_thread2((StackConfiguration(StackConfiguration::NORMAL))); - PlatformThreadHandle target_thread_handle1, target_thread_handle2; + UnwindScenario scenario1(BindRepeating(&CallWithPlainFunction)); + UnwindScenario::SampleEvents events1; + TargetThread target_thread1( + BindLambdaForTesting([&]() { scenario1.Execute(&events1); })); + PlatformThreadHandle target_thread_handle1; EXPECT_TRUE( PlatformThread::Create(0, &target_thread1, &target_thread_handle1)); + events1.ready_for_sample.Wait(); + + UnwindScenario scenario2(BindRepeating(&CallWithPlainFunction)); + UnwindScenario::SampleEvents events2; + TargetThread target_thread2( + BindLambdaForTesting([&]() { scenario2.Execute(&events2); })); + + PlatformThreadHandle target_thread_handle2; EXPECT_TRUE( PlatformThread::Create(0, &target_thread2, &target_thread_handle2)); - target_thread1.WaitForThreadStart(); - target_thread2.WaitForThreadStart(); + events2.ready_for_sample.Wait(); // Providing an initial delay makes it more likely that both will be // scheduled before either starts to run. Once started, samples will @@ -1546,8 +1448,8 @@ EXPECT_EQ(9u, profile1.frame_sets.size()); EXPECT_EQ(8u, profile2.frame_sets.size()); - target_thread1.SignalThreadToFinish(); - target_thread2.SignalThreadToFinish(); + events1.sample_finished.Signal(); + events2.sample_finished.Signal(); PlatformThread::Join(target_thread_handle1); PlatformThread::Join(target_thread_handle2); }
diff --git a/base/task/task_scheduler/OWNERS b/base/task/task_scheduler/OWNERS deleted file mode 100644 index d37bf7ea..0000000 --- a/base/task/task_scheduler/OWNERS +++ /dev/null
@@ -1,8 +0,0 @@ -# TODO: Remove this (had to keep it during move because of buggy presubmit) - -fdoray@chromium.org -gab@chromium.org -robliao@chromium.org - -# TEAM: scheduler-dev@chromium.org -# COMPONENT: Internals>ThreadPool
diff --git a/base/task/thread_pool/OWNERS b/base/task/thread_pool/OWNERS index b956a61..c32490a 100644 --- a/base/task/thread_pool/OWNERS +++ b/base/task/thread_pool/OWNERS
@@ -4,4 +4,3 @@ # TEAM: scheduler-dev@chromium.org # COMPONENT: Internals>ThreadPool -# TODO(gab): Rename component to ThreadPool
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index d2e2e4f..4ba6bc4 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8915423448712991328 \ No newline at end of file +8915396245975155376 \ No newline at end of file
diff --git a/cc/scheduler/scheduler_state_machine.cc b/cc/scheduler/scheduler_state_machine.cc index a4433d4..29479c7d 100644 --- a/cc/scheduler/scheduler_state_machine.cc +++ b/cc/scheduler/scheduler_state_machine.cc
@@ -365,11 +365,6 @@ if (forced_redraw_state_ == ForcedRedrawOnTimeoutState::WAITING_FOR_DRAW) return true; - // Delay draws when we have pending animation worklet updates to give them - // time to produce output before we draw. - if (processing_animation_worklets_for_active_tree_) - return false; - return needs_redraw_; }
diff --git a/cc/scheduler/scheduler_state_machine_unittest.cc b/cc/scheduler/scheduler_state_machine_unittest.cc index 489cd110..676b83e 100644 --- a/cc/scheduler/scheduler_state_machine_unittest.cc +++ b/cc/scheduler/scheduler_state_machine_unittest.cc
@@ -2725,7 +2725,7 @@ EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::Action::ACTIVATE_SYNC_TREE); } -TEST(SchedulerStateMachineTest, BlockDrawIfAnimationWorkletsPending) { +TEST(SchedulerStateMachineTest, DelayDrawIfAnimationWorkletsPending) { SchedulerSettings default_scheduler_settings; StateMachine state(default_scheduler_settings); SET_UP_STATE(state) @@ -2774,6 +2774,8 @@ EXPECT_EQ(SchedulerStateMachine::BeginImplFrameDeadlineMode::IMMEDIATE, state.CurrentBeginImplFrameDeadlineMode()); + // AnimationWorkletState does not effect CanDraw, only whether an early draw + // deadline should be used (crbug/937975). state.SetNeedsRedraw(true); state.OnBeginImplFrameDeadline(); EXPECT_IMPL_FRAME_STATE( @@ -2782,7 +2784,7 @@ state.NotifyAnimationWorkletStateChange( SchedulerStateMachine::AnimationWorkletState::PROCESSING, SchedulerStateMachine::TreeType::ACTIVE); - EXPECT_FALSE(state.ShouldDraw()); + EXPECT_TRUE(state.ShouldDraw()); state.NotifyAnimationWorkletStateChange( SchedulerStateMachine::AnimationWorkletState::IDLE, SchedulerStateMachine::TreeType::ACTIVE);
diff --git a/chrome/android/chrome_test_java_sources.gni b/chrome/android/chrome_test_java_sources.gni index 81da070e..b79e489 100644 --- a/chrome/android/chrome_test_java_sources.gni +++ b/chrome/android/chrome_test_java_sources.gni
@@ -134,6 +134,7 @@ "javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleMetricsTest.java", "javatests/src/org/chromium/chrome/browser/datareduction/DataReductionPromoUtilsTest.java", "javatests/src/org/chromium/chrome/browser/datareduction/DataReductionSavingsMilestonePromoTest.java", + "javatests/src/org/chromium/chrome/browser/dependency_injection/ModuleOverridesRule.java", "javatests/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionStatsPreferenceTest.java", "javatests/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTest.java", "javatests/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTestRule.java",
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiToolbarView.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiToolbarView.java index 5577bda..a2ec9d73 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiToolbarView.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiToolbarView.java
@@ -6,13 +6,13 @@ import android.content.Context; import android.content.res.ColorStateList; -import android.support.v4.graphics.drawable.DrawableCompat; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; +import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.ui.widget.ChromeImageView; @@ -76,8 +76,8 @@ } void setTint(ColorStateList tint) { - DrawableCompat.setTintList(mLeftButton.getDrawable(), tint); - DrawableCompat.setTintList(mRightButton.getDrawable(), tint); + ApiCompatibilityUtils.setImageTintList(mLeftButton, tint); + ApiCompatibilityUtils.setImageTintList(mRightButton, tint); if (mTitleTextView != null) mTitleTextView.setTextColor(tint); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java index 77466515..3e00c010 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java
@@ -383,6 +383,9 @@ } else if (requiresHiddenSheet(extensionState)) { mKeyboardAccessory.closeActiveTab(); mAccessorySheet.hide(); + // The compositor should relayout the view when the sheet is hidden. This is necessary + // to trigger events that rely on the relayout (like toggling the overview button): + mActivity.getCompositorViewHolder().requestLayout(); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ModuleFactoryOverrides.java b/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ModuleFactoryOverrides.java index b3630c4..c3fa79e56 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ModuleFactoryOverrides.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/ModuleFactoryOverrides.java
@@ -10,7 +10,7 @@ import java.util.Map; /** - * This class is for overriding factories of Modules in tests. + * This class is for overriding factories of Modules in tests. See also ModuleOverridesRule. * * The chosen approach for substituting dagger bindings in integrational tests is to override * Modules, without touching Components. Substituting the entire structure of Components in each @@ -32,7 +32,7 @@ private static Map<Class<?>, Object> sOverrides; /** Override the Module factory of specified type. */ - public static <T> void setOverride(Class<T> factoryClass, T override) { + static void setOverride(Class<?> factoryClass, Object override) { if (sOverrides == null) { sOverrides = new HashMap<>(); } @@ -40,7 +40,7 @@ } /** Clear all overrides */ - public static void clearOverrides() { + static void clearOverrides() { sOverrides = null; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS index d5bee6b2..ac207d2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/OWNERS
@@ -1,4 +1,6 @@ dominickn@chromium.org mlamouri@chromium.org +peconn@chromium.org +peter@chromium.org -# COMPONENT: Content>WebApps +# COMPONENT: UI>Browser>WebAppInstalls
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsTest.java index 7c23497..a6951b8 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsTest.java
@@ -22,6 +22,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.runner.RunWith; @@ -38,7 +39,7 @@ import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.contextual_suggestions.ContextualSuggestionsModel.PropertyKey; import org.chromium.chrome.browser.dependency_injection.ChromeAppModule; -import org.chromium.chrome.browser.dependency_injection.ModuleFactoryOverrides; +import org.chromium.chrome.browser.dependency_injection.ModuleOverridesRule; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.fullscreen.FullscreenManagerTestUtils; import org.chromium.chrome.browser.multiwindow.MultiWindowTestHelper; @@ -84,8 +85,17 @@ @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) @CommandLineFlags.Add(ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE) public class ContextualSuggestionsTest { + private final TestRule mModuleOverridesRule = new ModuleOverridesRule() + .setOverride(ContextualSuggestionsModuleForTest.Factory.class, + ContextualSuggestionsModuleForTest::new) + .setOverride(ChromeAppModule.Factory.class, ChromeAppModuleForTest::new); + + private final ChromeTabbedActivityTestRule mActivityTestRule = + new ChromeTabbedActivityTestRule(); + @Rule - public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); + public TestRule mOverrideModulesThenLaunchRule = + RuleChain.outerRule(mModuleOverridesRule).around(mActivityTestRule); @Rule public ScreenShooter mScreenShooter = new ScreenShooter(); @Rule @@ -141,11 +151,6 @@ @Before public void setUp() throws Exception { - ModuleFactoryOverrides.setOverride(ContextualSuggestionsModuleForTest.Factory.class, - ContextualSuggestionsModuleForTest::new); - ModuleFactoryOverrides.setOverride( - ChromeAppModule.Factory.class, ChromeAppModuleForTest::new); - FetchHelper.setDisableDelayForTesting(true); ContextualSuggestionsMediator.setOverrideIPHTimeoutForTesting(true); @@ -183,7 +188,6 @@ mTestServer.stopAndDestroyServer(); FetchHelper.setDisableDelayForTesting(false); ContextualSuggestionsMediator.setOverrideIPHTimeoutForTesting(false); - ModuleFactoryOverrides.clearOverrides(); } @Test
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java index d86e131..310e441 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java
@@ -90,7 +90,6 @@ import org.chromium.chrome.browser.browserservices.Origin; import org.chromium.chrome.browser.browserservices.OriginVerifier; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController.FinishReason; -import org.chromium.chrome.browser.dependency_injection.ModuleFactoryOverrides; import org.chromium.chrome.browser.document.ChromeLauncherActivity; import org.chromium.chrome.browser.firstrun.FirstRunStatus; import org.chromium.chrome.browser.history.BrowsingHistoryBridge; @@ -242,8 +241,6 @@ if (handler != null) handler.hideAppMenu(); }); mWebServer.shutdown(); - - ModuleFactoryOverrides.clearOverrides(); } private CustomTabActivity getActivity() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleNavigationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleNavigationTest.java index 59cf764..6fb583bb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleNavigationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleNavigationTest.java
@@ -14,6 +14,8 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.RuleChain; +import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.chromium.base.library_loader.LibraryLoader; @@ -28,9 +30,10 @@ import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.customtabs.CustomTabActivity; import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; +import org.chromium.chrome.browser.customtabs.dynamicmodule.CustomTabsDynamicModuleTestUtils.AppHooksModuleForTest; import org.chromium.chrome.browser.customtabs.dynamicmodule.CustomTabsDynamicModuleTestUtils.FakeCCTActivityDelegate; import org.chromium.chrome.browser.customtabs.dynamicmodule.CustomTabsDynamicModuleTestUtils.IntentBuilder; -import org.chromium.chrome.browser.dependency_injection.ModuleFactoryOverrides; +import org.chromium.chrome.browser.dependency_injection.ModuleOverridesRule; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeJUnit4RunnerDelegate; import org.chromium.chrome.test.util.browser.Features.DisableFeatures; @@ -53,8 +56,15 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, ContentSwitches.HOST_RESOLVER_RULES + "=MAP * 127.0.0.1", "ignore-certificate-errors"}) public class CustomTabsDynamicModuleNavigationTest { + + private final TestRule mModuleOverridesRule = new ModuleOverridesRule() + .setOverride(AppHooksModule.Factory.class, AppHooksModuleForTest::new); + + private final CustomTabActivityTestRule mActivityRule = new CustomTabActivityTestRule(); + @Rule - public CustomTabActivityTestRule mActivityRule = new CustomTabActivityTestRule(); + public final TestRule mOverrideModulesThenLaunchRule = + RuleChain.outerRule(mModuleOverridesRule).around(mActivityRule); private String mTestPage; private String mTestPage2; @@ -76,9 +86,6 @@ public void setUp() throws Exception { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); - ModuleFactoryOverrides.setOverride(AppHooksModule.Factory.class, - CustomTabsDynamicModuleTestUtils.AppHooksModuleForTest::new); - // Module managed hosts only work with HTTPS. mTestServer = EmbeddedTestServer.createAndStartHTTPSServer( InstrumentationRegistry.getInstrumentation().getContext(), @@ -98,7 +105,6 @@ @After public void tearDown() { mTestServer.stopAndDestroyServer(); - ModuleFactoryOverrides.clearOverrides(); DynamicModuleCoordinator.setAllowNonStandardPortNumber(false); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModulePostMessageTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModulePostMessageTest.java index 9ed6b4c..f8e36c76 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModulePostMessageTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModulePostMessageTest.java
@@ -20,6 +20,8 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.RuleChain; +import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.chromium.base.library_loader.LibraryLoader; @@ -31,8 +33,9 @@ import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.customtabs.CustomTabActivity; import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; +import org.chromium.chrome.browser.customtabs.dynamicmodule.CustomTabsDynamicModuleTestUtils.AppHooksModuleForTest; import org.chromium.chrome.browser.customtabs.dynamicmodule.CustomTabsDynamicModuleTestUtils.IntentBuilder; -import org.chromium.chrome.browser.dependency_injection.ModuleFactoryOverrides; +import org.chromium.chrome.browser.dependency_injection.ModuleOverridesRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.ChromeTabUtils; import org.chromium.chrome.test.util.browser.Features; @@ -44,8 +47,15 @@ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class CustomTabsDynamicModulePostMessageTest { + + private final TestRule mModuleOverridesRule = new ModuleOverridesRule() + .setOverride(AppHooksModule.Factory.class, AppHooksModuleForTest::new); + + private final CustomTabActivityTestRule mActivityRule = new CustomTabActivityTestRule(); + @Rule - public CustomTabActivityTestRule mActivityRule = new CustomTabActivityTestRule(); + public final TestRule mOverrideModulesThenLaunchRule = + RuleChain.outerRule(mModuleOverridesRule).around(mActivityRule); private TestWebServer mServer; @@ -82,14 +92,11 @@ public void setUp() throws Exception { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); mServer = TestWebServer.start(); - ModuleFactoryOverrides.setOverride(AppHooksModule.Factory.class, - CustomTabsDynamicModuleTestUtils.AppHooksModuleForTest::new); } @After public void tearDown() throws Exception { mServer.shutdown(); - ModuleFactoryOverrides.clearOverrides(); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleUITest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleUITest.java index 5ad0fb10..b5378d0 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleUITest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/dynamicmodule/CustomTabsDynamicModuleUITest.java
@@ -23,6 +23,8 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.RuleChain; +import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.chromium.base.ActivityState; @@ -39,8 +41,9 @@ import org.chromium.chrome.browser.customtabs.CustomTabActivity; import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; import org.chromium.chrome.browser.customtabs.CustomTabsTestUtils; +import org.chromium.chrome.browser.customtabs.dynamicmodule.CustomTabsDynamicModuleTestUtils.AppHooksModuleForTest; import org.chromium.chrome.browser.customtabs.dynamicmodule.CustomTabsDynamicModuleTestUtils.IntentBuilder; -import org.chromium.chrome.browser.dependency_injection.ModuleFactoryOverrides; +import org.chromium.chrome.browser.dependency_injection.ModuleOverridesRule; import org.chromium.chrome.browser.toolbar.top.CustomTabToolbar; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.ChromeTabUtils; @@ -66,8 +69,15 @@ // EmbeddedTestServer, running on 127.0.0.1, without a valid certificate. ContentSwitches.HOST_RESOLVER_RULES + "=MAP * 127.0.0.1", "ignore-certificate-errors"}) public class CustomTabsDynamicModuleUITest { + + private TestRule mModuleOverridesRule = new ModuleOverridesRule() + .setOverride(AppHooksModule.Factory.class, AppHooksModuleForTest::new); + + private CustomTabActivityTestRule mActivityRule = new CustomTabActivityTestRule(); + @Rule - public CustomTabActivityTestRule mActivityRule = new CustomTabActivityTestRule(); + public TestRule mOverrideModulesThenLaunchRule = + RuleChain.outerRule(mModuleOverridesRule).around(mActivityRule); private static final String TEST_PAGE = "/chrome/test/data/android/google.html"; private static final String TEST_PAGE_2 = "/chrome/test/data/android/test.html"; @@ -85,9 +95,6 @@ public void setUp() throws Exception { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); - ModuleFactoryOverrides.setOverride(AppHooksModule.Factory.class, - CustomTabsDynamicModuleTestUtils.AppHooksModuleForTest::new); - // Module managed hosts only work with HTTPS. mTestServer = EmbeddedTestServer.createAndStartHTTPSServer( InstrumentationRegistry.getInstrumentation().getContext(), @@ -104,7 +111,6 @@ @After public void tearDown() throws Exception { - ModuleFactoryOverrides.clearOverrides(); DynamicModuleCoordinator.setAllowNonStandardPortNumber(false); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/dependency_injection/ModuleOverridesRule.java b/chrome/android/javatests/src/org/chromium/chrome/browser/dependency_injection/ModuleOverridesRule.java new file mode 100644 index 0000000..34961c8d --- /dev/null +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/dependency_injection/ModuleOverridesRule.java
@@ -0,0 +1,38 @@ +// Copyright 2019 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. + +package org.chromium.chrome.browser.dependency_injection; + +import android.util.Pair; + +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; + +import java.util.ArrayList; +import java.util.List; + +/** + * A TestRule for overriding Dagger Module factories. + */ +public class ModuleOverridesRule extends TestWatcher { + private final List<Pair<Class<?>, ?>> mOverrides = new ArrayList<>(); + + /** Override the Module factory of specified type. */ + public <T> ModuleOverridesRule setOverride(Class<T> factoryClass, T override) { + mOverrides.add(new Pair<>(factoryClass, override)); + return this; + } + + @Override + protected void starting(Description description) { + for (Pair<Class<?>, ?> override : mOverrides) { + ModuleFactoryOverrides.setOverride(override.first, override.second); + } + } + + @Override + protected void finished(Description description) { + ModuleFactoryOverrides.clearOverrides(); + } +}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreferenceTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreferenceTest.java index 82ad4338..d3ef76a0 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreferenceTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreferenceTest.java
@@ -15,13 +15,15 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.RuleChain; +import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.contextual_suggestions.EmptyEnabledStateMonitor; import org.chromium.chrome.browser.contextual_suggestions.EnabledStateMonitor; import org.chromium.chrome.browser.dependency_injection.ChromeAppModule; -import org.chromium.chrome.browser.dependency_injection.ModuleFactoryOverrides; +import org.chromium.chrome.browser.dependency_injection.ModuleOverridesRule; import org.chromium.chrome.browser.test.ChromeBrowserTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.browser.Features; @@ -33,8 +35,13 @@ @RunWith(ChromeJUnit4ClassRunner.class) @Features.DisableFeatures(SEARCH_ENGINE_PROMO_EXISTING_DEVICE) public class ContextualSuggestionsPreferenceTest { + + private final TestRule mModuleOverridesRule = new ModuleOverridesRule() + .setOverride(ChromeAppModule.Factory.class, ChromeAppModuleForTest::new); + @Rule - public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule(); + public final TestRule mOverrideModulesThenLaunchRule = + RuleChain.outerRule(mModuleOverridesRule).around(new ChromeBrowserTestRule()); private ContextualSuggestionsPreference mFragment; @@ -89,9 +96,6 @@ @Before public void setUp() { - ModuleFactoryOverrides.setOverride( - ChromeAppModule.Factory.class, ChromeAppModuleForTest::new); - Preferences preferences = PreferencesTest.startPreferences(InstrumentationRegistry.getInstrumentation(), ContextualSuggestionsPreference.class.getName()); @@ -104,7 +108,6 @@ @After public void tearDown() { TestThreadUtils.runOnUiThreadBlocking(() -> setSwitchState(mInitialSwitchState)); - ModuleFactoryOverrides.clearOverrides(); } @Test
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/sync/SyncCustomizationFragmentTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/sync/SyncCustomizationFragmentTest.java index e94af485..e27c9f6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/sync/SyncCustomizationFragmentTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/sync/SyncCustomizationFragmentTest.java
@@ -362,6 +362,7 @@ @Test @SmallTest @Feature({"Sync"}) + @DisabledTest(message = "crbug.com/955490") public void testPaymentsIntegrationCheckboxClearsServerAutofillCreditCards() { mSyncTestRule.setUpTestAccountAndSignIn(); @@ -390,7 +391,7 @@ @Test @SmallTest @Feature({"Sync"}) - @DisabledTest + @DisabledTest(message = "crbug.com/951141") public void testSyncSwitchClearsServerAutofillCreditCards() { mSyncTestRule.setUpTestAccountAndSignIn();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tasks/ReturnToChromeTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tasks/ReturnToChromeTest.java index cf195df..1b2d259 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tasks/ReturnToChromeTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tasks/ReturnToChromeTest.java
@@ -22,6 +22,7 @@ import org.chromium.base.ApplicationStatus; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; @@ -75,6 +76,7 @@ @Test @SmallTest @Feature({"ReturnToChrome"}) + @DisabledTest(message = "crbug.com/955436") @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "enable-features=" + ChromeFeatureList.TAB_SWITCHER_ON_RETURN + "<FakeStudyName", "force-fieldtrials=FakeStudyName/Enabled", @@ -83,7 +85,7 @@ testObserverModeTriggeredWithDelay() throws Exception { finishActivityCompletely(); - // Sleep past the timeout + // Sleep past the timeout. SystemClock.sleep(30); mActivityTestRule.startMainActivityFromLauncher();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrArSessionTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrArSessionTest.java index a0bc349..49df1f0 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrArSessionTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/WebXrArSessionTest.java
@@ -22,6 +22,7 @@ import org.chromium.base.test.params.ParameterSet; import org.chromium.base.test.params.ParameterizedRunner; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.vr.rules.XrActivityRestriction; @@ -39,6 +40,7 @@ @UseRunnerDelegate(ChromeJUnit4RunnerDelegate.class) @CommandLineFlags. Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "enable-features=WebXR,WebXRHitTest"}) +@DisabledTest(message = "crbug.com/955447") @MinAndroidSdkLevel(Build.VERSION_CODES.N) // WebXR for AR is only supported on N+ public class WebXrArSessionTest { @ClassParameter
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java index e8bbe2f..a53d1e7 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java
@@ -69,6 +69,7 @@ import org.chromium.chrome.browser.autofill.keyboard_accessory.data.PropertyProvider; import org.chromium.chrome.browser.autofill.keyboard_accessory.sheet_component.AccessorySheetCoordinator; import org.chromium.chrome.browser.autofill.keyboard_accessory.sheet_tabs.PasswordAccessorySheetCoordinator; +import org.chromium.chrome.browser.compositor.CompositorViewHolder; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.Tab.TabHidingType; @@ -113,6 +114,8 @@ private KeyboardAccessoryCoordinator mMockKeyboardAccessory; @Mock private AccessorySheetCoordinator mMockAccessorySheet; + @Mock + private CompositorViewHolder mMockCompositorViewHolder; @Rule public Features.JUnitProcessor mFeaturesProcessor = new Features.JUnitProcessor(); @@ -267,6 +270,7 @@ when(mMockActivity.getActivityTabProvider()).thenReturn(mock(ActivityTabProvider.class)); ChromeFullscreenManager fullscreenManager = new ChromeFullscreenManager(mMockActivity, 0); when(mMockActivity.getFullscreenManager()).thenReturn(fullscreenManager); + when(mMockActivity.getCompositorViewHolder()).thenReturn(mMockCompositorViewHolder); when(mMockActivity.getResources()).thenReturn(mMockResources); when(mMockActivity.getPackageManager()) .thenReturn(RuntimeEnvironment.application.getPackageManager()); @@ -746,6 +750,7 @@ verify(mMockAccessorySheet).hide(); verify(mMockKeyboardAccessory).closeActiveTab(); verify(mMockKeyboardAccessory).dismiss(); + verify(mMockCompositorViewHolder).requestLayout(); // Triggered as if it was a keyboard. } @Test @@ -780,6 +785,7 @@ verify(mMockKeyboard).showKeyboard(any()); verify(mMockAccessorySheet).hide(); verify(mMockKeyboardAccessory).closeActiveTab(); + verify(mMockCompositorViewHolder).requestLayout(); // Triggered as if it was a keyboard. verify(mMockKeyboardAccessory).show(); }
diff --git a/chrome/android/touchless/java/res/values-v17/dimens.xml b/chrome/android/touchless/java/res/values-v17/dimens.xml index bbca39d6..65c00369 100644 --- a/chrome/android/touchless/java/res/values-v17/dimens.xml +++ b/chrome/android/touchless/java/res/values-v17/dimens.xml
@@ -4,7 +4,7 @@ found in the LICENSE file. --> <resources> <dimen name="touchless_new_tab_view_top_margin">12dp</dimen> - <dimen name="touchless_new_tab_view_padding_horizontal">12dp</dimen> + <dimen name="touchless_new_tab_view_padding_horizontal">8dp</dimen> <dimen name="notouch_tooltip_padding">8dp</dimen> <dimen name="notouch_tooltip_margin_bottom">16dp</dimen>
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 4989fa55..8f38b22 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -365,6 +365,15 @@ <message name="IDS_CONTENT_CONTEXT_INSPECTELEMENT" desc="The name of the Inspect Element command in the content area context menu"> I&nspect </message> + <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_DIALOG_TITLE" desc="The title of a dialog that asks whether to integrate the accessibility image labeling service of Google to Chrome."> + Get image descriptions from Google? + </message> + <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_BUBBLE_ENABLE" desc="The button text that allows integrating the accessibility labels service of Google. This should use the same verb as IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_SEND."> + Yes, I'm in + </message> + <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_BUBBLE_DISABLE" desc="The button text that disallows integrating the accessibility labels service of Google."> + No thanks + </message> <if expr="not use_titlecase"> <message name="IDS_CONTENT_CONTEXT_BACK" desc="The name of the Back command in the content area context menu"> &Back @@ -534,7 +543,7 @@ <message name="IDS_CONTENT_CONTEXT_ADD_TO_DICTIONARY" desc="The name of the Add to dictionary command in the content area context menu"> &Add to dictionary </message> - <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_MENU_OPTION" desc="The context-menu item that asks whether to integrate the accessibility image labeling service of Google to Chrome. This text is also used as the title of a bubble which confirms it."> + <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_MENU_OPTION" desc="The context-menu item that asks whether to integrate the accessibility image labeling service of Google to Chrome."> Get image descriptions from Google </message> <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_SEND" desc="The context-menu sub-item that asks whether to integrate the accessibility image labeling service of Google to Chrome always."> @@ -543,12 +552,6 @@ <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_SEND_ONCE" desc="The context-menu sub-item that asks whether to integrate the accessibility image labeling service of Google to Chrome, for a single use."> Just once </message> - <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_BUBBLE_ENABLE" desc="The button text that allows integrating the accessibility labels service of Google. This should use the same verb as IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_SEND."> - Yes, I'm in - </message> - <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_BUBBLE_DISABLE" desc="The button text that disallows integrating the accessibility labels service of Google."> - No thanks - </message> <message name="IDS_CONTENT_CONTEXT_SPELLING_ASK_GOOGLE" desc="The context-menu item that asks whether to integrate the spelling service of Google to Chrome."> Use enhanced spell check </message> @@ -770,7 +773,7 @@ <message name="IDS_CONTENT_CONTEXT_ADD_TO_DICTIONARY" desc="In Title Case: The name of the Add to dictionary command in the content area context menu"> &Add to Dictionary </message> - <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_MENU_OPTION" desc="The context-menu item that asks whether to integrate the accessibility image labeling service of Google to Chrome. This text is also used as the title of a bubble which confirms it."> + <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_MENU_OPTION" desc="The context-menu item that asks whether to integrate the accessibility image labeling service of Google to Chrome."> Get Image Descriptions from Google </message> <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_SEND" desc="The context-menu sub-item that asks whether to integrate the accessibility image labeling service of Google to Chrome always."> @@ -779,12 +782,6 @@ <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_SEND_ONCE" desc="The context-menu sub-item that asks whether to integrate the accessibility image labeling service of Google to Chrome, for a single use."> Just Once </message> - <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_BUBBLE_ENABLE" desc="The button text that allows integrating the accessibility labels service of Google. This should use the same verb as IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_SEND."> - Yes, I'm In - </message> - <message name="IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_BUBBLE_DISABLE" desc="The button text that disallows integrating the accessibility labels service of Google."> - No Thanks - </message> <message name="IDS_CONTENT_CONTEXT_SPELLING_ASK_GOOGLE" desc="In Title Case: The context-menu item that asks whether to integrate the spelling service of Google to Chrome."> Use Enhanced Spell Check </message>
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 4bb98a52..ee79f98 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -178,7 +178,7 @@ Get image descriptions from Google </message> <message name="IDS_SETTINGS_ACCESSIBLE_IMAGE_LABELS_SUBTITLE" desc="Subtitle for screen reader image labels feature."> - If an image doesn’t have a useful description, Chrome will provide one for you. Images are scanned by Google. + If an image doesn’t have a useful description, Chrome will try to provide one for you. To create descriptions, images are sent to Google. </message> <if expr="chromeos"> <message name="IDS_SETTINGS_OPTIONS_IN_MENU_LABEL" desc="Label for checkbox which enables showing accessibility options in the system menu.">
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 68ffba8..52b1c4b 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1315,6 +1315,8 @@ "previews/previews_lite_page_serving_url_loader.h", "previews/previews_lite_page_url_loader_interceptor.cc", "previews/previews_lite_page_url_loader_interceptor.h", + "previews/previews_offline_helper.cc", + "previews/previews_offline_helper.h", "previews/previews_service.cc", "previews/previews_service.h", "previews/previews_service_factory.cc", @@ -1516,8 +1518,6 @@ "signin/account_investigator_factory.h", "signin/account_reconcilor_factory.cc", "signin/account_reconcilor_factory.h", - "signin/account_tracker_service_factory.cc", - "signin/account_tracker_service_factory.h", "signin/chrome_device_id_helper.cc", "signin/chrome_device_id_helper.h", "signin/chrome_signin_client.cc", @@ -1797,7 +1797,7 @@ "//components/nacl/common:buildflags", "//components/payments/core", "//components/sync", - "//components/sync:device_info", + "//components/sync/device_info", "//content/public/browser", "//ipc", "//sql",
diff --git a/chrome/browser/android/preferences/website_preference_bridge.cc b/chrome/browser/android/preferences/website_preference_bridge.cc index e7e2b52..760cfa45 100644 --- a/chrome/browser/android/preferences/website_preference_bridge.cc +++ b/chrome/browser/android/preferences/website_preference_bridge.cc
@@ -269,6 +269,17 @@ } } +std::string GetChooserObjectName(ContentSettingsType type, + base::Value& object) { + switch (type) { + case CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA: + return UsbChooserContext::GetObjectName(object); + default: + NOTREACHED(); + return std::string(); + } +} + bool OriginMatcher(const url::Origin& origin, const GURL& other) { return origin == url::Origin::Create(other); } @@ -545,8 +556,9 @@ JNIEnv* env, jint content_settings_type, const JavaParamRef<jobject>& list) { - ChooserContextBase* context = GetChooserContext( - static_cast<ContentSettingsType>(content_settings_type)); + ContentSettingsType type = + static_cast<ContentSettingsType>(content_settings_type); + ChooserContextBase* context = GetChooserContext(type); for (const auto& object : context->GetAllGrantedObjects()) { // Remove the trailing slash so that origins are matched correctly in // SingleWebsitePreferences.mergePermissionInfoForTopLevelOrigin. @@ -563,7 +575,7 @@ jembedder = ConvertUTF8ToJavaString(env, embedder); ScopedJavaLocalRef<jstring> jname = - ConvertUTF8ToJavaString(env, context->GetObjectName(object->value)); + ConvertUTF8ToJavaString(env, GetChooserObjectName(type, object->value)); std::string serialized; bool written = base::JSONWriter::Write(object->value, &serialized);
diff --git a/chrome/browser/background_fetch/background_fetch_delegate_impl.cc b/chrome/browser/background_fetch/background_fetch_delegate_impl.cc index 985c6f4..f5b5a3cd 100644 --- a/chrome/browser/background_fetch/background_fetch_delegate_impl.cc +++ b/chrome/browser/background_fetch/background_fetch_delegate_impl.cc
@@ -555,9 +555,10 @@ } UpdateOfflineItemAndUpdateObservers(&job_details); - if (job_details.client) + if (job_details.client) { job_details.client->OnDownloadUpdated(job_unique_id, download_guid, bytes_uploaded, bytes_downloaded); + } } void BackgroundFetchDelegateImpl::OnDownloadFailed(
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index 367de341..6430b06 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1673,10 +1673,14 @@ "policy/server_backed_state_keys_broker.h", "policy/single_app_install_event_log.cc", "policy/single_app_install_event_log.h", + "policy/status_collector/activity_storage.cc", + "policy/status_collector/activity_storage.h", "policy/status_collector/device_status_collector.cc", "policy/status_collector/device_status_collector.h", "policy/status_collector/status_collector.cc", "policy/status_collector/status_collector.h", + "policy/status_collector/status_collector_state.cc", + "policy/status_collector/status_collector_state.h", "policy/status_uploader.cc", "policy/status_uploader.h", "policy/system_log_uploader.cc",
diff --git a/chrome/browser/chromeos/arc/intent_helper/arc_settings_service.cc b/chrome/browser/chromeos/arc/intent_helper/arc_settings_service.cc index e430278..b06ad3f8 100644 --- a/chrome/browser/chromeos/arc/intent_helper/arc_settings_service.cc +++ b/chrome/browser/chromeos/arc/intent_helper/arc_settings_service.cc
@@ -23,6 +23,7 @@ #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h" #include "chrome/common/pref_names.h" +#include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state.h" @@ -426,6 +427,11 @@ } void ArcSettingsServiceImpl::SyncFontSize() const { + // When OS settings are split from browser, don't use the browser's font size + // to change ARC++ font scale. + if (base::FeatureList::IsEnabled(chromeos::features::kSplitSettings)) + return; + int default_size = GetIntegerPref(::prefs::kWebKitDefaultFontSize); int default_fixed_size = GetIntegerPref(::prefs::kWebKitDefaultFixedFontSize); int minimum_size = GetIntegerPref(::prefs::kWebKitMinimumFontSize); @@ -440,6 +446,11 @@ } void ArcSettingsServiceImpl::SyncPageZoom() const { + // When OS settings are split from browser, don't use the browser's page zoom + // to set ARC++ application density. + if (base::FeatureList::IsEnabled(chromeos::features::kSplitSettings)) + return; + double zoom_level = profile_->GetZoomLevelPrefs()->GetDefaultZoomLevelPref(); double zoom_factor = content::ZoomLevelToZoomFactor(zoom_level);
diff --git a/chrome/browser/chromeos/arc/intent_helper/arc_settings_service_unittest.cc b/chrome/browser/chromeos/arc/intent_helper/arc_settings_service_unittest.cc index 9d0478b..de8ba2f1 100644 --- a/chrome/browser/chromeos/arc/intent_helper/arc_settings_service_unittest.cc +++ b/chrome/browser/chromeos/arc/intent_helper/arc_settings_service_unittest.cc
@@ -8,12 +8,16 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/test/scoped_feature_list.h" #include "chrome/browser/chromeos/arc/arc_optin_uma.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/settings/stats_reporting_controller.h" +#include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h" +#include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_profile.h" +#include "chromeos/constants/chromeos_features.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/network/network_handler.h" #include "components/arc/arc_prefs.h" @@ -235,4 +239,40 @@ profile()->GetPrefs()->GetBoolean(prefs::kArcInitialSettingsPending)); } +TEST_F(ArcSettingsServiceTest, SplitSettingsDisablesFontSize) { + constexpr char kSetFontScale[] = + "org.chromium.arc.intent_helper.SET_FONT_SCALE"; + + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(chromeos::features::kSplitSettings); + + // No initial broadcast. + arc_session_manager()->RequestEnable(); + SetInstances(); + FakeIntentHelperInstance* intent_helper = intent_helper_instance(); + EXPECT_EQ(0U, intent_helper->GetBroadcastsForAction(kSetFontScale).size()); + + // No broadcast after update. + profile()->GetPrefs()->SetInteger(::prefs::kWebKitDefaultFontSize, 20); + EXPECT_EQ(0U, intent_helper->GetBroadcastsForAction(kSetFontScale).size()); +} + +TEST_F(ArcSettingsServiceTest, SplitSettingsDisablesPageZoom) { + constexpr char kSetPageZoom[] = + "org.chromium.arc.intent_helper.SET_PAGE_ZOOM"; + + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(chromeos::features::kSplitSettings); + + // No initial broadcast. + arc_session_manager()->RequestEnable(); + SetInstances(); + FakeIntentHelperInstance* intent_helper = intent_helper_instance(); + EXPECT_EQ(0U, intent_helper->GetBroadcastsForAction(kSetPageZoom).size()); + + // No broadcast after update. + profile()->GetZoomLevelPrefs()->SetDefaultZoomLevelPref(150.0); + EXPECT_EQ(0U, intent_helper->GetBroadcastsForAction(kSetPageZoom).size()); +} + } // namespace arc
diff --git a/chrome/browser/chromeos/customization/customization_wallpaper_util.cc b/chrome/browser/chromeos/customization/customization_wallpaper_util.cc index 0e02406..bbab4fefb 100644 --- a/chrome/browser/chromeos/customization/customization_wallpaper_util.cc +++ b/chrome/browser/chromeos/customization/customization_wallpaper_util.cc
@@ -53,14 +53,14 @@ // Resizes and saves the customized default wallpapers. bool ResizeAndSaveCustomizedDefaultWallpaper( - std::unique_ptr<gfx::ImageSkia> image, + gfx::ImageSkia image, const base::FilePath& resized_small_path, const base::FilePath& resized_large_path) { - return SaveResizedWallpaper(*image, + return SaveResizedWallpaper(image, gfx::Size(ash::kSmallWallpaperMaxWidth, ash::kSmallWallpaperMaxHeight), resized_small_path) && - SaveResizedWallpaper(*image, + SaveResizedWallpaper(image, gfx::Size(ash::kLargeWallpaperMaxWidth, ash::kLargeWallpaperMaxHeight), resized_large_path); @@ -108,8 +108,8 @@ base::PostTaskAndReplyWithResult( task_runner.get(), FROM_HERE, base::Bind(&ResizeAndSaveCustomizedDefaultWallpaper, - base::Passed(wallpaper->image().DeepCopy()), - resized_small_path, resized_large_path), + wallpaper->image().DeepCopy(), resized_small_path, + resized_large_path), base::Bind(&OnCustomizedDefaultWallpaperResizedAndSaved, wallpaper_url, resized_small_path, resized_large_path)); }
diff --git a/chrome/browser/chromeos/login/active_directory_login_browsertest.cc b/chrome/browser/chromeos/login/active_directory_login_browsertest.cc index 867628f..43393937 100644 --- a/chrome/browser/chromeos/login/active_directory_login_browsertest.cc +++ b/chrome/browser/chromeos/login/active_directory_login_browsertest.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/authpolicy/kerberos_files_handler.h" #include "chrome/browser/chromeos/login/test/active_directory_login_mixin.h" +#include "chrome/browser/chromeos/login/test/device_state_mixin.h" #include "chrome/browser/chromeos/login/test/oobe_base_test.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chromeos/dbus/auth_policy/fake_auth_policy_client.h" @@ -71,7 +72,10 @@ const std::string test_realm_; const std::string test_user_; - ActiveDirectoryLoginMixin ad_login_{&mixin_host_, test_realm_}; + DeviceStateMixin device_state_{ + &mixin_host_, + DeviceStateMixin::State::OOBE_COMPLETED_ACTIVE_DIRECTORY_ENROLLED}; + ActiveDirectoryLoginMixin ad_login_{&mixin_host_}; private: DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryLoginTest);
diff --git a/chrome/browser/chromeos/login/enrollment/OWNERS b/chrome/browser/chromeos/login/enrollment/OWNERS index 1aeb4f3..4acefe9 100644 --- a/chrome/browser/chromeos/login/enrollment/OWNERS +++ b/chrome/browser/chromeos/login/enrollment/OWNERS
@@ -6,6 +6,5 @@ pmarko@chromium.org poromov@chromium.org rsorokin@chromium.org -tnagel@chromium.org # COMPONENT: Enterprise>Enrollment
diff --git a/chrome/browser/chromeos/login/existing_user_controller.cc b/chrome/browser/chromeos/login/existing_user_controller.cc index 1817e8c..6ecc4567 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.cc +++ b/chrome/browser/chromeos/login/existing_user_controller.cc
@@ -1109,7 +1109,9 @@ auto cloud_policy_client = std::make_unique<policy::CloudPolicyClient>( std::string() /* machine_id */, std::string() /* machine_model */, - std::string() /* brand_code */, device_management_service, + std::string() /* brand_code */, std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, device_management_service, sigin_profile_url_loader_factory, nullptr /* signing_service */, chromeos::GetDeviceDMTokenForUserPolicyGetter( user_context.GetAccountId()));
diff --git a/chrome/browser/chromeos/login/test/active_directory_login_mixin.cc b/chrome/browser/chromeos/login/test/active_directory_login_mixin.cc index a10b488..d633f515 100644 --- a/chrome/browser/chromeos/login/test/active_directory_login_mixin.cc +++ b/chrome/browser/chromeos/login/test/active_directory_login_mixin.cc
@@ -11,7 +11,6 @@ #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "chromeos/dbus/auth_policy/fake_auth_policy_client.h" -#include "chromeos/tpm/stub_install_attributes.h" #include "content/public/test/browser_test_utils.h" namespace chromeos { @@ -42,13 +41,8 @@ } // namespace ActiveDirectoryLoginMixin::ActiveDirectoryLoginMixin( - InProcessBrowserTestMixinHost* host, - const std::string& realm) - : InProcessBrowserTestMixin(host), - install_attributes_( - chromeos::StubInstallAttributes::CreateActiveDirectoryManaged( - realm, - "device_id")) {} + InProcessBrowserTestMixinHost* host) + : InProcessBrowserTestMixin(host) {} void ActiveDirectoryLoginMixin::SetUpInProcessBrowserTestFixture() { AuthPolicyClient::InitializeFake();
diff --git a/chrome/browser/chromeos/login/test/active_directory_login_mixin.h b/chrome/browser/chromeos/login/test/active_directory_login_mixin.h index 10a4f5b7..85fa9cba 100644 --- a/chrome/browser/chromeos/login/test/active_directory_login_mixin.h +++ b/chrome/browser/chromeos/login/test/active_directory_login_mixin.h
@@ -12,7 +12,6 @@ #include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" #include "chrome/browser/chromeos/policy/server_backed_state_keys_broker.h" #include "chrome/browser/policy/test/local_policy_test_server.h" -#include "chromeos/tpm/stub_install_attributes.h" #include "components/policy/proto/chrome_device_policy.pb.h" #include "components/policy/proto/device_management_backend.pb.h" #include "content/public/test/browser_test_utils.h" @@ -23,8 +22,7 @@ // password change screen. class ActiveDirectoryLoginMixin : public InProcessBrowserTestMixin { public: - explicit ActiveDirectoryLoginMixin(InProcessBrowserTestMixinHost* host, - const std::string& realm); + explicit ActiveDirectoryLoginMixin(InProcessBrowserTestMixinHost* host); ~ActiveDirectoryLoginMixin() override; // InProcessBrowserTestMixin: @@ -87,7 +85,6 @@ std::string autocomplete_realm_; std::unique_ptr<content::DOMMessageQueue> message_queue_; - chromeos::ScopedStubInstallAttributes install_attributes_; DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryLoginMixin); };
diff --git a/chrome/browser/chromeos/login/test/device_state_mixin.cc b/chrome/browser/chromeos/login/test/device_state_mixin.cc index 5e15ea8..28c9615 100644 --- a/chrome/browser/chromeos/login/test/device_state_mixin.cc +++ b/chrome/browser/chromeos/login/test/device_state_mixin.cc
@@ -21,6 +21,8 @@ constexpr char kFakeDomain[] = "example.com"; constexpr char kFakeDeviceId[] = "device_id"; +bool g_instance_created = false; + cryptohome::SerializedInstallAttributes BuildInstallAttributes( const std::string& mode, const std::string& domain, @@ -50,7 +52,10 @@ DeviceStateMixin::DeviceStateMixin(InProcessBrowserTestMixinHost* host, State initial_state) - : InProcessBrowserTestMixin(host), state_(initial_state) {} + : InProcessBrowserTestMixin(host), state_(initial_state) { + DCHECK(!g_instance_created); + g_instance_created = true; +} bool DeviceStateMixin::SetUpUserDataDirectory() { SetDeviceState(); @@ -83,8 +88,11 @@ std::string device_mode, domain, realm, device_id; switch (state_) { case DeviceStateMixin::State::BEFORE_OOBE: - case DeviceStateMixin::State::OOBE_COMPLETED_UNOWNED: + // No file at all. return; + case DeviceStateMixin::State::OOBE_COMPLETED_UNOWNED: + // Write file with empty install attributes. + break; case DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED: device_mode = "enterprise"; domain = !domain_.empty() ? domain_ : kFakeDomain;
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc index 15a748e..b573fc40 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc
@@ -27,6 +27,7 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/login_manager_test.h" #include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/test/device_state_mixin.h" #include "chrome/browser/chromeos/login/test/fake_gaia_mixin.h" #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h" #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_test_util.h" @@ -52,7 +53,6 @@ #include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" -#include "chromeos/tpm/stub_install_attributes.h" #include "components/ownership/mock_owner_key_util.h" #include "components/policy/core/common/cloud/cloud_policy_core.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" @@ -684,8 +684,8 @@ return policy; } - ScopedStubInstallAttributes test_install_attributes_{ - StubInstallAttributes::CreateCloudManaged("fake-domain", "fake-id")}; + DeviceStateMixin device_state_{ + &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; policy::UserPolicyBuilder user_policy_; policy::DevicePolicyBuilder device_policy_; scoped_refptr<ownership::MockOwnerKeyUtil> owner_key_util_;
diff --git a/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc b/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc index 86f3f889..ef0a42b0 100644 --- a/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc +++ b/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc
@@ -23,6 +23,7 @@ #include "base/threading/thread_restrictions.h" #include "chrome/browser/chromeos/login/login_manager_test.h" #include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/test/device_state_mixin.h" #include "chrome/browser/chromeos/login/test/fake_gaia_mixin.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" @@ -45,7 +46,6 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" -#include "chromeos/tpm/stub_install_attributes.h" #include "components/ownership/mock_owner_key_util.h" #include "components/policy/core/common/cloud/cloud_policy_core.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" @@ -325,9 +325,6 @@ true /* success */); } - ScopedStubInstallAttributes test_install_attributes_{ - StubInstallAttributes::CreateCloudManaged("fake-domain", "fake-id")}; - base::FilePath test_data_dir_; std::unique_ptr<base::RunLoop> run_loop_; int wallpaper_change_count_ = 0; @@ -336,6 +333,8 @@ scoped_refptr<ownership::MockOwnerKeyUtil> owner_key_util_; std::vector<AccountId> testUsers_; FakeGaiaMixin fake_gaia_{&mixin_host_, embedded_test_server()}; + DeviceStateMixin device_state_{ + &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; private: // The binding this instance uses to implement ash::mojom::WallpaperObserver. @@ -350,8 +349,7 @@ DISALLOW_COPY_AND_ASSIGN(WallpaperPolicyTest); }; -// Disabled due to flakiness: https://crbug.com/873908. -IN_PROC_BROWSER_TEST_F(WallpaperPolicyTest, DISABLED_PRE_SetResetClear) { +IN_PROC_BROWSER_TEST_F(WallpaperPolicyTest, PRE_SetResetClear) { RegisterUser(testUsers_[0]); RegisterUser(testUsers_[1]); StartupUtils::MarkOobeCompleted();
diff --git a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc index 8d5edaef..7c8e0de7 100644 --- a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc
@@ -29,6 +29,7 @@ #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/login_shelf_test_helper.h" #include "chrome/browser/chromeos/login/login_wizard.h" +#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" #include "chrome/browser/chromeos/login/oobe_screen.h" #include "chrome/browser/chromeos/login/screens/device_disabled_screen.h" #include "chrome/browser/chromeos/login/screens/error_screen.h" @@ -48,6 +49,7 @@ #include "chrome/browser/chromeos/login/screens/welcome_screen.h" #include "chrome/browser/chromeos/login/screens/wrong_hwid_screen.h" #include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/test/device_state_mixin.h" #include "chrome/browser/chromeos/login/test/oobe_configuration_waiter.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/ui/webui_login_view.h" @@ -64,7 +66,6 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" -#include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "chromeos/audio/cras_audio_handler.h" #include "chromeos/constants/chromeos_switches.h" @@ -347,18 +348,21 @@ } // namespace -class WizardControllerTest : public InProcessBrowserTest { +class WizardControllerTest : public MixinBasedInProcessBrowserTest { protected: WizardControllerTest() = default; ~WizardControllerTest() override = default; + // MixinBasedInProcessBrowserTest: void SetUpOnMainThread() override { + MixinBasedInProcessBrowserTest::SetUpOnMainThread(); AccessibilityManager::Get()->SetProfileForTest( ProfileHelper::GetSigninProfile()); ShowLoginWizard(OobeScreen::SCREEN_TEST_NO_WINDOW); } void SetUpCommandLine(base::CommandLine* command_line) override { + MixinBasedInProcessBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kLoginManager); } @@ -487,6 +491,7 @@ protected: WizardControllerSupervisionTransitionOobeTest() = default; + // WizardControllerTest: void SetUpOnMainThread() override { WizardControllerTest::SetUpOnMainThread(); // Setup existing user session and profile. @@ -514,6 +519,7 @@ } void SetUpCommandLine(base::CommandLine* command_line) override { + WizardControllerTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kLoginManager); command_line->AppendSwitchASCII(switches::kLoginProfile, TestingProfile::kTestUserProfileDir); @@ -559,7 +565,7 @@ class WizardControllerFlowTest : public WizardControllerTest { protected: WizardControllerFlowTest() {} - // Overriden from InProcessBrowserTest: + // WizardControllerTest: void SetUpOnMainThread() override { WizardControllerTest::SetUpOnMainThread(); @@ -1054,6 +1060,7 @@ protected: WizardControllerUpdateAfterCompletedOobeTest() = default; + // WizardControllerFlowTest: void SetUpOnMainThread() override { StartupUtils::MarkOobeCompleted(); // Pretend OOBE was complete. WizardControllerFlowTest::SetUpOnMainThread(); @@ -1134,6 +1141,7 @@ loop.Run(); } + // WizardControllerFlowTest: void SetUpInProcessBrowserTestFixture() override { WizardControllerFlowTest::SetUpInProcessBrowserTestFixture(); @@ -1177,8 +1185,8 @@ base::HistogramTester* histogram_tester() { return histogram_tester_.get(); } private: - ScopedStubInstallAttributes test_install_attributes_{ - StubInstallAttributes::CreateUnset()}; + DeviceStateMixin device_state_{&mixin_host_, + DeviceStateMixin::State::BEFORE_OOBE}; std::unique_ptr<base::HistogramTester> histogram_tester_; @@ -1286,6 +1294,7 @@ EXPECT_CALL(*device_disabled_screen_view_, Show()).Times(1); mock_auto_enrollment_check_screen_->ExitScreen(); + base::RunLoop().RunUntilIdle(); ResetAutoEnrollmentCheckScreen(); // Make sure the device disabled screen is shown. @@ -1309,6 +1318,7 @@ protected: WizardControllerDeviceStateExplicitRequirementTest() {} + // WizardControllerDeviceStateTest: void SetUpOnMainThread() override { WizardControllerDeviceStateTest::SetUpOnMainThread(); @@ -2033,6 +2043,7 @@ WizardControllerBrokenLocalStateTest() = default; ~WizardControllerBrokenLocalStateTest() override = default; + // WizardControllerTest: void SetUpOnMainThread() override { PrefServiceFactory factory; factory.set_user_prefs(base::MakeRefCounted<PrefStoreStub>()); @@ -2082,7 +2093,7 @@ base::FilePath()) {} ~WizardControllerProxyAuthOnSigninTest() override {} - // Overridden from WizardControllerTest: + // WizardControllerTest: void SetUp() override { ASSERT_TRUE(proxy_server_.Start()); WizardControllerTest::SetUp(); @@ -2095,6 +2106,7 @@ } void SetUpCommandLine(base::CommandLine* command_line) override { + WizardControllerTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(::switches::kProxyServer, proxy_server_.host_port_pair().ToString()); } @@ -2124,7 +2136,7 @@ protected: WizardControllerKioskFlowTest() {} - // Overridden from InProcessBrowserTest: + // MixinBasedInProcessBrowserTest: void SetUpCommandLine(base::CommandLine* command_line) override { WizardControllerFlowTest::SetUpCommandLine(command_line); base::FilePath test_data_dir; @@ -2243,7 +2255,7 @@ protected: WizardControllerEnableDebuggingTest() {} - // Overridden from InProcessBrowserTest: + // MixinBasedInProcessBrowserTest: void SetUpCommandLine(base::CommandLine* command_line) override { WizardControllerFlowTest::SetUpCommandLine(command_line); command_line->AppendSwitch(chromeos::switches::kSystemDevMode); @@ -2292,7 +2304,7 @@ WizardControllerDemoSetupTest() = default; ~WizardControllerDemoSetupTest() override = default; - // InProcessBrowserTest: + // MixinBasedInProcessBrowserTest: void SetUpOnMainThread() override { WizardControllerFlowTest::SetUpOnMainThread(); testing::Mock::VerifyAndClearExpectations(mock_welcome_screen_); @@ -2607,7 +2619,7 @@ WizardControllerDemoSetupDeviceDisabledTest() = default; ~WizardControllerDemoSetupDeviceDisabledTest() override = default; - // InProcessBrowserTest: + // MixinBasedInProcessBrowserTest: void SetUpOnMainThread() override { WizardControllerDeviceStateTest::SetUpOnMainThread(); testing::Mock::VerifyAndClearExpectations(mock_welcome_screen_); @@ -2708,7 +2720,7 @@ class WizardControllerOobeResumeTest : public WizardControllerTest { protected: WizardControllerOobeResumeTest() {} - // Overriden from InProcessBrowserTest: + // WizardControllerTest: void SetUpOnMainThread() override { WizardControllerTest::SetUpOnMainThread(); @@ -2785,6 +2797,7 @@ protected: WizardControllerCellularFirstTest() {} + // WizardControllerFlowTest: void SetUpCommandLine(base::CommandLine* command_line) override { WizardControllerFlowTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kCellularFirst); @@ -2802,6 +2815,7 @@ protected: WizardControllerOobeConfigurationTest() {} + // WizardControllerTest: void SetUpCommandLine(base::CommandLine* command_line) override { WizardControllerTest ::SetUpCommandLine(command_line); @@ -2813,7 +2827,7 @@ configuration_file); } - // Overriden from InProcessBrowserTest: + // WizardControllerTest: void SetUpOnMainThread() override { WizardControllerTest::SetUpOnMainThread();
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_initializer.cc b/chrome/browser/chromeos/policy/device_cloud_policy_initializer.cc index b933c92d..48e1e36 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_initializer.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_initializer.cc
@@ -12,6 +12,7 @@ #include "base/command_line.h" #include "base/logging.h" #include "base/sequenced_task_runner.h" +#include "base/strings/string_util.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/attestation/attestation_ca_client.h" @@ -44,6 +45,16 @@ namespace policy { +namespace { + +// Format MAC address from AA:AA:AA:AA:AA:AA into AAAAAAAAAAAA (12 digit string) +void FormatMacAddress(std::string* mac_address) { + base::ReplaceChars(*mac_address, ":", "", mac_address); + DCHECK(mac_address->empty() || mac_address->size() == 12); +} + +} // namespace + DeviceCloudPolicyInitializer::DeviceCloudPolicyInitializer( PrefService* local_state, DeviceManagementService* enterprise_service, @@ -310,10 +321,24 @@ std::string brand_code; statistics_provider_->GetMachineStatistic(chromeos::system::kRlzBrandCodeKey, &brand_code); + // The :'s should be removed from MAC addresses to match the format of + // reporting MAC addresses and corresponding VPD fields. + std::string ethernet_mac_address; + statistics_provider_->GetMachineStatistic( + chromeos::system::kEthernetMacAddressKey, ðernet_mac_address); + FormatMacAddress(ðernet_mac_address); + std::string dock_mac_address; + statistics_provider_->GetMachineStatistic( + chromeos::system::kDockMacAddressKey, &dock_mac_address); + FormatMacAddress(&dock_mac_address); + std::string manufacture_date; + statistics_provider_->GetMachineStatistic( + chromeos::system::kManufactureDateKey, &manufacture_date); // DeviceDMToken callback is empty here because for device policies this // DMToken is already provided in the policy fetch requests. return std::make_unique<CloudPolicyClient>( statistics_provider_->GetEnterpriseMachineID(), machine_model, brand_code, + ethernet_mac_address, dock_mac_address, manufacture_date, device_management_service, system_url_loader_factory_for_testing_ ? system_url_loader_factory_for_testing_
diff --git a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc index 20ea74d..1a8c3a5 100644 --- a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc
@@ -2122,10 +2122,7 @@ VerifyKeyboardLayoutMatchesLocale(); } -// https://crbug.com/865702: Flaky (crashes intermittently) on -// linux-chromeos-rel builder. -IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, - DISABLED_TermsOfServiceWithLocaleSwitch) { +IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, TermsOfServiceWithLocaleSwitch) { // Specify Terms of Service URL. ASSERT_TRUE(embedded_test_server()->Start()); device_local_account_policy_.payload().mutable_termsofserviceurl()->set_value(
diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_service.cc b/chrome/browser/chromeos/policy/device_local_account_policy_service.cc index dc7afe13..6f3e1b1 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_service.cc +++ b/chrome/browser/chromeos/policy/device_local_account_policy_service.cc
@@ -78,7 +78,10 @@ std::unique_ptr<CloudPolicyClient> client = std::make_unique<CloudPolicyClient>( std::string() /* machine_id */, std::string() /* machine_model */, - std::string() /* brand_code */, device_management_service, + std::string() /* brand_code */, + std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, device_management_service, system_url_loader_factory, nullptr /* signing_service */, base::BindRepeating(&GetDeviceDMToken, device_settings_service)); std::vector<std::string> user_affiliation_ids(
diff --git a/chrome/browser/chromeos/policy/site_isolation_flag_handling_browsertest.cc b/chrome/browser/chromeos/policy/site_isolation_flag_handling_browsertest.cc index e8ce4c8..3af697a0 100644 --- a/chrome/browser/chromeos/policy/site_isolation_flag_handling_browsertest.cc +++ b/chrome/browser/chromeos/policy/site_isolation_flag_handling_browsertest.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/login/session/user_session_manager_test_api.h" +#include "chrome/browser/chromeos/login/test/device_state_mixin.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/users/chrome_user_manager_impl.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" @@ -29,7 +30,6 @@ #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/settings/cros_settings_names.h" -#include "chromeos/tpm/stub_install_attributes.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" @@ -367,10 +367,9 @@ // This will be set to |true| when chrome has requested a restart. bool attempt_restart_called_ = false; - // Set up fake install attributes to pretend the machine is enrolled. This - // is important because ephemeral users only work on enrolled machines. - ScopedStubInstallAttributes test_install_attributes_{ - StubInstallAttributes::CreateCloudManaged("example.com", "fake-id")}; + // This is important because ephemeral users only work on enrolled machines. + DeviceStateMixin device_state_{ + &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; // Observes for user session start. std::unique_ptr<content::WindowedNotificationObserver>
diff --git a/chrome/browser/chromeos/policy/status_collector/activity_storage.cc b/chrome/browser/chromeos/policy/status_collector/activity_storage.cc new file mode 100644 index 0000000..08a85f8 --- /dev/null +++ b/chrome/browser/chromeos/policy/status_collector/activity_storage.cc
@@ -0,0 +1,251 @@ +// Copyright 2019 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 "chrome/browser/chromeos/policy/status_collector/activity_storage.h" + +#include "base/base64.h" +#include "base/strings/string_number_conversions.h" +#include "base/values.h" +#include "chrome/common/pref_names.h" +#include "components/prefs/pref_service.h" +#include "components/prefs/scoped_user_pref_update.h" +#include "components/user_manager/user_manager.h" + +namespace policy { +namespace { + +using ::base::Time; +using ::base::TimeDelta; + +// Activity periods are keyed with day and user in format: +// '<day_timestamp>:<BASE64 encoded user email>' +constexpr char kActivityKeySeparator = ':'; + +} // namespace + +ActivityStorage::ActivityStorage(PrefService* pref_service, + const std::string& pref_name, + TimeDelta activity_day_start, + bool is_enterprise_reporting) + : pref_service_(pref_service), + pref_name_(pref_name), + day_start_(activity_day_start), + is_enterprise_reporting_(is_enterprise_reporting) { + DCHECK(pref_service_); + const PrefService::PrefInitializationStatus pref_service_status = + pref_service_->GetInitializationStatus(); + DCHECK(pref_service_status != PrefService::INITIALIZATION_STATUS_WAITING && + pref_service_status != PrefService::INITIALIZATION_STATUS_ERROR); +} + +ActivityStorage::~ActivityStorage() = default; + +void ActivityStorage::AddActivityPeriod(Time start, + Time end, + Time now, + const std::string& active_user_email) { + DCHECK(start <= end); + + // Maintain the list of active periods in a local_state pref. + DictionaryPrefUpdate update(pref_service_, pref_name_); + base::DictionaryValue* activity_times = update.Get(); + + // Assign the period to day buckets in local time. + Time day_start = start.LocalMidnight() + day_start_; + if (start < day_start) + day_start -= TimeDelta::FromDays(1); + while (day_start < end) { + day_start += TimeDelta::FromDays(1); + int64_t activity = (std::min(end, day_start) - start).InMilliseconds(); + const std::string key = + MakeActivityPeriodPrefKey(TimestampToDayKey(start), active_user_email); + int previous_activity = 0; + activity_times->GetInteger(key, &previous_activity); + activity_times->SetInteger(key, previous_activity + activity); + + // If the user is a child, the child screen time pref may need to be + // updated. + if (user_manager::UserManager::Get()->IsLoggedInAsChildUser() && + !is_enterprise_reporting_) { + StoreChildScreenTime(day_start - TimeDelta::FromDays(1), + TimeDelta::FromMilliseconds(activity), now); + } + + start = day_start; + } +} + +void ActivityStorage::PruneActivityPeriods( + Time base_time, + TimeDelta max_past_activity_interval, + TimeDelta max_future_activity_interval) { + Time min_time = base_time - max_past_activity_interval; + Time max_time = base_time + max_future_activity_interval; + TrimActivityPeriods(TimestampToDayKey(min_time), 0, + TimestampToDayKey(max_time)); +} + +void ActivityStorage::TrimActivityPeriods(int64_t min_day_key, + int min_day_trim_duration, + int64_t max_day_key) { + const base::DictionaryValue* activity_times = + pref_service_->GetDictionary(pref_name_); + + std::unique_ptr<base::DictionaryValue> copy(activity_times->DeepCopy()); + for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd(); + it.Advance()) { + int64_t timestamp; + std::string active_user_email; + if (ParseActivityPeriodPrefKey(it.key(), ×tamp, &active_user_email)) { + // Remove data that is too old, or too far in the future. + if (timestamp >= min_day_key && timestamp < max_day_key) { + if (timestamp == min_day_key) { + int new_activity_duration = 0; + if (it.value().GetAsInteger(&new_activity_duration)) { + new_activity_duration = + std::max(new_activity_duration - min_day_trim_duration, 0); + } + copy->SetInteger(it.key(), new_activity_duration); + } + continue; + } + } + // The entry is out of range or couldn't be parsed. Remove it. + copy->Remove(it.key(), NULL); + } + pref_service_->Set(pref_name_, *copy); +} + +void ActivityStorage::FilterActivityPeriodsByUsers( + const std::vector<std::string>& reporting_users) { + const base::DictionaryValue* stored_activity_periods = + pref_service_->GetDictionary(pref_name_); + base::DictionaryValue filtered_activity_periods; + ProcessActivityPeriods(*stored_activity_periods, reporting_users, + &filtered_activity_periods); + pref_service_->Set(pref_name_, filtered_activity_periods); +} + +std::vector<ActivityStorage::ActivityPeriod> +ActivityStorage::GetFilteredActivityPeriods(bool omit_emails) { + DictionaryPrefUpdate update(pref_service_, pref_name_); + base::DictionaryValue* stored_activity_periods = update.Get(); + + base::DictionaryValue filtered_activity_periods; + if (omit_emails) { + std::vector<std::string> empty_user_list; + ProcessActivityPeriods(*stored_activity_periods, empty_user_list, + &filtered_activity_periods); + stored_activity_periods = &filtered_activity_periods; + } + + std::vector<ActivityPeriod> activity_periods; + for (base::DictionaryValue::Iterator it(*stored_activity_periods); + !it.IsAtEnd(); it.Advance()) { + ActivityPeriod activity_period; + if (ParseActivityPeriodPrefKey(it.key(), &activity_period.start_timestamp, + &activity_period.user_email) && + it.value().GetAsInteger(&activity_period.activity_milliseconds)) { + activity_periods.push_back(activity_period); + } + } + return activity_periods; +} + +// static +std::string ActivityStorage::MakeActivityPeriodPrefKey( + int64_t start, + const std::string& user_email) { + const std::string day_key = base::NumberToString(start); + if (user_email.empty()) + return day_key; + + std::string encoded_email; + base::Base64Encode(user_email, &encoded_email); + return day_key + kActivityKeySeparator + encoded_email; +} + +// static +bool ActivityStorage::ParseActivityPeriodPrefKey(const std::string& key, + int64_t* start_timestamp, + std::string* user_email) { + auto separator_pos = key.find(kActivityKeySeparator); + if (separator_pos == std::string::npos) { + user_email->clear(); + return base::StringToInt64(key, start_timestamp); + } + return base::StringToInt64(key.substr(0, separator_pos), start_timestamp) && + base::Base64Decode(key.substr(separator_pos + 1), user_email); +} + +void ActivityStorage::ProcessActivityPeriods( + const base::DictionaryValue& activity_times, + const std::vector<std::string>& reporting_users, + base::DictionaryValue* const filtered_times) { + std::set<std::string> reporting_users_set(reporting_users.begin(), + reporting_users.end()); + const std::string empty; + for (const auto& it : activity_times.DictItems()) { + DCHECK(it.second.is_int()); + int64_t timestamp; + std::string user_email; + if (!ParseActivityPeriodPrefKey(it.first, ×tamp, &user_email)) + continue; + if (!user_email.empty() && reporting_users_set.count(user_email) == 0) { + int value = 0; + std::string timestamp_str = MakeActivityPeriodPrefKey(timestamp, empty); + const base::Value* prev_value = filtered_times->FindKeyOfType( + timestamp_str, base::Value::Type::INTEGER); + if (prev_value) + value = prev_value->GetInt(); + filtered_times->SetKey(timestamp_str, + base::Value(value + it.second.GetInt())); + } else { + filtered_times->SetKey(it.first, it.second.Clone()); + } + } +} + +int64_t ActivityStorage::TimestampToDayKey(Time timestamp) { + Time::Exploded exploded; + Time day_start = timestamp.LocalMidnight() + day_start_; + if (timestamp < day_start) + day_start -= TimeDelta::FromDays(1); + day_start.LocalExplode(&exploded); + Time out_time; + bool conversion_success = Time::FromUTCExploded(exploded, &out_time); + DCHECK(conversion_success); + return out_time.ToJavaTime(); +} + +void ActivityStorage::StoreChildScreenTime(Time activity_day_start, + TimeDelta activity, + Time now) { + DCHECK(user_manager::UserManager::Get()->IsLoggedInAsChildUser() && + !is_enterprise_reporting_); + + // Today's start time. + Time today_start = now.LocalMidnight() + day_start_; + if (today_start > now) + today_start -= TimeDelta::FromDays(1); + + // The activity windows always start and end on the reset time of two + // consecutive days, so it is not possible to have a window starting after + // the current day's reset time. + DCHECK(activity_day_start <= today_start); + + TimeDelta previous_activity = TimeDelta::FromMilliseconds( + pref_service_->GetInteger(prefs::kChildScreenTimeMilliseconds)); + + // If this activity window belongs to the current day, the screen time pref + // should be updated. + if (activity_day_start == today_start) { + pref_service_->SetInteger(prefs::kChildScreenTimeMilliseconds, + (previous_activity + activity).InMilliseconds()); + pref_service_->SetTime(prefs::kLastChildScreenTimeSaved, now); + } + pref_service_->CommitPendingWrite(); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/status_collector/activity_storage.h b/chrome/browser/chromeos/policy/status_collector/activity_storage.h new file mode 100644 index 0000000..b39bbee --- /dev/null +++ b/chrome/browser/chromeos/policy/status_collector/activity_storage.h
@@ -0,0 +1,115 @@ +// Copyright 2019 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 CHROME_BROWSER_CHROMEOS_POLICY_STATUS_COLLECTOR_ACTIVITY_STORAGE_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_STATUS_COLLECTOR_ACTIVITY_STORAGE_H_ + +#include <stdint.h> + +#include <string> +#include <vector> + +#include "base/macros.h" +#include "base/time/time.h" + +namespace base { +class DictionaryValue; +} + +class PrefService; + +namespace policy { + +// Handles storing activity time periods needed for reporting. Provides +// filtering of the user identifying data. +// +// TODO(crbug.com/827386): refactor this class, removing child related parts. +class ActivityStorage { + public: + // Stored activity period. + struct ActivityPeriod { + // Email can be empty. + std::string user_email; + + // Timestamp dating the beginning of the captured activity. + int64_t start_timestamp; + + // User's activity in milliseconds. + int activity_milliseconds; + }; + + // Creates activity storage. Activity data will be stored in the given + // |pref_service| under |pref_name| preference. Activity data are aggregated + // by day. The start of the new day is counted from |activity_day_start| that + // represents the distance from midnight. + ActivityStorage(PrefService* pref_service, + const std::string& pref_name, + base::TimeDelta activity_day_start, + bool is_enterprise_reporting); + ~ActivityStorage(); + + // Adds an activity period. Accepts empty |active_user_email| if it should not + // be stored. + void AddActivityPeriod(base::Time start, + base::Time end, + base::Time now, + const std::string& active_user_email); + + // Clears stored activity periods outside of storage range defined by + // |max_past_activity_interval| and |max_future_activity_interval| from + // |base_time|. + void PruneActivityPeriods(base::Time base_time, + base::TimeDelta max_past_activity_interval, + base::TimeDelta max_future_activity_interval); + + // Trims the store activity periods to only retain data within the + // [|min_day_key|, |max_day_key|). The record for |min_day_key| will be + // adjusted by subtracting |min_day_trim_duration|. + void TrimActivityPeriods(int64_t min_day_key, + int min_day_trim_duration, + int64_t max_day_key); + + // Updates stored activity period according to users' reporting preferences. + // Removes user's email and aggregates the activity data if user's information + // should no longer be reported. + void FilterActivityPeriodsByUsers( + const std::vector<std::string>& reporting_users); + + // Returns the list of stored activity periods. Aggregated data are returned + // without email addresses if |omit_emails| is set. + std::vector<ActivityPeriod> GetFilteredActivityPeriods(bool omit_emails); + + private: + static std::string MakeActivityPeriodPrefKey(int64_t start, + const std::string& user_email); + static bool ParseActivityPeriodPrefKey(const std::string& key, + int64_t* start_timestamp, + std::string* user_email); + void ProcessActivityPeriods(const base::DictionaryValue& activity_times, + const std::vector<std::string>& reporting_users, + base::DictionaryValue* const filtered_times); + void StoreChildScreenTime(base::Time activity_day_start, + base::TimeDelta activity, + base::Time now); + + // Determine the day key (milliseconds since epoch for corresponding + // |day_start_| in UTC) for a given |timestamp|. + int64_t TimestampToDayKey(base::Time timestamp); + + PrefService* const pref_service_ = nullptr; + const std::string pref_name_; + + // New day start time used for aggregating data represented by the distance + // from midnight. + const base::TimeDelta day_start_; + + // Whether reporting is for enterprise or consumer. + bool is_enterprise_reporting_ = false; + + DISALLOW_COPY_AND_ASSIGN(ActivityStorage); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_STATUS_COLLECTOR_ACTIVITY_STORAGE_H_
diff --git a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc index b600316..651f640 100644 --- a/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/status_collector/device_status_collector.cc
@@ -14,7 +14,6 @@ #include <sstream> #include <utility> -#include "base/base64.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/feature_list.h" @@ -22,8 +21,11 @@ #include "base/files/file_util.h" #include "base/format_macros.h" #include "base/logging.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" #include "base/optional.h" #include "base/posix/eintr_wrapper.h" +#include "base/sequenced_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -31,6 +33,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" #include "base/task/post_task.h" +#include "base/task/task_traits.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" #include "base/version.h" @@ -41,6 +44,8 @@ #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_local_account.h" +#include "chrome/browser/chromeos/policy/status_collector/activity_storage.h" +#include "chrome/browser/chromeos/policy/status_collector/status_collector_state.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" @@ -77,7 +82,6 @@ #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" -#include "components/prefs/scoped_user_pref_update.h" #include "components/session_manager/session_manager_types.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" @@ -116,10 +120,6 @@ const char kHwmonDirectoryPattern[] = "hwmon*"; const char kCPUTempFilePattern[] = "temp*_input"; -// Activity periods are keyed with day and user in format: -// '<day_timestamp>:<BASE64 encoded user email>' -constexpr char kActivityKeySeparator = ':'; - // How often the child's usage time is stored. static constexpr base::TimeDelta kUpdateChildActiveTimeInterval = base::TimeDelta::FromSeconds(30); @@ -354,41 +354,16 @@ namespace policy { -// Helper class for state tracking of async status queries. Creates device and -// session status blobs in the constructor and sends them to the the status -// response callback in the destructor. -// -// Some methods like |SampleVolumeInfo| queue async queries to collect data. The -// response callback of these queries, e.g. |OnVolumeInfoReceived|, holds a -// reference to the instance of this class, so that the destructor will not be -// invoked and the status response callback will not be fired until the original -// owner of the instance releases its reference and all async queries finish. -// -// Therefore, if you create an instance of this class, make sure to release your -// reference after quering all async queries (if any), e.g. by using a local -// |scoped_refptr<GetStatusState>| and letting it go out of scope. -class GetStatusState : public base::RefCountedThreadSafe<GetStatusState> { +class DeviceStatusCollectorState : public StatusCollectorState { public: - explicit GetStatusState( + explicit DeviceStatusCollectorState( const scoped_refptr<base::SequencedTaskRunner> task_runner, - const policy::StatusCollectorCallback& response) - : task_runner_(task_runner), response_(response) {} - - inline em::DeviceStatusReportRequest* device_status() { - return response_params_.device_status.get(); - } - - inline em::SessionStatusReportRequest* session_status() { - return response_params_.session_status.get(); - } - - inline void ResetDeviceStatus() { response_params_.device_status.reset(); } - - inline void ResetSessionStatus() { response_params_.session_status.reset(); } + const StatusCollectorCallback& response) + : StatusCollectorState(task_runner, response) {} // Queues an async callback to query disk volume information. - void SampleVolumeInfo(const policy::DeviceStatusCollector::VolumeInfoFetcher& - volume_info_fetcher) { + void SampleVolumeInfo( + const DeviceStatusCollector::VolumeInfoFetcher& volume_info_fetcher) { // Create list of mounted disk volumes to query status. std::vector<storage::MountPoints::MountPointInfo> external_mount_points; storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo( @@ -408,48 +383,40 @@ base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(volume_info_fetcher, mount_points), - base::Bind(&GetStatusState::OnVolumeInfoReceived, this)); + base::Bind(&DeviceStatusCollectorState::OnVolumeInfoReceived, this)); } // Queues an async callback to query CPU temperature information. void SampleCPUTempInfo( - const policy::DeviceStatusCollector::CPUTempFetcher& cpu_temp_fetcher) { + const DeviceStatusCollector::CPUTempFetcher& cpu_temp_fetcher) { // Call out to the blocking pool to sample CPU temp. base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, cpu_temp_fetcher, - base::Bind(&GetStatusState::OnCPUTempInfoReceived, this)); + base::Bind(&DeviceStatusCollectorState::OnCPUTempInfoReceived, this)); } - bool FetchAndroidStatus( - const policy::DeviceStatusCollector::AndroidStatusFetcher& - android_status_fetcher) { + bool FetchAndroidStatus(const DeviceStatusCollector::AndroidStatusFetcher& + android_status_fetcher) { return android_status_fetcher.Run( - base::Bind(&GetStatusState::OnAndroidInfoReceived, this)); + base::Bind(&DeviceStatusCollectorState::OnAndroidInfoReceived, this)); } - void FetchTpmStatus(const policy::DeviceStatusCollector::TpmStatusFetcher& - tpm_status_fetcher) { + void FetchTpmStatus( + const DeviceStatusCollector::TpmStatusFetcher& tpm_status_fetcher) { tpm_status_fetcher.Run( - base::BindOnce(&GetStatusState::OnTpmStatusReceived, this)); + base::BindOnce(&DeviceStatusCollectorState::OnTpmStatusReceived, this)); } void FetchProbeData( - policy::DeviceStatusCollector::ProbeDataFetcher probe_data_fetcher) { + DeviceStatusCollector::ProbeDataFetcher probe_data_fetcher) { std::move(probe_data_fetcher) - .Run(base::BindOnce(&GetStatusState::OnProbeDataReceived, this)); + .Run(base::BindOnce(&DeviceStatusCollectorState::OnProbeDataReceived, + this)); } private: - friend class RefCountedThreadSafe<GetStatusState>; - - // Posts the response on the UI thread. As long as there is an outstanding - // async query, the query holds a reference to us, so the destructor is - // not called. - ~GetStatusState() { - task_runner_->PostTask( - FROM_HERE, base::BindOnce(response_, base::Passed(&response_params_))); - } + ~DeviceStatusCollectorState() override = default; void OnVolumeInfoReceived(const std::vector<em::VolumeInfo>& volume_info) { response_params_.device_status->clear_volume_infos(); @@ -569,97 +536,6 @@ } } } - - const scoped_refptr<base::SequencedTaskRunner> task_runner_; - policy::StatusCollectorCallback response_; - StatusCollectorParams response_params_; -}; - -// Handles storing activity time periods needed for reporting. Provides -// filtering of the user identifying data. -class DeviceStatusCollector::ActivityStorage { - public: - // Stored activity period. - struct ActivityPeriod { - // Email can be empty. - std::string user_email; - - // Timestamp dating the beginning of the captured activity. - int64_t start_timestamp; - - // User's activity in milliseconds. - int activity_milliseconds; - }; - - // Creates activity storage. Activity data will be stored in the given - // |pref_service| under |pref_name| preference. Activity data are aggregated - // by day. The start of the new day is counted from |activity_day_start| that - // represents the distance from midnight. - ActivityStorage(PrefService* pref_service, - const std::string& pref_name, - TimeDelta activity_day_start, - bool is_enterprise_reporting); - ~ActivityStorage(); - - // Adds an activity period. Accepts empty |active_user_email| if it should not - // be stored. - void AddActivityPeriod(Time start, - Time end, - Time now, - const std::string& active_user_email); - - // Clears stored activity periods outside of storage range defined by - // |max_past_activity_interval| and |max_future_activity_interval| from - // |base_time|. - void PruneActivityPeriods(Time base_time, - TimeDelta max_past_activity_interval, - TimeDelta max_future_activity_interval); - - // Trims the store activity periods to only retain data within the - // [|min_day_key|, |max_day_key|). The record for |min_day_key| will be - // adjusted by subtracting |min_day_trim_duration|. - void TrimActivityPeriods(int64_t min_day_key, - int min_day_trim_duration, - int64_t max_day_key); - - // Updates stored activity period according to users' reporting preferences. - // Removes user's email and aggregates the activity data if user's information - // should no longer be reported. - void FilterActivityPeriodsByUsers( - const std::vector<std::string>& reporting_users); - - // Returns the list of stored activity periods. Aggregated data are returned - // without email addresses if |omit_emails| is set. - std::vector<ActivityPeriod> GetFilteredActivityPeriods(bool omit_emails); - - private: - static std::string MakeActivityPeriodPrefKey(int64_t start, - const std::string& user_email); - static bool ParseActivityPeriodPrefKey(const std::string& key, - int64_t* start_timestamp, - std::string* user_email); - void ProcessActivityPeriods(const base::DictionaryValue& activity_times, - const std::vector<std::string>& reporting_users, - base::DictionaryValue* const filtered_times); - void StoreChildScreenTime(Time activity_day_start, - TimeDelta activity, - Time now); - - // Determine the day key (milliseconds since epoch for corresponding - // |day_start_| in UTC) for a given |timestamp|. - int64_t TimestampToDayKey(Time timestamp); - - PrefService* const pref_service_ = nullptr; - const std::string pref_name_; - - // New day start time used for aggregating data represented by the distance - // from midnight. - const TimeDelta day_start_; - - // Whether reporting is for enterprise or consumer. - bool is_enterprise_reporting_ = false; - - DISALLOW_COPY_AND_ASSIGN(ActivityStorage); }; TpmStatusInfo::TpmStatusInfo() = default; @@ -688,237 +564,6 @@ boot_lockbox_finalized(boot_lockbox_finalized) {} TpmStatusInfo::~TpmStatusInfo() = default; -DeviceStatusCollector::ActivityStorage::ActivityStorage( - PrefService* pref_service, - const std::string& pref_name, - TimeDelta activity_day_start, - bool is_enterprise_reporting) - : pref_service_(pref_service), - pref_name_(pref_name), - day_start_(activity_day_start), - is_enterprise_reporting_(is_enterprise_reporting) { - DCHECK(pref_service_); - const PrefService::PrefInitializationStatus pref_service_status = - pref_service_->GetInitializationStatus(); - DCHECK(pref_service_status != PrefService::INITIALIZATION_STATUS_WAITING && - pref_service_status != PrefService::INITIALIZATION_STATUS_ERROR); -} - -DeviceStatusCollector::ActivityStorage::~ActivityStorage() = default; - -void DeviceStatusCollector::ActivityStorage::AddActivityPeriod( - Time start, - Time end, - Time now, - const std::string& active_user_email) { - DCHECK(start <= end); - - // Maintain the list of active periods in a local_state pref. - DictionaryPrefUpdate update(pref_service_, pref_name_); - base::DictionaryValue* activity_times = update.Get(); - - // Assign the period to day buckets in local time. - Time day_start = start.LocalMidnight() + day_start_; - if (start < day_start) - day_start -= TimeDelta::FromDays(1); - while (day_start < end) { - day_start += TimeDelta::FromDays(1); - int64_t activity = (std::min(end, day_start) - start).InMilliseconds(); - const std::string key = - MakeActivityPeriodPrefKey(TimestampToDayKey(start), active_user_email); - int previous_activity = 0; - activity_times->GetInteger(key, &previous_activity); - activity_times->SetInteger(key, previous_activity + activity); - - // If the user is a child, the child screen time pref may need to be - // updated. - if (user_manager::UserManager::Get()->IsLoggedInAsChildUser() && - !is_enterprise_reporting_) { - StoreChildScreenTime(day_start - TimeDelta::FromDays(1), - TimeDelta::FromMilliseconds(activity), now); - } - - start = day_start; - } -} - -void DeviceStatusCollector::ActivityStorage::PruneActivityPeriods( - Time base_time, - TimeDelta max_past_activity_interval, - TimeDelta max_future_activity_interval) { - Time min_time = base_time - max_past_activity_interval; - Time max_time = base_time + max_future_activity_interval; - TrimActivityPeriods(TimestampToDayKey(min_time), 0, - TimestampToDayKey(max_time)); -} - -void DeviceStatusCollector::ActivityStorage::TrimActivityPeriods( - int64_t min_day_key, - int min_day_trim_duration, - int64_t max_day_key) { - const base::DictionaryValue* activity_times = - pref_service_->GetDictionary(pref_name_); - - std::unique_ptr<base::DictionaryValue> copy(activity_times->DeepCopy()); - for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd(); - it.Advance()) { - int64_t timestamp; - std::string active_user_email; - if (ParseActivityPeriodPrefKey(it.key(), ×tamp, &active_user_email)) { - // Remove data that is too old, or too far in the future. - if (timestamp >= min_day_key && timestamp < max_day_key) { - if (timestamp == min_day_key) { - int new_activity_duration = 0; - if (it.value().GetAsInteger(&new_activity_duration)) { - new_activity_duration = - std::max(new_activity_duration - min_day_trim_duration, 0); - } - copy->SetInteger(it.key(), new_activity_duration); - } - continue; - } - } - // The entry is out of range or couldn't be parsed. Remove it. - copy->Remove(it.key(), NULL); - } - pref_service_->Set(pref_name_, *copy); -} - -void DeviceStatusCollector::ActivityStorage::FilterActivityPeriodsByUsers( - const std::vector<std::string>& reporting_users) { - const base::DictionaryValue* stored_activity_periods = - pref_service_->GetDictionary(pref_name_); - base::DictionaryValue filtered_activity_periods; - ProcessActivityPeriods(*stored_activity_periods, reporting_users, - &filtered_activity_periods); - pref_service_->Set(pref_name_, filtered_activity_periods); -} - -std::vector<DeviceStatusCollector::ActivityStorage::ActivityPeriod> -DeviceStatusCollector::ActivityStorage::GetFilteredActivityPeriods( - bool omit_emails) { - DictionaryPrefUpdate update(pref_service_, pref_name_); - base::DictionaryValue* stored_activity_periods = update.Get(); - - base::DictionaryValue filtered_activity_periods; - if (omit_emails) { - std::vector<std::string> empty_user_list; - ProcessActivityPeriods(*stored_activity_periods, empty_user_list, - &filtered_activity_periods); - stored_activity_periods = &filtered_activity_periods; - } - - std::vector<ActivityPeriod> activity_periods; - for (base::DictionaryValue::Iterator it(*stored_activity_periods); - !it.IsAtEnd(); it.Advance()) { - ActivityPeriod activity_period; - if (ParseActivityPeriodPrefKey(it.key(), &activity_period.start_timestamp, - &activity_period.user_email) && - it.value().GetAsInteger(&activity_period.activity_milliseconds)) { - activity_periods.push_back(activity_period); - } - } - return activity_periods; -} - -// static -std::string DeviceStatusCollector::ActivityStorage::MakeActivityPeriodPrefKey( - int64_t start, - const std::string& user_email) { - const std::string day_key = base::NumberToString(start); - if (user_email.empty()) - return day_key; - - std::string encoded_email; - base::Base64Encode(user_email, &encoded_email); - return day_key + kActivityKeySeparator + encoded_email; -} - -// static -bool DeviceStatusCollector::ActivityStorage::ParseActivityPeriodPrefKey( - const std::string& key, - int64_t* start_timestamp, - std::string* user_email) { - auto separator_pos = key.find(kActivityKeySeparator); - if (separator_pos == std::string::npos) { - user_email->clear(); - return base::StringToInt64(key, start_timestamp); - } - return base::StringToInt64(key.substr(0, separator_pos), start_timestamp) && - base::Base64Decode(key.substr(separator_pos + 1), user_email); -} - -void DeviceStatusCollector::ActivityStorage::ProcessActivityPeriods( - const base::DictionaryValue& activity_times, - const std::vector<std::string>& reporting_users, - base::DictionaryValue* const filtered_times) { - std::set<std::string> reporting_users_set(reporting_users.begin(), - reporting_users.end()); - const std::string empty; - for (const auto& it : activity_times.DictItems()) { - DCHECK(it.second.is_int()); - int64_t timestamp; - std::string user_email; - if (!ParseActivityPeriodPrefKey(it.first, ×tamp, &user_email)) - continue; - if (!user_email.empty() && reporting_users_set.count(user_email) == 0) { - int value = 0; - std::string timestamp_str = MakeActivityPeriodPrefKey(timestamp, empty); - const base::Value* prev_value = filtered_times->FindKeyOfType( - timestamp_str, base::Value::Type::INTEGER); - if (prev_value) - value = prev_value->GetInt(); - filtered_times->SetKey(timestamp_str, - base::Value(value + it.second.GetInt())); - } else { - filtered_times->SetKey(it.first, it.second.Clone()); - } - } -} - -int64_t DeviceStatusCollector::ActivityStorage::TimestampToDayKey( - Time timestamp) { - Time::Exploded exploded; - Time day_start = timestamp.LocalMidnight() + day_start_; - if (timestamp < day_start) - day_start -= TimeDelta::FromDays(1); - day_start.LocalExplode(&exploded); - Time out_time; - bool conversion_success = Time::FromUTCExploded(exploded, &out_time); - DCHECK(conversion_success); - return out_time.ToJavaTime(); -} - -void DeviceStatusCollector::ActivityStorage::StoreChildScreenTime( - Time activity_day_start, - TimeDelta activity, - Time now) { - DCHECK(user_manager::UserManager::Get()->IsLoggedInAsChildUser() && - !is_enterprise_reporting_); - - // Today's start time. - Time today_start = now.LocalMidnight() + day_start_; - if (today_start > now) - today_start -= TimeDelta::FromDays(1); - - // The activity windows always start and end on the reset time of two - // consecutive days, so it is not possible to have a window starting after - // the current day's reset time. - DCHECK(activity_day_start <= today_start); - - TimeDelta previous_activity = TimeDelta::FromMilliseconds( - pref_service_->GetInteger(prefs::kChildScreenTimeMilliseconds)); - - // If this activity window belongs to the current day, the screen time pref - // should be updated. - if (activity_day_start == today_start) { - pref_service_->SetInteger(prefs::kChildScreenTimeMilliseconds, - (previous_activity + activity).InMilliseconds()); - pref_service_->SetTime(prefs::kLastChildScreenTimeSaved, now); - } - pref_service_->CommitPendingWrite(); -} - SampledData::SampledData() = default; SampledData::~SampledData() = default; @@ -1511,8 +1156,7 @@ std::move(callback).Run(); } -void DeviceStatusCollector::FetchProbeData( - policy::DeviceStatusCollector::ProbeDataReceiver callback) { +void DeviceStatusCollector::FetchProbeData(ProbeDataReceiver callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); runtime_probe::ProbeRequest request; if (report_power_status_) @@ -1533,7 +1177,7 @@ } void DeviceStatusCollector::OnProbeDataFetched( - policy::DeviceStatusCollector::ProbeDataReceiver callback, + ProbeDataReceiver callback, base::Optional<runtime_probe::ProbeResult> reply) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::move(callback).Run(reply, sampled_data_); @@ -1817,8 +1461,10 @@ } bool DeviceStatusCollector::GetHardwareStatus( - em::DeviceStatusReportRequest* status, - scoped_refptr<GetStatusState> state) { + scoped_refptr<DeviceStatusCollectorState> state) { + em::DeviceStatusReportRequest* status = + state->response_params().device_status.get(); + // Sample disk volume info in a background thread. state->SampleVolumeInfo(volume_info_fetcher_); @@ -1954,8 +1600,8 @@ // Some of the data we're collecting is gathered in background threads. // This object keeps track of the state of each async request. - scoped_refptr<GetStatusState> state( - new GetStatusState(task_runner_, response)); + scoped_refptr<DeviceStatusCollectorState> state( + new DeviceStatusCollectorState(task_runner_, response)); // Gather device status (might queue some async queries) GetDeviceStatus(state); @@ -1970,8 +1616,9 @@ } void DeviceStatusCollector::GetDeviceStatus( - scoped_refptr<GetStatusState> state) { - em::DeviceStatusReportRequest* status = state->device_status(); + scoped_refptr<DeviceStatusCollectorState> state) { + em::DeviceStatusReportRequest* status = + state->response_params().device_status.get(); bool anything_reported = false; if (report_activity_times_) @@ -1990,7 +1637,7 @@ anything_reported |= GetUsers(status); if (report_hardware_status_) { - anything_reported |= GetHardwareStatus(status, state); + anything_reported |= GetHardwareStatus(state); anything_reported |= GetWriteProtectSwitch(status); } @@ -2002,7 +1649,7 @@ // Wipe pointer if we didn't actually add any data. if (!anything_reported) - state->ResetDeviceStatus(); + state->response_params().device_status.reset(); } std::string DeviceStatusCollector::GetDMTokenForProfile(Profile* profile) { @@ -2021,7 +1668,7 @@ } bool DeviceStatusCollector::GetSessionStatusForUser( - scoped_refptr<GetStatusState> state, + scoped_refptr<DeviceStatusCollectorState> state, em::SessionStatusReportRequest* status, const user_manager::User* user) { Profile* const profile = @@ -2057,8 +1704,9 @@ } void DeviceStatusCollector::GetSessionStatus( - scoped_refptr<GetStatusState> state) { - em::SessionStatusReportRequest* status = state->session_status(); + scoped_refptr<DeviceStatusCollectorState> state) { + em::SessionStatusReportRequest* status = + state->response_params().session_status.get(); bool anything_reported = false; user_manager::UserManager* user_manager = user_manager::UserManager::Get(); @@ -2077,7 +1725,7 @@ // Wipe pointer if we didn't actually add any data. if (!anything_reported) - state->ResetSessionStatus(); + state->response_params().session_status.reset(); } bool DeviceStatusCollector::GetKioskSessionStatus( @@ -2113,7 +1761,7 @@ bool DeviceStatusCollector::GetAndroidStatus( em::SessionStatusReportRequest* status, - const scoped_refptr<GetStatusState>& state) { + const scoped_refptr<DeviceStatusCollectorState>& state) { return state->FetchAndroidStatus(android_status_fetcher_); }
diff --git a/chrome/browser/chromeos/policy/status_collector/device_status_collector.h b/chrome/browser/chromeos/policy/status_collector/device_status_collector.h index be309f03..d73eef53 100644 --- a/chrome/browser/chromeos/policy/status_collector/device_status_collector.h +++ b/chrome/browser/chromeos/policy/status_collector/device_status_collector.h
@@ -63,8 +63,9 @@ namespace policy { +class ActivityStorage; struct DeviceLocalAccount; -class GetStatusState; +class DeviceStatusCollectorState; // Holds TPM status info. Cf. TpmStatusInfo in device_management_backend.proto. struct TpmStatusInfo { @@ -256,8 +257,6 @@ void UpdateChildUsageTime(); private: - class ActivityStorage; - // Callbacks used during sampling data collection, that allows to pass // additional data using partial function application. using SamplingProbeResultCallback = @@ -273,16 +272,16 @@ void OnTpmVersion( const chromeos::CryptohomeClient::TpmVersionInfo& tpm_version_info); - void GetDeviceStatus(scoped_refptr<GetStatusState> state); - void GetSessionStatus(scoped_refptr<GetStatusState> state); + void GetDeviceStatus(scoped_refptr<DeviceStatusCollectorState> state); + void GetSessionStatus(scoped_refptr<DeviceStatusCollectorState> state); bool GetSessionStatusForUser( - scoped_refptr<GetStatusState> state, + scoped_refptr<DeviceStatusCollectorState> state, enterprise_management::SessionStatusReportRequest* status, const user_manager::User* user); // Helpers for the various portions of DEVICE STATUS. Return true if they // actually report any status. Functions that queue async queries take - // a |GetStatusState| instance. + // a |DeviceStatusCollectorState| instance. bool GetActivityTimes( enterprise_management::DeviceStatusReportRequest* status); bool GetVersionInfo(enterprise_management::DeviceStatusReportRequest* status); @@ -292,9 +291,8 @@ bool GetNetworkInterfaces( enterprise_management::DeviceStatusReportRequest* status); bool GetUsers(enterprise_management::DeviceStatusReportRequest* status); - bool GetHardwareStatus( - enterprise_management::DeviceStatusReportRequest* status, - scoped_refptr<GetStatusState> state); // Queues async queries! + bool GetHardwareStatus(scoped_refptr<DeviceStatusCollectorState> + state); // Queues async queries! bool GetOsUpdateStatus( enterprise_management::DeviceStatusReportRequest* status); bool GetRunningKioskApp( @@ -302,12 +300,13 @@ // Helpers for the various portions of SESSION STATUS. Return true if they // actually report any status. Functions that queue async queries take - // a |GetStatusState| instance. + // a |DeviceStatusCollectorState| instance. bool GetKioskSessionStatus( enterprise_management::SessionStatusReportRequest* status); bool GetAndroidStatus( enterprise_management::SessionStatusReportRequest* status, - const scoped_refptr<GetStatusState>& state); // Queues async queries! + const scoped_refptr<DeviceStatusCollectorState>& + state); // Queues async queries! bool GetCrostiniUsage( enterprise_management::SessionStatusReportRequest* status, Profile* profile); @@ -319,8 +318,8 @@ void ReceiveCPUStatistics(const base::Time& timestamp, const std::string& statistics); - // Callback for RuntimeProbe that samples probe live data. |callback| will be - // called once all sampling is finished. + // Callback for RuntimeProbe that samples probe live data. |callback| will + // be called once all sampling is finished. void SampleProbeData(std::unique_ptr<SampledData> sample, SamplingProbeResultCallback callback, base::Optional<runtime_probe::ProbeResult> result); @@ -342,14 +341,12 @@ // ProbeDataReceiver interface implementation, fetches data from // RuntimeProbe passes it to |callback| via OnProbeDataFetched(). - void FetchProbeData( - policy::DeviceStatusCollector::ProbeDataReceiver callback); + void FetchProbeData(ProbeDataReceiver callback); // Callback for RuntimeProbe that performs final sampling and // actually invokes |callback|. - void OnProbeDataFetched( - policy::DeviceStatusCollector::ProbeDataReceiver callback, - base::Optional<runtime_probe::ProbeResult> reply); + void OnProbeDataFetched(ProbeDataReceiver callback, + base::Optional<runtime_probe::ProbeResult> reply); // Callback invoked when reporting users pref is changed. void ReportingUsersChanged();
diff --git a/chrome/browser/chromeos/policy/status_collector/status_collector_state.cc b/chrome/browser/chromeos/policy/status_collector/status_collector_state.cc new file mode 100644 index 0000000..24b3a45 --- /dev/null +++ b/chrome/browser/chromeos/policy/status_collector/status_collector_state.cc
@@ -0,0 +1,28 @@ +// Copyright 2019 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 "chrome/browser/chromeos/policy/status_collector/status_collector_state.h" + +#include "base/bind.h" +#include "base/task/post_task.h" +#include "base/task/task_traits.h" + +namespace policy { + +StatusCollectorState::StatusCollectorState( + const scoped_refptr<base::SequencedTaskRunner> task_runner, + const StatusCollectorCallback& response) + : task_runner_(task_runner), response_(response) {} + +StatusCollectorParams& StatusCollectorState::response_params() { + return response_params_; +} + +// Protected. +StatusCollectorState::~StatusCollectorState() { + task_runner_->PostTask( + FROM_HERE, base::BindOnce(response_, base::Passed(&response_params_))); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/status_collector/status_collector_state.h b/chrome/browser/chromeos/policy/status_collector/status_collector_state.h new file mode 100644 index 0000000..87f3c8e --- /dev/null +++ b/chrome/browser/chromeos/policy/status_collector/status_collector_state.h
@@ -0,0 +1,54 @@ +// Copyright 2019 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 CHROME_BROWSER_CHROMEOS_POLICY_STATUS_COLLECTOR_STATUS_COLLECTOR_STATE_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_STATUS_COLLECTOR_STATUS_COLLECTOR_STATE_H_ + +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" +#include "base/sequenced_task_runner.h" +#include "chrome/browser/chromeos/policy/status_collector/status_collector.h" +#include "components/policy/proto/device_management_backend.pb.h" + +namespace policy { + +// Helper class for state tracking of status queries (sync and async). Creates +// status blobs in the constructor and sends them to the the status response +// callback in the destructor. +// +// Some methods queue async queries to collect data. The response callback of +// these queries holds a reference to the instance of this class, so that the +// destructor will not be invoked and the status response callback will not be +// fired until the original owner of the instance releases its reference and all +// async queries finish. +// +// Therefore, if you create an instance of this class, make sure to release your +// reference after querying all async queries (if any), e.g. by using a local +// |scoped_refptr<StatusCollectorState>| and letting it go out of scope. +class StatusCollectorState + : public base::RefCountedThreadSafe<StatusCollectorState> { + public: + explicit StatusCollectorState( + const scoped_refptr<base::SequencedTaskRunner> task_runner, + const StatusCollectorCallback& response); + + // Returns a reference to the internal state of this object. + StatusCollectorParams& response_params(); + + protected: + friend class base::RefCountedThreadSafe<StatusCollectorState>; + + // Posts the response on the UI thread. As long as there is an outstanding + // async query, the query holds a reference to us, so the destructor is + // not called. + virtual ~StatusCollectorState(); + + const scoped_refptr<base::SequencedTaskRunner> task_runner_; + StatusCollectorCallback response_; + StatusCollectorParams response_params_; +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_STATUS_COLLECTOR_STATUS_COLLECTOR_STATE_H_
diff --git a/chrome/browser/chromeos/policy/status_uploader_unittest.cc b/chrome/browser/chromeos/policy/status_uploader_unittest.cc index a1bcf519..f7a5e33 100644 --- a/chrome/browser/chromeos/policy/status_uploader_unittest.cc +++ b/chrome/browser/chromeos/policy/status_uploader_unittest.cc
@@ -50,6 +50,8 @@ constexpr base::TimeDelta kMinImmediateUploadInterval = base::TimeDelta::FromSeconds(10); +// Using a DeviceStatusCollector to have a concrete StatusCollector, but the +// exact type doesn't really matter, as it is being mocked. class MockDeviceStatusCollector : public policy::DeviceStatusCollector { public: explicit MockDeviceStatusCollector(PrefService* local_state)
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc index 772ac871..96e8a89 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc
@@ -227,7 +227,10 @@ std::unique_ptr<CloudPolicyClient> cloud_policy_client = std::make_unique<CloudPolicyClient>( std::string() /* machine_id */, std::string() /* machine_model */, - std::string() /* brand_code */, device_management_service, + std::string() /* brand_code */, + std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, device_management_service, system_url_loader_factory, nullptr /* signing_service */, chromeos::GetDeviceDMTokenForUserPolicyGetter(account_id_)); CreateComponentCloudPolicyService(
diff --git a/chrome/browser/content_settings/content_settings_default_provider_unittest.cc b/chrome/browser/content_settings/content_settings_default_provider_unittest.cc index 4e6f33b..c58b9252 100644 --- a/chrome/browser/content_settings/content_settings_default_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_default_provider_unittest.cc
@@ -44,10 +44,10 @@ TestUtils::GetContentSetting(&provider_, GURL(), GURL(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), false)); - provider_.SetWebsiteSetting(ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider_.SetWebsiteSetting( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&provider_, GURL(), GURL(), CONTENT_SETTINGS_TYPE_COOKIES, @@ -57,10 +57,10 @@ TestUtils::GetContentSetting(&provider_, GURL(), GURL(), CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), false)); - provider_.SetWebsiteSetting(ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider_.SetWebsiteSetting( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&provider_, GURL(), GURL(), CONTENT_SETTINGS_TYPE_GEOLOCATION, @@ -84,9 +84,7 @@ bool owned = provider_.SetWebsiteSetting( ContentSettingsPattern::FromURL(primary_url), ContentSettingsPattern::FromURL(secondary_url), - CONTENT_SETTINGS_TYPE_COOKIES, - std::string(), - value.get()); + CONTENT_SETTINGS_TYPE_COOKIES, std::string(), std::move(value)); EXPECT_FALSE(owned); EXPECT_EQ(CONTENT_SETTING_ALLOW, TestUtils::GetContentSetting(&provider_, primary_url, secondary_url, @@ -100,27 +98,27 @@ OnContentSettingChanged( _, _, CONTENT_SETTINGS_TYPE_COOKIES, "")); provider_.AddObserver(&mock_observer); - provider_.SetWebsiteSetting(ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider_.SetWebsiteSetting( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_CALL(mock_observer, OnContentSettingChanged( _, _, CONTENT_SETTINGS_TYPE_GEOLOCATION, "")); - provider_.SetWebsiteSetting(ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider_.SetWebsiteSetting( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); } TEST_F(ContentSettingsDefaultProviderTest, ObservePref) { PrefService* prefs = profile_.GetPrefs(); - provider_.SetWebsiteSetting(ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider_.SetWebsiteSetting( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&provider_, GURL(), GURL(), CONTENT_SETTINGS_TYPE_COOKIES, @@ -222,10 +220,10 @@ // Changing content settings on the main provider should also affect the // incognito map. - provider_.SetWebsiteSetting(ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider_.SetWebsiteSetting( + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting( &provider_, GURL(), GURL(), CONTENT_SETTINGS_TYPE_COOKIES, @@ -239,11 +237,8 @@ // Changing content settings on the incognito provider should be ignored. std::unique_ptr<base::Value> value(new base::Value(CONTENT_SETTING_ALLOW)); bool owned = otr_provider.SetWebsiteSetting( - ContentSettingsPattern::Wildcard(), - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_COOKIES, - std::string(), - value.release()); + ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_COOKIES, std::string(), std::move(value)); EXPECT_TRUE(owned); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(
diff --git a/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc b/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc index 276f59e..0214ca0 100644 --- a/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc
@@ -193,11 +193,9 @@ // SetWebsiteSetting does nothing. std::unique_ptr<base::Value> value_block( new base::Value(CONTENT_SETTING_BLOCK)); - bool owned = provider.SetWebsiteSetting(yt_url_pattern, - yt_url_pattern, - CONTENT_SETTINGS_TYPE_COOKIES, - std::string(), - value_block.get()); + bool owned = provider.SetWebsiteSetting( + yt_url_pattern, yt_url_pattern, CONTENT_SETTINGS_TYPE_COOKIES, + std::string(), std::move(value_block)); EXPECT_FALSE(owned); EXPECT_EQ(CONTENT_SETTING_DEFAULT, TestUtils::GetContentSetting(&provider, youtube_url, youtube_url,
diff --git a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc index 951c93d6..9caec49 100644 --- a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc
@@ -112,7 +112,7 @@ const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, const ResourceIdentifier& resource_identifier, - base::Value* in_value) { + std::unique_ptr<base::Value>&& in_value) { auto* registry = ContentSettingsRegistry::GetInstance(); auto* content_setting_info = registry->Get(CONTENT_SETTINGS_TYPE_PLUGINS); PrefChangeRegistrar pref_change_registrar; @@ -123,7 +123,7 @@ false /* is_incognito */, base::DoNothing()); return content_settings_pref.SetWebsiteSetting( primary_pattern, secondary_pattern, resource_identifier, - base::Time::Now(), in_value); + base::Time::Now(), std::move(in_value)); } class PrefProviderTest : public testing::Test { @@ -155,7 +155,7 @@ pref_content_settings_provider.SetWebsiteSetting( pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); pref_content_settings_provider.ShutdownOnUIThread(); } @@ -247,7 +247,7 @@ ContentSettingsPattern::FromString("[*.]example.com"); pref_content_settings_provider.SetWebsiteSetting( pattern, pattern, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); GURL host("http://example.com/"); // The value should of course be visible in the regular PrefProvider. @@ -287,9 +287,9 @@ &provider, primary_url, primary_url, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), false)); - provider.SetWebsiteSetting(primary_pattern, primary_pattern, - CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider.SetWebsiteSetting( + primary_pattern, primary_pattern, CONTENT_SETTINGS_TYPE_COOKIES, + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&provider, primary_url, primary_url, CONTENT_SETTINGS_TYPE_COOKIES, @@ -303,7 +303,7 @@ provider.SetWebsiteSetting(primary_pattern, primary_pattern, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - NULL); + nullptr); EXPECT_EQ(NULL, TestUtils::GetContentSettingValue( &provider, primary_url, primary_url, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), false)); @@ -333,7 +333,7 @@ std::string(), false)); pref_content_settings_provider.SetWebsiteSetting( pattern1, pattern1, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&pref_content_settings_provider, host1, host1, CONTENT_SETTINGS_TYPE_COOKIES, @@ -349,7 +349,7 @@ std::string(), false)); pref_content_settings_provider.SetWebsiteSetting( pattern2, pattern2, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&pref_content_settings_provider, host3, host3, CONTENT_SETTINGS_TYPE_COOKIES, @@ -361,7 +361,7 @@ std::string(), false)); pref_content_settings_provider.SetWebsiteSetting( pattern3, pattern3, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&pref_content_settings_provider, host4, host4, CONTENT_SETTINGS_TYPE_COOKIES, @@ -388,11 +388,9 @@ host, CONTENT_SETTINGS_TYPE_PLUGINS, resource1, false)); std::unique_ptr<base::Value> value(new base::Value(CONTENT_SETTING_BLOCK)); - if (pref_content_settings_provider.SetWebsiteSetting( - pattern, pattern, CONTENT_SETTINGS_TYPE_PLUGINS, resource1, - value.get())) { - value.release(); - } + pref_content_settings_provider.SetWebsiteSetting( + pattern, pattern, CONTENT_SETTINGS_TYPE_PLUGINS, resource1, + std::move(value)); ASSERT_EQ(ContentSettingsInfo::EPHEMERAL, ContentSettingsRegistry::GetInstance() @@ -452,9 +450,9 @@ // Create a normal provider and set a setting. PrefProvider normal_provider(&prefs, false /* incognito */, true /* store_last_modified */); - normal_provider.SetWebsiteSetting(pattern_1, wildcard, - CONTENT_SETTINGS_TYPE_COOKIES, - std::string(), value->DeepCopy()); + normal_provider.SetWebsiteSetting( + pattern_1, wildcard, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + std::make_unique<base::Value>(value->Clone())); // Non-OTR provider, Non-OTR iterator has one setting (pattern 1). { @@ -475,9 +473,9 @@ // Create an incognito provider and set a setting. PrefProvider incognito_provider(&prefs, true /* incognito */, true /* store_last_modified */); - incognito_provider.SetWebsiteSetting(pattern_2, wildcard, - CONTENT_SETTINGS_TYPE_COOKIES, - std::string(), value->DeepCopy()); + incognito_provider.SetWebsiteSetting( + pattern_2, wildcard, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), + std::make_unique<base::Value>(value->Clone())); // OTR provider, non-OTR iterator has one setting (pattern 1). { @@ -515,14 +513,14 @@ true /* store_last_modified */); // Non-empty pattern, syncable, empty resource identifier. - provider.SetWebsiteSetting(pattern, wildcard, - CONTENT_SETTINGS_TYPE_JAVASCRIPT, - ResourceIdentifier(), value->DeepCopy()); + provider.SetWebsiteSetting( + pattern, wildcard, CONTENT_SETTINGS_TYPE_JAVASCRIPT, ResourceIdentifier(), + std::make_unique<base::Value>(value->Clone())); // Non-empty pattern, non-syncable, empty resource identifier. - provider.SetWebsiteSetting(pattern, wildcard, - CONTENT_SETTINGS_TYPE_GEOLOCATION, - ResourceIdentifier(), value->DeepCopy()); + provider.SetWebsiteSetting( + pattern, wildcard, CONTENT_SETTINGS_TYPE_GEOLOCATION, + ResourceIdentifier(), std::make_unique<base::Value>(value->Clone())); #if BUILDFLAG(ENABLE_PLUGINS) // Plugin settings became emphemeral as of Chrome M71 and are no longer @@ -536,21 +534,24 @@ // Legacy, persisted exception for CONTENT_SETTINGS_TYPE_PLUGINS with a // non-empty pattern, and non-empty resource identifier. ASSERT_TRUE(SetLegacyPersistedPluginSetting( - &prefs, pattern, wildcard, ResourceIdentifier(), value->DeepCopy())); + &prefs, pattern, wildcard, ResourceIdentifier(), + std::make_unique<base::Value>(value->Clone()))); // Non-empty pattern, plugins, empty resource identifier. provider.SetWebsiteSetting(pattern, wildcard, CONTENT_SETTINGS_TYPE_PLUGINS, - ResourceIdentifier(), value->DeepCopy()); + ResourceIdentifier(), + std::make_unique<base::Value>(value->Clone())); #endif // Non-empty pattern, syncable, empty resource identifier. provider.SetWebsiteSetting(pattern, wildcard, CONTENT_SETTINGS_TYPE_COOKIES, - ResourceIdentifier(), value->DeepCopy()); + ResourceIdentifier(), + std::make_unique<base::Value>(value->Clone())); // Non-empty pattern, non-syncable, empty resource identifier. - provider.SetWebsiteSetting(pattern, wildcard, - CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - ResourceIdentifier(), value->DeepCopy()); + provider.SetWebsiteSetting( + pattern, wildcard, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + ResourceIdentifier(), std::make_unique<base::Value>(value->Clone())); // Test that the preferences for images, geolocation and plugins get cleared. WebsiteSettingsRegistry* registry = WebsiteSettingsRegistry::GetInstance(); @@ -618,10 +619,10 @@ provider.SetWebsiteSetting(pattern_1, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - value->DeepCopy()); + std::make_unique<base::Value>(value->Clone())); provider.SetWebsiteSetting(pattern_2, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - value->DeepCopy()); + std::make_unique<base::Value>(value->Clone())); // Make sure that the timestamps for pattern_1 and patter_2 are before |t2|. test_clock.Advance(base::TimeDelta::FromSeconds(1)); base::Time t2 = test_clock.Now(); @@ -639,7 +640,7 @@ auto value2 = std::make_unique<base::Value>(CONTENT_SETTING_BLOCK); provider.SetWebsiteSetting(pattern_1, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), - value2->DeepCopy()); + std::make_unique<base::Value>(value2->Clone())); last_modified = provider.GetWebsiteSettingLastModified( pattern_1, ContentSettingsPattern::Wildcard(), @@ -684,8 +685,9 @@ ContentSettingsPattern::FromString("https://example.com"); std::unique_ptr<base::Value> value(new base::Value(CONTENT_SETTING_ALLOW)); - EXPECT_FALSE(provider.SetWebsiteSetting( - site_pattern, site_pattern, ephemeral_type, std::string(), value.get())); + EXPECT_FALSE(provider.SetWebsiteSetting(site_pattern, site_pattern, + ephemeral_type, std::string(), + std::move(value))); std::unique_ptr<RuleIterator> rule_iterator = provider.GetRuleIterator(ephemeral_type, std::string(), false); EXPECT_EQ(nullptr, rule_iterator);
diff --git a/chrome/browser/content_settings/content_settings_supervised_provider.cc b/chrome/browser/content_settings/content_settings_supervised_provider.cc index 264096a9..1b58367 100644 --- a/chrome/browser/content_settings/content_settings_supervised_provider.cc +++ b/chrome/browser/content_settings/content_settings_supervised_provider.cc
@@ -103,7 +103,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) { + std::unique_ptr<base::Value>&& value) { return false; }
diff --git a/chrome/browser/content_settings/content_settings_supervised_provider.h b/chrome/browser/content_settings/content_settings_supervised_provider.h index a66e3ac..bc4b542 100644 --- a/chrome/browser/content_settings/content_settings_supervised_provider.h +++ b/chrome/browser/content_settings/content_settings_supervised_provider.h
@@ -35,7 +35,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override;
diff --git a/chrome/browser/content_settings/host_content_settings_map_unittest.cc b/chrome/browser/content_settings/host_content_settings_map_unittest.cc index dd220389..030fd73 100644 --- a/chrome/browser/content_settings/host_content_settings_map_unittest.cc +++ b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
@@ -71,7 +71,7 @@ const ContentSettingsPattern&, ContentSettingsType, const content_settings::ResourceIdentifier&, - base::Value*)); + std::unique_ptr<base::Value>&&)); MOCK_METHOD1(ClearAllContentSettingsRules, void(ContentSettingsType)); @@ -2074,7 +2074,7 @@ content_settings::PrefProvider pref_provider(profile.GetPrefs(), true, true); pref_provider.SetWebsiteSetting( pattern, pattern, ephemeral_type, std::string(), - std::make_unique<base::Value>(CONTENT_SETTING_ALLOW).get()); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); EXPECT_EQ(CONTENT_SETTING_ASK, map->GetContentSetting(url, url, ephemeral_type, std::string()));
diff --git a/chrome/browser/devtools/device/devtools_device_discovery.cc b/chrome/browser/devtools/device/devtools_device_discovery.cc index 0ca19c50..adc8c75 100644 --- a/chrome/browser/devtools/device/devtools_device_discovery.cc +++ b/chrome/browser/devtools/device/devtools_device_discovery.cc
@@ -152,7 +152,7 @@ const std::string& local_id, const std::string& target_path, const std::string& type, - base::Value* value); + base::DictionaryValue* value); ~AgentHostDelegate() override; private: @@ -162,7 +162,7 @@ const std::string& local_id, const std::string& target_path, const std::string& type, - base::Value* value); + base::DictionaryValue* value); // DevToolsExternalAgentProxyDelegate overrides. void Attach(content::DevToolsExternalAgentProxy* proxy) override; void Detach(content::DevToolsExternalAgentProxy* proxy) override; @@ -197,20 +197,22 @@ DISALLOW_COPY_AND_ASSIGN(AgentHostDelegate); }; -static std::string GetStringProperty(const base::Value& value, +static std::string GetStringProperty(base::DictionaryValue* value, const std::string& name) { - const std::string* result = value.FindStringKey(name); - return result ? *result : std::string(); + std::string result; + value->GetString(name, &result); + return result; } -static std::string BuildUniqueTargetId(const std::string& serial, - const std::string& browser_id, - const base::Value& value) { +static std::string BuildUniqueTargetId( + const std::string& serial, + const std::string& browser_id, + base::DictionaryValue* value) { return base::StringPrintf("%s:%s:%s", serial.c_str(), browser_id.c_str(), GetStringProperty(value, "id").c_str()); } -static std::string GetFrontendURLFromValue(const base::Value& value, +static std::string GetFrontendURLFromValue(base::DictionaryValue* value, const std::string& browser_version) { std::string frontend_url = GetStringProperty(value, "devtoolsFrontendUrl"); size_t ws_param = frontend_url.find("?ws"); @@ -223,7 +225,7 @@ return frontend_url; } -static std::string GetTargetPath(const base::Value& value) { +static std::string GetTargetPath(base::DictionaryValue* value) { std::string target_path = GetStringProperty(value, "webSocketDebuggerUrl"); if (base::StartsWith(target_path, "ws://", base::CompareCase::SENSITIVE)) { @@ -246,7 +248,7 @@ const std::string& local_id, const std::string& target_path, const std::string& type, - base::Value* value) { + base::DictionaryValue* value) { DCHECK_CURRENTLY_ON(BrowserThread::UI); scoped_refptr<DevToolsAgentHost> result = DevToolsAgentHost::GetForId(local_id); @@ -268,21 +270,21 @@ const std::string& local_id, const std::string& target_path, const std::string& type, - base::Value* value) + base::DictionaryValue* value) : device_(device), browser_id_(browser_id), local_id_(local_id), target_path_(target_path), remote_type_(type), - remote_id_(value ? GetStringProperty(*value, "id") : ""), - frontend_url_(value ? GetFrontendURLFromValue(*value, browser_version) + remote_id_(value ? GetStringProperty(value, "id") : ""), + frontend_url_(value ? GetFrontendURLFromValue(value, browser_version) : ""), title_(value ? base::UTF16ToUTF8(net::UnescapeForHTML( - base::UTF8ToUTF16(GetStringProperty(*value, "title")))) + base::UTF8ToUTF16(GetStringProperty(value, "title")))) : ""), - description_(value ? GetStringProperty(*value, "description") : ""), - url_(GURL(value ? GetStringProperty(*value, "url") : "")), - favicon_url_(GURL(value ? GetStringProperty(*value, "faviconUrl") : "")), + description_(value ? GetStringProperty(value, "description") : ""), + url_(GURL(value ? GetStringProperty(value, "url") : "")), + favicon_url_(GURL(value ? GetStringProperty(value, "faviconUrl") : "")), agent_host_(nullptr) {} AgentHostDelegate::~AgentHostDelegate() { @@ -457,24 +459,26 @@ if (result < 0) return; // Parse version, append to package name if available, - base::Optional<base::Value> value = base::JSONReader::Read(response); - if (value && value->is_dict()) { - const std::string* browser_name = value->FindStringKey("Browser"); - if (browser_name) { + std::unique_ptr<base::Value> value = + base::JSONReader::ReadDeprecated(response); + base::DictionaryValue* dict; + if (value && value->GetAsDictionary(&dict)) { + std::string browser_name; + if (dict->GetString("Browser", &browser_name)) { std::vector<std::string> parts = base::SplitString( - *browser_name, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + browser_name, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); if (parts.size() == 2) browser->version_ = parts[1]; else - browser->version_ = *browser_name; + browser->version_ = browser_name; } - browser->browser_target_id_ = GetTargetPath(*value); + browser->browser_target_id_ = GetTargetPath(dict); if (browser->browser_target_id_.empty()) browser->browser_target_id_ = kBrowserTargetSocket; - const std::string* package = value->FindStringKey("Android-Package"); - if (package) { + std::string package; + if (dict->GetString("Android-Package", &package)) { browser->display_name_ = - AndroidDeviceManager::GetBrowserName(browser->socket(), *package); + AndroidDeviceManager::GetBrowserName(browser->socket(), package); } } } @@ -487,13 +491,15 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (result < 0) return; - base::Optional<base::Value> value = base::JSONReader::Read(response); - if (value && value->is_list()) { - for (base::Value& page_value : value->GetList()) { - if (page_value.is_dict()) + std::unique_ptr<base::Value> value = + base::JSONReader::ReadDeprecated(response); + base::ListValue* list_value; + if (value && value->GetAsList(&list_value)) { + for (const auto& page_value : *list_value) { + const base::DictionaryValue* dict; + if (page_value.GetAsDictionary(&dict)) browser->pages_.push_back(new RemotePage(device, browser->browser_id_, - browser->version_, - std::move(page_value))); + browser->version_, *dict)); } } } @@ -504,24 +510,25 @@ scoped_refptr<AndroidDeviceManager::Device> device, const std::string& browser_id, const std::string& browser_version, - base::Value dict) + const base::DictionaryValue& dict) : device_(device), browser_id_(browser_id), browser_version_(browser_version), - dict_(std::move(dict)) {} + dict_(dict.DeepCopy()) {} DevToolsDeviceDiscovery::RemotePage::~RemotePage() { } scoped_refptr<content::DevToolsAgentHost> DevToolsDeviceDiscovery::RemotePage::CreateTarget() { - std::string local_id = - BuildUniqueTargetId(device_->serial(), browser_id_, dict_); - std::string target_path = GetTargetPath(dict_); - std::string type = GetStringProperty(dict_, "type"); + std::string local_id = BuildUniqueTargetId(device_->serial(), + browser_id_, + dict_.get()); + std::string target_path = GetTargetPath(dict_.get()); + std::string type = GetStringProperty(dict_.get(), "type"); agent_host_ = AgentHostDelegate::GetOrCreateAgentHost( device_, browser_id_, browser_version_, local_id, target_path, type, - &dict_); + dict_.get()); return agent_host_; }
diff --git a/chrome/browser/devtools/device/devtools_device_discovery.h b/chrome/browser/devtools/device/devtools_device_discovery.h index 5c8d6b1..3cb1453 100644 --- a/chrome/browser/devtools/device/devtools_device_discovery.h +++ b/chrome/browser/devtools/device/devtools_device_discovery.h
@@ -32,7 +32,7 @@ RemotePage(scoped_refptr<AndroidDeviceManager::Device> device, const std::string& browser_id, const std::string& browser_version, - base::Value dict); + const base::DictionaryValue& dict); virtual ~RemotePage(); @@ -40,7 +40,7 @@ std::string browser_id_; std::string browser_version_; std::string frontend_url_; - base::Value dict_; + std::unique_ptr<base::DictionaryValue> dict_; scoped_refptr<content::DevToolsAgentHost> agent_host_; DISALLOW_COPY_AND_ASSIGN(RemotePage);
diff --git a/chrome/browser/devtools/device/port_forwarding_controller.cc b/chrome/browser/devtools/device/port_forwarding_controller.cc index 814533b..1f7f9bb 100644 --- a/chrome/browser/devtools/device/port_forwarding_controller.cc +++ b/chrome/browser/devtools/device/port_forwarding_controller.cc
@@ -54,7 +54,8 @@ kStatusOK = 0, }; -const char kErrorCodePath[] = "error.code"; +const char kErrorCodeParam[] = "code"; +const char kErrorParam[] = "error"; const char kIdParam[] = "id"; const char kMethodParam[] = "method"; const char kParamsParam[] = "params"; @@ -67,47 +68,54 @@ static bool ParseNotification(const std::string& json, std::string* method, - base::Optional<base::Value>* params) { - base::Optional<base::Value> value = base::JSONReader::Read(json); + std::unique_ptr<base::DictionaryValue>* params) { + std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(json); if (!value || !value->is_dict()) return false; - const std::string* method_value = value->FindStringKey(kMethodParam); - if (!method_value) - return false; - *method = *method_value; + std::unique_ptr<base::DictionaryValue> dict( + static_cast<base::DictionaryValue*>(value.release())); - auto extracted_param = value->ExtractKey(kParamsParam); - if (extracted_param && extracted_param->is_dict()) - *params = std::move(extracted_param); + if (!dict->GetString(kMethodParam, method)) + return false; + + std::unique_ptr<base::Value> params_value; + dict->Remove(kParamsParam, ¶ms_value); + if (params_value && params_value->is_dict()) + params->reset(static_cast<base::DictionaryValue*>(params_value.release())); + return true; } static bool ParseResponse(const std::string& json, int* command_id, int* error_code) { - base::Optional<base::Value> value = base::JSONReader::Read(json); + std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(json); if (!value || !value->is_dict()) return false; - base::Optional<int> command_id_opt = value->FindIntKey(kIdParam); - if (!command_id_opt) + + std::unique_ptr<base::DictionaryValue> dict( + static_cast<base::DictionaryValue*>(value.release())); + + if (!dict->GetInteger(kIdParam, command_id)) return false; - *command_id = *command_id_opt; - base::Optional<int> error_value = value->FindIntPath(kErrorCodePath); - if (error_value) - *error_code = *error_value; - + *error_code = 0; + base::DictionaryValue* error_dict = nullptr; + if (dict->GetDictionary(kErrorParam, &error_dict)) + error_dict->GetInteger(kErrorCodeParam, error_code); return true; } -static std::string SerializeCommand(int command_id, - const std::string& method, - base::Value params) { - base::Value command(base::Value::Type::DICTIONARY); - command.SetIntKey(kIdParam, command_id); - command.SetStringKey(kMethodParam, method); - command.SetKey(kParamsParam, std::move(params)); +static std::string SerializeCommand( + int command_id, + const std::string& method, + std::unique_ptr<base::DictionaryValue> params) { + base::DictionaryValue command; + command.SetInteger(kIdParam, command_id); + command.SetString(kMethodParam, method); + if (params) + command.Set(kParamsParam, std::move(params)); std::string json_command; base::JSONWriter::Write(command, &json_command); @@ -481,9 +489,13 @@ void PortForwardingController::Connection::SendCommand( const std::string& method, int port) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::Value params(base::Value::Type::DICTIONARY); - DCHECK(method == kBindMethod || kUnbindMethod == method); - params.SetIntKey(kPortParam, port); + std::unique_ptr<base::DictionaryValue> params(new base::DictionaryValue); + if (method == kBindMethod) { + params->SetInteger(kPortParam, port); + } else { + DCHECK_EQ(kUnbindMethod, method); + params->SetInteger(kPortParam, port); + } int id = ++command_id_; if (method == kBindMethod) { @@ -567,21 +579,20 @@ return; std::string method; - base::Optional<base::Value> params; + std::unique_ptr<base::DictionaryValue> params; if (!ParseNotification(message, &method, ¶ms)) return; if (method != kAcceptedEvent || !params) return; - base::Optional<int> port = params->FindIntKey(kPortParam); - if (!port) - return; - const std::string* connection_id = params->FindStringKey(kConnectionIdParam); - if (!connection_id) + int port; + std::string connection_id; + if (!params->GetInteger(kPortParam, &port) || + !params->GetString(kConnectionIdParam, &connection_id)) return; - auto it = forwarding_map_.find(*port); + auto it = forwarding_map_.find(port); if (it == forwarding_map_.end()) return; @@ -593,7 +604,7 @@ return; std::string destination_host = tokens[0]; - device_->OpenSocket(*connection_id, + device_->OpenSocket(connection_id.c_str(), base::Bind(&SocketTunnel::StartTunnel, profile_, destination_host, destination_port)); } @@ -647,14 +658,15 @@ forwarding_map_.clear(); if (pref_service_->GetBoolean(prefs::kDevToolsPortForwardingEnabled)) { - const base::Value* value = + const base::DictionaryValue* dict = pref_service_->GetDictionary(prefs::kDevToolsPortForwardingConfig); - for (const auto& dict_element : value->DictItems()) { + for (base::DictionaryValue::Iterator it(*dict); + !it.IsAtEnd(); it.Advance()) { int port_num; - if (base::StringToInt(dict_element.first, &port_num) && - dict_element.second.is_string()) { - forwarding_map_[port_num] = dict_element.second.GetString(); - } + std::string location; + if (base::StringToInt(it.key(), &port_num) && + dict->GetString(it.key(), &location)) + forwarding_map_[port_num] = location; } }
diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index b511182..656c6ea 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -572,28 +572,29 @@ const std::string& message) { if (!frontend_host_) return; - const std::string* method = nullptr; - base::Value* params = nullptr; - base::Optional<base::Value> parsed_message = base::JSONReader::Read(message); - if (parsed_message && parsed_message->is_dict()) { - method = parsed_message->FindStringKey(kFrontendHostMethod); - params = parsed_message->FindKey(kFrontendHostParams); - } - if (!method || (params && !params->is_list())) { + std::string method; + base::ListValue empty_params; + base::ListValue* params = &empty_params; + + base::DictionaryValue* dict = NULL; + std::unique_ptr<base::Value> parsed_message = + base::JSONReader::ReadDeprecated(message); + if (!parsed_message || + !parsed_message->GetAsDictionary(&dict) || + !dict->GetString(kFrontendHostMethod, &method) || + (dict->HasKey(kFrontendHostParams) && + !dict->GetList(kFrontendHostParams, ¶ms))) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } - base::Value empty_params(base::Value::Type::LIST); - if (!params) { - params = &empty_params; - } - int id = parsed_message->FindIntKey(kFrontendHostId).value_or(0); - base::ListValue* params_list; - params->GetAsList(¶ms_list); + int id = 0; + dict->GetInteger(kFrontendHostId, &id); embedder_message_dispatcher_->Dispatch( base::Bind(&DevToolsUIBindings::SendMessageAck, - weak_factory_.GetWeakPtr(), id), - *method, params_list); + weak_factory_.GetWeakPtr(), + id), + method, + params); } // content::DevToolsAgentHostClient implementation -------------------------- @@ -849,8 +850,8 @@ if (indexing_jobs_.count(index_request_id) != 0) return; std::vector<std::string> excluded_folders; - base::Optional<base::Value> parsed_excluded_folders = - base::JSONReader::Read(excluded_folders_message); + std::unique_ptr<base::Value> parsed_excluded_folders = + base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { const std::vector<base::Value>& folder_paths = parsed_excluded_folders->GetList(); @@ -933,24 +934,29 @@ const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) { - base::Optional<base::Value> parsed_port_forwarding = - base::JSONReader::Read(port_forwarding_config); - if (!parsed_port_forwarding || !parsed_port_forwarding->is_dict()) + base::DictionaryValue* port_forwarding_dict = nullptr; + std::unique_ptr<base::Value> parsed_port_forwarding = + base::JSONReader::ReadDeprecated(port_forwarding_config); + if (!parsed_port_forwarding || + !parsed_port_forwarding->GetAsDictionary(&port_forwarding_dict)) { return; - base::Optional<base::Value> parsed_network = - base::JSONReader::Read(network_discovery_config); - if (!parsed_network || !parsed_network->is_list()) + } + + base::ListValue* network_list = nullptr; + std::unique_ptr<base::Value> parsed_network = + base::JSONReader::ReadDeprecated(network_discovery_config); + if (!parsed_network || !parsed_network->GetAsList(&network_list)) return; + profile_->GetPrefs()->SetBoolean( prefs::kDevToolsDiscoverUsbDevicesEnabled, discover_usb_devices); profile_->GetPrefs()->SetBoolean( prefs::kDevToolsPortForwardingEnabled, port_forwarding_enabled); profile_->GetPrefs()->Set(prefs::kDevToolsPortForwardingConfig, - *parsed_port_forwarding); + *port_forwarding_dict); profile_->GetPrefs()->SetBoolean(prefs::kDevToolsDiscoverTCPTargetsEnabled, network_discovery_enabled); - profile_->GetPrefs()->Set(prefs::kDevToolsTCPDiscoveryConfig, - *parsed_network); + profile_->GetPrefs()->Set(prefs::kDevToolsTCPDiscoveryConfig, *network_list); } void DevToolsUIBindings::DevicesDiscoveryConfigUpdated() {
diff --git a/chrome/browser/devtools/devtools_window.cc b/chrome/browser/devtools/devtools_window.cc index 350caba..be110f6 100644 --- a/chrome/browser/devtools/devtools_window.cc +++ b/chrome/browser/devtools/devtools_window.cc
@@ -115,14 +115,16 @@ } void SetPreferencesFromJson(Profile* profile, const std::string& json) { - base::Optional<base::Value> parsed = base::JSONReader::Read(json); - if (!parsed || !parsed->is_dict()) + base::DictionaryValue* dict = nullptr; + std::unique_ptr<base::Value> parsed = base::JSONReader::ReadDeprecated(json); + if (!parsed || !parsed->GetAsDictionary(&dict)) return; DictionaryPrefUpdate update(profile->GetPrefs(), prefs::kDevToolsPreferences); - for (const auto& dict_value : parsed->DictItems()) { - if (!dict_value.second.is_string()) + for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { + if (!it.value().is_string()) continue; - update.Get()->SetKey(dict_value.first, std::move(dict_value.second)); + update.Get()->SetWithoutPathExpansion( + it.key(), it.value().CreateDeepCopy()); } } @@ -264,16 +266,22 @@ void DevToolsEventForwarder::SetWhitelistedShortcuts( const std::string& message) { - base::Optional<base::Value> parsed_message = base::JSONReader::Read(message); - if (!parsed_message || !parsed_message->is_list()) - return; - for (const auto& list_item : parsed_message->GetList()) { - if (!list_item.is_dict()) + std::unique_ptr<base::Value> parsed_message = + base::JSONReader::ReadDeprecated(message); + base::ListValue* shortcut_list; + if (!parsed_message || !parsed_message->GetAsList(&shortcut_list)) + return; + auto it = shortcut_list->begin(); + for (; it != shortcut_list->end(); ++it) { + base::DictionaryValue* dictionary; + if (!it->GetAsDictionary(&dictionary)) continue; - int key_code = list_item.FindIntKey("keyCode").value_or(0); + int key_code = 0; + dictionary->GetInteger("keyCode", &key_code); if (key_code == 0) continue; - int modifiers = list_item.FindIntKey("modifiers").value_or(0); + int modifiers = 0; + dictionary->GetInteger("modifiers", &modifiers); if (!KeyWhitelistingAllowed(key_code, modifiers)) { LOG(WARNING) << "Key whitelisting forbidden: " << "(" << key_code << "," << modifiers << ")"; @@ -307,15 +315,14 @@ if (whitelisted_keys_.find(key) == whitelisted_keys_.end()) return false; - base::Value event_data(base::Value::Type::DICTIONARY); - event_data.SetStringKey("type", event_type); - event_data.SetStringKey("key", ui::KeycodeConverter::DomKeyToKeyString( - static_cast<ui::DomKey>(event.dom_key))); - event_data.SetStringKey("code", - ui::KeycodeConverter::DomCodeToCodeString( - static_cast<ui::DomCode>(event.dom_code))); - event_data.SetIntKey("keyCode", key_code); - event_data.SetIntKey("modifiers", modifiers); + base::DictionaryValue event_data; + event_data.SetString("type", event_type); + event_data.SetString("key", ui::KeycodeConverter::DomKeyToKeyString( + static_cast<ui::DomKey>(event.dom_key))); + event_data.SetString("code", ui::KeycodeConverter::DomCodeToCodeString( + static_cast<ui::DomCode>(event.dom_code))); + event_data.SetInteger("keyCode", key_code); + event_data.SetInteger("modifiers", modifiers); devtools_window_->bindings_->CallClientFunction( "DevToolsAPI.keyEventUnhandled", &event_data, NULL, NULL); return true; @@ -1444,14 +1451,32 @@ } void DevToolsWindow::ShowCertificateViewer(const std::string& cert_chain) { - base::Optional<base::Value> value = base::JSONReader::Read(cert_chain); - CHECK(!value || !value->is_list()); + std::unique_ptr<base::Value> value = + base::JSONReader::ReadDeprecated(cert_chain); + if (!value || value->type() != base::Value::Type::LIST) { + NOTREACHED(); + return; + } + + std::unique_ptr<base::ListValue> list = + base::ListValue::From(std::move(value)); std::vector<std::string> decoded; - for (const auto& item : value->GetList()) { - CHECK(!item.is_string()); + for (size_t i = 0; i < list->GetSize(); ++i) { + base::Value* item; + if (!list->Get(i, &item) || !item->is_string()) { + NOTREACHED(); + return; + } std::string temp; - CHECK(!base::Base64Decode(item.GetString(), &temp)); - decoded.push_back(std::move(temp)); + if (!item->GetAsString(&temp)) { + NOTREACHED(); + return; + } + if (!base::Base64Decode(temp, &temp)) { + NOTREACHED(); + return; + } + decoded.push_back(temp); } std::vector<base::StringPiece> cert_string_piece; @@ -1459,7 +1484,10 @@ cert_string_piece.push_back(str); scoped_refptr<net::X509Certificate> cert = net::X509Certificate::CreateFromDERCertChain(cert_string_piece); - CHECK(!cert); + if (!cert) { + NOTREACHED(); + return; + } WebContents* inspected_contents = is_docked_ ? GetInspectedWebContents() : main_web_contents_; @@ -1520,15 +1548,15 @@ // Ensure there is always a default size so that // BrowserFrame::InitBrowserFrame can retrieve it later. DictionaryPrefUpdate update(prefs, prefs::kAppWindowPlacement); - base::Value* wp_prefs = update.Get(); - base::Value dev_tools_defaults(base::Value::Type::DICTIONARY); - dev_tools_defaults.SetIntKey("left", 100); - dev_tools_defaults.SetIntKey("top", 100); - dev_tools_defaults.SetIntKey("right", 740); - dev_tools_defaults.SetIntKey("bottom", 740); - dev_tools_defaults.SetBoolKey("maximized", false); - dev_tools_defaults.SetBoolKey("always_on_top", false); - wp_prefs->SetKey(kDevToolsApp, std::move(dev_tools_defaults)); + base::DictionaryValue* wp_prefs = update.Get(); + auto dev_tools_defaults = std::make_unique<base::DictionaryValue>(); + dev_tools_defaults->SetInteger("left", 100); + dev_tools_defaults->SetInteger("top", 100); + dev_tools_defaults->SetInteger("right", 740); + dev_tools_defaults->SetInteger("bottom", 740); + dev_tools_defaults->SetBoolean("maximized", false); + dev_tools_defaults->SetBoolean("always_on_top", false); + wp_prefs->Set(kDevToolsApp, std::move(dev_tools_defaults)); } browser_ = new Browser(Browser::CreateParams::CreateForDevTools(profile_));
diff --git a/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc b/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc index a2259e7..9a60355 100644 --- a/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc +++ b/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc
@@ -225,19 +225,19 @@ ACTION_TEMPLATE(InvokeCallbackArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - std::get<k>(args).Run(); + std::move(std::get<k>(args)).Run(); } ACTION_TEMPLATE(InvokeCallbackArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(p0)) { - std::get<k>(args).Run(p0); + std::move(std::get<k>(args)).Run(p0); } ACTION_TEMPLATE(InvokeCallbackWithScopedPtrArg, HAS_2_TEMPLATE_PARAMS(int, k, typename, T), AND_1_VALUE_PARAMS(p0)) { - std::get<k>(args).Run(std::unique_ptr<T>(p0)); + std::move(std::get<k>(args)).Run(std::unique_ptr<T>(p0)); } BluetoothGattConnection* CreateGattConnection( @@ -978,7 +978,7 @@ .WillRepeatedly(Return(desc0_.get())); std::vector<uint8_t> value; - EXPECT_CALL(*desc0_, ReadRemoteDescriptor(_, _)) + EXPECT_CALL(*desc0_, ReadRemoteDescriptor_(_, _)) .Times(8) .WillOnce(InvokeCallbackArgument<1>( BluetoothRemoteGattService::GATT_ERROR_FAILED)) @@ -1038,7 +1038,7 @@ .WillRepeatedly(Return(desc0_.get())); std::vector<uint8_t> write_value; - EXPECT_CALL(*desc0_, WriteRemoteDescriptor(_, _, _)) + EXPECT_CALL(*desc0_, WriteRemoteDescriptor_(_, _, _)) .Times(2) .WillOnce(InvokeCallbackArgument<2>( BluetoothRemoteGattService::GATT_ERROR_FAILED))
diff --git a/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc b/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc index 013ef4f1..3e2ffead 100644 --- a/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc +++ b/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc
@@ -37,7 +37,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) { + std::unique_ptr<base::Value>&& value) { return false; }
diff --git a/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h b/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h index 0f84a6a9..fb461b9e 100644 --- a/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h +++ b/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h
@@ -34,7 +34,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override { }
diff --git a/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc b/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc index e53e39d..538751dcb 100644 --- a/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc +++ b/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc
@@ -61,7 +61,9 @@ cloud_policy_client_ = std::make_unique<policy::CloudPolicyClient>( std::string() /* machine_id */, std::string() /* machine_model */, - std::string() /* brand_code */, device_management_service, + std::string() /* brand_code */, std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, device_management_service, std::move(url_loader_factory), nullptr, policy::CloudPolicyClient::DeviceDMTokenCallback()); dm_token_ = policy::BrowserDMTokenStorage::Get()->RetrieveDMToken();
diff --git a/chrome/browser/extensions/api/identity/identity_api.cc b/chrome/browser/extensions/api/identity/identity_api.cc index 49dbcec..ad6f8c01 100644 --- a/chrome/browser/extensions/api/identity/identity_api.cc +++ b/chrome/browser/extensions/api/identity/identity_api.cc
@@ -43,7 +43,7 @@ #if BUILDFLAG(ENABLE_DICE_SUPPORT) const base::Feature kExtensionsAllAccountsFeature{ - "ExtensionsAllAccounts", base::FEATURE_DISABLED_BY_DEFAULT}; + "ExtensionsAllAccounts", base::FEATURE_ENABLED_BY_DEFAULT}; #endif IdentityTokenCacheValue::IdentityTokenCacheValue()
diff --git a/chrome/browser/extensions/chrome_app_icon_unittest.cc b/chrome/browser/extensions/chrome_app_icon_unittest.cc index 58338b7..3167c08 100644 --- a/chrome/browser/extensions/chrome_app_icon_unittest.cc +++ b/chrome/browser/extensions/chrome_app_icon_unittest.cc
@@ -183,8 +183,8 @@ void WaitForIconUpdates(const gfx::ImageSkia& icon) { icon.EnsureRepsForSupportedScales(); - std::unique_ptr<gfx::ImageSkia> reference_image = icon.DeepCopy(); - while (!AreAllImageRepresentationsDifferent(*reference_image, icon)) + gfx::ImageSkia reference_image = icon.DeepCopy(); + while (!AreAllImageRepresentationsDifferent(reference_image, icon)) base::RunLoop().RunUntilIdle(); } @@ -314,8 +314,7 @@ ChromeAppListItem* app_list_item = FindAppListItem(kTestAppId); ASSERT_TRUE(app_list_item); WaitForIconUpdates(app_list_item->icon()); - std::unique_ptr<gfx::ImageSkia> app_list_item_image = - app_list_item->icon().DeepCopy(); + gfx::ImageSkia app_list_item_image = app_list_item->icon().DeepCopy(); const ChromeAppIconService::ResizeFunction resize_function = base::BindRepeating(&app_list::MaybeResizeAndPadIconForMd); @@ -333,7 +332,7 @@ // Now compare with app list icon snapshot. EXPECT_TRUE( - AreEqual(reference_icon_app_list.image_skia(), *app_list_item_image)); + AreEqual(reference_icon_app_list.image_skia(), app_list_item_image)); // Load reference icon sized for the search result. TestAppIcon reference_icon_search(
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 9328a38..99ce4d44 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -2652,8 +2652,8 @@ }, { "name": "per-method-can-make-payment-quota", - // "owners": [ "your-team" ], - "expiry_milestone": 76 + "owners": [ "rouslan" ], + "expiry_milestone": 78 }, { "name": "postscript-printing",
diff --git a/chrome/browser/installable/installed_webapp_provider.cc b/chrome/browser/installable/installed_webapp_provider.cc index 78ca0beb..c004aa5 100644 --- a/chrome/browser/installable/installed_webapp_provider.cc +++ b/chrome/browser/installable/installed_webapp_provider.cc
@@ -72,7 +72,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) { + std::unique_ptr<base::Value>&& value) { // You can't set settings through this provider. return false; }
diff --git a/chrome/browser/installable/installed_webapp_provider.h b/chrome/browser/installable/installed_webapp_provider.h index 1b7d3b8..dfa0c0a 100644 --- a/chrome/browser/installable/installed_webapp_provider.h +++ b/chrome/browser/installable/installed_webapp_provider.h
@@ -33,7 +33,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const content_settings::ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override; void ShutdownOnUIThread() override;
diff --git a/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc b/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc index 163cf7bc..a60f381 100644 --- a/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc +++ b/chrome/browser/media/webrtc/webrtc_video_display_perf_browsertest.cc
@@ -4,6 +4,8 @@ #include <algorithm> +#include "base/json/json_reader.h" +#include "base/strings/string_tokenizer.h" #include "base/strings/stringprintf.h" #include "base/test/trace_event_analyzer.h" #include "chrome/browser/media/webrtc/webrtc_browsertest_base.h" @@ -11,6 +13,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/test/base/tracing.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/common/content_switches.h" @@ -107,6 +110,58 @@ } } +content::WebContents* OpenWebrtcInternalsTab(Browser* browser) { + chrome::AddTabAt(browser, GURL(), -1, true); + ui_test_utils::NavigateToURL(browser, GURL("chrome://webrtc-internals")); + return browser->tab_strip_model()->GetActiveWebContents(); +} + +std::vector<double> ParseGoogMaxDecodeFromWebrtcInternalsTab( + const std::string& webrtc_internals_stats_json) { + std::vector<double> goog_decode_ms; + + std::unique_ptr<base::Value> parsed_json = + base::JSONReader::ReadDeprecated(webrtc_internals_stats_json); + base::DictionaryValue* dictionary = nullptr; + if (!parsed_json.get() || !parsed_json->GetAsDictionary(&dictionary)) + return goog_decode_ms; + ignore_result(parsed_json.release()); + + // |dictionary| should have exactly two entries, one per ssrc. + if (!dictionary || dictionary->size() != 2u) + return goog_decode_ms; + + // Only a given |dictionary| entry will have a "stats" entry that has a key + // that ends with "recv-googMaxDecodeMs" inside (it will start with the ssrc + // id, but we don't care about that). Then collect the string of "values" out + // of that key and convert those into the |goog_decode_ms| vector of doubles. + for (const auto& dictionary_entry : *dictionary) { + for (const auto& ssrc_entry : dictionary_entry.second->DictItems()) { + if (ssrc_entry.first != "stats") + continue; + + for (const auto& stat_entry : ssrc_entry.second.DictItems()) { + if (!base::EndsWith(stat_entry.first, "recv-googMaxDecodeMs", + base::CompareCase::SENSITIVE)) { + continue; + } + base::Value* values_entry = stat_entry.second.FindKey({"values"}); + if (!values_entry) + continue; + base::StringTokenizer values_tokenizer(values_entry->GetString(), + "[,]"); + while (values_tokenizer.GetNext()) { + if (values_tokenizer.token_is_delim()) + continue; + goog_decode_ms.push_back(atof(values_tokenizer.token().c_str()) * + base::Time::kMicrosecondsPerMillisecond); + } + } + } + } + return goog_decode_ms; +} + } // anonymous namespace // Tests the performance of Chrome displaying remote video. @@ -149,6 +204,10 @@ void TestVideoDisplayPerf(const std::string& video_codec) { ASSERT_TRUE(embedded_test_server()->Start()); + // chrome:webrtc-internals doesn't start tracing anything until the + // connection(s) are up. + content::WebContents* webrtc_internals_tab = + OpenWebrtcInternalsTab(browser()); content::WebContents* left_tab = OpenPageAndGetUserMediaInNewTabWithConstraints( @@ -173,10 +232,9 @@ right_tab, disable_cpu_adaptation_constraint); if (!video_codec.empty()) { - SetDefaultVideoCodec(left_tab, video_codec, - true /*prefer_hw_video_codec*/); - SetDefaultVideoCodec(right_tab, video_codec, - true /*prefer_hw_video_codec*/); + constexpr bool kPreferHwVideoCodec = true; + SetDefaultVideoCodec(left_tab, video_codec, kPreferHwVideoCodec); + SetDefaultVideoCodec(right_tab, video_codec, kPreferHwVideoCodec); } NegotiateCall(left_tab, right_tab); @@ -189,6 +247,13 @@ // Run the connection for 5 seconds to collect metrics. test::SleepInJavascript(left_tab, 5000); + const std::string webrtc_internals_stats_json = ExecuteJavascript( + "window.domAutomationController.send(" + " JSON.stringify(peerConnectionDataStore));", + webrtc_internals_tab); + webrtc_decode_latencies_ = + ParseGoogMaxDecodeFromWebrtcInternalsTab(webrtc_internals_stats_json); + std::string json_events; ASSERT_TRUE(tracing::EndTracing(&json_events)); std::unique_ptr<trace_analyzer::TraceAnalyzer> analyzer( @@ -199,6 +264,7 @@ HangUp(right_tab); chrome::CloseWebContents(browser(), left_tab, false); chrome::CloseWebContents(browser(), right_tab, false); + chrome::CloseWebContents(browser(), webrtc_internals_tab, false); ASSERT_TRUE(CalculatePerfResults(analyzer.get(), process_id)); PrintResults(video_codec); @@ -358,6 +424,8 @@ PrintMeanAndMax("Post-decode-to-raster latency", name_modifier, video_frame_submmitter_latencies_); + PrintMeanAndMax("WebRTC decode latency", name_modifier, + webrtc_decode_latencies_); } VideoDisplayPerfTestConfig test_config_; @@ -371,7 +439,10 @@ std::vector<double> total_controlled_durations_; std::vector<double> total_durations_; + // These two put together represent the whole delay from encoded video frames + // to OS swap buffers call (or callback, depending on the platform). std::vector<double> video_frame_submmitter_latencies_; + std::vector<double> webrtc_decode_latencies_; }; INSTANTIATE_TEST_SUITE_P(WebRtcVideoDisplayPerfBrowserTests,
diff --git a/chrome/browser/notifications/notification_channels_provider_android.cc b/chrome/browser/notifications/notification_channels_provider_android.cc index b99d48a..c9bc0095 100644 --- a/chrome/browser/notifications/notification_channels_provider_android.cc +++ b/chrome/browser/notifications/notification_channels_provider_android.cc
@@ -310,7 +310,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const content_settings::ResourceIdentifier& resource_identifier, - base::Value* value) { + std::unique_ptr<base::Value>&& value) { if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS || !platform_supports_channels_) { return false; @@ -328,7 +328,7 @@ DCHECK(!origin.opaque()); const std::string origin_string = origin.Serialize(); - ContentSetting setting = content_settings::ValueToContentSetting(value); + ContentSetting setting = content_settings::ValueToContentSetting(value.get()); switch (setting) { case CONTENT_SETTING_ALLOW: CreateChannelIfRequired(origin_string, @@ -351,7 +351,7 @@ NOTREACHED(); break; } - delete value; + value.reset(); return true; }
diff --git a/chrome/browser/notifications/notification_channels_provider_android.h b/chrome/browser/notifications/notification_channels_provider_android.h index eea17b1..6d9ca9a 100644 --- a/chrome/browser/notifications/notification_channels_provider_android.h +++ b/chrome/browser/notifications/notification_channels_provider_android.h
@@ -92,7 +92,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const content_settings::ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override; void ShutdownOnUIThread() override; base::Time GetWebsiteSettingLastModified(
diff --git a/chrome/browser/notifications/notification_channels_provider_android_unittest.cc b/chrome/browser/notifications/notification_channels_provider_android_unittest.cc index 8e3c0a2..970529f 100644 --- a/chrome/browser/notifications/notification_channels_provider_android_unittest.cc +++ b/chrome/browser/notifications/notification_channels_provider_android_unittest.cc
@@ -165,7 +165,7 @@ bool result = channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_FALSE(result); } @@ -177,7 +177,7 @@ bool result = channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); EXPECT_TRUE(result); std::unique_ptr<content_settings::RuleIterator> rule_iterator = @@ -198,7 +198,7 @@ bool result = channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_TRUE(result); std::unique_ptr<content_settings::RuleIterator> rule_iterator = @@ -219,11 +219,11 @@ channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); bool result = channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); EXPECT_TRUE(result); std::unique_ptr<content_settings::RuleIterator> rule_iterator = @@ -244,11 +244,11 @@ channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); bool result = channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_TRUE(result); std::unique_ptr<content_settings::RuleIterator> rule_iterator = @@ -268,7 +268,7 @@ channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); bool result = channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), @@ -294,7 +294,7 @@ channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); EXPECT_FALSE( channels_provider_->GetRuleIterator(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), true /* incognito */)); @@ -315,14 +315,14 @@ ContentSettingsPattern::FromURLNoWildcard(GURL("https://abc.com")); ContentSettingsPattern xyz_pattern = ContentSettingsPattern::FromURLNoWildcard(GURL("https://xyz.com")); - channels_provider_->SetWebsiteSetting(abc_pattern, ContentSettingsPattern(), - CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); - channels_provider_->SetWebsiteSetting(xyz_pattern, ContentSettingsPattern(), - CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + channels_provider_->SetWebsiteSetting( + abc_pattern, ContentSettingsPattern(), + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); + channels_provider_->SetWebsiteSetting( + xyz_pattern, ContentSettingsPattern(), + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); std::unique_ptr<content_settings::RuleIterator> rule_iterator = channels_provider_->GetRuleIterator(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, @@ -353,7 +353,7 @@ channels_provider_->SetWebsiteSetting( ContentSettingsPattern::FromString("https://example.com"), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_ALLOW)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); content::RunAllTasksUntilIdle(); // Emulate user blocking the channel. @@ -385,14 +385,14 @@ ContentSettingsPattern::FromURLNoWildcard(GURL("https://abc.com")); ContentSettingsPattern xyz_pattern = ContentSettingsPattern::FromURLNoWildcard(GURL("https://xyz.com")); - channels_provider_->SetWebsiteSetting(abc_pattern, ContentSettingsPattern(), - CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); - channels_provider_->SetWebsiteSetting(xyz_pattern, ContentSettingsPattern(), - CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + channels_provider_->SetWebsiteSetting( + abc_pattern, ContentSettingsPattern(), + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); + channels_provider_->SetWebsiteSetting( + xyz_pattern, ContentSettingsPattern(), + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_NE(base::Time(), channels_provider_->GetWebsiteSettingLastModified( @@ -428,14 +428,14 @@ ContentSettingsPattern::FromURLNoWildcard(GURL("https://abc.com")); ContentSettingsPattern xyz_pattern = ContentSettingsPattern::FromURLNoWildcard(GURL("https://xyz.com")); - channels_provider_->SetWebsiteSetting(abc_pattern, ContentSettingsPattern(), - CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); - channels_provider_->SetWebsiteSetting(xyz_pattern, ContentSettingsPattern(), - CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + channels_provider_->SetWebsiteSetting( + abc_pattern, ContentSettingsPattern(), + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); + channels_provider_->SetWebsiteSetting( + xyz_pattern, ContentSettingsPattern(), + CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); channels_provider_->ClearAllContentSettingsRules( CONTENT_SETTINGS_TYPE_COOKIES); @@ -473,7 +473,7 @@ channels_provider_->SetWebsiteSetting( GetTestPattern(), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); auto result = channels_provider_->GetWebsiteSettingLastModified( GetTestPattern(), ContentSettingsPattern(), @@ -502,7 +502,7 @@ channels_provider_->SetWebsiteSetting( ContentSettingsPattern::FromString(first_origin), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_ALLOW)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); clock->Advance(base::TimeDelta::FromSeconds(1)); base::Time last_modified = channels_provider_->GetWebsiteSettingLastModified( @@ -522,7 +522,7 @@ channels_provider_->SetWebsiteSetting( ContentSettingsPattern::FromString(first_origin), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_ALLOW)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); // Last modified time should be updated. last_modified = channels_provider_->GetWebsiteSettingLastModified( @@ -537,7 +537,7 @@ channels_provider_->SetWebsiteSetting( ContentSettingsPattern::FromString(second_origin), ContentSettingsPattern(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_ALLOW)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); // Expect first origin's last-modified time to be unchanged. last_modified = channels_provider_->GetWebsiteSettingLastModified( @@ -554,7 +554,7 @@ old_provider->SetWebsiteSetting( ContentSettingsPattern::FromString("https://blocked.com"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_COOKIES, - std::string(), new base::Value(CONTENT_SETTING_BLOCK)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); channels_provider_->MigrateToChannelsIfNecessary(profile_->GetPrefs(), old_provider.get()); @@ -570,11 +570,11 @@ old_provider->SetWebsiteSetting( ContentSettingsPattern::FromString("https://blocked.com"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_BLOCK)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); old_provider->SetWebsiteSetting( ContentSettingsPattern::FromString("https://allowed.com"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_ALLOW)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); channels_provider_->MigrateToChannelsIfNecessary(profile_->GetPrefs(), old_provider.get()); @@ -590,11 +590,11 @@ old_provider->SetWebsiteSetting( ContentSettingsPattern::FromString("https://blocked.com"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_BLOCK)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); old_provider->SetWebsiteSetting( ContentSettingsPattern::FromString("https://allowed.com"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_ALLOW)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); channels_provider_->MigrateToChannelsIfNecessary(profile_->GetPrefs(), old_provider.get()); @@ -630,7 +630,7 @@ old_provider->SetWebsiteSetting( ContentSettingsPattern::FromString("https://blocked.com"), ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string(), new base::Value(CONTENT_SETTING_BLOCK)); + std::string(), std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); channels_provider_->MigrateToChannelsIfNecessary(profile_->GetPrefs(), old_provider.get());
diff --git a/chrome/browser/permissions/chooser_context_base.cc b/chrome/browser/permissions/chooser_context_base.cc index af8a226..67ac2de 100644 --- a/chrome/browser/permissions/chooser_context_base.cc +++ b/chrome/browser/permissions/chooser_context_base.cc
@@ -26,15 +26,14 @@ ChooserContextBase::Object::Object(GURL requesting_origin, GURL embedding_origin, - base::DictionaryValue* value, + base::Value value, content_settings::SettingSource source, bool incognito) : requesting_origin(requesting_origin), embedding_origin(embedding_origin), + value(std::move(value)), source(source), - incognito(incognito) { - this->value.Swap(value); -} + incognito(incognito) {} ChooserContextBase::Object::~Object() = default; @@ -71,28 +70,23 @@ const GURL& embedding_origin) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); + std::vector<std::unique_ptr<Object>> results; if (!CanRequestObjectPermission(requesting_origin, embedding_origin)) - return {}; + return results; - std::vector<std::unique_ptr<Object>> results; content_settings::SettingInfo info; - std::unique_ptr<base::DictionaryValue> setting = + base::Value setting = GetWebsiteSetting(requesting_origin, embedding_origin, &info); - std::unique_ptr<base::Value> objects; - if (!setting->Remove(kObjectListKey, &objects)) + + base::Value* objects = setting.FindListKey(kObjectListKey); + if (!objects) return results; - std::unique_ptr<base::ListValue> object_list = - base::ListValue::From(std::move(objects)); - if (!object_list) - return results; - - for (auto& object : *object_list) { - base::DictionaryValue* object_dict; - if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) { + for (auto& object : objects->GetList()) { + if (IsValidObject(object)) { results.push_back(std::make_unique<Object>( - requesting_origin, embedding_origin, object_dict, info.source, + requesting_origin, embedding_origin, std::move(object), info.source, host_content_settings_map_->is_incognito())); } } @@ -116,21 +110,19 @@ continue; content_settings::SettingInfo info; - std::unique_ptr<base::DictionaryValue> setting = + base::Value setting = GetWebsiteSetting(requesting_origin, embedding_origin, &info); - base::ListValue* object_list; - if (!setting->GetList(kObjectListKey, &object_list)) + base::Value* objects = setting.FindListKey(kObjectListKey); + if (!objects) continue; - for (auto& object : *object_list) { - base::DictionaryValue* object_dict; - if (!object.GetAsDictionary(&object_dict) || - !IsValidObject(*object_dict)) { + for (auto& object : objects->GetList()) { + if (!IsValidObject(object)) { continue; } results.push_back(std::make_unique<Object>( - requesting_origin, embedding_origin, object_dict, info.source, + requesting_origin, embedding_origin, std::move(object), info.source, content_setting.incognito)); } } @@ -138,41 +130,47 @@ return results; } -void ChooserContextBase::GrantObjectPermission( - const GURL& requesting_origin, - const GURL& embedding_origin, - std::unique_ptr<base::DictionaryValue> object) { - DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); - DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); - DCHECK(object); - DCHECK(IsValidObject(*object)); - - std::unique_ptr<base::DictionaryValue> setting = - GetWebsiteSetting(requesting_origin, embedding_origin, /*info=*/nullptr); - base::ListValue* object_list; - if (!setting->GetList(kObjectListKey, &object_list)) { - object_list = - setting->SetList(kObjectListKey, std::make_unique<base::ListValue>()); - } - object_list->AppendIfNotPresent(std::move(object)); - SetWebsiteSetting(requesting_origin, embedding_origin, std::move(setting)); - NotifyPermissionChanged(); -} - -void ChooserContextBase::RevokeObjectPermission( - const GURL& requesting_origin, - const GURL& embedding_origin, - const base::DictionaryValue& object) { +void ChooserContextBase::GrantObjectPermission(const GURL& requesting_origin, + const GURL& embedding_origin, + base::Value object) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); DCHECK(IsValidObject(object)); - std::unique_ptr<base::DictionaryValue> setting = + base::Value setting = GetWebsiteSetting(requesting_origin, embedding_origin, /*info=*/nullptr); - base::ListValue* object_list; - if (!setting->GetList(kObjectListKey, &object_list)) + base::Value* objects = setting.FindListKey(kObjectListKey); + if (!objects) { + objects = + setting.SetKey(kObjectListKey, base::Value(base::Value::Type::LIST)); + } + + auto& object_list = objects->GetList(); + if (!base::ContainsValue(object_list, object)) + object_list.push_back(std::move(object)); + + SetWebsiteSetting(requesting_origin, embedding_origin, std::move(setting)); + NotifyPermissionChanged(); +} + +void ChooserContextBase::RevokeObjectPermission(const GURL& requesting_origin, + const GURL& embedding_origin, + const base::Value& object) { + DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); + DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); + DCHECK(IsValidObject(object)); + + base::Value setting = + GetWebsiteSetting(requesting_origin, embedding_origin, /*info=*/nullptr); + base::Value* objects = setting.FindListKey(kObjectListKey); + if (!objects) return; - object_list->Remove(object, nullptr); + + auto& object_list = objects->GetList(); + auto it = std::find(object_list.begin(), object_list.end(), object); + if (it != object_list.end()) + objects->GetList().erase(it); + SetWebsiteSetting(requesting_origin, embedding_origin, std::move(setting)); NotifyPermissionRevoked(requesting_origin, embedding_origin); } @@ -193,24 +191,23 @@ } } -std::unique_ptr<base::DictionaryValue> ChooserContextBase::GetWebsiteSetting( +base::Value ChooserContextBase::GetWebsiteSetting( const GURL& requesting_origin, const GURL& embedding_origin, content_settings::SettingInfo* info) { - std::unique_ptr<base::DictionaryValue> value = - base::DictionaryValue::From(host_content_settings_map_->GetWebsiteSetting( + std::unique_ptr<base::Value> value = + host_content_settings_map_->GetWebsiteSetting( requesting_origin, embedding_origin, data_content_settings_type_, - std::string(), info)); - if (!value) - value.reset(new base::DictionaryValue()); - - return value; + std::string(), info); + if (value) + return base::Value::FromUniquePtrValue(std::move(value)); + return base::Value(base::Value::Type::DICTIONARY); } void ChooserContextBase::SetWebsiteSetting(const GURL& requesting_origin, const GURL& embedding_origin, - std::unique_ptr<base::Value> value) { + base::Value value) { host_content_settings_map_->SetWebsiteSettingDefaultScope( requesting_origin, embedding_origin, data_content_settings_type_, - std::string(), std::move(value)); + std::string(), base::Value::ToUniquePtrValue(std::move(value))); }
diff --git a/chrome/browser/permissions/chooser_context_base.h b/chrome/browser/permissions/chooser_context_base.h index da19932..4ec269f 100644 --- a/chrome/browser/permissions/chooser_context_base.h +++ b/chrome/browser/permissions/chooser_context_base.h
@@ -26,17 +26,16 @@ class ChooserContextBase : public KeyedService { public: struct Object { - // The contents of |object| are Swap()ed into the internal dictionary. Object(GURL requesting_origin, GURL embedding_origin, - base::DictionaryValue* value, + base::Value value, content_settings::SettingSource source, bool incognito); ~Object(); GURL requesting_origin; GURL embedding_origin; - base::DictionaryValue value; + base::Value value; content_settings::SettingSource source; bool incognito; }; @@ -92,7 +91,7 @@ // |embedding_origin| by writing it into |host_content_settings_map_|. void GrantObjectPermission(const GURL& requesting_origin, const GURL& embedding_origin, - std::unique_ptr<base::DictionaryValue> object); + base::Value object); // Revokes |requesting_origin|'s permission to access |object| when embedded // within |embedding_origin|. @@ -102,14 +101,11 @@ // |host_content_settings_map_|. virtual void RevokeObjectPermission(const GURL& requesting_origin, const GURL& embedding_origin, - const base::DictionaryValue& object); + const base::Value& object); // Validates the structure of an object read from // |host_content_settings_map_|. - virtual bool IsValidObject(const base::DictionaryValue& object) = 0; - - // Returns the human readable string representing the given object. - virtual std::string GetObjectName(const base::DictionaryValue& object) = 0; + virtual bool IsValidObject(const base::Value& object) = 0; protected: void NotifyPermissionChanged(); @@ -121,13 +117,12 @@ base::ObserverList<PermissionObserver> permission_observer_list_; private: - std::unique_ptr<base::DictionaryValue> GetWebsiteSetting( - const GURL& requesting_origin, - const GURL& embedding_origin, - content_settings::SettingInfo* info); + base::Value GetWebsiteSetting(const GURL& requesting_origin, + const GURL& embedding_origin, + content_settings::SettingInfo* info); void SetWebsiteSetting(const GURL& requesting_origin, const GURL& embedding_origin, - std::unique_ptr<base::Value> value); + base::Value value); HostContentSettingsMap* const host_content_settings_map_; };
diff --git a/chrome/browser/permissions/chooser_context_base_unittest.cc b/chrome/browser/permissions/chooser_context_base_unittest.cc index 6ce522f..89a396c 100644 --- a/chrome/browser/permissions/chooser_context_base_unittest.cc +++ b/chrome/browser/permissions/chooser_context_base_unittest.cc
@@ -26,14 +26,9 @@ CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA) {} ~TestChooserContext() override {} - bool IsValidObject(const base::DictionaryValue& object) override { - return object.size() == 2 && object.HasKey(kRequiredKey1) && - object.HasKey(kRequiredKey2); - } - - std::string GetObjectName(const base::DictionaryValue& object) override { - NOTREACHED(); - return std::string(); + bool IsValidObject(const base::Value& object) override { + return object.DictSize() == 2 && object.FindKey(kRequiredKey1) && + object.FindKey(kRequiredKey2); } }; @@ -42,11 +37,14 @@ class ChooserContextBaseTest : public testing::Test { public: ChooserContextBaseTest() - : origin1_("https://google.com"), origin2_("https://chromium.org") { - object1_.SetString(kRequiredKey1, "value1"); - object1_.SetString(kRequiredKey2, "value2"); - object2_.SetString(kRequiredKey1, "value3"); - object2_.SetString(kRequiredKey2, "value4"); + : origin1_("https://google.com"), + origin2_("https://chromium.org"), + object1_(base::Value::Type::DICTIONARY), + object2_(base::Value::Type::DICTIONARY) { + object1_.SetStringKey(kRequiredKey1, "value1"); + object1_.SetStringKey(kRequiredKey2, "value2"); + object2_.SetStringKey(kRequiredKey1, "value3"); + object2_.SetStringKey(kRequiredKey2, "value4"); } ~ChooserContextBaseTest() override {} @@ -60,8 +58,8 @@ protected: GURL origin1_; GURL origin2_; - base::DictionaryValue object1_; - base::DictionaryValue object2_; + base::Value object1_; + base::Value object2_; }; TEST_F(ChooserContextBaseTest, GrantAndRevokeObjectPermissions) { @@ -70,8 +68,8 @@ context.AddObserver(&mock_observer); EXPECT_CALL(mock_observer, OnChooserObjectPermissionChanged(_, _)).Times(2); - context.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); - context.GrantObjectPermission(origin1_, origin1_, object2_.CreateDeepCopy()); + context.GrantObjectPermission(origin1_, origin1_, object1_.Clone()); + context.GrantObjectPermission(origin1_, origin1_, object2_.Clone()); std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = context.GetGrantedObjects(origin1_, origin1_); @@ -101,8 +99,8 @@ context.AddObserver(&mock_observer); EXPECT_CALL(mock_observer, OnChooserObjectPermissionChanged(_, _)).Times(2); - context.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); - context.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); + context.GrantObjectPermission(origin1_, origin1_, object1_.Clone()); + context.GrantObjectPermission(origin1_, origin1_, object1_.Clone()); std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = context.GetGrantedObjects(origin1_, origin1_); @@ -122,7 +120,7 @@ context.AddObserver(&mock_observer); EXPECT_CALL(mock_observer, OnChooserObjectPermissionChanged(_, _)); - context.GrantObjectPermission(origin1_, origin2_, object1_.CreateDeepCopy()); + context.GrantObjectPermission(origin1_, origin2_, object1_.Clone()); std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = context.GetGrantedObjects(origin1_, origin2_); @@ -144,8 +142,8 @@ context.AddObserver(&mock_observer); EXPECT_CALL(mock_observer, OnChooserObjectPermissionChanged(_, _)).Times(2); - context.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); - context.GrantObjectPermission(origin2_, origin2_, object2_.CreateDeepCopy()); + context.GrantObjectPermission(origin1_, origin1_, object1_.Clone()); + context.GrantObjectPermission(origin2_, origin2_, object2_.Clone()); std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = context.GetAllGrantedObjects(); @@ -182,8 +180,8 @@ context.AddObserver(&mock_observer); EXPECT_CALL(mock_observer, OnChooserObjectPermissionChanged(_, _)).Times(2); - context.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); - context.GrantObjectPermission(origin2_, origin2_, object2_.CreateDeepCopy()); + context.GrantObjectPermission(origin1_, origin1_, object1_.Clone()); + context.GrantObjectPermission(origin2_, origin2_, object2_.Clone()); std::vector<std::unique_ptr<ChooserContextBase::Object>> objects1 = context.GetGrantedObjects(origin1_, origin1_); @@ -206,8 +204,8 @@ context.AddObserver(&mock_observer); EXPECT_CALL(mock_observer, OnChooserObjectPermissionChanged(_, _)).Times(2); - context.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); - context.GrantObjectPermission(origin2_, origin2_, object2_.CreateDeepCopy()); + context.GrantObjectPermission(origin1_, origin1_, object1_.Clone()); + context.GrantObjectPermission(origin2_, origin2_, object2_.Clone()); std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = context.GetAllGrantedObjects();
diff --git a/chrome/browser/policy/cloud/machine_level_user_cloud_policy_helper.cc b/chrome/browser/policy/cloud/machine_level_user_cloud_policy_helper.cc index b8561666..218d9eb 100644 --- a/chrome/browser/policy/cloud/machine_level_user_cloud_policy_helper.cc +++ b/chrome/browser/policy/cloud/machine_level_user_cloud_policy_helper.cc
@@ -59,7 +59,10 @@ std::unique_ptr<CloudPolicyClient> policy_client = std::make_unique<CloudPolicyClient>( std::string() /* machine_id */, std::string() /* machine_model */, - std::string() /* brand_code */, device_management_service_, + std::string() /* brand_code */, + std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, device_management_service_, url_loader_factory_, nullptr, CloudPolicyClient::DeviceDMTokenCallback()); @@ -97,7 +100,10 @@ std::unique_ptr<CloudPolicyClient> client = std::make_unique<CloudPolicyClient>( std::string() /* machine_id */, std::string() /* machine_model */, - std::string() /* brand_code */, device_management_service_, + std::string() /* brand_code */, + std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, device_management_service_, url_loader_factory, nullptr, CloudPolicyClient::DeviceDMTokenCallback()); InitializeManager(std::move(client));
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index e857cdc..777b4d3 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -50,6 +50,7 @@ #include "chrome/browser/prefs/origin_trial_prefs.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/previews/previews_lite_page_decider.h" +#include "chrome/browser/previews/previews_offline_helper.h" #include "chrome/browser/profiles/chrome_version_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_impl.h" @@ -683,6 +684,7 @@ PrefProxyConfigTrackerImpl::RegisterProfilePrefs(registry); PrefsTabHelper::RegisterProfilePrefs(registry, locale); PreviewsLitePageDecider::RegisterProfilePrefs(registry); + PreviewsOfflineHelper::RegisterProfilePrefs(registry); Profile::RegisterProfilePrefs(registry); ProfileImpl::RegisterProfilePrefs(registry); ProfileNetworkContextService::RegisterProfilePrefs(registry);
diff --git a/chrome/browser/previews/previews_content_util.cc b/chrome/browser/previews/previews_content_util.cc index 8d5b7ad..af87ffc 100644 --- a/chrome/browser/previews/previews_content_util.cc +++ b/chrome/browser/previews/previews_content_util.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/previews/previews_lite_page_decider.h" #include "chrome/browser/previews/previews_lite_page_navigation_throttle.h" #include "chrome/browser/previews/previews_lite_page_navigation_throttle_manager.h" +#include "chrome/browser/previews/previews_offline_helper.h" #include "chrome/browser/previews/previews_service.h" #include "chrome/browser/previews/previews_service_factory.h" #include "chrome/browser/profiles/profile.h" @@ -238,6 +239,12 @@ if (!is_data_saver_user) return previews_state; + auto* previews_service = + navigation_handle + ? PreviewsServiceFactory::GetForProfile(Profile::FromBrowserContext( + navigation_handle->GetWebContents()->GetBrowserContext())) + : nullptr; + // Offline previews state should not be updated during a redirect. The Offline // Previews URLLoader will not receive an updated PreviewsState, so the state // should stay consistent throughout the navigation. @@ -247,10 +254,21 @@ // Keep the same OFFLINE previews bit as the original URL. previews_state |= (previews_data->allowed_previews_state() & content::OFFLINE_PAGE_ON); - } else if (previews_decider->ShouldAllowPreviewAtNavigationStart( - previews_data, url, is_reload, - previews::PreviewsType::OFFLINE)) { - previews_state |= content::OFFLINE_PAGE_ON; + } else { + bool allow_offline = true; + // If |previews_service| is null, skip the previews offline helper check. + // This only happens in testing. + if (previews_service) { + allow_offline = previews_service->previews_offline_helper() + ->ShouldAttemptOfflinePreview(url); + } + allow_offline = + allow_offline && + previews_decider->ShouldAllowPreviewAtNavigationStart( + previews_data, url, is_reload, previews::PreviewsType::OFFLINE); + + if (allow_offline) + previews_state |= content::OFFLINE_PAGE_ON; } // Check PageHint preview types first.
diff --git a/chrome/browser/previews/previews_offline_helper.cc b/chrome/browser/previews/previews_offline_helper.cc new file mode 100644 index 0000000..28fbe81 --- /dev/null +++ b/chrome/browser/previews/previews_offline_helper.cc
@@ -0,0 +1,208 @@ +// Copyright 2019 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 "chrome/browser/previews/previews_offline_helper.h" + +#include <stdint.h> +#include <string> +#include <vector> + +#include "base/feature_list.h" +#include "base/hash/hash.h" +#include "base/optional.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/stringprintf.h" +#include "base/time/time.h" +#include "chrome/browser/offline_pages/offline_page_model_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "components/offline_pages/buildflags/buildflags.h" +#include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" +#include "components/previews/core/previews_experiments.h" +#include "components/previews/core/previews_features.h" +#include "content/public/browser/browser_context.h" + +namespace { +// Pref key for the available hashed pages kept in class. +const char kHashedAvailablePages[] = "previews.offline_helper.available_pages"; + +std::string HashURL(const GURL& url) { + // We are ok with some hash collisions in exchange for non-arbitrary key + // lengths (as in using the url.spec()). Therefore, use a hash and return that + // as a string since base::DictionaryValue only accepts strings as keys. + std::string clean_url = url.GetAsReferrer().spec(); + uint32_t hash = base::PersistentHash(clean_url); + return base::StringPrintf("%x", hash); +} + +std::string TimeToDictionaryValue(base::Time time) { + return base::NumberToString(time.ToDeltaSinceWindowsEpoch().InMicroseconds()); +} + +base::Optional<base::Time> TimeFromDictionaryValue(std::string value) { + int64_t int_value = 0; + if (!base::StringToInt64(value, &int_value)) + return base::nullopt; + + return base::Time::FromDeltaSinceWindowsEpoch( + base::TimeDelta::FromMicroseconds(int_value)); +} + +// Cleans up the given dictionary by removing all stale (expiry has passed) +// entries. +void RemoveStaleEntries(base::DictionaryValue* dict) { + // TODO(crbug.com/914577): Cap the size of the pref by deleting the oldest one + // above a certain size. + std::vector<std::string> keys_to_delete; + for (const auto& iter : dict->DictItems()) { + // Check for a corrupted value and throw it out if so. + if (!iter.second.is_string()) { + keys_to_delete.push_back(iter.first); + continue; + } + + base::Optional<base::Time> time = + TimeFromDictionaryValue(iter.second.GetString()); + if (!time.has_value()) { + keys_to_delete.push_back(iter.first); + continue; + } + + base::Time expiry = + time.value() + previews::params::OfflinePreviewFreshnessDuration(); + bool is_expired = expiry <= base::Time::Now(); + + if (is_expired) + keys_to_delete.push_back(iter.first); + } + + for (const std::string& key : keys_to_delete) + dict->RemoveKey(key); +} + +} // namespace + +PreviewsOfflineHelper::PreviewsOfflineHelper( + content::BrowserContext* browser_context) + : pref_service_(nullptr), + available_pages_(std::make_unique<base::DictionaryValue>()), + offline_page_model_(nullptr) { + if (!browser_context || browser_context->IsOffTheRecord()) + return; + + pref_service_ = Profile::FromBrowserContext(browser_context)->GetPrefs(); + + available_pages_ = + pref_service_->GetDictionary(kHashedAvailablePages)->CreateDeepCopy(); + + // Tidy up the pref in case it's been a while since the last stale item + // removal. + RemoveStaleEntries(available_pages_.get()); + UpdatePref(); + +#if BUILDFLAG(ENABLE_OFFLINE_PAGES) + offline_page_model_ = + offline_pages::OfflinePageModelFactory::GetForBrowserContext( + browser_context); + if (offline_page_model_) + offline_page_model_->AddObserver(this); +#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES) +} + +PreviewsOfflineHelper::~PreviewsOfflineHelper() { + if (offline_page_model_) + offline_page_model_->RemoveObserver(this); +} + +// static +void PreviewsOfflineHelper::RegisterProfilePrefs(PrefRegistrySimple* registry) { + registry->RegisterDictionaryPref(kHashedAvailablePages); +} + +bool PreviewsOfflineHelper::ShouldAttemptOfflinePreview(const GURL& url) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (!base::FeatureList::IsEnabled( + previews::features::kOfflinePreviewsFalsePositivePrevention)) { + // This is the default behavior without this optimization. + return true; + } + std::string hashed_url = HashURL(url); + + base::Value* value = available_pages_->FindKey(hashed_url); + if (!value) + return false; + + if (!value->is_string()) { + NOTREACHED(); + return false; + } + base::Optional<base::Time> time_value = + TimeFromDictionaryValue(value->GetString()); + if (!time_value.has_value()) + return false; + + base::Time expiry = + time_value.value() + previews::params::OfflinePreviewFreshnessDuration(); + bool is_expired = expiry <= base::Time::Now(); + if (is_expired) { + available_pages_->RemoveKey(hashed_url); + UpdatePref(); + } + + return !is_expired; +} + +void PreviewsOfflineHelper::Shutdown() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (offline_page_model_) { + offline_page_model_->RemoveObserver(this); + offline_page_model_ = nullptr; + } +} + +void PreviewsOfflineHelper::OfflinePageModelLoaded( + offline_pages::OfflinePageModel* model) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // TODO(robertogden): Implement. +} + +void PreviewsOfflineHelper::OfflinePageAdded( + offline_pages::OfflinePageModel* model, + const offline_pages::OfflinePageItem& added_page) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + available_pages_->SetKey( + HashURL(added_page.url), + base::Value(TimeToDictionaryValue(added_page.creation_time))); + + // Also remember the original url (pre-redirects) if one exists. + if (!added_page.original_url_if_different.is_empty()) { + available_pages_->SetKey( + HashURL(added_page.original_url_if_different), + base::Value(TimeToDictionaryValue(added_page.creation_time))); + } + + RemoveStaleEntries(available_pages_.get()); + UpdatePref(); +} + +void PreviewsOfflineHelper::OfflinePageDeleted( + const offline_pages::OfflinePageModel::DeletedPageInfo& page_info) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // Has no effect if the url was never in the dictionary. + available_pages_->RemoveKey(HashURL(page_info.url)); + + RemoveStaleEntries(available_pages_.get()); + UpdatePref(); +} + +void PreviewsOfflineHelper::UpdatePref() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (pref_service_) + pref_service_->Set(kHashedAvailablePages, *available_pages_); +}
diff --git a/chrome/browser/previews/previews_offline_helper.h b/chrome/browser/previews/previews_offline_helper.h new file mode 100644 index 0000000..16f7a9a --- /dev/null +++ b/chrome/browser/previews/previews_offline_helper.h
@@ -0,0 +1,73 @@ +// Copyright 2019 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 CHROME_BROWSER_PREVIEWS_PREVIEWS_OFFLINE_HELPER_H_ +#define CHROME_BROWSER_PREVIEWS_PREVIEWS_OFFLINE_HELPER_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/sequence_checker.h" +#include "base/values.h" +#include "components/offline_pages/core/offline_page_model.h" +#include "url/gurl.h" + +class PrefService; + +namespace content { +class BrowserContext; +} // namespace content + +class PrefRegistrySimple; +class PrefService; + +// This class keeps track of available offline pages to help optimize triggering +// of offline previews for cases that have a high probability of actually having +// an offline page to load. +class PreviewsOfflineHelper : public offline_pages::OfflinePageModel::Observer { + public: + explicit PreviewsOfflineHelper(content::BrowserContext* browser_context); + ~PreviewsOfflineHelper() override; + + // Registers the prefs used in this class. + static void RegisterProfilePrefs(PrefRegistrySimple* registry); + + // Returns true if there is a high likelihood that a offline page exists with + // the given URL. + bool ShouldAttemptOfflinePreview(const GURL& url); + + // Removes |this| as an observer from offline pages. + void Shutdown(); + + // offline_pages::OfflinePageModel::Observer: + void OfflinePageModelLoaded(offline_pages::OfflinePageModel* model) override; + void OfflinePageAdded( + offline_pages::OfflinePageModel* model, + const offline_pages::OfflinePageItem& added_page) override; + void OfflinePageDeleted( + const offline_pages::OfflinePageModel::DeletedPageInfo& page_info) + override; + + void SetPrefServiceForTesting(PrefService* pref_service) { + pref_service_ = pref_service; + } + + private: + // Helper method to update |available_pages_| in |pref_service_|. + void UpdatePref(); + + // A reference to the profile's |PrefService|. + PrefService* pref_service_; + + // A mapping from url_hash to original storage time (as a double). + std::unique_ptr<base::DictionaryValue> available_pages_; + + offline_pages::OfflinePageModel* offline_page_model_; + + SEQUENCE_CHECKER(sequence_checker_); + + DISALLOW_COPY_AND_ASSIGN(PreviewsOfflineHelper); +}; + +#endif // CHROME_BROWSER_PREVIEWS_PREVIEWS_OFFLINE_HELPER_H_
diff --git a/chrome/browser/previews/previews_offline_helper_unittest.cc b/chrome/browser/previews/previews_offline_helper_unittest.cc new file mode 100644 index 0000000..d6de492 --- /dev/null +++ b/chrome/browser/previews/previews_offline_helper_unittest.cc
@@ -0,0 +1,218 @@ +// Copyright 2019 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 "chrome/browser/previews/previews_offline_helper.h" + +#include <memory> +#include <string> +#include <vector> + +#include "base/test/scoped_feature_list.h" +#include "base/time/time.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "components/prefs/testing_pref_service.h" +#include "components/previews/core/previews_experiments.h" +#include "components/previews/core/previews_features.h" +#include "testing/gtest/include/gtest/gtest.h" + +class PreviewsOfflineHelperTest : public ChromeRenderViewHostTestHarness { + public: + void TearDown() override { + if (helper_) + helper_->Shutdown(); + ChromeRenderViewHostTestHarness::TearDown(); + } + + PreviewsOfflineHelper* NewHelper() { + helper_.reset(new PreviewsOfflineHelper(browser_context())); + return helper_.get(); + } + + offline_pages::OfflinePageItem MakeAddedPageItem( + const std::string& url, + const std::string& original_url, + const base::Time& creation_time) { + offline_pages::OfflinePageItem item; + item.url = GURL(url); + item.original_url_if_different = GURL(original_url); + item.creation_time = creation_time; + return item; + } + + offline_pages::OfflinePageModel::DeletedPageInfo MakeDeletedPageInfo( + const std::string& url) { + offline_pages::OfflinePageModel::DeletedPageInfo info; + info.url = GURL(url); + return info; + } + + private: + std::unique_ptr<PreviewsOfflineHelper> helper_; +}; + +TEST_F(PreviewsOfflineHelperTest, TestAddRemovePages) { + struct TestCase { + std::string msg; + bool enable_feature; + std::vector<std::string> add_fresh_pages; + std::vector<std::string> add_expired_pages; + std::vector<std::string> delete_pages; + std::vector<std::string> want_pages; + std::vector<std::string> not_want_pages; + std::string original_url; + size_t want_pref_size; + }; + const TestCase kTestCases[]{ + { + .msg = "All pages should return true when the feature is disabled", + .enable_feature = false, + .add_fresh_pages = {}, + .add_expired_pages = {}, + .delete_pages = {}, + .want_pages = {"http://chromium.org"}, + .not_want_pages = {}, + .original_url = "", + .want_pref_size = 0, + }, + { + .msg = "Unknown page returns false", + .enable_feature = true, + .add_fresh_pages = {}, + .add_expired_pages = {}, + .delete_pages = {}, + .want_pages = {}, + .not_want_pages = {"http://chromium.org"}, + .original_url = "", + .want_pref_size = 0, + }, + { + .msg = "Fresh page returns true", + .enable_feature = true, + .add_fresh_pages = {"http://chromium.org"}, + .add_expired_pages = {}, + .delete_pages = {}, + .want_pages = {"http://chromium.org"}, + .not_want_pages = {}, + .original_url = "", + .want_pref_size = 1, + }, + { + .msg = "Fresh page with the original URL returns true", + .enable_feature = true, + .add_fresh_pages = {"http://chromium.org"}, + .add_expired_pages = {}, + .delete_pages = {}, + .want_pages = {"http://google.com"}, + .not_want_pages = {}, + .original_url = "http://google.com", + .want_pref_size = 2, + }, + { + .msg = "Expired page returns false", + .enable_feature = true, + .add_fresh_pages = {}, + .add_expired_pages = {"http://chromium.org"}, + .delete_pages = {}, + .want_pages = {}, + .not_want_pages = {"http://chromium.org"}, + .original_url = "", + .want_pref_size = 0, + }, + { + .msg = "Added then deleted page returns false", + .enable_feature = true, + .add_fresh_pages = {"http://chromium.org"}, + .add_expired_pages = {}, + .delete_pages = {"http://chromium.org"}, + .want_pages = {}, + .not_want_pages = {"http://chromium.org"}, + .original_url = "", + .want_pref_size = 0, + }, + { + .msg = "Expired then refreshed page returns true", + .enable_feature = true, + .add_fresh_pages = {"http://chromium.org"}, + .add_expired_pages = {"http://chromium.org"}, + .delete_pages = {}, + .want_pages = {"http://chromium.org"}, + .not_want_pages = {}, + .original_url = "", + .want_pref_size = 1, + }, + { + .msg = "URL Fragments don't matter", + .enable_feature = true, + .add_fresh_pages = {"http://chromium.org"}, + .add_expired_pages = {}, + .delete_pages = {}, + .want_pages = {"http://chromium.org", + "http://chromium.org/#previews"}, + .not_want_pages = {}, + .original_url = "", + .want_pref_size = 1, + }, + { + .msg = "URLs with paths are different", + .enable_feature = true, + .add_fresh_pages = {"http://chromium.org/fresh", + "http://chromium.org/fresh_but_deleted"}, + .add_expired_pages = {"http://chromium.org/old"}, + .delete_pages = {"http://chromium.org/fresh_but_deleted"}, + .want_pages = {"http://chromium.org/fresh"}, + .not_want_pages = {"http://chromium.org/old", + "http://chromium.org/fresh_but_deleted"}, + .original_url = "", + .want_pref_size = 1, + }, + }; + + base::Time fresh = base::Time::Now(); + base::Time expired = fresh - + previews::params::OfflinePreviewFreshnessDuration() - + base::TimeDelta::FromHours(1); + + const char kDictKey[] = "previews.offline_helper.available_pages"; + + for (const TestCase& test_case : kTestCases) { + SCOPED_TRACE(test_case.msg); + + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatureState( + previews::features::kOfflinePreviewsFalsePositivePrevention, + test_case.enable_feature); + + TestingPrefServiceSimple test_prefs; + PreviewsOfflineHelper::RegisterProfilePrefs(test_prefs.registry()); + + PreviewsOfflineHelper* helper = NewHelper(); + helper->SetPrefServiceForTesting(&test_prefs); + + // The tests above rely on this ordering. + for (const std::string& expired_page : test_case.add_expired_pages) { + helper->OfflinePageAdded( + nullptr, + MakeAddedPageItem(expired_page, test_case.original_url, expired)); + } + for (const std::string& fresh_page : test_case.add_fresh_pages) { + helper->OfflinePageAdded( + nullptr, + MakeAddedPageItem(fresh_page, test_case.original_url, fresh)); + } + for (const std::string& deleted_page : test_case.delete_pages) { + helper->OfflinePageDeleted(MakeDeletedPageInfo(deleted_page)); + } + + EXPECT_EQ(test_prefs.GetDictionary(kDictKey)->size(), + test_case.want_pref_size); + + for (const std::string want : test_case.want_pages) { + EXPECT_TRUE(helper->ShouldAttemptOfflinePreview(GURL(want))); + } + + for (const std::string not_want : test_case.not_want_pages) { + EXPECT_FALSE(helper->ShouldAttemptOfflinePreview(GURL(not_want))); + } + } +}
diff --git a/chrome/browser/previews/previews_service.cc b/chrome/browser/previews/previews_service.cc index 2fbf933..817006f3 100644 --- a/chrome/browser/previews/previews_service.cc +++ b/chrome/browser/previews/previews_service.cc
@@ -11,6 +11,7 @@ #include "base/time/default_clock.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/previews/previews_lite_page_decider.h" +#include "chrome/browser/previews/previews_offline_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_constants.h" #include "components/blacklist/opt_out_blacklist/opt_out_store.h" @@ -109,6 +110,8 @@ browser_context)), previews_lite_page_decider_( std::make_unique<PreviewsLitePageDecider>(browser_context)), + previews_offline_helper_( + std::make_unique<PreviewsOfflineHelper>(browser_context)), previews_url_loader_factory_( content::BrowserContext::GetDefaultStoragePartition( Profile::FromBrowserContext(browser_context)) @@ -152,7 +155,11 @@ } void PreviewsService::Shutdown() { - previews_lite_page_decider_->Shutdown(); + if (previews_lite_page_decider_) + previews_lite_page_decider_->Shutdown(); + + if (previews_offline_helper_) + previews_offline_helper_->Shutdown(); } void PreviewsService::ClearBlackList(base::Time begin_time,
diff --git a/chrome/browser/previews/previews_service.h b/chrome/browser/previews/previews_service.h index 11e25fa..7932863 100644 --- a/chrome/browser/previews/previews_service.h +++ b/chrome/browser/previews/previews_service.h
@@ -39,6 +39,8 @@ class PreviewsUIService; } +class PreviewsOfflineHelper; + // Keyed service that owns a previews::PreviewsUIService. PreviewsService lives // on the UI thread. class PreviewsService : public KeyedService { @@ -79,6 +81,10 @@ return previews_lite_page_decider_.get(); } + PreviewsOfflineHelper* previews_offline_helper() { + return previews_offline_helper_.get(); + } + // Returns the enabled PreviewsTypes with their version. static blacklist::BlacklistData::AllowedTypesAndVersions GetAllowedPreviews(); @@ -93,6 +99,9 @@ // The server lite page preview decider. std::unique_ptr<PreviewsLitePageDecider> previews_lite_page_decider_; + // The offline previews helper. + std::unique_ptr<PreviewsOfflineHelper> previews_offline_helper_; + // URL Factory for the Previews Optimization Guide's Hints Fetcher. scoped_refptr<network::SharedURLLoaderFactory> previews_url_loader_factory_;
diff --git a/chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.cc b/chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.cc index 158713e..81a89cf1 100644 --- a/chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.cc +++ b/chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.cc
@@ -43,7 +43,7 @@ base::string16 AccessibilityLabelsBubbleModel::GetTitle() const { return l10n_util::GetStringUTF16( - IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_MENU_OPTION); + IDS_CONTENT_CONTEXT_ACCESSIBILITY_LABELS_DIALOG_TITLE); } base::string16 AccessibilityLabelsBubbleModel::GetMessageText() const {
diff --git a/chrome/browser/resources/app_management/main_view.js b/chrome/browser/resources/app_management/main_view.js index 59e0dac..4dd7d91d 100644 --- a/chrome/browser/resources/app_management/main_view.js +++ b/chrome/browser/resources/app_management/main_view.js
@@ -48,7 +48,9 @@ */ onAppsChanged_: function() { this.appsList = Object.values(this.apps_) - .sort((a, b) => a.title.localeCompare(assert(b.title))); + .sort( + (a, b) => app_management.util.alphabeticalSort( + assert(a.title), assert(b.title))); }, /** @private */
diff --git a/chrome/browser/resources/app_management/reducers.js b/chrome/browser/resources/app_management/reducers.js index 3e8a04e01..1a10663 100644 --- a/chrome/browser/resources/app_management/reducers.js +++ b/chrome/browser/resources/app_management/reducers.js
@@ -137,12 +137,19 @@ * @return {SearchState} */ SearchState.startSearch = function(apps, search, action) { + const searchTerm = action.term.toLowerCase(); const results = []; + for (const app of Object.values(apps)) { - if (app.title.includes(action.term)) { + if (app.title.toLowerCase().includes(searchTerm)) { results.push(app); } } + + results.sort( + (a, b) => app_management.util.alphabeticalSort( + assert(a.title), assert(b.title))); + return /** @type {SearchState} */ (Object.assign({}, search, { term: action.term, results: results,
diff --git a/chrome/browser/resources/app_management/util.js b/chrome/browser/resources/app_management/util.js index e995007..5330b4d 100644 --- a/chrome/browser/resources/app_management/util.js +++ b/chrome/browser/resources/app_management/util.js
@@ -208,8 +208,19 @@ return selectedAppId ? state.apps[selectedAppId] : null; } + /** + * A comparator function to sort strings alphabetically. + * + * @param {string} a + * @param {string} b + */ + function alphabeticalSort(a, b) { + return a.localeCompare(b); + } + return { addIfNeeded: addIfNeeded, + alphabeticalSort: alphabeticalSort, createEmptyState: createEmptyState, createInitialState: createInitialState, createPermission: createPermission,
diff --git a/chrome/browser/resources/chromeos/login/md_login.html b/chrome/browser/resources/chromeos/login/md_login.html index c57e172..04e2673 100644 --- a/chrome/browser/resources/chromeos/login/md_login.html +++ b/chrome/browser/resources/chromeos/login/md_login.html
@@ -32,7 +32,6 @@ <script src="chrome://resources/js/event_tracker.js"></script> <script src="chrome://resources/js/cr/event_target.js"></script> <script src="chrome://resources/js/cr/ui.js"></script> -<script src="chrome://resources/js/cr/ui/touch_handler.js"></script> <script src="chrome://resources/js/cr/ui/array_data_model.js"></script> <script src="chrome://resources/js/cr/ui/dialogs.js"></script> <script src="chrome://resources/js/cr/ui/list_selection_controller.js"></script>
diff --git a/chrome/browser/resources/chromeos/login/oobe.html b/chrome/browser/resources/chromeos/login/oobe.html index 506f7b5c..79111f9a 100644 --- a/chrome/browser/resources/chromeos/login/oobe.html +++ b/chrome/browser/resources/chromeos/login/oobe.html
@@ -36,7 +36,6 @@ <script src="chrome://resources/js/event_tracker.js"></script> <script src="chrome://resources/js/cr/event_target.js"></script> <script src="chrome://resources/js/cr/ui.js"></script> -<script src="chrome://resources/js/cr/ui/touch_handler.js"></script> <script src="chrome://resources/js/cr/ui/array_data_model.js"></script> <script src="chrome://resources/js/cr/ui/dialogs.js"></script> <script src="chrome://resources/js/cr/ui/list_selection_controller.js"></script>
diff --git a/chrome/browser/resources/chromeos/login/saml_password_attributes_test.unitjs b/chrome/browser/resources/chromeos/login/saml_password_attributes_test.unitjs index 6575756..fce08225 100644 --- a/chrome/browser/resources/chromeos/login/saml_password_attributes_test.unitjs +++ b/chrome/browser/resources/chromeos/login/saml_password_attributes_test.unitjs
@@ -2,11 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** @const {string} Path to source root. */ -const ROOT_PATH = '../../../../../'; - GEN_INCLUDE([ - ROOT_PATH + 'ui/webui/resources/js/cr.js', + '//ui/webui/resources/js/cr.js', 'saml_timestamps.js', 'saml_password_attributes.js', ]);
diff --git a/chrome/browser/resources/chromeos/login/saml_timestamps_test.unitjs b/chrome/browser/resources/chromeos/login/saml_timestamps_test.unitjs index 5d7d9b4..2069bee 100644 --- a/chrome/browser/resources/chromeos/login/saml_timestamps_test.unitjs +++ b/chrome/browser/resources/chromeos/login/saml_timestamps_test.unitjs
@@ -2,11 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** @const {string} Path to source root. */ -const ROOT_PATH = '../../../../../'; - GEN_INCLUDE([ - ROOT_PATH + 'ui/webui/resources/js/cr.js', + '//ui/webui/resources/js/cr.js', 'saml_timestamps.js', ]);
diff --git a/chrome/browser/resources/chromeos/wallpaper_manager/js/main_scripts.js b/chrome/browser/resources/chromeos/wallpaper_manager/js/main_scripts.js index e8b500c..71abe3e 100644 --- a/chrome/browser/resources/chromeos/wallpaper_manager/js/main_scripts.js +++ b/chrome/browser/resources/chromeos/wallpaper_manager/js/main_scripts.js
@@ -11,8 +11,6 @@ // <include src="../../../../../../ui/webui/resources/js/cr/ui.js"> // <include src="../../../../../../ui/webui/resources/js/cr/event_target.js"> // <include -// src="../../../../../../ui/webui/resources/js/cr/ui/touch_handler.js"> -// <include // src="../../../../../../ui/webui/resources/js/cr/ui/array_data_model.js"> // <include src="../../../../../../ui/webui/resources/js/cr/ui/list_item.js"> // <include
diff --git a/chrome/browser/resources/chromeos/wallpaper_manager/main.html b/chrome/browser/resources/chromeos/wallpaper_manager/main.html index adcd334..13dcbbd 100644 --- a/chrome/browser/resources/chromeos/wallpaper_manager/main.html +++ b/chrome/browser/resources/chromeos/wallpaper_manager/main.html
@@ -25,7 +25,6 @@ <script src="../../../../../ui/webui/resources/js/util.js"></script> <script src="../../../../../ui/webui/resources/js/cr/ui.js"></script> <script src="../../../../../ui/webui/resources/js/cr/event_target.js"></script> - <script src="../../../../../ui/webui/resources/js/cr/ui/touch_handler.js"></script> <script src="../../../../../ui/webui/resources/js/cr/ui/array_data_model.js"></script> <script src="../../../../../ui/webui/resources/js/cr/ui/list_item.js"></script> <script src="../../../../../ui/webui/resources/js/cr/ui/list_selection_model.js"></script>
diff --git a/chrome/browser/serial/serial_chooser_context.cc b/chrome/browser/serial/serial_chooser_context.cc index d52bcbea..7a9c7a9 100644 --- a/chrome/browser/serial/serial_chooser_context.cc +++ b/chrome/browser/serial/serial_chooser_context.cc
@@ -42,10 +42,10 @@ base::Value PortInfoToValue(const device::mojom::SerialPortInfo& port) { base::Value value(base::Value::Type::DICTIONARY); if (port.display_name) - value.SetKey(kPortNameKey, base::Value(*port.display_name)); + value.SetStringKey(kPortNameKey, *port.display_name); else - value.SetKey(kPortNameKey, base::Value(port.path.LossyDisplayName())); - value.SetKey(kTokenKey, base::Value(EncodeToken(port.token))); + value.SetStringKey(kPortNameKey, port.path.LossyDisplayName()); + value.SetStringKey(kTokenKey, EncodeToken(port.token)); return value; } @@ -59,16 +59,17 @@ SerialChooserContext::~SerialChooserContext() = default; -bool SerialChooserContext::IsValidObject(const base::DictionaryValue& object) { +bool SerialChooserContext::IsValidObject(const base::Value& object) { const std::string* token = object.FindStringKey(kTokenKey); - return object.size() == 2 && object.FindStringKey(kPortNameKey) && token && - DecodeToken(*token); + return object.is_dict() && object.DictSize() == 2 && + object.FindStringKey(kPortNameKey) && token && DecodeToken(*token); } -std::string SerialChooserContext::GetObjectName( - const base::DictionaryValue& object) { - DCHECK(IsValidObject(object)); - return *object.FindStringKey(kPortNameKey); +// static +std::string SerialChooserContext::GetObjectName(const base::Value& object) { + const std::string* name = object.FindStringKey(kPortNameKey); + DCHECK(name); + return *name; } std::vector<std::unique_ptr<ChooserContextBase::Object>> @@ -90,13 +91,8 @@ if (it == port_info_.end()) continue; - // Object's constructor should take a base::Value directly. - base::Value clone = it->second.Clone(); - base::DictionaryValue* object; - clone.GetAsDictionary(&object); - objects.push_back(std::make_unique<Object>( - requesting_origin, embedding_origin, object, + requesting_origin, embedding_origin, it->second.Clone(), content_settings::SettingSource::SETTING_SOURCE_USER, is_incognito_)); } @@ -118,13 +114,8 @@ if (it == port_info_.end()) continue; - // Object's constructor should take a base::Value directly. - base::Value clone = it->second.Clone(); - base::DictionaryValue* object; - clone.GetAsDictionary(&object); - objects.push_back(std::make_unique<Object>( - requesting_origin, embedding_origin, object, + requesting_origin, embedding_origin, it->second.Clone(), content_settings::SettingSource::SETTING_SOURCE_USER, is_incognito_)); } } @@ -132,10 +123,9 @@ return objects; } -void SerialChooserContext::RevokeObjectPermission( - const GURL& requesting_origin, - const GURL& embedding_origin, - const base::DictionaryValue& object) { +void SerialChooserContext::RevokeObjectPermission(const GURL& requesting_origin, + const GURL& embedding_origin, + const base::Value& object) { auto origin_it = ephemeral_ports_.find( std::make_pair(url::Origin::Create(requesting_origin), url::Origin::Create(embedding_origin)));
diff --git a/chrome/browser/serial/serial_chooser_context.h b/chrome/browser/serial/serial_chooser_context.h index 7079a73c..b11b315 100644 --- a/chrome/browser/serial/serial_chooser_context.h +++ b/chrome/browser/serial/serial_chooser_context.h
@@ -21,7 +21,7 @@ #include "url/origin.h" namespace base { -class DictionaryValue; +class Value; } class SerialChooserContext : public ChooserContextBase { @@ -30,8 +30,10 @@ ~SerialChooserContext() override; // ChooserContextBase implementation. - bool IsValidObject(const base::DictionaryValue& object) override; - std::string GetObjectName(const base::DictionaryValue& object) override; + bool IsValidObject(const base::Value& object) override; + + // Returns the human readable string representing the given object. + static std::string GetObjectName(const base::Value& object); // In addition these methods from ChooserContextBase are overridden in order // to expose ephemeral devices through the public interface. @@ -41,7 +43,7 @@ std::vector<std::unique_ptr<Object>> GetAllGrantedObjects() override; void RevokeObjectPermission(const GURL& requesting_origin, const GURL& embedding_origin, - const base::DictionaryValue& object) override; + const base::Value& object) override; // Serial-specific interface for granting and checking permissions. void GrantPortPermission(const url::Origin& requesting_origin,
diff --git a/chrome/browser/signin/account_reconcilor_factory.cc b/chrome/browser/signin/account_reconcilor_factory.cc index 3bd5b6c..7576bf3 100644 --- a/chrome/browser/signin/account_reconcilor_factory.cc +++ b/chrome/browser/signin/account_reconcilor_factory.cc
@@ -18,6 +18,7 @@ #include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" +#include "components/signin/core/browser/consistency_cookie_manager_base.h" #include "components/signin/core/browser/mirror_account_reconcilor_delegate.h" #include "components/signin/core/browser/signin_buildflags.h" @@ -33,6 +34,7 @@ #endif #if defined(OS_ANDROID) +#include "components/signin/core/browser/consistency_cookie_manager_android.h" #include "components/signin/core/browser/mice_account_reconcilor_delegate.h" #endif @@ -138,11 +140,14 @@ KeyedService* AccountReconcilorFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); + SigninClient* signin_client = + ChromeSigninClientFactory::GetForProfile(profile); AccountReconcilor* reconcilor = new AccountReconcilor( - IdentityManagerFactory::GetForProfile(profile), - ChromeSigninClientFactory::GetForProfile(profile), + IdentityManagerFactory::GetForProfile(profile), signin_client, CreateAccountReconcilorDelegate(profile)); reconcilor->Initialize(true /* start_reconcile_if_tokens_available */); + reconcilor->SetConsistencyCookieManager( + CreateConsistencyCookieManager(signin_client, reconcilor)); return reconcilor; } @@ -195,3 +200,16 @@ NOTREACHED(); return nullptr; } + +std::unique_ptr<signin::ConsistencyCookieManagerBase> +AccountReconcilorFactory::CreateConsistencyCookieManager( + SigninClient* signin_client, + AccountReconcilor* account_reconcilor) const { +#if defined(OS_ANDROID) + if (base::FeatureList::IsEnabled(signin::kMiceFeature)) { + return std::make_unique<signin::ConsistencyCookieManagerAndroid>( + signin_client, account_reconcilor); + } +#endif + return nullptr; +}
diff --git a/chrome/browser/signin/account_reconcilor_factory.h b/chrome/browser/signin/account_reconcilor_factory.h index 9d3b7b5..a4c9115 100644 --- a/chrome/browser/signin/account_reconcilor_factory.h +++ b/chrome/browser/signin/account_reconcilor_factory.h
@@ -12,10 +12,12 @@ namespace signin { class AccountReconcilorDelegate; +class ConsistencyCookieManagerBase; } class AccountReconcilor; class Profile; +class SigninClient; // Singleton that owns all AccountReconcilors and associates them with // Profiles. Listens for the Profile's destruction notification and cleans up. @@ -43,6 +45,10 @@ // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; + + std::unique_ptr<signin::ConsistencyCookieManagerBase> + CreateConsistencyCookieManager(SigninClient* signin_client, + AccountReconcilor* account_reconcilor) const; }; #endif // CHROME_BROWSER_SIGNIN_ACCOUNT_RECONCILOR_FACTORY_H_
diff --git a/chrome/browser/signin/account_tracker_service_factory.cc b/chrome/browser/signin/account_tracker_service_factory.cc deleted file mode 100644 index 786cafe..0000000 --- a/chrome/browser/signin/account_tracker_service_factory.cc +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright (c) 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. - -#include "chrome/browser/signin/account_tracker_service_factory.h" - -#include <memory> - -#include "chrome/browser/profiles/profile.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/account_tracker_service.h" - -AccountTrackerServiceFactory::AccountTrackerServiceFactory() - : BrowserContextKeyedServiceFactory( - "AccountTrackerServiceFactory", - BrowserContextDependencyManager::GetInstance()) { -} - -AccountTrackerServiceFactory::~AccountTrackerServiceFactory() { -} - -// static -AccountTrackerService* -AccountTrackerServiceFactory::GetForProfile(Profile* profile) { - return static_cast<AccountTrackerService*>( - GetInstance()->GetServiceForBrowserContext(profile, true)); -} - -// static -AccountTrackerServiceFactory* AccountTrackerServiceFactory::GetInstance() { - return base::Singleton<AccountTrackerServiceFactory>::get(); -} - -void AccountTrackerServiceFactory::RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) { - AccountTrackerService::RegisterPrefs(registry); -} - -KeyedService* AccountTrackerServiceFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - Profile* profile = static_cast<Profile*>(context); - AccountTrackerService* service = new AccountTrackerService(); - service->Initialize(profile->GetPrefs(), profile->GetPath()); - return service; -}
diff --git a/chrome/browser/signin/account_tracker_service_factory.h b/chrome/browser/signin/account_tracker_service_factory.h deleted file mode 100644 index d1dd810..0000000 --- a/chrome/browser/signin/account_tracker_service_factory.h +++ /dev/null
@@ -1,45 +0,0 @@ -// 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 CHROME_BROWSER_SIGNIN_ACCOUNT_TRACKER_SERVICE_FACTORY_H_ -#define CHROME_BROWSER_SIGNIN_ACCOUNT_TRACKER_SERVICE_FACTORY_H_ - -#include "base/macros.h" -#include "base/memory/singleton.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -class AccountTrackerService; -class Profile; - -// Singleton that owns all AccountTrackerServices and associates them with -// Profiles. Listens for the Profile's destruction notification and cleans up -// the associated AccountTrackerService. -class AccountTrackerServiceFactory - : public BrowserContextKeyedServiceFactory { - public: - // Returns the instance of AccountTrackerService associated with this - // profile (creating one if none exists). Returns NULL if this profile - // cannot have a AccountTrackerService (for example, if |profile| is - // incognito). - static AccountTrackerService* GetForProfile(Profile* profile); - - // Returns an instance of the AccountTrackerServiceFactory singleton. - static AccountTrackerServiceFactory* GetInstance(); - - private: - friend struct base::DefaultSingletonTraits<AccountTrackerServiceFactory>; - - AccountTrackerServiceFactory(); - ~AccountTrackerServiceFactory() override; - - // BrowserContextKeyedServiceFactory implementation. - void RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; - - DISALLOW_COPY_AND_ASSIGN(AccountTrackerServiceFactory); -}; - -#endif // CHROME_BROWSER_SIGNIN_ACCOUNT_TRACKER_SERVICE_FACTORY_H_
diff --git a/chrome/browser/signin/identity_manager_factory.cc b/chrome/browser/signin/identity_manager_factory.cc index 602af01b..d405d8d 100644 --- a/chrome/browser/signin/identity_manager_factory.cc +++ b/chrome/browser/signin/identity_manager_factory.cc
@@ -11,7 +11,6 @@ #include "chrome/browser/image_fetcher/image_decoder_impl.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" -#include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_builder.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" @@ -48,11 +47,11 @@ // |profile|. May return null if mutation of the signed-in state is not // supported on the current platform. std::unique_ptr<identity::PrimaryAccountMutator> BuildPrimaryAccountMutator( - Profile* profile, + AccountTrackerService* account_tracker_service, ConcreteSigninManager* signin_manager) { #if !defined(OS_CHROMEOS) return std::make_unique<identity::PrimaryAccountMutatorImpl>( - AccountTrackerServiceFactory::GetForProfile(profile), + account_tracker_service, SigninManager::FromSigninManagerBase(signin_manager)); #else return nullptr; @@ -64,12 +63,13 @@ // current platform. std::unique_ptr<identity::AccountsMutator> BuildAccountsMutator( Profile* profile, + AccountTrackerService* account_tracker_service, ProfileOAuth2TokenService* token_service, SigninManagerBase* signin_manager) { #if !defined(OS_ANDROID) return std::make_unique<identity::AccountsMutatorImpl>( - token_service, AccountTrackerServiceFactory::GetForProfile(profile), - signin_manager, profile->GetPrefs()); + token_service, account_tracker_service, signin_manager, + profile->GetPrefs()); #else return nullptr; #endif @@ -77,6 +77,7 @@ std::unique_ptr<ConcreteSigninManager> BuildSigninManager( Profile* profile, + AccountTrackerService* account_tracker_service, ProfileOAuth2TokenService* token_service, GaiaCookieManagerService* gaia_cookie_manager_service) { std::unique_ptr<ConcreteSigninManager> signin_manager; @@ -84,12 +85,10 @@ ChromeSigninClientFactory::GetInstance()->GetForProfile(profile); #if defined(OS_CHROMEOS) signin_manager = std::make_unique<ConcreteSigninManager>( - client, token_service, - AccountTrackerServiceFactory::GetForProfile(profile)); + client, token_service, account_tracker_service); #else signin_manager = std::make_unique<ConcreteSigninManager>( - client, token_service, - AccountTrackerServiceFactory::GetForProfile(profile), + client, token_service, account_tracker_service, gaia_cookie_manager_service, AccountConsistencyModeManager::GetMethodForProfile(profile)); #endif @@ -97,6 +96,13 @@ return signin_manager; } +std::unique_ptr<AccountTrackerService> BuildAccountTrackerService( + Profile* profile) { + auto account_tracker_service = std::make_unique<AccountTrackerService>(); + account_tracker_service->Initialize(profile->GetPrefs(), profile->GetPath()); + return account_tracker_service; +} + std::unique_ptr<AccountFetcherService> BuildAccountFetcherService( SigninClient* signin_client, ProfileOAuth2TokenService* token_service, @@ -125,7 +131,6 @@ #if !defined(OS_ANDROID) DependsOn(WebDataServiceFactory::GetInstance()); #endif - DependsOn(AccountTrackerServiceFactory::GetInstance()); DependsOn(ChromeSigninClientFactory::GetInstance()); } @@ -154,7 +159,6 @@ // static void IdentityManagerFactory::EnsureFactoryAndDependeeFactoriesBuilt() { IdentityManagerFactory::GetInstance(); - AccountTrackerServiceFactory::GetInstance(); ChromeSigninClientFactory::GetInstance(); } @@ -171,20 +175,27 @@ Profile* profile = Profile::FromBrowserContext(context); // Construct the dependencies that IdentityManager will own. - auto token_service = - ProfileOAuth2TokenServiceBuilder::BuildInstanceFor(context); + std::unique_ptr<AccountTrackerService> account_tracker_service = + BuildAccountTrackerService(profile); + + std::unique_ptr<ProfileOAuth2TokenService> token_service = + ProfileOAuth2TokenServiceBuilder::BuildInstanceFor( + context, account_tracker_service.get()); auto gaia_cookie_manager_service = std::make_unique<GaiaCookieManagerService>( token_service.get(), ChromeSigninClientFactory::GetForProfile(profile)); std::unique_ptr<ConcreteSigninManager> signin_manager = BuildSigninManager( - profile, token_service.get(), gaia_cookie_manager_service.get()); + profile, account_tracker_service.get(), token_service.get(), + gaia_cookie_manager_service.get()); std::unique_ptr<identity::PrimaryAccountMutator> primary_account_mutator = - BuildPrimaryAccountMutator(profile, signin_manager.get()); + BuildPrimaryAccountMutator(account_tracker_service.get(), + signin_manager.get()); std::unique_ptr<identity::AccountsMutator> accounts_mutator = - BuildAccountsMutator(profile, token_service.get(), signin_manager.get()); + BuildAccountsMutator(profile, account_tracker_service.get(), + token_service.get(), signin_manager.get()); auto accounts_cookie_mutator = std::make_unique<identity::AccountsCookieMutatorImpl>( @@ -194,16 +205,13 @@ std::make_unique<identity::DiagnosticsProviderImpl>( token_service.get(), gaia_cookie_manager_service.get()); - AccountTrackerService* account_tracker_service = - AccountTrackerServiceFactory::GetForProfile(profile); - std::unique_ptr<AccountFetcherService> account_fetcher_service = BuildAccountFetcherService( ChromeSigninClientFactory::GetForProfile(profile), - token_service.get(), account_tracker_service); + token_service.get(), account_tracker_service.get()); auto identity_manager = std::make_unique<IdentityManagerWrapper>( - account_tracker_service, std::move(token_service), + std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(signin_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), std::move(accounts_mutator), std::move(accounts_cookie_mutator),
diff --git a/chrome/browser/signin/identity_test_environment_profile_adaptor.cc b/chrome/browser/signin/identity_test_environment_profile_adaptor.cc index 50f8c48..509547f6 100644 --- a/chrome/browser/signin/identity_test_environment_profile_adaptor.cc +++ b/chrome/browser/signin/identity_test_environment_profile_adaptor.cc
@@ -5,7 +5,6 @@ #include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" #include "base/bind.h" -#include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" @@ -74,13 +73,10 @@ IdentityTestEnvironmentProfileAdaptor::BuildIdentityManagerForTests( content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); - auto fake_token_service = - std::make_unique<FakeProfileOAuth2TokenService>(profile->GetPrefs()); return identity::IdentityTestEnvironment::BuildIdentityManagerForTests( ChromeSigninClientFactory::GetForProfile(profile), profile->GetPrefs(), - std::move(fake_token_service), - AccountTrackerServiceFactory::GetForProfile(profile)); + profile->GetPath()); } IdentityTestEnvironmentProfileAdaptor::IdentityTestEnvironmentProfileAdaptor(
diff --git a/chrome/browser/signin/profile_oauth2_token_service_builder.cc b/chrome/browser/signin/profile_oauth2_token_service_builder.cc index 7036cd3..86dc82e 100644 --- a/chrome/browser/signin/profile_oauth2_token_service_builder.cc +++ b/chrome/browser/signin/profile_oauth2_token_service_builder.cc
@@ -1,4 +1,4 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright (c) 2019 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. @@ -13,7 +13,6 @@ #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" -#include "chrome/browser/signin/account_tracker_service_factory.h" #include "components/signin/core/browser/device_id_helper.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "content/public/browser/network_service_instance.h" @@ -46,7 +45,8 @@ #if defined(OS_CHROMEOS) std::unique_ptr<signin::ProfileOAuth2TokenServiceDelegateChromeOS> -CreateCrOsOAuthDelegate(Profile* profile) { +CreateCrOsOAuthDelegate(Profile* profile, + AccountTrackerService* account_tracker_service) { chromeos::AccountManagerFactory* factory = g_browser_process->platform_part()->GetAccountManagerFactory(); DCHECK(factory); @@ -58,9 +58,8 @@ !chromeos::ProfileHelper::IsSigninProfile(profile) && !chromeos::ProfileHelper::IsLockScreenAppProfile(profile); return std::make_unique<signin::ProfileOAuth2TokenServiceDelegateChromeOS>( - AccountTrackerServiceFactory::GetInstance()->GetForProfile(profile), - content::GetNetworkConnectionTracker(), account_manager, - is_regular_profile); + account_tracker_service, content::GetNetworkConnectionTracker(), + account_manager, is_regular_profile); } #endif // defined(OS_CHROMEOS) @@ -84,7 +83,9 @@ } std::unique_ptr<MutableProfileOAuth2TokenServiceDelegate> -CreateMutableProfileOAuthDelegate(Profile* profile) { +CreateMutableProfileOAuthDelegate( + Profile* profile, + AccountTrackerService* account_tracker_service) { signin::AccountConsistencyMethod account_consistency = AccountConsistencyModeManager::GetMethodForProfile(profile); // When signin cookies are cleared on exit and Dice is enabled, all tokens @@ -96,8 +97,7 @@ return std::make_unique<MutableProfileOAuth2TokenServiceDelegate>( ChromeSigninClientFactory::GetInstance()->GetForProfile(profile), - AccountTrackerServiceFactory::GetInstance()->GetForProfile(profile), - content::GetNetworkConnectionTracker(), + account_tracker_service, content::GetNetworkConnectionTracker(), WebDataServiceFactory::GetTokenWebDataForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), account_consistency, revoke_all_tokens_on_load, @@ -112,16 +112,17 @@ #endif // !defined(OS_ANDROID) std::unique_ptr<OAuth2TokenServiceDelegate> CreateOAuth2TokenServiceDelegate( - Profile* profile) { + Profile* profile, + AccountTrackerService* account_tracker_service) { #if defined(OS_ANDROID) return std::make_unique<OAuth2TokenServiceDelegateAndroid>( - AccountTrackerServiceFactory::GetInstance()->GetForProfile(profile)); + account_tracker_service); #else // defined(OS_ANDROID) #if defined(OS_CHROMEOS) if (chromeos::switches::IsAccountManagerEnabled()) { - return CreateCrOsOAuthDelegate(profile); + return CreateCrOsOAuthDelegate(profile, account_tracker_service); } #endif // defined(OS_CHROMEOS) @@ -129,7 +130,7 @@ // 1. On all platforms other than Android and Chrome OS. // 2. On Chrome OS, if Account Manager has not been switched on yet // (chromeos::switches::IsAccountManagerEnabled). - return CreateMutableProfileOAuthDelegate(profile); + return CreateMutableProfileOAuthDelegate(profile, account_tracker_service); #endif // defined(OS_ANDROID) } @@ -139,7 +140,8 @@ // static std::unique_ptr<ProfileOAuth2TokenService> ProfileOAuth2TokenServiceBuilder::BuildInstanceFor( - content::BrowserContext* context) { + content::BrowserContext* context, + AccountTrackerService* account_tracker_service) { Profile* profile = static_cast<Profile*>(context); // On ChromeOS the device ID is not managed by the token service. @@ -152,5 +154,6 @@ #endif return std::make_unique<ProfileOAuth2TokenService>( - profile->GetPrefs(), CreateOAuth2TokenServiceDelegate(profile)); + profile->GetPrefs(), + CreateOAuth2TokenServiceDelegate(profile, account_tracker_service)); }
diff --git a/chrome/browser/signin/profile_oauth2_token_service_builder.h b/chrome/browser/signin/profile_oauth2_token_service_builder.h index d528fdc..e98ed992 100644 --- a/chrome/browser/signin/profile_oauth2_token_service_builder.h +++ b/chrome/browser/signin/profile_oauth2_token_service_builder.h
@@ -11,6 +11,7 @@ class BrowserContext; } +class AccountTrackerService; class ProfileOAuth2TokenService; class IdentityManagerFactory; @@ -18,7 +19,8 @@ private: // Builds a ProfileOAuth2TokenService instance for use by IdentityManager. static std::unique_ptr<ProfileOAuth2TokenService> BuildInstanceFor( - content::BrowserContext* context); + content::BrowserContext* context, + AccountTrackerService* account_tracker_service); friend IdentityManagerFactory; };
diff --git a/chrome/browser/sync/test/integration/wallet_helper.cc b/chrome/browser/sync/test/integration/wallet_helper.cc index 5d936a7f..1f8754e 100644 --- a/chrome/browser/sync/test/integration/wallet_helper.cc +++ b/chrome/browser/sync/test/integration/wallet_helper.cc
@@ -584,29 +584,17 @@ } bool AutofillWalletMetadataSizeChecker::IsExitConditionSatisfied() { - // Make sure we do not nest IsExitConditionSatisfiedImpl() (as it can happen - // that OnPersonalDataChanged() gets notified while we're inside - // IsExitConditionSatisfiedImpl(), waiting for the DB task that loads metadata - // to finish). - switch (state_) { - case IDLE: - do { - state_ = CHECKING; - if (IsExitConditionSatisfiedImpl()) { - return true; - } - } while (state_ == SHOULD_RECHECK); - state_ = IDLE; - return false; - case CHECKING: - // Make sure that each IsExitConditionSatisfied() call is followed by a - // IsExitConditionSatisfiedImpl() call so that we do not miss any updates - // to the DB. - state_ = SHOULD_RECHECK; - return false; - case SHOULD_RECHECK: - return false; - } + // This checker used to be flaky (crbug.com/921386) because of using RunLoops + // to load synchronously data from the DB in IsExitConditionSatisfiedImpl. + // Such a waiting RunLoop often processed another OnPersonalDataChanged() call + // resulting in nested RunLoops. This should be avoided now by blocking using + // WaitableEvent, instead. This check enforces that we do not nest it anymore. + DCHECK(!checking_exit_condition_in_flight_) + << "There should be no nested calls for IsExitConditionSatisfied()"; + checking_exit_condition_in_flight_ = true; + bool exit_condition_is_satisfied = IsExitConditionSatisfiedImpl(); + checking_exit_condition_in_flight_ = false; + return exit_condition_is_satisfied; } std::string AutofillWalletMetadataSizeChecker::GetDebugMessage() const {
diff --git a/chrome/browser/sync/test/integration/wallet_helper.h b/chrome/browser/sync/test/integration/wallet_helper.h index 8eba7f97..8b4ae6efe 100644 --- a/chrome/browser/sync/test/integration/wallet_helper.h +++ b/chrome/browser/sync/test/integration/wallet_helper.h
@@ -172,14 +172,11 @@ void OnPersonalDataChanged() override; private: - // A state machine that makes sure we do not nest checking exit conditions. - enum State { IDLE, CHECKING, SHOULD_RECHECK }; - bool IsExitConditionSatisfiedImpl(); - State state_ = IDLE; const int profile_a_; const int profile_b_; + bool checking_exit_condition_in_flight_ = false; }; // Class that enables or disables USS for Wallet metadata based on test
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 3ac01bd..476a18eb 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -359,7 +359,7 @@ public_deps = [ "//components/dom_distiller/core", "//components/sync", - "//components/sync:user_events", + "//components/sync/user_events", "//components/translate/content/browser", "//content/public/browser", ]
diff --git a/chrome/browser/ui/browser_finder.cc b/chrome/browser/ui/browser_finder.cc index f46a024..441237597 100644 --- a/chrome/browser/ui/browser_finder.cc +++ b/chrome/browser/ui/browser_finder.cc
@@ -18,14 +18,6 @@ #include "ui/display/display.h" #include "ui/display/screen.h" -#if defined(OS_WIN) -#include <shobjidl.h> -#include <wrl/client.h> -#include "base/win/windows_version.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#endif - #if defined(OS_CHROMEOS) #include "chrome/browser/ui/ash/multi_user/multi_user_util.h" #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_client.h" @@ -44,40 +36,6 @@ const int kMatchCanSupportWindowFeature = 1 << 1; const int kMatchTabbed = 1 << 2; const int kMatchDisplayId = 1 << 3; -#if defined(OS_WIN) -const int kMatchCurrentWorkspace = 1 << 4; -#endif - -#if defined(OS_WIN) -// Returns true if the browser window is on another virtual desktop, false if -// we can't tell, or it's on the current virtual desktop. -// Must not be called while application is dispatching an input synchronous -// call like SendMessage, because IsWindowOnCurrentVirtualDesktop will return -// an error. -bool IsOnOtherVirtualDesktop(Browser* browser) { - if (base::win::GetVersion() < base::win::Version::WIN10) - return false; - - Microsoft::WRL::ComPtr<IVirtualDesktopManager> virtual_desktop_manager; - if (!SUCCEEDED(::CoCreateInstance(__uuidof(VirtualDesktopManager), nullptr, - CLSCTX_ALL, - IID_PPV_ARGS(&virtual_desktop_manager)))) { - return false; - } - BrowserWindow* window = browser->window(); - // In tests, |window| can be null. - if (!window) - return false; - - BOOL on_current_desktop; - aura::Window* native_win = window->GetNativeWindow(); - return native_win && - SUCCEEDED(virtual_desktop_manager->IsWindowOnCurrentVirtualDesktop( - native_win->GetHost()->GetAcceleratedWidget(), - &on_current_desktop)) && - !on_current_desktop; -} -#endif // OS_WIN // Returns true if the specified |browser| matches the specified arguments. // |match_types| is a bitmask dictating what parameters to match: @@ -135,13 +93,6 @@ if ((match_types & kMatchTabbed) && !browser->is_type_tabbed()) return false; -#if defined(OS_WIN) - if ((match_types & kMatchCurrentWorkspace) && - IsOnOtherVirtualDesktop(browser)) { - return false; - } -#endif // OS_WIN - if (match_types & kMatchDisplayId) { return display::Screen::GetScreen() ->GetDisplayNearestWindow(browser->window()->GetNativeWindow()) @@ -183,9 +134,6 @@ match_types |= kMatchOriginalProfile; if (display_id != display::kInvalidDisplayId) match_types |= kMatchDisplayId; -#if defined(OS_WIN) - match_types |= kMatchCurrentWorkspace; -#endif Browser* browser = FindBrowserMatching(browser_list_impl->begin_last_active(), browser_list_impl->end_last_active(), profile,
diff --git a/chrome/browser/ui/content_settings/content_setting_image_model.cc b/chrome/browser/ui/content_settings/content_setting_image_model.cc index fc87795e..16951d9 100644 --- a/chrome/browser/ui/content_settings/content_setting_image_model.cc +++ b/chrome/browser/ui/content_settings/content_setting_image_model.cc
@@ -587,6 +587,17 @@ if (!blocked && !allowed) return false; + HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile( + Profile::FromBrowserContext(web_contents->GetBrowserContext())); + + // Do not show any indicator if sensors are allowed by default and they were + // not blocked in this page. + if (!blocked && content_type() == CONTENT_SETTINGS_TYPE_SENSORS && + map->GetDefaultContentSetting(content_type(), nullptr) == + CONTENT_SETTING_ALLOW) { + return false; + } + set_icon(kSensorsIcon, allowed ? gfx::kNoneIcon : kBlockedBadgeIcon); set_tooltip(l10n_util::GetStringUTF16(allowed ? IDS_SENSORS_ALLOWED_TOOLTIP : IDS_SENSORS_BLOCKED_TOOLTIP));
diff --git a/chrome/browser/ui/content_settings/content_setting_image_model_unittest.cc b/chrome/browser/ui/content_settings/content_setting_image_model_unittest.cc index d57c3da..14b7068 100644 --- a/chrome/browser/ui/content_settings/content_setting_image_model_unittest.cc +++ b/chrome/browser/ui/content_settings/content_setting_image_model_unittest.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/ui/content_settings/content_setting_image_model.h" + #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chrome_notification_types.h" @@ -9,7 +11,7 @@ #include "chrome/browser/content_settings/tab_specific_content_settings.h" #include "chrome/browser/prerender/prerender_manager.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/content_settings/content_setting_image_model.h" +#include "chrome/grit/generated_resources.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -19,6 +21,7 @@ #include "content/public/test/test_renderer_host.h" #include "net/cookies/cookie_options.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/l10n/l10n_util.h" #include "ui/gfx/color_palette.h" namespace { @@ -121,6 +124,73 @@ EXPECT_FALSE(content_setting_image_model->get_tooltip().empty()); } +TEST_F(ContentSettingImageModelTest, SensorAccessed) { + TabSpecificContentSettings::CreateForWebContents(web_contents()); + TabSpecificContentSettings* content_settings = + TabSpecificContentSettings::FromWebContents(web_contents()); + + auto content_setting_image_model = + ContentSettingImageModel::CreateForContentType( + ContentSettingImageModel::ImageType::SENSORS); + EXPECT_FALSE(content_setting_image_model->is_visible()); + EXPECT_TRUE(content_setting_image_model->get_tooltip().empty()); + + // Allowing by default means sensor access will not cause the indicator to be + // shown. + HostContentSettingsMapFactory::GetForProfile(profile()) + ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_SENSORS, + CONTENT_SETTING_ALLOW); + content_settings->OnContentAllowed(CONTENT_SETTINGS_TYPE_SENSORS); + content_setting_image_model->Update(web_contents()); + EXPECT_FALSE(content_setting_image_model->is_visible()); + EXPECT_TRUE(content_setting_image_model->get_tooltip().empty()); + + content_settings->ClearContentSettingsExceptForNavigationRelatedSettings(); + + // Allowing by default but blocking (e.g. due to a feature policy) causes the + // indicator to be shown. + HostContentSettingsMapFactory::GetForProfile(profile()) + ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_SENSORS, + CONTENT_SETTING_ALLOW); + content_settings->OnContentBlocked(CONTENT_SETTINGS_TYPE_SENSORS); + content_setting_image_model->Update(web_contents()); + EXPECT_TRUE(content_setting_image_model->is_visible()); + EXPECT_TRUE(HasIcon(*content_setting_image_model)); + EXPECT_FALSE(content_setting_image_model->get_tooltip().empty()); + EXPECT_EQ(content_setting_image_model->get_tooltip(), + l10n_util::GetStringUTF16(IDS_SENSORS_BLOCKED_TOOLTIP)); + + content_settings->ClearContentSettingsExceptForNavigationRelatedSettings(); + + // Blocking by default but allowing (e.g. via a site-specific exception) + // causes the indicator to be shown. + HostContentSettingsMapFactory::GetForProfile(profile()) + ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_SENSORS, + CONTENT_SETTING_BLOCK); + content_settings->OnContentAllowed(CONTENT_SETTINGS_TYPE_SENSORS); + content_setting_image_model->Update(web_contents()); + EXPECT_TRUE(content_setting_image_model->is_visible()); + EXPECT_TRUE(HasIcon(*content_setting_image_model)); + EXPECT_FALSE(content_setting_image_model->get_tooltip().empty()); + EXPECT_EQ(content_setting_image_model->get_tooltip(), + l10n_util::GetStringUTF16(IDS_SENSORS_ALLOWED_TOOLTIP)); + + content_settings->ClearContentSettingsExceptForNavigationRelatedSettings(); + + // Blocking access by default also causes the indicator to be shown so users + // can set an exception. + HostContentSettingsMapFactory::GetForProfile(profile()) + ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_SENSORS, + CONTENT_SETTING_BLOCK); + content_settings->OnContentBlocked(CONTENT_SETTINGS_TYPE_SENSORS); + content_setting_image_model->Update(web_contents()); + EXPECT_TRUE(content_setting_image_model->is_visible()); + EXPECT_TRUE(HasIcon(*content_setting_image_model)); + EXPECT_FALSE(content_setting_image_model->get_tooltip().empty()); + EXPECT_EQ(content_setting_image_model->get_tooltip(), + l10n_util::GetStringUTF16(IDS_SENSORS_BLOCKED_TOOLTIP)); +} + // Regression test for http://crbug.com/161854. TEST_F(ContentSettingImageModelTest, NULLTabSpecificContentSettings) { auto content_setting_image_model =
diff --git a/chrome/browser/ui/page_info/page_info.cc b/chrome/browser/ui/page_info/page_info.cc index 980ed729..5e23f325 100644 --- a/chrome/browser/ui/page_info/page_info.cc +++ b/chrome/browser/ui/page_info/page_info.cc
@@ -94,8 +94,8 @@ #endif using base::ASCIIToUTF16; -using base::UTF8ToUTF16; using base::UTF16ToUTF8; +using base::UTF8ToUTF16; using content::BrowserThread; #if defined(FULL_SAFE_BROWSING) using PasswordReuseEvent = @@ -288,12 +288,12 @@ {CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA, &GetUsbChooserContext, IDS_PAGE_INFO_USB_DEVICE_SECONDARY_LABEL, IDS_PAGE_INFO_USB_DEVICE_ALLOWED_BY_POLICY_LABEL, - IDS_PAGE_INFO_DELETE_USB_DEVICE, "name"}, + IDS_PAGE_INFO_DELETE_USB_DEVICE, &UsbChooserContext::GetObjectName}, #if !defined(OS_ANDROID) {CONTENT_SETTINGS_TYPE_SERIAL_CHOOSER_DATA, &GetSerialChooserContext, IDS_PAGE_INFO_SERIAL_PORT_SECONDARY_LABEL, /*allowed_by_policy_description_string_id=*/-1, - IDS_PAGE_INFO_DELETE_SERIAL_PORT, "name"}, + IDS_PAGE_INFO_DELETE_SERIAL_PORT, &SerialChooserContext::GetObjectName}, #endif }; @@ -491,7 +491,7 @@ } void PageInfo::OnSiteChosenObjectDeleted(const ChooserUIInfo& ui_info, - const base::DictionaryValue& object) { + const base::Value& object) { // TODO(reillyg): Create metrics for revocations. crbug.com/556845 ChooserContextBase* context = ui_info.get_context(profile_); const GURL origin = site_url_.GetOrigin();
diff --git a/chrome/browser/ui/page_info/page_info.h b/chrome/browser/ui/page_info/page_info.h index f795f86..2b8ab1b68 100644 --- a/chrome/browser/ui/page_info/page_info.h +++ b/chrome/browser/ui/page_info/page_info.h
@@ -133,7 +133,7 @@ int description_string_id; int allowed_by_policy_description_string_id; int delete_tooltip_string_id; - const char* ui_name_key; + std::string (*get_object_name)(const base::Value&); }; // Creates a PageInfo for the passed |url| using the given |ssl| status @@ -155,7 +155,7 @@ // This method is called whenever access to an object is revoked. void OnSiteChosenObjectDeleted(const ChooserUIInfo& ui_info, - const base::DictionaryValue& object); + const base::Value& object); // This method is called by the UI when the UI is closing. void OnUIClosing();
diff --git a/chrome/browser/ui/page_info/page_info_ui.cc b/chrome/browser/ui/page_info/page_info_ui.cc index cad65668..a03bf33 100644 --- a/chrome/browser/ui/page_info/page_info_ui.cc +++ b/chrome/browser/ui/page_info/page_info_ui.cc
@@ -8,6 +8,7 @@ #include "base/command_line.h" #include "base/stl_util.h" +#include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/permissions/permission_manager.h" @@ -422,9 +423,8 @@ // static base::string16 PageInfoUI::ChosenObjectToUIString( const ChosenObjectInfo& object) { - base::string16 name; - object.chooser_object->value.GetString(object.ui_info.ui_name_key, &name); - return name; + return base::UTF8ToUTF16( + object.ui_info.get_object_name(object.chooser_object->value)); } #if defined(OS_ANDROID)
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index 63f6585..1aa0191 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -912,28 +912,6 @@ } // static -void StartupBrowserCreator::ProcessCommandLineAlreadyRunningImpl( - const base::CommandLine& command_line, - const base::FilePath& cur_dir, - const base::FilePath& profile_path) { - ProfileManager* profile_manager = g_browser_process->profile_manager(); - Profile* profile = profile_manager->GetProfileByPath(profile_path); - - // The profile isn't loaded yet and so needs to be loaded asynchronously. - if (!profile) { - profile_manager->CreateProfileAsync( - profile_path, - base::BindRepeating(&ProcessCommandLineOnProfileCreated, command_line, - cur_dir), - base::string16(), std::string()); - return; - } - StartupBrowserCreator startup_browser_creator; - startup_browser_creator.ProcessCmdLineImpl( - command_line, cur_dir, /*process_startup=*/false, profile, Profiles()); -} - -// static void StartupBrowserCreator::ProcessCommandLineOnProfileCreated( const base::CommandLine& command_line, const base::FilePath& cur_dir, @@ -951,15 +929,20 @@ const base::CommandLine& command_line, const base::FilePath& cur_dir, const base::FilePath& profile_path) { - // The Windows-specific code in browser_finder.cc that determines if a window - // is on the current virtual desktop uses a COM interface that can't be - // invoked if we're processing a SendMessage call. So, we post a task to - // finish the command line processing. - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce( - &StartupBrowserCreator::ProcessCommandLineAlreadyRunningImpl, - command_line, cur_dir, profile_path)); + ProfileManager* profile_manager = g_browser_process->profile_manager(); + Profile* profile = profile_manager->GetProfileByPath(profile_path); + + // The profile isn't loaded yet and so needs to be loaded asynchronously. + if (!profile) { + profile_manager->CreateProfileAsync( + profile_path, + base::Bind(&ProcessCommandLineOnProfileCreated, command_line, cur_dir), + base::string16(), std::string()); + return; + } + StartupBrowserCreator startup_browser_creator; + startup_browser_creator.ProcessCmdLineImpl(command_line, cur_dir, false, + profile, Profiles()); } // static
diff --git a/chrome/browser/ui/startup/startup_browser_creator.h b/chrome/browser/ui/startup/startup_browser_creator.h index 448df5d..187c30d 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.h +++ b/chrome/browser/ui/startup/startup_browser_creator.h
@@ -181,12 +181,6 @@ const base::FilePath& cur_dir, Profile* profile); - // This is run as a task by ProcessCommandLineAlreadyRunning. - static void ProcessCommandLineAlreadyRunningImpl( - const base::CommandLine& command_line, - const base::FilePath& cur_dir, - const base::FilePath& profile_path); - // Callback after a profile has been created. static void ProcessCommandLineOnProfileCreated( const base::CommandLine& command_line,
diff --git a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc index 06d333d..fbb7e5c 100644 --- a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc +++ b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/app_menu_model.h" #include "chrome/grit/generated_resources.h" +#include "components/favicon_base/favicon_request_metrics.h" #include "components/favicon_base/favicon_types.h" #include "components/feature_engagement/buildflags.h" #include "components/prefs/scoped_user_pref_update.h" @@ -575,6 +576,9 @@ scoped_refptr<base::RefCountedMemory> favicon_png; if (open_tabs && open_tabs->GetSyncedFaviconForPageURL(url.spec(), &favicon_png)) { + favicon::RecordFaviconRequestMetric( + favicon::FaviconRequestOrigin::RECENTLY_CLOSED_TABS, + favicon::FaviconAvailability::kSync); gfx::Image image = gfx::Image::CreateFrom1xPNGBytes(favicon_png); SetIcon(index_in_menu, image); return; @@ -603,8 +607,16 @@ void RecentTabsSubMenuModel::OnFaviconDataAvailable( int command_id, const favicon_base::FaviconImageResult& image_result) { - if (image_result.image.IsEmpty()) + if (image_result.image.IsEmpty()) { + favicon::RecordFaviconRequestMetric( + favicon::FaviconRequestOrigin::RECENTLY_CLOSED_TABS, + favicon::FaviconAvailability::kNotAvailable); return; + } + + favicon::RecordFaviconRequestMetric( + favicon::FaviconRequestOrigin::RECENTLY_CLOSED_TABS, + favicon::FaviconAvailability::kLocal); int index_in_menu = GetIndexOfCommandId(command_id); DCHECK_GT(index_in_menu, -1); SetIcon(index_in_menu, image_result.image);
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_sink_button.cc b/chrome/browser/ui/views/media_router/cast_dialog_sink_button.cc index abbf004..0387bd73 100644 --- a/chrome/browser/ui/views/media_router/cast_dialog_sink_button.cc +++ b/chrome/browser/ui/views/media_router/cast_dialog_sink_button.cc
@@ -170,7 +170,6 @@ } void CastDialogSinkButton::OnEnabledChanged() { - HoverButton::OnEnabledChanged(); // Prevent a DCHECK failure seen at https://crbug.com/912687 by not having an // InkDrop if the button is disabled. SetInkDropMode(enabled() ? InkDropMode::ON : InkDropMode::OFF);
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_sink_button.h b/chrome/browser/ui/views/media_router/cast_dialog_sink_button.h index 2a9c6db..b72f44d 100644 --- a/chrome/browser/ui/views/media_router/cast_dialog_sink_button.h +++ b/chrome/browser/ui/views/media_router/cast_dialog_sink_button.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_VIEWS_MEDIA_ROUTER_CAST_DIALOG_SINK_BUTTON_H_ #define CHROME_BROWSER_UI_VIEWS_MEDIA_ROUTER_CAST_DIALOG_SINK_BUTTON_H_ +#include "base/bind.h" #include "chrome/browser/ui/media_router/ui_media_sink.h" #include "chrome/browser/ui/views/hover_button.h" @@ -29,7 +30,6 @@ // views::View: bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; - void OnEnabledChanged() override; void RequestFocus() override; void OnFocus() override; void OnBlur() override; @@ -46,8 +46,14 @@ FRIEND_TEST_ALL_PREFIXES(CastDialogSinkButtonTest, SetStatusLabelForSinkWithIssue); + void OnEnabledChanged(); + const UIMediaSink sink_; base::Optional<base::string16> saved_status_text_; + views::PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&CastDialogSinkButton::OnEnabledChanged, + base::Unretained(this))); DISALLOW_COPY_AND_ASSIGN(CastDialogSinkButton); };
diff --git a/chrome/browser/ui/views/payments/credit_card_editor_view_controller.cc b/chrome/browser/ui/views/payments/credit_card_editor_view_controller.cc index 293299e..be99d4e 100644 --- a/chrome/browser/ui/views/payments/credit_card_editor_view_controller.cc +++ b/chrome/browser/ui/views/payments/credit_card_editor_view_controller.cc
@@ -231,7 +231,7 @@ std::unique_ptr<views::ImageView> card_icon_view = CreateInstrumentIconView( autofill::data_util::GetPaymentRequestData(autofill_card_type) .icon_resource_id, - /*img=*/nullptr, base::UTF8ToUTF16(supported_network), opacity); + gfx::ImageSkia(), base::UTF8ToUTF16(supported_network), opacity); card_icon_view->SetImageSize(kCardIconSize); // Keep track of this card icon to later adjust opacity.
diff --git a/chrome/browser/ui/views/payments/payment_handler_web_flow_view_controller.cc b/chrome/browser/ui/views/payments/payment_handler_web_flow_view_controller.cc index 8c6b887..2376598 100644 --- a/chrome/browser/ui/views/payments/payment_handler_web_flow_view_controller.cc +++ b/chrome/browser/ui/views/payments/payment_handler_web_flow_view_controller.cc
@@ -57,7 +57,7 @@ public: ReadOnlyOriginView(const base::string16& page_title, const GURL& origin, - const gfx::ImageSkia* icon_image_skia, + gfx::ImageSkia icon_image_skia, SkColor background_color, views::ButtonListener* site_settings_listener) { std::unique_ptr<views::View> title_origin_container = @@ -116,12 +116,11 @@ views::GridLayout::USE_PREF, 0, 0); // Payment handler icon should be 32 pixels tall. constexpr int kPaymentHandlerIconHeight = 32; - bool has_icon = icon_image_skia && icon_image_skia->width() && - icon_image_skia->height(); - float adjusted_width = base::checked_cast<float>(icon_image_skia->width()); + const bool has_icon = icon_image_skia.width() && icon_image_skia.height(); + float adjusted_width = base::checked_cast<float>(icon_image_skia.width()); if (has_icon) { - adjusted_width = adjusted_width * kPaymentHandlerIconHeight / - icon_image_skia->height(); + adjusted_width = + adjusted_width * kPaymentHandlerIconHeight / icon_image_skia.height(); // A column for the instrument icon. top_level_columns->AddColumn( views::GridLayout::LEADING, views::GridLayout::FILL,
diff --git a/chrome/browser/ui/views/payments/payment_request_views_util.cc b/chrome/browser/ui/views/payments/payment_request_views_util.cc index 798f3cc..4176b3e6 100644 --- a/chrome/browser/ui/views/payments/payment_request_views_util.cc +++ b/chrome/browser/ui/views/payments/payment_request_views_util.cc
@@ -236,16 +236,16 @@ std::unique_ptr<views::ImageView> CreateInstrumentIconView( int icon_resource_id, - const gfx::ImageSkia* img, + gfx::ImageSkia img, const base::string16& tooltip_text, float opacity) { std::unique_ptr<views::ImageView> icon_view = std::make_unique<views::ImageView>(); icon_view->set_can_process_events_within_subtree(false); - if (img) { - icon_view->SetImage(*img); - float width = base::checked_cast<float>(img->width()); - float height = base::checked_cast<float>(img->height()); + if (!img.isNull() || !icon_resource_id) { + icon_view->SetImage(img); + float width = base::checked_cast<float>(img.width()); + float height = base::checked_cast<float>(img.height()); float ratio = 1; if (width && height) ratio = width / height;
diff --git a/chrome/browser/ui/views/payments/payment_request_views_util.h b/chrome/browser/ui/views/payments/payment_request_views_util.h index cb2439ce..ee5dd59 100644 --- a/chrome/browser/ui/views/payments/payment_request_views_util.h +++ b/chrome/browser/ui/views/payments/payment_request_views_util.h
@@ -81,7 +81,7 @@ // size of the resulting ImageView. Callers should set a |tooltip_text|. std::unique_ptr<views::ImageView> CreateInstrumentIconView( int icon_resource_id, - const gfx::ImageSkia* img, + gfx::ImageSkia img, const base::string16& tooltip_text, float opacity = 1.0f);
diff --git a/chrome/browser/ui/webui/favicon_source.cc b/chrome/browser/ui/webui/favicon_source.cc index 7a04b20..77ab61a 100644 --- a/chrome/browser/ui/webui/favicon_source.cc +++ b/chrome/browser/ui/webui/favicon_source.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/top_sites_factory.h" @@ -19,27 +20,42 @@ #include "components/history/core/browser/top_sites.h" #include "components/sync_sessions/open_tabs_ui_delegate.h" #include "components/sync_sessions/session_sync_service.h" +#include "content/public/browser/web_contents.h" #include "net/url_request/url_request.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/web_ui_util.h" #include "ui/native_theme/native_theme.h" #include "ui/resources/grit/ui_resources.h" +#include "url/gurl.h" + +namespace { +favicon::FaviconRequestOrigin ParseFaviconRequestOrigin(const GURL& url) { + GURL history_url(chrome::kChromeUIHistoryURL); + if (url == history_url.Resolve("/syncedTabs")) + return favicon::FaviconRequestOrigin::HISTORY_SYNCED_TABS; + if (url == history_url) + return favicon::FaviconRequestOrigin::HISTORY; + return favicon::FaviconRequestOrigin::UNKNOWN; +} +} // namespace FaviconSource::IconRequest::IconRequest() - : size_in_dip(gfx::kFaviconSize), device_scale_factor(1.0f) { -} + : size_in_dip(gfx::kFaviconSize), + device_scale_factor(1.0f), + icon_request_origin(favicon::FaviconRequestOrigin::UNKNOWN) {} FaviconSource::IconRequest::IconRequest( const content::URLDataSource::GotDataCallback& cb, const GURL& path, int size, - float scale) + float scale, + favicon::FaviconRequestOrigin origin) : callback(cb), request_path(path), size_in_dip(size), - device_scale_factor(scale) { -} + device_scale_factor(scale), + icon_request_origin(origin) {} FaviconSource::IconRequest::IconRequest(const IconRequest& other) = default; @@ -84,15 +100,22 @@ int desired_size_in_pixel = std::ceil(parsed.size_in_dip * parsed.device_scale_factor); + content::WebContents* web_contents = wc_getter.Run(); + // web_contents->GetURL will not necessarily yield the original URL that + // started the request, but for collecting metrics for chrome://history and + // chrome://history/syncedTabs this will be ok. + favicon::FaviconRequestOrigin unsafe_request_origin = + web_contents ? ParseFaviconRequestOrigin(web_contents->GetURL()) + : favicon::FaviconRequestOrigin::UNKNOWN; if (parsed.is_icon_url) { // TODO(michaelbai): Change GetRawFavicon to support combination of // IconType. favicon_service->GetRawFavicon( url, favicon_base::IconType::kFavicon, desired_size_in_pixel, - base::Bind(&FaviconSource::OnFaviconDataAvailable, - base::Unretained(this), - IconRequest(callback, url, parsed.size_in_dip, - parsed.device_scale_factor)), + base::Bind( + &FaviconSource::OnFaviconDataAvailable, base::Unretained(this), + IconRequest(callback, url, parsed.size_in_dip, + parsed.device_scale_factor, unsafe_request_origin)), &cancelable_task_tracker_); } else { // Intercept requests for prepopulated pages if TopSites exists. @@ -123,10 +146,10 @@ favicon_service->GetRawFaviconForPageURL( url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel, fallback_to_host, - base::Bind(&FaviconSource::OnFaviconDataAvailable, - base::Unretained(this), - IconRequest(callback, url, parsed.size_in_dip, - parsed.device_scale_factor)), + base::Bind( + &FaviconSource::OnFaviconDataAvailable, base::Unretained(this), + IconRequest(callback, url, parsed.size_in_dip, + parsed.device_scale_factor, unsafe_request_origin)), &cancelable_task_tracker_); } } @@ -184,16 +207,26 @@ const IconRequest& request, const favicon_base::FaviconRawBitmapResult& bitmap_result) { if (bitmap_result.is_valid()) { + favicon::RecordFaviconRequestMetric(request.icon_request_origin, + favicon::FaviconAvailability::kLocal); // Forward the data along to the networking system. request.callback.Run(bitmap_result.bitmap_data.get()); - } else if (!HandleMissingResource(request)) { + } else if (HandleMissingResource(request)) { + favicon::RecordFaviconRequestMetric(request.icon_request_origin, + favicon::FaviconAvailability::kSync); + // The response was already treated by HandleMissingResource. + } else { + favicon::RecordFaviconRequestMetric( + request.icon_request_origin, + favicon::FaviconAvailability::kNotAvailable); SendDefaultResponse(request); } } void FaviconSource::SendDefaultResponse( const content::URLDataSource::GotDataCallback& callback) { - SendDefaultResponse(IconRequest(callback, GURL(), 16, 1.0f)); + SendDefaultResponse(IconRequest(callback, GURL(), 16, 1.0f, + favicon::FaviconRequestOrigin::UNKNOWN)); } void FaviconSource::SendDefaultResponse(const IconRequest& icon_request) {
diff --git a/chrome/browser/ui/webui/favicon_source.h b/chrome/browser/ui/webui/favicon_source.h index 53e8673..4b72ee5 100644 --- a/chrome/browser/ui/webui/favicon_source.h +++ b/chrome/browser/ui/webui/favicon_source.h
@@ -12,6 +12,7 @@ #include "base/memory/ref_counted.h" #include "base/task/cancelable_task_tracker.h" #include "components/favicon/core/favicon_service.h" +#include "components/favicon_base/favicon_request_metrics.h" #include "content/public/browser/url_data_source.h" #include "ui/gfx/favicon_size.h" @@ -78,7 +79,8 @@ IconRequest(const content::URLDataSource::GotDataCallback& cb, const GURL& path, int size, - float scale); + float scale, + favicon::FaviconRequestOrigin origin); IconRequest(const IconRequest& other); ~IconRequest(); @@ -86,6 +88,7 @@ GURL request_path; int size_in_dip; float device_scale_factor; + favicon::FaviconRequestOrigin icon_request_origin; }; // Called when the favicon data is missing to perform additional checks to
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chrome/browser/ui/webui/settings/site_settings_handler.cc index e63a5032..7b65a8d4 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler.cc +++ b/chrome/browser/ui/webui/settings/site_settings_handler.cc
@@ -870,10 +870,9 @@ site_settings::ChooserTypeFromGroupName(type); CHECK(chooser_type); - std::unique_ptr<base::ListValue> exceptions = - site_settings::GetChooserExceptionListFromProfile(profile_, - *chooser_type); - ResolveJavascriptCallback(*callback_id, *exceptions.get()); + base::Value exceptions = site_settings::GetChooserExceptionListFromProfile( + profile_, *chooser_type); + ResolveJavascriptCallback(*callback_id, std::move(exceptions)); } void SiteSettingsHandler::HandleGetOriginPermissions( @@ -1145,12 +1144,9 @@ GURL embedding_origin(embedding_origin_str); CHECK(embedding_origin.is_valid() || embedding_origin.is_empty()); - const base::DictionaryValue* object = nullptr; - CHECK(args->GetDictionary(3, &object)); - ChooserContextBase* chooser_context = chooser_type->get_context(profile_); chooser_context->RevokeObjectPermission(requesting_origin, embedding_origin, - *object); + args->GetList()[3]); } void SiteSettingsHandler::HandleIsOriginValid(const base::ListValue* args) {
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc index 0266666..096e057 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc
@@ -1599,15 +1599,22 @@ const base::Value& exception, const std::string& requesting_origin, const std::string& embedding_origin) { - const base::Value* site_value = exception.FindKey(site_settings::kSites); - for (const auto& site : site_value->GetList()) { - const base::Value* origin_value = site.FindKey(site_settings::kOrigin); - if (origin_value->GetString() != requesting_origin) + const base::Value* sites = exception.FindListKey(site_settings::kSites); + if (!sites) + return false; + + for (const auto& site : sites->GetList()) { + const std::string* origin = site.FindStringKey(site_settings::kOrigin); + if (!origin) + continue; + if (*origin != requesting_origin) continue; - const base::Value* embedding_origin_value = - site.FindKey(site_settings::kEmbeddingOrigin); - if (embedding_origin_value->GetString() == embedding_origin) + const std::string* exception_embedding_origin = + site.FindStringKey(site_settings::kEmbeddingOrigin); + if (!exception_embedding_origin) + continue; + if (*exception_embedding_origin == embedding_origin) return true; } return false; @@ -1617,14 +1624,20 @@ // chooser exception with |display_name| that contains a site exception for // |requesting_origin| and |embedding_origin|. bool ChooserExceptionContainsSiteException( - const base::Value& exception_list, + const base::Value& exceptions, const std::string& display_name, const std::string& requesting_origin, const std::string& embedding_origin) { - for (const auto& exception : exception_list.GetList()) { - const base::Value* display_name_value = - exception.FindKey(site_settings::kDisplayName); - if (display_name_value->GetString() == display_name) { + if (!exceptions.is_list()) + return false; + + for (const auto& exception : exceptions.GetList()) { + const std::string* exception_display_name = + exception.FindStringKey(site_settings::kDisplayName); + if (!exception_display_name) + continue; + + if (*exception_display_name == display_name) { return ChooserExceptionContainsSiteException( exception, requesting_origin, embedding_origin); } @@ -1711,8 +1724,8 @@ args.AppendString(kUsbChooserGroupName); args.AppendString(kAndroidOriginStr); args.AppendString(kChromiumOriginStr); - args.Append( - UsbChooserContext::DeviceInfoToDictValue(*persistent_device_info_)); + args.Append(base::Value::ToUniquePtrValue( + UsbChooserContext::DeviceInfoToValue(*persistent_device_info_))); EXPECT_CALL(observer_, OnChooserObjectPermissionChanged( CONTENT_SETTINGS_TYPE_USB_GUARD, @@ -1743,8 +1756,8 @@ args.AppendString(kUsbChooserGroupName); args.AppendString(kChromiumOriginStr); args.AppendString(kChromiumOriginStr); - args.Append( - UsbChooserContext::DeviceInfoToDictValue(*persistent_device_info_)); + args.Append(base::Value::ToUniquePtrValue( + UsbChooserContext::DeviceInfoToValue(*persistent_device_info_))); { const base::Value& exceptions = @@ -1791,8 +1804,8 @@ args.AppendString(kUsbChooserGroupName); args.AppendString(kAndroidOriginStr); args.AppendString(kAndroidOriginStr); - args.Append( - UsbChooserContext::DeviceInfoToDictValue(*user_granted_device_info_)); + args.Append(base::Value::ToUniquePtrValue( + UsbChooserContext::DeviceInfoToValue(*user_granted_device_info_))); { const base::Value& exceptions =
diff --git a/chrome/browser/ui/webui/site_settings_helper.cc b/chrome/browser/ui/webui/site_settings_helper.cc index c0be6a6..24707cd4 100644 --- a/chrome/browser/ui/webui/site_settings_helper.cc +++ b/chrome/browser/ui/webui/site_settings_helper.cc
@@ -247,8 +247,10 @@ } const ChooserTypeNameEntry kChooserTypeGroupNames[] = { - {&GetUsbChooserContext, kUsbChooserDataGroupType}, - {&GetSerialChooserContext, kSerialChooserDataGroupType}, + {&GetUsbChooserContext, &UsbChooserContext::GetObjectName, + kUsbChooserDataGroupType}, + {&GetSerialChooserContext, &SerialChooserContext::GetObjectName, + kSerialChooserDataGroupType}, }; } // namespace @@ -592,23 +594,23 @@ // Create a DictionaryValue* that will act as a data source for a single row // in a chooser permission exceptions table. The chooser permission will contain // a list of site exceptions that correspond to the exception. -std::unique_ptr<base::DictionaryValue> CreateChooserExceptionObject( +base::Value CreateChooserExceptionObject( const std::string& display_name, const base::Value& object, const std::string& chooser_type, const ChooserExceptionDetails& chooser_exception_details) { - auto exception = std::make_unique<base::DictionaryValue>(); + base::Value exception(base::Value::Type::DICTIONARY); std::string setting_string = content_settings::ContentSettingToString(CONTENT_SETTING_DEFAULT); DCHECK(!setting_string.empty()); - exception->SetString(kDisplayName, display_name); - exception->SetKey(kObject, object.Clone()); - exception->SetString(kChooserType, chooser_type); + exception.SetStringKey(kDisplayName, display_name); + exception.SetKey(kObject, object.Clone()); + exception.SetStringKey(kChooserType, chooser_type); // Order the sites by the provider precedence order. - std::vector<std::unique_ptr<base::Value>> + std::vector<base::Value> all_provider_sites[HostContentSettingsMap::NUM_PROVIDER_TYPES]; for (const auto& details : chooser_exception_details) { const GURL& requesting_origin = details.first.first; @@ -621,35 +623,35 @@ for (const auto& embedding_origin_incognito_pair : details.second) { const GURL& embedding_origin = embedding_origin_incognito_pair.first; const bool incognito = embedding_origin_incognito_pair.second; - auto site = std::make_unique<base::DictionaryValue>(); + base::Value site(base::Value::Type::DICTIONARY); - site->SetString(kOrigin, requesting_origin.spec()); - site->SetString(kDisplayName, requesting_origin.spec()); - site->SetString(kEmbeddingOrigin, embedding_origin.is_empty() - ? std::string() - : embedding_origin.spec()); - site->SetString(kSetting, setting_string); - site->SetString(kSource, source); - site->SetBoolean(kIncognito, incognito); + site.SetStringKey(kOrigin, requesting_origin.spec()); + site.SetStringKey(kDisplayName, requesting_origin.spec()); + site.SetStringKey(kEmbeddingOrigin, embedding_origin.is_empty() + ? std::string() + : embedding_origin.spec()); + site.SetStringKey(kSetting, setting_string); + site.SetStringKey(kSource, source); + site.SetBoolKey(kIncognito, incognito); this_provider_sites.push_back(std::move(site)); } } - auto sites = std::make_unique<base::ListValue>(); + base::Value sites(base::Value::Type::LIST); for (auto& one_provider_sites : all_provider_sites) { for (auto& site : one_provider_sites) { - sites->Append(std::move(site)); + sites.GetList().push_back(std::move(site)); } } - exception->SetList(kSites, std::move(sites)); + exception.SetKey(kSites, std::move(sites)); return exception; } -std::unique_ptr<base::ListValue> GetChooserExceptionListFromProfile( +base::Value GetChooserExceptionListFromProfile( Profile* profile, const ChooserTypeNameEntry& chooser_type) { - auto exceptions = std::make_unique<base::ListValue>(); + base::Value exceptions(base::Value::Type::LIST); ContentSettingsType content_type = ContentSettingsTypeFromGroupName(std::string(chooser_type.name)); @@ -670,7 +672,7 @@ AllChooserObjects all_chooser_objects; for (const auto& object : objects) { - std::string name = chooser_context->GetObjectName(object->value); + std::string name = chooser_type.get_object_name(object->value); auto& chooser_exception_details = all_chooser_objects[std::make_pair(name, object->value.Clone())]; @@ -692,7 +694,7 @@ const base::Value& object = all_chooser_objects_entry.first.second; const ChooserExceptionDetails& chooser_exception_details = all_chooser_objects_entry.second; - exceptions->Append(CreateChooserExceptionObject( + exceptions.GetList().push_back(CreateChooserExceptionObject( name, object, chooser_type.name, chooser_exception_details)); }
diff --git a/chrome/browser/ui/webui/site_settings_helper.h b/chrome/browser/ui/webui/site_settings_helper.h index c3150f9..f952cdb 100644 --- a/chrome/browser/ui/webui/site_settings_helper.h +++ b/chrome/browser/ui/webui/site_settings_helper.h
@@ -25,6 +25,7 @@ namespace base { class DictionaryValue; class ListValue; +class Value; } // namespace base namespace extensions { @@ -149,6 +150,7 @@ // by functions below. struct ChooserTypeNameEntry { ChooserContextBase* (*get_context)(Profile*); + std::string (*get_object_name)(const base::Value&); const char* name; }; @@ -167,14 +169,14 @@ // * sites: Array<SiteException> // The structure of the SiteException objects is the same as the objects // returned by GetExceptionForPage(). -std::unique_ptr<base::DictionaryValue> CreateChooserExceptionObject( +base::Value CreateChooserExceptionObject( const std::string& display_name, const base::Value& object, const std::string& chooser_type, const ChooserExceptionDetails& chooser_exception_details); // Returns an array of chooser exception objects. -std::unique_ptr<base::ListValue> GetChooserExceptionListFromProfile( +base::Value GetChooserExceptionListFromProfile( Profile* profile, const ChooserTypeNameEntry& chooser_type);
diff --git a/chrome/browser/ui/webui/site_settings_helper_unittest.cc b/chrome/browser/ui/webui/site_settings_helper_unittest.cc index c90aa3e..cc1285f 100644 --- a/chrome/browser/ui/webui/site_settings_helper_unittest.cc +++ b/chrome/browser/ui/webui/site_settings_helper_unittest.cc
@@ -86,7 +86,7 @@ policy_provider->SetWebsiteSetting( ContentSettingsPattern::FromString(star_google_com), ContentSettingsPattern::Wildcard(), kContentType, "", - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); policy_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(policy_provider), HostContentSettingsMap::POLICY_PROVIDER); @@ -104,7 +104,7 @@ extension_provider->SetWebsiteSetting( ContentSettingsPattern::FromString(drive_google_com), ContentSettingsPattern::Wildcard(), kContentType, "", - new base::Value(CONTENT_SETTING_ASK)); + std::make_unique<base::Value>(CONTENT_SETTING_ASK)); extension_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(extension_provider), @@ -194,10 +194,10 @@ // Extension. auto extension_provider = std::make_unique<content_settings::MockProvider>(); - extension_provider->SetWebsiteSetting(ContentSettingsPattern::FromURL(origin), - ContentSettingsPattern::FromURL(origin), - kContentType, "", - new base::Value(CONTENT_SETTING_BLOCK)); + extension_provider->SetWebsiteSetting( + ContentSettingsPattern::FromURL(origin), + ContentSettingsPattern::FromURL(origin), kContentType, "", + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); extension_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(extension_provider), @@ -210,10 +210,10 @@ // Enterprise policy. auto policy_provider = std::make_unique<content_settings::MockProvider>(); - policy_provider->SetWebsiteSetting(ContentSettingsPattern::FromURL(origin), - ContentSettingsPattern::FromURL(origin), - kContentType, "", - new base::Value(CONTENT_SETTING_ALLOW)); + policy_provider->SetWebsiteSetting( + ContentSettingsPattern::FromURL(origin), + ContentSettingsPattern::FromURL(origin), kContentType, "", + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); policy_provider->set_read_only(true); content_settings::TestUtils::OverrideProvider( map, std::move(policy_provider), HostContentSettingsMap::POLICY_PROVIDER); @@ -341,10 +341,10 @@ /*chooser_type=*/kUsbChooserGroupName, /*chooser_exception_details=*/exception_details); ExpectValidChooserExceptionObject( - *exception, /*chooser_type=*/kUsbChooserGroupName, + exception, /*chooser_type=*/kUsbChooserGroupName, /*display_name=*/kObjectName, *chooser_object); - const auto& sites_list = exception->FindKey(kSites)->GetList(); + const auto& sites_list = exception.FindKey(kSites)->GetList(); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[0], /*origin=*/kGoogleOrigin, /*embedding_origin=*/kChromiumOrigin, @@ -364,14 +364,14 @@ /*object=*/*chooser_object, /*chooser_type=*/kUsbChooserGroupName, /*chooser_exception_details=*/exception_details); - ExpectValidChooserExceptionObject(*exception, + ExpectValidChooserExceptionObject(exception, /*chooser_type=*/kUsbChooserGroupName, /*display_name=*/kObjectName, *chooser_object); // The map sorts the sites by requesting origin, so |kAndroidOrigin| should // be first, followed by the origin pair (kGoogleOrigin, kChromiumOrigin). - const auto& sites_list = exception->FindKey(kSites)->GetList(); + const auto& sites_list = exception.FindKey(kSites)->GetList(); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[0], /*origin=*/kAndroidOrigin, /*embedding_origin=*/kAndroidOrigin, @@ -394,7 +394,7 @@ /*object=*/*chooser_object, /*chooser_type=*/kUsbChooserGroupName, /*chooser_exception_details=*/exception_details); - ExpectValidChooserExceptionObject(*exception, + ExpectValidChooserExceptionObject(exception, /*chooser_type=*/kUsbChooserGroupName, /*display_name=*/kObjectName, *chooser_object); @@ -403,7 +403,7 @@ // CreateChooserExceptionObject method sorts the sites further by the // source. Therefore, policy granted sites are listed before user granted // sites. - const auto& sites_list = exception->FindKey(kSites)->GetList(); + const auto& sites_list = exception.FindKey(kSites)->GetList(); ExpectValidSiteExceptionObject(/*actual_site_object=*/sites_list[0], /*origin=*/kGoogleOrigin, /*embedding_origin=*/GURL::EmptyGURL(), @@ -494,10 +494,10 @@ void ExpectDisplayNameEq(const base::Value& actual_exception_object, const std::string& display_name) { - const base::Value* display_name_value = actual_exception_object.FindKeyOfType( - kDisplayName, base::Value::Type::STRING); - ASSERT_TRUE(display_name_value); - EXPECT_EQ(display_name_value->GetString(), display_name); + const std::string* actual_display_name = + actual_exception_object.FindStringKey(kDisplayName); + ASSERT_TRUE(actual_display_name); + EXPECT_EQ(*actual_display_name, display_name); } } // namespace @@ -518,10 +518,10 @@ // origin and the embedding origin. User granted permissions that are also // granted by policy are combined with the policy so that duplicate // permissions are not displayed. - std::unique_ptr<base::ListValue> exceptions = + base::Value exceptions = GetChooserExceptionListFromProfile(profile(), *chooser_type); - ASSERT_EQ(exceptions->GetSize(), 4u); - auto& exceptions_list = exceptions->GetList(); + auto& exceptions_list = exceptions.GetList(); + ASSERT_EQ(exceptions_list.size(), 4u); // This exception should describe the permissions for any device with the // vendor ID corresponding to "Google Inc.". There are no user granted
diff --git a/chrome/browser/usb/usb_chooser_context.cc b/chrome/browser/usb/usb_chooser_context.cc index c84f71fd..b1860dc 100644 --- a/chrome/browser/usb/usb_chooser_context.cc +++ b/chrome/browser/usb/usb_chooser_context.cc
@@ -57,12 +57,12 @@ return !device_info.serial_number->empty(); } -std::pair<int, int> GetDeviceIds(const base::DictionaryValue& object) { - DCHECK(object.FindKeyOfType(kVendorIdKey, base::Value::Type::INTEGER)); - int vendor_id = object.FindKey(kVendorIdKey)->GetInt(); +std::pair<int, int> GetDeviceIds(const base::Value& object) { + DCHECK(object.FindIntKey(kVendorIdKey)); + int vendor_id = *object.FindIntKey(kVendorIdKey); - DCHECK(object.FindKeyOfType(kProductIdKey, base::Value::Type::INTEGER)); - int product_id = object.FindKey(kProductIdKey)->GetInt(); + DCHECK(object.FindIntKey(kProductIdKey)); + int product_id = *object.FindIntKey(kProductIdKey); return std::make_pair(vendor_id, product_id); } @@ -103,17 +103,16 @@ base::ASCIIToUTF16(base::StringPrintf("0x%04X", vendor_id))); } -std::unique_ptr<base::DictionaryValue> DeviceIdsToDictValue(int vendor_id, - int product_id) { - auto device_dict = std::make_unique<base::DictionaryValue>(); +base::Value DeviceIdsToValue(int vendor_id, int product_id) { + base::Value device_value(base::Value::Type::DICTIONARY); base::string16 device_name = GetDeviceNameFromIds(vendor_id, product_id); - device_dict->SetKey(kDeviceNameKey, base::Value(device_name)); - device_dict->SetKey(kVendorIdKey, base::Value(vendor_id)); - device_dict->SetKey(kProductIdKey, base::Value(product_id)); - device_dict->SetKey(kSerialNumberKey, base::Value(std::string())); + device_value.SetStringKey(kDeviceNameKey, device_name); + device_value.SetIntKey(kVendorIdKey, vendor_id); + device_value.SetIntKey(kProductIdKey, product_id); + device_value.SetStringKey(kSerialNumberKey, std::string()); - return device_dict; + return device_value; } } // namespace @@ -138,25 +137,23 @@ } // static -std::unique_ptr<base::DictionaryValue> UsbChooserContext::DeviceInfoToDictValue( +base::Value UsbChooserContext::DeviceInfoToValue( const device::mojom::UsbDeviceInfo& device_info) { - auto device_dict = std::make_unique<base::DictionaryValue>(); - device_dict->SetKey(kDeviceNameKey, - device_info.product_name - ? base::Value(*device_info.product_name) - : base::Value("")); - device_dict->SetKey(kVendorIdKey, base::Value(device_info.vendor_id)); - device_dict->SetKey(kProductIdKey, base::Value(device_info.product_id)); + base::Value device_value(base::Value::Type::DICTIONARY); + device_value.SetStringKey(kDeviceNameKey, device_info.product_name + ? *device_info.product_name + : base::StringPiece16()); + device_value.SetIntKey(kVendorIdKey, device_info.vendor_id); + device_value.SetIntKey(kProductIdKey, device_info.product_id); // CanStorePersistentEntry checks if |device_info.serial_number| is not empty. if (CanStorePersistentEntry(device_info)) { - device_dict->SetKey(kSerialNumberKey, - base::Value(*device_info.serial_number)); + device_value.SetStringKey(kSerialNumberKey, *device_info.serial_number); } else { - device_dict->SetKey(kGuidKey, base::Value(device_info.guid)); + device_value.SetStringKey(kGuidKey, device_info.guid); } - return device_dict; + return device_value; } void UsbChooserContext::InitDeviceList( @@ -231,7 +228,7 @@ DCHECK(base::ContainsKey(devices_, guid)); objects.push_back(std::make_unique<ChooserContextBase::Object>( requesting_origin, embedding_origin, - DeviceInfoToDictValue(*devices_[guid]).get(), + DeviceInfoToValue(*devices_[guid]), content_settings::SettingSource::SETTING_SOURCE_USER, is_incognito_)); } @@ -246,12 +243,12 @@ // GetAllGrantedObjects(), so it could potentially be centralized. std::map<std::pair<int, int>, base::Value> device_ids_to_object_map; for (auto it = objects.begin(); it != objects.end();) { - ChooserContextBase::Object& object = **it; - auto device_ids = GetDeviceIds(object.value); + base::Value& object = (*it)->value; + auto device_ids = GetDeviceIds(object); if (usb_policy_allowed_devices_->IsDeviceAllowed( requesting_origin, embedding_origin, device_ids)) { - device_ids_to_object_map[device_ids] = std::move(object.value); + device_ids_to_object_map[device_ids] = std::move(object); it = objects.erase(it); } else { ++it; @@ -278,18 +275,17 @@ // If there is an entry for the device in |device_ids_to_object_map|, use // that object to represent the device. Otherwise, attempt to figure out // the name of the device from the |vendor_id| and |product_id|. - std::unique_ptr<base::DictionaryValue> object; + base::Value object(base::Value::Type::DICTIONARY); auto it = device_ids_to_object_map.find(std::make_pair(vendor_id, product_id)); if (it != device_ids_to_object_map.end()) { - object = base::DictionaryValue::From( - base::Value::ToUniquePtrValue(std::move(it->second))); + object = std::move(it->second); } else { - object = DeviceIdsToDictValue(vendor_id, product_id); + object = DeviceIdsToValue(vendor_id, product_id); } objects.push_back(std::make_unique<ChooserContextBase::Object>( - url_pair.first, url_pair.second, object.get(), + url_pair.first, url_pair.second, std::move(object), content_settings::SETTING_SOURCE_POLICY, is_incognito_)); } } @@ -311,10 +307,9 @@ for (const std::string& guid : map_entry.second) { DCHECK(base::ContainsKey(devices_, guid)); - // ChooserContextBase::Object constructor will swap the object. - auto object = DeviceInfoToDictValue(*devices_[guid]); objects.push_back(std::make_unique<ChooserContextBase::Object>( - requesting_origin, embedding_origin, object.get(), + requesting_origin, embedding_origin, + DeviceInfoToValue(*devices_[guid]), content_settings::SETTING_SOURCE_USER, is_incognito_)); } } @@ -349,18 +344,17 @@ // If there is an entry for the device in |device_ids_to_object_map|, use // that object to represent the device. Otherwise, attempt to figure out // the name of the device from the |vendor_id| and |product_id|. - std::unique_ptr<base::DictionaryValue> object; + base::Value object(base::Value::Type::DICTIONARY); auto it = device_ids_to_object_map.find(std::make_pair(vendor_id, product_id)); if (it != device_ids_to_object_map.end()) { - object = base::DictionaryValue::From( - base::Value::ToUniquePtrValue(it->second.Clone())); + object = it->second.Clone(); } else { - object = DeviceIdsToDictValue(vendor_id, product_id); + object = DeviceIdsToValue(vendor_id, product_id); } objects.push_back(std::make_unique<ChooserContextBase::Object>( - url_pair.first, url_pair.second, object.get(), + url_pair.first, url_pair.second, std::move(object), content_settings::SettingSource::SETTING_SOURCE_POLICY, is_incognito_)); } @@ -369,27 +363,28 @@ return objects; } -void UsbChooserContext::RevokeObjectPermission( - const GURL& requesting_origin, - const GURL& embedding_origin, - const base::DictionaryValue& object) { - std::string guid; - if (object.GetString(kGuidKey, &guid)) { - auto it = ephemeral_devices_.find( - std::make_pair(requesting_origin, embedding_origin)); - if (it != ephemeral_devices_.end()) { - it->second.erase(guid); - if (it->second.empty()) - ephemeral_devices_.erase(it); - NotifyPermissionRevoked(requesting_origin, embedding_origin); - } +void UsbChooserContext::RevokeObjectPermission(const GURL& requesting_origin, + const GURL& embedding_origin, + const base::Value& object) { + const std::string* guid = object.FindStringKey(kGuidKey); - RecordPermissionRevocation(WEBUSB_PERMISSION_REVOKED_EPHEMERAL); - } else { + if (!guid) { ChooserContextBase::RevokeObjectPermission(requesting_origin, embedding_origin, object); RecordPermissionRevocation(WEBUSB_PERMISSION_REVOKED); + return; } + + auto it = ephemeral_devices_.find( + std::make_pair(requesting_origin, embedding_origin)); + if (it != ephemeral_devices_.end()) { + it->second.erase(*guid); + if (it->second.empty()) + ephemeral_devices_.erase(it); + NotifyPermissionRevoked(requesting_origin, embedding_origin); + } + + RecordPermissionRevocation(WEBUSB_PERMISSION_REVOKED_EPHEMERAL); } void UsbChooserContext::GrantDevicePermission( @@ -398,7 +393,7 @@ const device::mojom::UsbDeviceInfo& device_info) { if (CanStorePersistentEntry(device_info)) { GrantObjectPermission(requesting_origin, embedding_origin, - DeviceInfoToDictValue(device_info)); + DeviceInfoToValue(device_info)); } else { ephemeral_devices_[std::make_pair(requesting_origin, embedding_origin)] .insert(device_info.guid); @@ -431,16 +426,15 @@ std::vector<std::unique_ptr<ChooserContextBase::Object>> object_list = GetGrantedObjects(requesting_origin, embedding_origin); for (const auto& object : object_list) { - int vendor_id; - int product_id; - base::string16 serial_number; - const base::DictionaryValue& device_dict = object->value; - if (device_dict.GetInteger(kVendorIdKey, &vendor_id) && - device_info.vendor_id == vendor_id && - device_dict.GetInteger(kProductIdKey, &product_id) && - device_info.product_id == product_id && - device_dict.GetString(kSerialNumberKey, &serial_number) && - device_info.serial_number == serial_number) { + const base::Value& device = object->value; + DCHECK(IsValidObject(device)); + + const int vendor_id = *device.FindIntKey(kVendorIdKey); + const int product_id = *device.FindIntKey(kProductIdKey); + const std::string* serial_number = device.FindStringKey(kSerialNumberKey); + if (device_info.vendor_id == vendor_id && + device_info.product_id == product_id && serial_number && + device_info.serial_number == base::UTF8ToUTF16(*serial_number)) { return true; } } @@ -491,19 +485,25 @@ return weak_factory_.GetWeakPtr(); } -bool UsbChooserContext::IsValidObject(const base::DictionaryValue& object) { - return object.size() == 4 && object.HasKey(kDeviceNameKey) && - object.HasKey(kVendorIdKey) && object.HasKey(kProductIdKey) && - (object.HasKey(kSerialNumberKey) || object.HasKey(kGuidKey)); +bool UsbChooserContext::IsValidObject(const base::Value& object) { + return object.is_dict() && object.DictSize() == 4 && + object.FindStringKey(kDeviceNameKey) && + object.FindIntKey(kVendorIdKey) && object.FindIntKey(kProductIdKey) && + (object.FindStringKey(kSerialNumberKey) || + object.FindStringKey(kGuidKey)); } -std::string UsbChooserContext::GetObjectName( - const base::DictionaryValue& object) { - DCHECK(IsValidObject(object)); - std::string name; - bool found = object.GetString(kDeviceNameKey, &name); - DCHECK(found); - return name; +// static +std::string UsbChooserContext::GetObjectName(const base::Value& object) { + const std::string* name = object.FindStringKey(kDeviceNameKey); + DCHECK(name); + if (name->empty()) { + base::Optional<int> vendor_id = object.FindIntKey(kVendorIdKey); + base::Optional<int> product_id = object.FindIntKey(kProductIdKey); + DCHECK(vendor_id && product_id); + return base::UTF16ToUTF8(GetDeviceNameFromIds(*vendor_id, *product_id)); + } + return *name; } void UsbChooserContext::OnDeviceAdded(
diff --git a/chrome/browser/usb/usb_chooser_context.h b/chrome/browser/usb/usb_chooser_context.h index aed3fa3..9bd6f159 100644 --- a/chrome/browser/usb/usb_chooser_context.h +++ b/chrome/browser/usb/usb_chooser_context.h
@@ -37,7 +37,7 @@ virtual void OnDeviceManagerConnectionError(); }; - static std::unique_ptr<base::DictionaryValue> DeviceInfoToDictValue( + static base::Value DeviceInfoToValue( const device::mojom::UsbDeviceInfo& device_info); // These methods from ChooserContextBase are overridden in order to expose @@ -49,7 +49,7 @@ GetAllGrantedObjects() override; void RevokeObjectPermission(const GURL& requesting_origin, const GURL& embedding_origin, - const base::DictionaryValue& object) override; + const base::Value& object) override; // Grants |requesting_origin| access to the USB device. void GrantDevicePermission(const GURL& requesting_origin, @@ -81,8 +81,10 @@ device::mojom::UsbDeviceManagerPtr fake_device_manager); // ChooserContextBase implementation. - bool IsValidObject(const base::DictionaryValue& object) override; - std::string GetObjectName(const base::DictionaryValue& object) override; + bool IsValidObject(const base::Value& object) override; + + // Returns the human readable string representing the given object. + static std::string GetObjectName(const base::Value& object); void InitDeviceList(std::vector<::device::mojom::UsbDeviceInfoPtr> devices); private:
diff --git a/chrome/browser/usb/usb_chooser_context_unittest.cc b/chrome/browser/usb/usb_chooser_context_unittest.cc index 2a53f53..5bc10e1 100644 --- a/chrome/browser/usb/usb_chooser_context_unittest.cc +++ b/chrome/browser/usb/usb_chooser_context_unittest.cc
@@ -8,6 +8,7 @@ #include "base/json/json_reader.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/values.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/permissions/chooser_context_base_mock_permission_observer.h" #include "chrome/browser/usb/usb_chooser_context.h" @@ -94,11 +95,11 @@ device_manager_.CreateAndAddDevice(0, 0, "Google", "Gizmo", "123ABC"); UsbChooserContext* store = GetChooserContext(profile()); - base::DictionaryValue object_dict; - object_dict.SetString(kDeviceNameKey, "Gizmo"); - object_dict.SetInteger(kVendorIdKey, 0); - object_dict.SetInteger(kProductIdKey, 0); - object_dict.SetString(kSerialNumberKey, "123ABC"); + base::Value object(base::Value::Type::DICTIONARY); + object.SetStringKey(kDeviceNameKey, "Gizmo"); + object.SetIntKey(kVendorIdKey, 0); + object.SetIntKey(kProductIdKey, 0); + object.SetStringKey(kSerialNumberKey, "123ABC"); EXPECT_FALSE(store->HasDevicePermission(origin, origin, *device_info)); EXPECT_CALL( @@ -111,14 +112,14 @@ std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = store->GetGrantedObjects(origin, origin); ASSERT_EQ(1u, objects.size()); - EXPECT_EQ(object_dict, objects[0]->value); + EXPECT_EQ(object, objects[0]->value); std::vector<std::unique_ptr<ChooserContextBase::Object>> all_origin_objects = store->GetAllGrantedObjects(); ASSERT_EQ(1u, all_origin_objects.size()); EXPECT_EQ(origin, all_origin_objects[0]->requesting_origin); EXPECT_EQ(origin, all_origin_objects[0]->embedding_origin); - EXPECT_EQ(object_dict, all_origin_objects[0]->value); + EXPECT_EQ(object, all_origin_objects[0]->value); EXPECT_FALSE(all_origin_objects[0]->incognito); EXPECT_CALL( @@ -146,11 +147,11 @@ UsbChooserContext* store = GetChooserContext(profile()); - base::DictionaryValue object_dict; - object_dict.SetString(kDeviceNameKey, "Gizmo"); - object_dict.SetString(kGuidKey, device_info->guid); - object_dict.SetInteger(kVendorIdKey, device_info->vendor_id); - object_dict.SetInteger(kProductIdKey, device_info->product_id); + base::Value object(base::Value::Type::DICTIONARY); + object.SetStringKey(kDeviceNameKey, "Gizmo"); + object.SetStringKey(kGuidKey, device_info->guid); + object.SetIntKey(kVendorIdKey, device_info->vendor_id); + object.SetIntKey(kProductIdKey, device_info->product_id); EXPECT_FALSE(store->HasDevicePermission(origin, origin, *device_info)); EXPECT_CALL( @@ -165,14 +166,14 @@ std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = store->GetGrantedObjects(origin, origin); EXPECT_EQ(1u, objects.size()); - EXPECT_EQ(object_dict, objects[0]->value); + EXPECT_EQ(object, objects[0]->value); std::vector<std::unique_ptr<ChooserContextBase::Object>> all_origin_objects = store->GetAllGrantedObjects(); EXPECT_EQ(1u, all_origin_objects.size()); EXPECT_EQ(origin, all_origin_objects[0]->requesting_origin); EXPECT_EQ(origin, all_origin_objects[0]->embedding_origin); - EXPECT_EQ(object_dict, all_origin_objects[0]->value); + EXPECT_EQ(object, all_origin_objects[0]->value); EXPECT_FALSE(all_origin_objects[0]->incognito); EXPECT_CALL( @@ -385,6 +386,20 @@ *ephemeral_device_info)); } +TEST_F(UsbChooserContextTest, GetObjectNameForNamelessDevice) { + const GURL kGoogleOrigin("https://google.com"); + UsbDeviceInfoPtr device_info = + device_manager_.CreateAndAddDevice(6353, 5678, "", "", ""); + + auto* store = GetChooserContext(profile()); + store->GrantDevicePermission(kGoogleOrigin, kGoogleOrigin, *device_info); + + auto objects = store->GetAllGrantedObjects(); + ASSERT_EQ(objects.size(), 1u); + EXPECT_EQ(store->GetObjectName(objects[0]->value), + "Unknown product 0x162E from Google Inc."); +} + namespace { constexpr char kPolicySetting[] = R"( @@ -573,24 +588,22 @@ const GURL kGadgetOrigin("https://gadget.com"); const GURL kCoolOrigin("https://cool.com"); -void ExpectDeviceObjectInfo(const base::DictionaryValue& actual, +void ExpectDeviceObjectInfo(const base::Value& actual, int vendor_id, int product_id, const std::string& name) { - const base::Value* vendor_id_value = - actual.FindKeyOfType(kVendorIdKey, base::Value::Type::INTEGER); - ASSERT_TRUE(vendor_id_value); - EXPECT_EQ(vendor_id_value->GetInt(), vendor_id); + const base::Optional<int> actual_vendor_id = actual.FindIntKey(kVendorIdKey); + ASSERT_TRUE(actual_vendor_id); + EXPECT_EQ(*actual_vendor_id, vendor_id); - const base::Value* product_id_value = - actual.FindKeyOfType(kProductIdKey, base::Value::Type::INTEGER); - ASSERT_TRUE(product_id_value); - EXPECT_EQ(product_id_value->GetInt(), product_id); + const base::Optional<int> actual_product_id = + actual.FindIntKey(kProductIdKey); + ASSERT_TRUE(actual_product_id); + EXPECT_EQ(*actual_product_id, product_id); - const base::Value* device_name_value = - actual.FindKeyOfType(kDeviceNameKey, base::Value::Type::STRING); - ASSERT_TRUE(device_name_value); - EXPECT_EQ(device_name_value->GetString(), name); + const std::string* actual_device_name = actual.FindStringKey(kDeviceNameKey); + ASSERT_TRUE(actual_device_name); + EXPECT_EQ(*actual_device_name, name); } void ExpectChooserObjectInfo(const ChooserContextBase::Object* actual,
diff --git a/chrome/browser/win/jumplist.cc b/chrome/browser/win/jumplist.cc index 9ddd96c..07cfc82 100644 --- a/chrome/browser/win/jumplist.cc +++ b/chrome/browser/win/jumplist.cc
@@ -537,8 +537,8 @@ if (!image_result.image.IsEmpty() && icon_urls_.front().second.get()) { gfx::ImageSkia image_skia = image_result.image.AsImageSkia(); image_skia.EnsureRepsForSupportedScales(); - std::unique_ptr<gfx::ImageSkia> deep_copy(image_skia.DeepCopy()); - icon_urls_.front().second->set_icon_image(*deep_copy); + gfx::ImageSkia deep_copy(image_skia.DeepCopy()); + icon_urls_.front().second->set_icon_image(deep_copy); } icon_urls_.pop_front(); }
diff --git a/chrome/chrome_cleaner/interfaces/typemaps/string16_embedded_nulls_mojom_traits.h b/chrome/chrome_cleaner/interfaces/typemaps/string16_embedded_nulls_mojom_traits.h index 0954278..02651e24 100644 --- a/chrome/chrome_cleaner/interfaces/typemaps/string16_embedded_nulls_mojom_traits.h +++ b/chrome/chrome_cleaner/interfaces/typemaps/string16_embedded_nulls_mojom_traits.h
@@ -8,7 +8,7 @@ #include <stdint.h> #include "base/containers/span.h" -#include "chrome/chrome_cleaner/interfaces//string16_embedded_nulls.mojom.h" +#include "chrome/chrome_cleaner/interfaces/string16_embedded_nulls.mojom.h" #include "chrome/chrome_cleaner/strings/string16_embedded_nulls.h" #include "mojo/public/cpp/bindings/struct_traits.h" #include "mojo/public/cpp/bindings/union_traits.h"
diff --git a/chrome/common/extensions/api/identity.idl b/chrome/common/extensions/api/identity.idl index bad51d5c..df8a1d6 100644 --- a/chrome/common/extensions/api/identity.idl +++ b/chrome/common/extensions/api/identity.idl
@@ -34,11 +34,9 @@ // return failure any time a prompt would be required. boolean? interactive; - // The account ID whose token should be returned. If not - // specified, the primary account for the profile will be used. - // - // <code>account</code> is only supported when the - // "enable-new-profile-management" flag is set. + // The account ID whose token should be returned. If not specified, the + // function will use an account from the Chrome profile: the Sync account if + // there is one, or otherwise the first Google web account. AccountInfo? account; // A list of OAuth2 scopes to request.
diff --git a/chrome/renderer/BUILD.gn b/chrome/renderer/BUILD.gn index 44798c35..04f84d2 100644 --- a/chrome/renderer/BUILD.gn +++ b/chrome/renderer/BUILD.gn
@@ -51,8 +51,6 @@ "chrome_render_frame_observer.h", "chrome_render_thread_observer.cc", "chrome_render_thread_observer.h", - "chrome_render_view_observer.cc", - "chrome_render_view_observer.h", "content_settings_observer.cc", "content_settings_observer.h", "custom_menu_commands.h",
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 202376e..673b95d 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -46,7 +46,6 @@ #include "chrome/renderer/benchmarking_extension.h" #include "chrome/renderer/chrome_render_frame_observer.h" #include "chrome/renderer/chrome_render_thread_observer.h" -#include "chrome/renderer/chrome_render_view_observer.h" #include "chrome/renderer/content_settings_observer.h" #include "chrome/renderer/loadtimes_extension_bindings.h" #include "chrome/renderer/media/flash_embed_rewrite.h" @@ -437,7 +436,7 @@ void ChromeContentRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { ChromeRenderFrameObserver* render_frame_observer = - new ChromeRenderFrameObserver(render_frame); + new ChromeRenderFrameObserver(render_frame, web_cache_impl_.get()); service_manager::BinderRegistry* registry = render_frame_observer->registry(); bool should_whitelist_for_content_settings = @@ -567,8 +566,6 @@ void ChromeContentRendererClient::RenderViewCreated( content::RenderView* render_view) { new prerender::PrerendererClient(render_view); - - new ChromeRenderViewObserver(render_view, web_cache_impl_.get()); } SkBitmap* ChromeContentRendererClient::GetSadPluginBitmap() {
diff --git a/chrome/renderer/chrome_render_frame_observer.cc b/chrome/renderer/chrome_render_frame_observer.cc index bc5fa16..0edcddc9 100644 --- a/chrome/renderer/chrome_render_frame_observer.cc +++ b/chrome/renderer/chrome_render_frame_observer.cc
@@ -29,6 +29,7 @@ #include "components/crash/core/common/crash_key.h" #include "components/offline_pages/buildflags/buildflags.h" #include "components/translate/content/renderer/translate_helper.h" +#include "components/web_cache/renderer/web_cache_impl.h" #include "content/public/common/bindings_policy.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" @@ -137,10 +138,12 @@ } // namespace ChromeRenderFrameObserver::ChromeRenderFrameObserver( - content::RenderFrame* render_frame) + content::RenderFrame* render_frame, + web_cache::WebCacheImpl* web_cache_impl) : content::RenderFrameObserver(render_frame), translate_helper_(nullptr), - phishing_classifier_(nullptr) { + phishing_classifier_(nullptr), + web_cache_impl_(web_cache_impl) { render_frame->GetAssociatedInterfaceRegistry()->AddInterface( base::Bind(&ChromeRenderFrameObserver::OnRenderFrameObserverRequest, base::Unretained(this))); @@ -377,6 +380,11 @@ void ChromeRenderFrameObserver::ReadyToCommitNavigation( WebDocumentLoader* document_loader) { + // Execute cache clear operations that were postponed until a navigation + // event (including tab reload). + if (render_frame()->IsMainFrame() && web_cache_impl_) + web_cache_impl_->ExecutePendingClearCache(); + // Let translate_helper do any preparatory work for loading a URL. if (!translate_helper_) return;
diff --git a/chrome/renderer/chrome_render_frame_observer.h b/chrome/renderer/chrome_render_frame_observer.h index 65d080f..7f4d9b27 100644 --- a/chrome/renderer/chrome_render_frame_observer.h +++ b/chrome/renderer/chrome_render_frame_observer.h
@@ -28,12 +28,17 @@ class TranslateHelper; } +namespace web_cache { +class WebCacheImpl; +} + // This class holds the Chrome specific parts of RenderFrame, and has the same // lifetime. class ChromeRenderFrameObserver : public content::RenderFrameObserver, public chrome::mojom::ChromeRenderFrame { public: - explicit ChromeRenderFrameObserver(content::RenderFrame* render_frame); + ChromeRenderFrameObserver(content::RenderFrame* render_frame, + web_cache::WebCacheImpl* web_cache_impl); ~ChromeRenderFrameObserver() override; service_manager::BinderRegistry* registry() { return ®istry_; } @@ -105,6 +110,8 @@ translate::TranslateHelper* translate_helper_; safe_browsing::PhishingClassifierDelegate* phishing_classifier_; + // Owned by ChromeContentRendererClient and outlive us. + web_cache::WebCacheImpl* web_cache_impl_; #if !defined(OS_ANDROID) // Save the JavaScript to preload if ExecuteWebUIJavaScript is invoked.
diff --git a/chrome/renderer/chrome_render_view_observer.cc b/chrome/renderer/chrome_render_view_observer.cc deleted file mode 100644 index f38858c..0000000 --- a/chrome/renderer/chrome_render_view_observer.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2012 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 "chrome/renderer/chrome_render_view_observer.h" - -#include "components/web_cache/renderer/web_cache_impl.h" - -ChromeRenderViewObserver::ChromeRenderViewObserver( - content::RenderView* render_view, - web_cache::WebCacheImpl* web_cache_impl) - : content::RenderViewObserver(render_view), - web_cache_impl_(web_cache_impl) {} - -ChromeRenderViewObserver::~ChromeRenderViewObserver() { -} - -void ChromeRenderViewObserver::Navigate(const GURL& url) { - // Execute cache clear operations that were postponed until a navigation - // event (including tab reload). - if (web_cache_impl_) - web_cache_impl_->ExecutePendingClearCache(); -} - -void ChromeRenderViewObserver::OnDestruct() { - delete this; -}
diff --git a/chrome/renderer/chrome_render_view_observer.h b/chrome/renderer/chrome_render_view_observer.h deleted file mode 100644 index c6090ea6..0000000 --- a/chrome/renderer/chrome_render_view_observer.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 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 CHROME_RENDERER_CHROME_RENDER_VIEW_OBSERVER_H_ -#define CHROME_RENDERER_CHROME_RENDER_VIEW_OBSERVER_H_ - -#include <string> - -#include "base/macros.h" -#include "content/public/common/browser_controls_state.h" -#include "content/public/renderer/render_view_observer.h" -#include "url/gurl.h" - -namespace web_cache { -class WebCacheImpl; -} - -// This class holds the Chrome specific parts of RenderView, and has the same -// lifetime. -class ChromeRenderViewObserver : public content::RenderViewObserver { - public: - // translate_helper can be NULL. - ChromeRenderViewObserver( - content::RenderView* render_view, - web_cache::WebCacheImpl* web_cache_render_thread_observer); - ~ChromeRenderViewObserver() override; - - private: - // RenderViewObserver implementation. - void Navigate(const GURL& url) override; - void OnDestruct() override; - - // Determines if a host is in the strict security host set. - bool IsStrictSecurityHost(const std::string& host); - - // Owned by ChromeContentRendererClient and outlive us. - web_cache::WebCacheImpl* web_cache_impl_; - - DISALLOW_COPY_AND_ASSIGN(ChromeRenderViewObserver); -}; - -#endif // CHROME_RENDERER_CHROME_RENDER_VIEW_OBSERVER_H_
diff --git a/chrome/renderer/sandbox_status_extension_android.cc b/chrome/renderer/sandbox_status_extension_android.cc index 1181442..321cb43 100644 --- a/chrome/renderer/sandbox_status_extension_android.cc +++ b/chrome/renderer/sandbox_status_extension_android.cc
@@ -83,8 +83,11 @@ ->GetFunction(context) .ToLocal(&function); if (success) { - success = chrome->Set( - gin::StringToSymbol(isolate, "getAndroidSandboxStatus"), function); + success = chrome + ->Set(context, + gin::StringToSymbol(isolate, "getAndroidSandboxStatus"), + function) + .IsJust(); } DCHECK(success); }
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index c7133739..33de0915 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2855,6 +2855,7 @@ "../browser/previews/previews_lite_page_infobar_delegate_unittest.cc", "../browser/previews/previews_lite_page_navigation_throttle_unittest.cc", "../browser/previews/previews_lite_page_url_loader_interceptor_unittest.cc", + "../browser/previews/previews_offline_helper_unittest.cc", "../browser/previews/previews_service_unittest.cc", "../browser/previews/previews_ui_tab_helper_unittest.cc", "../browser/process_singleton_win_unittest.cc", @@ -3548,6 +3549,7 @@ "//components/chrome_cleaner/test:test_name_helper", "//components/send_tab_to_self:test_support", "//components/signin/core/browser:signin_buildflags", + "//components/sync:test_support_js", "//services/metrics/public/cpp:ukm_builders", "//third_party/libaddressinput", "//ui/native_theme:test_support",
diff --git a/chrome/test/android/BUILD.gn b/chrome/test/android/BUILD.gn index eb92ec3..f87e9abd 100644 --- a/chrome/test/android/BUILD.gn +++ b/chrome/test/android/BUILD.gn
@@ -97,7 +97,6 @@ "//third_party/android_sdk:android_test_base_java", "//third_party/android_support_test_runner:rules_java", "//third_party/android_support_test_runner:runner_java", - "//third_party/gvr-android-sdk:gvr_common_java", "//third_party/hamcrest:hamcrest_core_java", "//third_party/jsr-305:jsr_305_javalib", "//third_party/junit",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java index 59d57112..12564c9 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeJUnit4ClassRunner.java
@@ -11,8 +11,6 @@ import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; -import com.google.vr.ndk.base.DaydreamApi; -import com.google.vr.ndk.base.GvrApi; import org.junit.rules.TestRule; import org.junit.runners.model.InitializationError; @@ -30,6 +28,8 @@ import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.policy.test.annotations.Policies; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.ExecutionException; @@ -67,35 +67,78 @@ super(targetContext); } + private Class getDaydreamApiClass() { + Class daydreamApiClass; + try { + daydreamApiClass = Class.forName("com.google.vr.ndk.base.DaydreamApi"); + } catch (ClassNotFoundException e) { + daydreamApiClass = null; + } + return daydreamApiClass; + } + + @SuppressWarnings("unchecked") private boolean isDaydreamReady() { // We normally check things like this through VrShellDelegate. However, with the // introduction of Dynamic Feature Modules (DFMs), we have tests that expect the VR // DFM to not be loaded. Using the normal approach (VrModuleProvider.getDelegate()) // causes the DFM to be loaded, which we don't want done before the test starts. So, - // access the Daydream API directly. - return DaydreamApi.isDaydreamReadyPlatform(ContextUtils.getApplicationContext()); + // access the Daydream API directly. VR is likely, but not guaranteed, to be compiled + // into the test binary, so use reflection. + Class daydreamApiClass = getDaydreamApiClass(); + if (daydreamApiClass == null) { + return false; + } + try { + Method isDaydreamMethod = + daydreamApiClass.getMethod("isDaydreamReadyPlatform", Context.class); + Boolean isDaydream = (Boolean) isDaydreamMethod.invoke( + null, ContextUtils.getApplicationContext()); + return isDaydream; + } catch (NoSuchMethodException | SecurityException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + return false; + } } + @SuppressWarnings("unchecked") private boolean isDaydreamViewPaired() { if (!isDaydreamReady()) { return false; } - // We need to ensure that the DaydreamApi instance is created on the main thread. - DaydreamApi daydreamApi; - try { - daydreamApi = TestThreadUtils.runOnUiThreadBlocking( - () -> { return DaydreamApi.create(ContextUtils.getApplicationContext()); }); - } catch (ExecutionException e) { + + Class daydreamApiClass = getDaydreamApiClass(); + if (daydreamApiClass == null) { return false; } - int viewerType; - // Getting the current viewer type may result in a disk write in VrCore, so allow that - // to prevent StrictMode errors. - try (StrictModeContext smc = StrictModeContext.allowDiskWrites()) { - viewerType = daydreamApi.getCurrentViewerType(); + + try { + Method createMethod = daydreamApiClass.getMethod("create", Context.class); + // We need to ensure that the DaydreamApi instance is created on the main thread. + Object daydreamApiInstance = TestThreadUtils.runOnUiThreadBlocking(() -> { + return createMethod.invoke(null, ContextUtils.getApplicationContext()); + }); + if (daydreamApiInstance == null) { + return false; + } + + Method currentViewerMethod = daydreamApiClass.getMethod("getCurrentViewerType"); + // Getting the current viewer type may result in a disk write in VrCore, so allow + // that to prevent StrictMode errors. + Integer viewerType; + try (StrictModeContext smc = StrictModeContext.allowDiskWrites()) { + viewerType = (Integer) currentViewerMethod.invoke(daydreamApiInstance); + } + Method closeMethod = daydreamApiClass.getMethod("close"); + closeMethod.invoke(daydreamApiInstance); + // 1 is the viewer type constant for Daydream headsets. We could use reflection to + // check against com.google.vr.ndk.base.GvrApi.ViewerType.DAYDREAM, but the + // constants have never changed, so check this way to be simpler. + return viewerType == 1; + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException + | ExecutionException e) { + return false; } - daydreamApi.close(); - return viewerType == GvrApi.ViewerType.DAYDREAM; } private boolean isOnStandaloneVrDevice() {
diff --git a/chrome/test/base/js2gtest.gni b/chrome/test/base/js2gtest.gni index 7eda20c8..97e7cfd 100644 --- a/chrome/test/base/js2gtest.gni +++ b/chrome/test/base/js2gtest.gni
@@ -85,7 +85,7 @@ } args += [ "{{source}}", - "{{source_root_relative_dir}}/{{source_file_part}}", + rebase_path("//", root_build_dir), # Path to source root. gen_source_pattern, rebase_path(copied_source_pattern, root_build_dir), ]
diff --git a/chrome/test/base/js2gtest.js b/chrome/test/base/js2gtest.js index 8ed7371..922de5c 100644 --- a/chrome/test/base/js2gtest.js +++ b/chrome/test/base/js2gtest.js
@@ -18,23 +18,34 @@ // python script gypv8sh.py. if (arguments.length != 6) { print('usage: ' + - arguments[0] + - ' path-to-testfile.js testfile.js path_to_deps.js output.cc test-type'); + arguments[0] + + ' path-to-testfile.js path-to-src-root/ path-to-deps.js output.cc' + + ' test-type'); quit(-1); } /** - * Full path to the test input file. + * Full path to the test input file, relative to the current working directory. * @type {string} */ -var jsFile = arguments[1]; +var fullTestFilePath = arguments[1]; /** - * Relative path to the test input file appropriate for use in the - * C++ TestFixture's addLibrary method. + * Path to source-root, relative to the current working directory. * @type {string} */ -var jsFileBase = arguments[2]; +var srcRootPath = arguments[2]; + +if (!fullTestFilePath.startsWith(srcRootPath)) { + print('Test file must be a descendant of source root directory'); + quit(-1); +} + +/** + * Path to test input file, relative to source root directory. + * @type {string} + */ +var testFile = fullTestFilePath.substr(srcRootPath.length); /** * Path to Closure library style deps.js file. @@ -75,8 +86,8 @@ var typedeffedCppFixtures = {}; /** - * Maintains a list of relative file paths to add to each gtest body - * for inclusion at runtime before running each JavaScript test. + * Maintains a list of file paths (relative to source-root directory) to add + * to each gtest body for inclusion at runtime before running each JS test. * @type {Array<string>} */ var genIncludes = []; @@ -197,31 +208,48 @@ /** - * Convert the |includeFile| to paths appropriate for immediate - * inclusion (path) and runtime inclusion (base). + * Get the path (relative to source root directory) of the given include-file. + * The include must either be relative to the file it is included from, + * or a source-absolute path starting with '//'. + * * @param {string} includeFile The file to include. - * @return {{path: string, base: string}} Object describing the paths - * for |includeFile|. |path| is relative to cwd; |base| is relative to - * source root. + * @return {string} Path of the file, relative to source root directory. */ -function includeFileToPaths(includeFile) { - paths = pathStack[pathStack.length - 1]; - return { - path: paths.path.replace(/[^\/\\]+$/, includeFile), - base: paths.base.replace(/[^\/\\]+$/, includeFile), - }; +function includeFileToPath(includeFile) { + if (includeFile.startsWith('//')) { + return includeFile.substr(2); // Path is already relative to source-root. + } else if (includeFile.startsWith('/')) { + print('Error including ' + includeFile); + print('Only relative "foo/bar" or source-absolute "//foo/bar" paths are ' + + 'supported - not file-system absolute: "/foo/bar"'); + quit(-1); + } else { + // The include-file path is relative to the file that included it. + var currentPath = pathStack[pathStack.length - 1]; + return currentPath.replace(/[^\/\\]+$/, includeFile) + } } /** * Returns the content of a javascript file with a sourceURL comment * appended to facilitate better stack traces. - * @param {string} path Relative path name. + * @param {string} path Path to JS file, relative to current working dir. * return {string} */ function readJsFile(path) { return read(path) + '\n//# sourceURL=' + path; } +/** + * Returns the content of a javascript file with a sourceURL comment + * appended to facilitate better stack traces. + * @param {string} path Path to JS file, relative to source root. + * return {string} + */ +function readSourceAbsoluteJsFile(path) { + return readJsFile(srcRootPath + path); +} + /** * Maps object names to the path to the file that provides them. @@ -334,12 +362,12 @@ */ function GEN_INCLUDE(includes) { for (var i = 0; i < includes.length; i++) { - var includePaths = includeFileToPaths(includes[i]); - var js = readJsFile(includePaths.path); - pathStack.push(includePaths); + var includePath = includeFileToPath(includes[i]); + var js = readSourceAbsoluteJsFile(includePath); + pathStack.push(includePath); ('global', eval)(js); pathStack.pop(); - genIncludes.push(includePaths.base); + genIncludes.push(includePath); } } @@ -380,11 +408,9 @@ var testShouldFail = this[testFixture].prototype.testShouldFail; var testPredicate = testShouldFail ? 'ASSERT_FALSE' : 'ASSERT_TRUE'; var extraLibraries = genIncludes.concat( - this[testFixture].prototype.extraLibraries.map( - function(includeFile) { - return includeFileToPaths(includeFile).base; - }), - resolveClosureModuleDeps(this[testFixture].prototype.closureModuleDeps)); + this[testFixture].prototype.extraLibraries.map(includeFileToPath), + resolveClosureModuleDeps(this[testFixture].prototype.closureModuleDeps), + [testFile]); var testFLine = getTestDeclarationLineNumber(); if (typedefCppFixture && !(testFixture in typedeffedCppFixtures)) { @@ -477,19 +503,16 @@ var outputLine = countOutputLines() + 3; output(` -#line ${testFLine} "${jsFile}" +#line ${testFLine} "${testFile}" ${testF}(${testFixture}, ${testFunction}) { #line ${outputLine} "${outputFile}"`); - for (var i = 0; i < extraLibraries.length; i++) { +for (var i = 0; i < extraLibraries.length; i++) { var libraryName = extraLibraries[i].replace(/\\/g, '/'); output(` AddLibrary(base::FilePath(FILE_PATH_LITERAL( "${libraryName}")));`); } - output(` - AddLibrary(base::FilePath(FILE_PATH_LITERAL( - "${jsFileBase.replace(/\\/g, '/')}")));`); if (addSetPreloadInfo) { output(` set_preload_test_fixture("${testFixture}"); @@ -530,9 +553,9 @@ TEST_F(testFixture, testFunction, testBody, preamble); } -// Now that generation functions are defined, load in |jsFile|. -var js = readJsFile(jsFile); -pathStack.push({path: jsFile, base: jsFileBase}); +// Now that generation functions are defined, load in |testFile|. +var js = readSourceAbsoluteJsFile(testFile); +pathStack.push(testFile); eval(js); pathStack.pop(); print(pendingOutput);
diff --git a/chromeos/dbus/power/power_policy_controller.cc b/chromeos/dbus/power/power_policy_controller.cc index 7031385b..24c4e60d 100644 --- a/chromeos/dbus/power/power_policy_controller.cc +++ b/chromeos/dbus/power/power_policy_controller.cc
@@ -107,32 +107,30 @@ delays->set_idle_warning_ms(warn_ms); } -power_manager::PowerManagementPolicy::PeakShiftDayConfig::WeekDay -GetProtoWeekDay(PowerPolicyController::WeekDay week_day) { +power_manager::PowerManagementPolicy::WeekDay GetProtoWeekDay( + PowerPolicyController::WeekDay week_day) { switch (week_day) { case PowerPolicyController::WeekDay::WEEK_DAY_MONDAY: - return power_manager::PowerManagementPolicy::PeakShiftDayConfig::MONDAY; + return power_manager::PowerManagementPolicy::MONDAY; case PowerPolicyController::WeekDay::WEEK_DAY_TUESDAY: - return power_manager::PowerManagementPolicy::PeakShiftDayConfig::TUESDAY; + return power_manager::PowerManagementPolicy::TUESDAY; case PowerPolicyController::WeekDay::WEEK_DAY_WEDNESDAY: - return power_manager::PowerManagementPolicy::PeakShiftDayConfig:: - WEDNESDAY; + return power_manager::PowerManagementPolicy::WEDNESDAY; case PowerPolicyController::WeekDay::WEEK_DAY_THURSDAY: - return power_manager::PowerManagementPolicy::PeakShiftDayConfig::THURSDAY; + return power_manager::PowerManagementPolicy::THURSDAY; case PowerPolicyController::WeekDay::WEEK_DAY_FRIDAY: - return power_manager::PowerManagementPolicy::PeakShiftDayConfig::FRIDAY; + return power_manager::PowerManagementPolicy::FRIDAY; case PowerPolicyController::WeekDay::WEEK_DAY_SATURDAY: - return power_manager::PowerManagementPolicy::PeakShiftDayConfig::SATURDAY; + return power_manager::PowerManagementPolicy::SATURDAY; case PowerPolicyController::WeekDay::WEEK_DAY_SUNDAY: - return power_manager::PowerManagementPolicy::PeakShiftDayConfig::SUNDAY; + return power_manager::PowerManagementPolicy::SUNDAY; } } -std::unique_ptr< - power_manager::PowerManagementPolicy::PeakShiftDayConfig::DayTime> -GetProtoDayTime(const PowerPolicyController::DayTime& day_time) { - auto proto = std::make_unique< - power_manager::PowerManagementPolicy::PeakShiftDayConfig::DayTime>(); +std::unique_ptr<power_manager::PowerManagementPolicy::DayTime> GetProtoDayTime( + const PowerPolicyController::DayTime& day_time) { + auto proto = + std::make_unique<power_manager::PowerManagementPolicy::DayTime>(); proto->set_hour(day_time.hour); proto->set_minute(day_time.minute); return proto;
diff --git a/chromeos/dbus/power/power_policy_controller_unittest.cc b/chromeos/dbus/power/power_policy_controller_unittest.cc index 3bc5542..ee4bb6a 100644 --- a/chromeos/dbus/power/power_policy_controller_unittest.cc +++ b/chromeos/dbus/power/power_policy_controller_unittest.cc
@@ -195,8 +195,7 @@ expected_policy.set_peak_shift_battery_percent_threshold(20); auto* proto_config = expected_policy.add_peak_shift_day_configs(); - proto_config->set_day( - power_manager::PowerManagementPolicy::PeakShiftDayConfig::TUESDAY); + proto_config->set_day(power_manager::PowerManagementPolicy::TUESDAY); proto_config->mutable_start_time()->set_hour(10); proto_config->mutable_start_time()->set_minute(0); proto_config->mutable_end_time()->set_hour(20);
diff --git a/chromeos/network/BUILD.gn b/chromeos/network/BUILD.gn index 99fb26a..d762e37 100644 --- a/chromeos/network/BUILD.gn +++ b/chromeos/network/BUILD.gn
@@ -36,6 +36,8 @@ sources = [ "auto_connect_handler.cc", "auto_connect_handler.h", + "cellular_metrics_logger.cc", + "cellular_metrics_logger.h", "certificate_helper.cc", "certificate_helper.h", "client_cert_resolver.cc", @@ -223,6 +225,7 @@ ] sources = [ "auto_connect_handler_unittest.cc", + "cellular_metrics_logger_unittest.cc", "certificate_helper_unittest.cc", "client_cert_resolver_unittest.cc", "fast_transition_observer_unittest.cc",
diff --git a/chromeos/network/cellular_metrics_logger.cc b/chromeos/network/cellular_metrics_logger.cc new file mode 100644 index 0000000..29dcfdd4e --- /dev/null +++ b/chromeos/network/cellular_metrics_logger.cc
@@ -0,0 +1,104 @@ +// Copyright 2019 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 "chromeos/network/cellular_metrics_logger.h" + +#include "base/metrics/histogram_macros.h" +#include "base/task/post_task.h" +#include "chromeos/network/network_event_log.h" +#include "chromeos/network/network_state_handler.h" + +namespace chromeos { + +// static +const base::TimeDelta CellularMetricsLogger::kInitializationTimeout = + base::TimeDelta::FromSeconds(15); + +CellularMetricsLogger::CellularMetricsLogger() = default; + +CellularMetricsLogger::~CellularMetricsLogger() { + if (network_state_handler_) + OnShuttingDown(); +} + +void CellularMetricsLogger::Init(NetworkStateHandler* network_state_handler) { + network_state_handler_ = network_state_handler; + network_state_handler_->AddObserver(this, FROM_HERE); + + // Devices may already be present before this method is called. + // Make sure that cellular availability is updated and initialization + // timer is started properly. + DeviceListChanged(); +} + +void CellularMetricsLogger::DeviceListChanged() { + NetworkStateHandler::DeviceStateList device_list; + network_state_handler_->GetDeviceListByType(NetworkTypePattern::Cellular(), + &device_list); + bool new_is_cellular_available = !device_list.empty(); + if (is_cellular_available_ == new_is_cellular_available) + return; + + is_cellular_available_ = new_is_cellular_available; + // Start a timer to wait for cellular networks to initialize. + // This makes sure that intermediate not-connected states are + // not logged before initialization is completed. + if (is_cellular_available_) { + initialization_timer_.Start(FROM_HERE, kInitializationTimeout, this, + &CellularMetricsLogger::LogCellularUsageCount); + } +} + +void CellularMetricsLogger::NetworkConnectionStateChanged( + const NetworkState* network) { + DCHECK(network_state_handler_); + LogCellularUsageCount(); +} + +void CellularMetricsLogger::LogCellularUsageCount() { + if (!is_cellular_available_) + return; + + NetworkStateHandler::NetworkStateList network_list; + network_state_handler_->GetVisibleNetworkListByType( + NetworkTypePattern::NonVirtual(), &network_list); + + bool is_cellular_connected = false; + bool is_non_cellular_connected = false; + for (const auto* network : network_list) { + if (!network->IsConnectedState()) + continue; + + if (network->Matches(NetworkTypePattern::Cellular())) + is_cellular_connected = true; + else + is_non_cellular_connected = true; + } + + // Discard not-connected states received before the timer runs out. + if (!is_cellular_connected && initialization_timer_.IsRunning()) + return; + + CellularUsage usage; + if (is_cellular_connected) { + usage = is_non_cellular_connected + ? CellularUsage::kConnectedWithOtherNetwork + : CellularUsage::kConnectedAndOnlyNetwork; + } else { + usage = CellularUsage::kNotConnected; + } + + if (usage == last_cellular_usage_) + return; + last_cellular_usage_ = usage; + + UMA_HISTOGRAM_ENUMERATION("Network.Cellular.Usage.Count", usage); +} + +void CellularMetricsLogger::OnShuttingDown() { + network_state_handler_->RemoveObserver(this, FROM_HERE); + network_state_handler_ = nullptr; +} + +} // namespace chromeos
diff --git a/chromeos/network/cellular_metrics_logger.h b/chromeos/network/cellular_metrics_logger.h new file mode 100644 index 0000000..8bf5bd920 --- /dev/null +++ b/chromeos/network/cellular_metrics_logger.h
@@ -0,0 +1,84 @@ +// Copyright (c) 2019 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 CHROMEOS_NETWORK_CELLULAR_METRICS_LOGGER_H_ +#define CHROMEOS_NETWORK_CELLULAR_METRICS_LOGGER_H_ + +#include "base/component_export.h" +#include "base/gtest_prod_util.h" +#include "base/macros.h" +#include "base/optional.h" +#include "base/timer/timer.h" +#include "chromeos/network/network_state_handler_observer.h" + +namespace chromeos { + +class NetworkStateHandler; +class NetworkState; +class CellularMetricsLoggerTest; + +// Class for tracking cellular network related metrics. +// +// This class adds observers on network state and logs histograms +// when relevant cellular network events are triggered. +// +// Note: This class does not start logging metrics until Init() is +// invoked. +class COMPONENT_EXPORT(CHROMEOS_NETWORK) CellularMetricsLogger + : public NetworkStateHandlerObserver { + public: + CellularMetricsLogger(); + ~CellularMetricsLogger() override; + + void Init(NetworkStateHandler* network_state_handler); + + // NetworkStateHandlerObserver:: + void DeviceListChanged() override; + void NetworkConnectionStateChanged(const NetworkState* network) override; + void OnShuttingDown() override; + + private: + friend class CellularMetricsLoggerTest; + FRIEND_TEST_ALL_PREFIXES(CellularMetricsLoggerTest, CellularUsageCountTest); + FRIEND_TEST_ALL_PREFIXES(CellularMetricsLoggerTest, + CellularUsageCountDongleTest); + + // The amount of time after cellular device is added to device list, + // after which cellular device is considered initialized. + static const base::TimeDelta kInitializationTimeout; + + // Usage type for cellular network. These values are persisted to logs. + // Entries should not be renumbered and numberic values should never + // be reused. + enum class CellularUsage { + kConnectedAndOnlyNetwork = 0, + kConnectedWithOtherNetwork = 1, + kNotConnected = 2, + kMaxValue = kNotConnected + }; + + // This checks the state of connected networks and logs + // cellular network usage histogram. Histogram is only logged + // when usage state changes. + void LogCellularUsageCount(); + + // Tracks the last cellular network usage state. + base::Optional<CellularUsage> last_cellular_usage_; + + // Tracks whether cellular device is available or not. + bool is_cellular_available_ = false; + + NetworkStateHandler* network_state_handler_ = nullptr; + + // A timer to wait for cellular initialization. This is useful + // to avoid tracking intermediate states when cellular network is + // starting up. + base::OneShotTimer initialization_timer_; + + DISALLOW_COPY_AND_ASSIGN(CellularMetricsLogger); +}; + +} // namespace chromeos + +#endif // CHROMEOS_NETWORK_CELLULAR_METRICS_LOGGER_H_
diff --git a/chromeos/network/cellular_metrics_logger_unittest.cc b/chromeos/network/cellular_metrics_logger_unittest.cc new file mode 100644 index 0000000..0339e87 --- /dev/null +++ b/chromeos/network/cellular_metrics_logger_unittest.cc
@@ -0,0 +1,183 @@ +// Copyright 2019 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 "chromeos/network/cellular_metrics_logger.h" + +#include <memory> + +#include "base/run_loop.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_task_environment.h" +#include "chromeos/network/network_state_handler.h" +#include "chromeos/network/network_state_test_helper.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/cros_system_api/dbus/service_constants.h" + +namespace chromeos { + +namespace { + +const char kTestCellularDevicePath[] = "/device/wwan0"; +const char kTestCellularServicePath[] = "/service/cellular0"; +const char kTestEthServicePath[] = "/service/eth0"; + +const char kUsageCountHistogram[] = "Network.Cellular.Usage.Count"; + +} // namespace + +class CellularMetricsLoggerTest : public testing::Test { + public: + CellularMetricsLoggerTest() + : scoped_task_environment_( + base::test::ScopedTaskEnvironment::MainThreadType::UI_MOCK_TIME) {} + ~CellularMetricsLoggerTest() override = default; + + void SetUp() override { + network_metrics_logger_.reset(new CellularMetricsLogger()); + network_metrics_logger_->Init( + network_state_test_helper_.network_state_handler()); + } + + protected: + void InitEthernet() { + ShillServiceClient::TestInterface* service_test = + network_state_test_helper_.service_test(); + service_test->AddService(kTestEthServicePath, "test_guid1", "test_eth", + shill::kTypeEthernet, shill::kStateIdle, true); + base::RunLoop().RunUntilIdle(); + } + + void InitCellular() { + ShillDeviceClient::TestInterface* device_test = + network_state_test_helper_.device_test(); + device_test->AddDevice(kTestCellularDevicePath, shill::kTypeCellular, + "test_cellular_device"); + + ShillServiceClient::TestInterface* service_test = + network_state_test_helper_.service_test(); + service_test->AddService(kTestCellularServicePath, "test_guid0", + "test_cellular", shill::kTypeCellular, + shill::kStateIdle, true); + base::RunLoop().RunUntilIdle(); + } + + void RemoveCellular() { + ShillServiceClient::TestInterface* service_test = + network_state_test_helper_.service_test(); + service_test->RemoveService(kTestCellularServicePath); + + ShillDeviceClient::TestInterface* device_test = + network_state_test_helper_.device_test(); + device_test->RemoveDevice(kTestCellularDevicePath); + base::RunLoop().RunUntilIdle(); + } + + base::test::ScopedTaskEnvironment scoped_task_environment_; + + ShillServiceClient::TestInterface* service_client_test() { + return network_state_test_helper_.service_test(); + } + + private: + NetworkStateTestHelper network_state_test_helper_{ + false /* use_default_devices_and_services */}; + std::unique_ptr<CellularMetricsLogger> network_metrics_logger_; + + DISALLOW_COPY_AND_ASSIGN(CellularMetricsLoggerTest); +}; + +TEST_F(CellularMetricsLoggerTest, CellularUsageCountTest) { + InitEthernet(); + InitCellular(); + base::HistogramTester histogram_tester; + static const base::Value kTestOnlineStateValue(shill::kStateOnline); + static const base::Value kTestIdleStateValue(shill::kStateIdle); + + // Should not log state until after timeout. + service_client_test()->SetServiceProperty( + kTestEthServicePath, shill::kStateProperty, kTestOnlineStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectTotalCount(kUsageCountHistogram, 0); + + scoped_task_environment_.FastForwardBy( + CellularMetricsLogger::kInitializationTimeout); + histogram_tester.ExpectBucketCount( + kUsageCountHistogram, CellularMetricsLogger::CellularUsage::kNotConnected, + 1); + + // Cellular connected with other network. + service_client_test()->SetServiceProperty( + kTestCellularServicePath, shill::kStateProperty, kTestOnlineStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectBucketCount( + kUsageCountHistogram, + CellularMetricsLogger::CellularUsage::kConnectedWithOtherNetwork, 1); + + // Cellular connected as only network. + service_client_test()->SetServiceProperty( + kTestEthServicePath, shill::kStateProperty, kTestIdleStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectBucketCount( + kUsageCountHistogram, + CellularMetricsLogger::CellularUsage::kConnectedAndOnlyNetwork, 1); + + // Cellular not connected. + service_client_test()->SetServiceProperty( + kTestCellularServicePath, shill::kStateProperty, kTestIdleStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectBucketCount( + kUsageCountHistogram, CellularMetricsLogger::CellularUsage::kNotConnected, + 2); +} + +TEST_F(CellularMetricsLoggerTest, CellularUsageCountDongleTest) { + InitEthernet(); + base::HistogramTester histogram_tester; + static const base::Value kTestOnlineStateValue(shill::kStateOnline); + static const base::Value kTestIdleStateValue(shill::kStateIdle); + + // Should not log state if no cellular devices are available. + scoped_task_environment_.FastForwardBy( + CellularMetricsLogger::kInitializationTimeout); + histogram_tester.ExpectTotalCount(kUsageCountHistogram, 0); + + service_client_test()->SetServiceProperty( + kTestEthServicePath, shill::kStateProperty, kTestOnlineStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectTotalCount(kUsageCountHistogram, 0); + + // Should log state if a new cellular device is plugged in. + InitCellular(); + scoped_task_environment_.FastForwardBy( + CellularMetricsLogger::kInitializationTimeout); + histogram_tester.ExpectBucketCount( + kUsageCountHistogram, CellularMetricsLogger::CellularUsage::kNotConnected, + 1); + + // Should log connected state for cellular device that was plugged in. + service_client_test()->SetServiceProperty( + kTestCellularServicePath, shill::kStateProperty, kTestOnlineStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectBucketCount( + kUsageCountHistogram, + CellularMetricsLogger::CellularUsage::kConnectedWithOtherNetwork, 1); + + // Should log connected as only network state for cellular device + // that was plugged in. + service_client_test()->SetServiceProperty( + kTestEthServicePath, shill::kStateProperty, kTestIdleStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectBucketCount( + kUsageCountHistogram, + CellularMetricsLogger::CellularUsage::kConnectedAndOnlyNetwork, 1); + + // Should not log state if cellular device is unplugged. + RemoveCellular(); + service_client_test()->SetServiceProperty( + kTestEthServicePath, shill::kStateProperty, kTestIdleStateValue); + base::RunLoop().RunUntilIdle(); + histogram_tester.ExpectTotalCount(kUsageCountHistogram, 3); +} + +} // namespace chromeos
diff --git a/chromeos/network/network_handler.cc b/chromeos/network/network_handler.cc index 8bbb0f9..130ae7f 100644 --- a/chromeos/network/network_handler.cc +++ b/chromeos/network/network_handler.cc
@@ -6,6 +6,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "chromeos/network/auto_connect_handler.h" +#include "chromeos/network/cellular_metrics_logger.h" #include "chromeos/network/client_cert_resolver.h" #include "chromeos/network/geolocation_handler.h" #include "chromeos/network/managed_network_configuration_handler_impl.h" @@ -45,6 +46,7 @@ } network_activation_handler_.reset(new NetworkActivationHandler()); network_connection_handler_.reset(new NetworkConnectionHandlerImpl()); + cellular_metrics_logger_.reset(new CellularMetricsLogger()); network_sms_handler_.reset(new NetworkSmsHandler()); geolocation_handler_.reset(new GeolocationHandler()); } @@ -67,6 +69,7 @@ network_state_handler_.get(), network_configuration_handler_.get(), managed_network_configuration_handler_.get()); + cellular_metrics_logger_->Init(network_state_handler_.get()); if (network_cert_migrator_) network_cert_migrator_->Init(network_state_handler_.get()); if (client_cert_resolver_) {
diff --git a/chromeos/network/network_handler.h b/chromeos/network/network_handler.h index 5a7ac44..c6f4663d 100644 --- a/chromeos/network/network_handler.h +++ b/chromeos/network/network_handler.h
@@ -33,6 +33,7 @@ class NetworkSmsHandler; class ProhibitedTechnologiesHandler; class UIProxyConfigService; +class CellularMetricsLogger; // Class for handling initialization and access to chromeos network handlers. // This class should NOT be used in unit tests. Instead, construct individual @@ -110,6 +111,7 @@ std::unique_ptr<ProhibitedTechnologiesHandler> prohibited_technologies_handler_; std::unique_ptr<UIProxyConfigService> ui_proxy_config_service_; + std::unique_ptr<CellularMetricsLogger> cellular_metrics_logger_; DISALLOW_COPY_AND_ASSIGN(NetworkHandler); };
diff --git a/chromeos/system/statistics_provider.cc b/chromeos/system/statistics_provider.cc index fbfdd0f..2721d33 100644 --- a/chromeos/system/statistics_provider.cc +++ b/chromeos/system/statistics_provider.cc
@@ -187,6 +187,8 @@ const char kDevSwitchBootKey[] = "devsw_boot"; const char kDevSwitchBootValueDev[] = "1"; const char kDevSwitchBootValueVerified[] = "0"; +const char kDockMacAddressKey[] = "dock_mac"; +const char kEthernetMacAddressKey[] = "ethernet_mac0"; const char kFirmwareWriteProtectBootKey[] = "wpsw_boot"; const char kFirmwareWriteProtectBootValueOn[] = "1"; const char kFirmwareWriteProtectBootValueOff[] = "0"; @@ -198,6 +200,7 @@ const char kIsVmKey[] = "is_vm"; const char kIsVmValueFalse[] = "0"; const char kIsVmValueTrue[] = "1"; +const char kManufactureDateKey[] = "mfg_date"; const char kOffersCouponCodeKey[] = "ubind_attribute"; const char kOffersGroupCodeKey[] = "gbind_attribute"; const char kRlzBrandCodeKey[] = "rlz_brand_code";
diff --git a/chromeos/system/statistics_provider.h b/chromeos/system/statistics_provider.h index 9182f5a..1421b2bb 100644 --- a/chromeos/system/statistics_provider.h +++ b/chromeos/system/statistics_provider.h
@@ -42,6 +42,12 @@ COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kDevSwitchBootValueVerified[]; +// Dock MAC address key. +COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kDockMacAddressKey[]; + +// Ethernet MAC address key. +COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kEthernetMacAddressKey[]; + // Firmware write protect switch value. COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kFirmwareWriteProtectBootKey[]; @@ -71,6 +77,9 @@ COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kIsVmValueFalse[]; COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kIsVmValueTrue[]; +// Manufacture date key. +COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kManufactureDateKey[]; + // OEM customization flag that permits exiting enterprise enrollment flow in // OOBE when 'oem_enterprise_managed' flag is set. COMPONENT_EXPORT(CHROMEOS_SYSTEM)
diff --git a/components/browser_sync/BUILD.gn b/components/browser_sync/BUILD.gn index 5e5ebdc..72d5cdb 100644 --- a/components/browser_sync/BUILD.gn +++ b/components/browser_sync/BUILD.gn
@@ -29,7 +29,7 @@ "//components/prefs", "//components/reading_list/features:flags", "//components/send_tab_to_self", - "//components/sync:user_events", + "//components/sync/user_events", "//components/sync_bookmarks", "//components/sync_sessions", "//components/version_info",
diff --git a/components/content_settings/core/browser/content_settings_default_provider.cc b/components/content_settings/core/browser/content_settings_default_provider.cc index c3829e0..248e334 100644 --- a/components/content_settings/core/browser/content_settings_default_provider.cc +++ b/components/content_settings/core/browser/content_settings_default_provider.cc
@@ -225,7 +225,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* in_value) { + std::unique_ptr<base::Value>&& in_value) { DCHECK(CalledOnValidThread()); DCHECK(prefs_); @@ -237,7 +237,7 @@ // Put |in_value| in a scoped pointer to ensure that it gets cleaned up // properly if we don't pass on the ownership. - std::unique_ptr<base::Value> value(in_value); + std::unique_ptr<base::Value> value(std::move(in_value)); // The default settings may not be directly modified for OTR sessions. // Instead, they are synced to the main profile's setting.
diff --git a/components/content_settings/core/browser/content_settings_default_provider.h b/components/content_settings/core/browser/content_settings_default_provider.h index 8970258..21a3f58b 100644 --- a/components/content_settings/core/browser/content_settings_default_provider.h +++ b/components/content_settings/core/browser/content_settings_default_provider.h
@@ -44,7 +44,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override;
diff --git a/components/content_settings/core/browser/content_settings_ephemeral_provider.cc b/components/content_settings/core/browser/content_settings_ephemeral_provider.cc index a577a8a..c6a91eb 100644 --- a/components/content_settings/core/browser/content_settings_ephemeral_provider.cc +++ b/components/content_settings/core/browser/content_settings_ephemeral_provider.cc
@@ -51,7 +51,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* in_value) { + std::unique_ptr<base::Value>&& in_value) { DCHECK(CalledOnValidThread()); if (!base::ContainsKey(supported_types_, content_type)) @@ -68,7 +68,7 @@ return false; } - std::unique_ptr<base::Value> value(in_value); + std::unique_ptr<base::Value> value(std::move(in_value)); if (value) { content_settings_rules_.SetValue( primary_pattern, secondary_pattern, content_type, resource_identifier,
diff --git a/components/content_settings/core/browser/content_settings_ephemeral_provider.h b/components/content_settings/core/browser/content_settings_ephemeral_provider.h index c960a0f5..6be17c12 100644 --- a/components/content_settings/core/browser/content_settings_ephemeral_provider.h +++ b/components/content_settings/core/browser/content_settings_ephemeral_provider.h
@@ -32,7 +32,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override; void ShutdownOnUIThread() override; base::Time GetWebsiteSettingLastModified(
diff --git a/components/content_settings/core/browser/content_settings_ephemeral_provider_unittest.cc b/components/content_settings/core/browser/content_settings_ephemeral_provider_unittest.cc index e19f36f..75093088 100644 --- a/components/content_settings/core/browser/content_settings_ephemeral_provider_unittest.cc +++ b/components/content_settings/core/browser/content_settings_ephemeral_provider_unittest.cc
@@ -53,7 +53,7 @@ EXPECT_TRUE(provider()->SetWebsiteSetting( site_pattern, site_pattern, ephemeral_type(0), std::string(), - new base::Value(CONTENT_SETTING_ALLOW))); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW))); std::unique_ptr<RuleIterator> rule_iterator = provider()->GetRuleIterator(ephemeral_type(0), std::string(), false); @@ -65,7 +65,7 @@ // Overwrite previous value. EXPECT_TRUE(provider()->SetWebsiteSetting( site_pattern, site_pattern, ephemeral_type(0), std::string(), - new base::Value(CONTENT_SETTING_BLOCK))); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK))); rule_iterator = provider()->GetRuleIterator(ephemeral_type(0), std::string(), false); @@ -83,7 +83,7 @@ std::unique_ptr<base::Value> value(new base::Value(false)); EXPECT_FALSE(provider()->SetWebsiteSetting(site_pattern, site_pattern, persistent_type(), std::string(), - value.get())); + std::move(value))); std::unique_ptr<RuleIterator> rule_iterator = provider()->GetRuleIterator(persistent_type(), std::string(), false); EXPECT_EQ(nullptr, rule_iterator); @@ -99,9 +99,9 @@ provider()->SetClockForTesting(&test_clock); base::Time t1 = test_clock.Now(); - provider()->SetWebsiteSetting(site_pattern, site_pattern, ephemeral_type(0), - std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider()->SetWebsiteSetting( + site_pattern, site_pattern, ephemeral_type(0), std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); base::Time last_modified = provider()->GetWebsiteSettingLastModified( site_pattern, site_pattern, ephemeral_type(0), std::string()); EXPECT_EQ(t1, last_modified); @@ -114,12 +114,12 @@ ContentSettingsPattern site_pattern2 = ContentSettingsPattern::FromString("https://example2.com"); - provider()->SetWebsiteSetting(site_pattern1, site_pattern1, ephemeral_type(0), - std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); - provider()->SetWebsiteSetting(site_pattern2, site_pattern2, ephemeral_type(0), - std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + provider()->SetWebsiteSetting( + site_pattern1, site_pattern1, ephemeral_type(0), std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); + provider()->SetWebsiteSetting( + site_pattern2, site_pattern2, ephemeral_type(0), std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); provider()->ClearAllContentSettingsRules(ephemeral_type(0)); std::unique_ptr<RuleIterator> rule_iterator = provider()->GetRuleIterator(ephemeral_type(0), std::string(), false); @@ -131,12 +131,12 @@ ContentSettingsPattern site_pattern = ContentSettingsPattern::FromString("https://example.com"); - provider()->SetWebsiteSetting(site_pattern, site_pattern, ephemeral_type(0), - std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); - provider()->SetWebsiteSetting(site_pattern, site_pattern, ephemeral_type(1), - std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + provider()->SetWebsiteSetting( + site_pattern, site_pattern, ephemeral_type(0), std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); + provider()->SetWebsiteSetting( + site_pattern, site_pattern, ephemeral_type(1), std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); provider()->ClearAllContentSettingsRules(ephemeral_type(0)); std::unique_ptr<RuleIterator> rule_iterator = provider()->GetRuleIterator(ephemeral_type(1), std::string(), false); @@ -148,9 +148,9 @@ ContentSettingsPattern site_pattern = ContentSettingsPattern::FromString("https://example.com"); - provider()->SetWebsiteSetting(site_pattern, site_pattern, ephemeral_type(0), - std::string(), - new base::Value(CONTENT_SETTING_BLOCK)); + provider()->SetWebsiteSetting( + site_pattern, site_pattern, ephemeral_type(0), std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); Reset(); std::unique_ptr<RuleIterator> rule_iterator = provider()->GetRuleIterator(ephemeral_type(0), std::string(), false); @@ -162,9 +162,9 @@ ContentSettingsPattern site_pattern = ContentSettingsPattern::FromString("https://example.com"); - provider()->SetWebsiteSetting(site_pattern, site_pattern, ephemeral_type(0), - std::string(), - new base::Value(CONTENT_SETTING_ALLOW)); + provider()->SetWebsiteSetting( + site_pattern, site_pattern, ephemeral_type(0), std::string(), + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); std::unique_ptr<RuleIterator> rule_iterator = provider()->GetRuleIterator(ephemeral_type(0), std::string(), false); EXPECT_NE(nullptr, rule_iterator);
diff --git a/components/content_settings/core/browser/content_settings_policy_provider.cc b/components/content_settings/core/browser/content_settings_policy_provider.cc index b3784368..095ddac 100644 --- a/components/content_settings/core/browser/content_settings_policy_provider.cc +++ b/components/content_settings/core/browser/content_settings_policy_provider.cc
@@ -429,7 +429,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) { + std::unique_ptr<base::Value>&& value) { return false; }
diff --git a/components/content_settings/core/browser/content_settings_policy_provider.h b/components/content_settings/core/browser/content_settings_policy_provider.h index 120d168..85a1a21 100644 --- a/components/content_settings/core/browser/content_settings_policy_provider.h +++ b/components/content_settings/core/browser/content_settings_policy_provider.h
@@ -40,7 +40,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override;
diff --git a/components/content_settings/core/browser/content_settings_pref.cc b/components/content_settings/core/browser/content_settings_pref.cc index 4f46fab..0efa391 100644 --- a/components/content_settings/core/browser/content_settings_pref.cc +++ b/components/content_settings/core/browser/content_settings_pref.cc
@@ -120,8 +120,8 @@ const ContentSettingsPattern& secondary_pattern, const ResourceIdentifier& resource_identifier, base::Time modified_time, - base::Value* in_value) { - DCHECK(!in_value || IsValueAllowedForType(in_value, content_type_)); + std::unique_ptr<base::Value>&& in_value) { + DCHECK(!in_value || IsValueAllowedForType(in_value.get(), content_type_)); DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(prefs_); DCHECK(primary_pattern != ContentSettingsPattern::Wildcard() || @@ -134,7 +134,7 @@ DCHECK(resource_identifier.empty() || allow_resource_identifiers_); // At this point take the ownership of the |in_value|. - std::unique_ptr<base::Value> value(in_value); + std::unique_ptr<base::Value> value(std::move(in_value)); // Update in memory value map. OriginIdentifierValueMap* map_to_modify = &incognito_value_map_;
diff --git a/components/content_settings/core/browser/content_settings_pref.h b/components/content_settings/core/browser/content_settings_pref.h index c38ea45..b3f3e1a2 100644 --- a/components/content_settings/core/browser/content_settings_pref.h +++ b/components/content_settings/core/browser/content_settings_pref.h
@@ -52,7 +52,7 @@ const ContentSettingsPattern& secondary_pattern, const ResourceIdentifier& resource_identifier, base::Time modified_time, - base::Value* value); + std::unique_ptr<base::Value>&& value); // Returns the |last_modified| date of a setting. base::Time GetWebsiteSettingLastModified(
diff --git a/components/content_settings/core/browser/content_settings_pref_provider.cc b/components/content_settings/core/browser/content_settings_pref_provider.cc index 1aa1b488..20310d5 100644 --- a/components/content_settings/core/browser/content_settings_pref_provider.cc +++ b/components/content_settings/core/browser/content_settings_pref_provider.cc
@@ -170,7 +170,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* in_value) { + std::unique_ptr<base::Value>&& in_value) { DCHECK(CalledOnValidThread()); DCHECK(prefs_); @@ -193,7 +193,8 @@ return GetPref(content_type) ->SetWebsiteSetting(primary_pattern, secondary_pattern, - resource_identifier, modified_time, in_value); + resource_identifier, modified_time, + std::move(in_value)); } base::Time PrefProvider::GetWebsiteSettingLastModified(
diff --git a/components/content_settings/core/browser/content_settings_pref_provider.h b/components/content_settings/core/browser/content_settings_pref_provider.h index 2dcdfba..5bc8a3bd 100644 --- a/components/content_settings/core/browser/content_settings_pref_provider.h +++ b/components/content_settings/core/browser/content_settings_pref_provider.h
@@ -48,7 +48,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override; void ShutdownOnUIThread() override; base::Time GetWebsiteSettingLastModified(
diff --git a/components/content_settings/core/browser/content_settings_provider.h b/components/content_settings/core/browser/content_settings_provider.h index 3ee28c7..b2615562 100644 --- a/components/content_settings/core/browser/content_settings_provider.h +++ b/components/content_settings/core/browser/content_settings_provider.h
@@ -50,7 +50,7 @@ const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) = 0; + std::unique_ptr<base::Value>&& value) = 0; // Resets all content settings for the given |content_type| and empty resource // identifier to CONTENT_SETTING_DEFAULT.
diff --git a/components/content_settings/core/browser/content_settings_provider_unittest.cc b/components/content_settings/core/browser/content_settings_provider_unittest.cc index 9e4e277..5a9ee5b 100644 --- a/components/content_settings/core/browser/content_settings_provider_unittest.cc +++ b/components/content_settings/core/browser/content_settings_provider_unittest.cc
@@ -18,9 +18,9 @@ GURL url("http://www.youtube.com"); MockProvider mock_provider(false); - mock_provider.SetWebsiteSetting(pattern, pattern, - CONTENT_SETTINGS_TYPE_PLUGINS, "java_plugin", - new base::Value(CONTENT_SETTING_BLOCK)); + mock_provider.SetWebsiteSetting( + pattern, pattern, CONTENT_SETTINGS_TYPE_PLUGINS, "java_plugin", + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&mock_provider, url, url, @@ -51,7 +51,7 @@ bool owned = mock_provider.SetWebsiteSetting( pattern, pattern, CONTENT_SETTINGS_TYPE_PLUGINS, "java_plugin", - new base::Value(CONTENT_SETTING_ALLOW)); + std::make_unique<base::Value>(CONTENT_SETTING_ALLOW)); EXPECT_TRUE(owned); EXPECT_EQ(CONTENT_SETTING_ALLOW, TestUtils::GetContentSetting(&mock_provider, url, url, @@ -60,12 +60,9 @@ mock_provider.set_read_only(true); std::unique_ptr<base::Value> value(new base::Value(CONTENT_SETTING_BLOCK)); - owned = mock_provider.SetWebsiteSetting( - pattern, - pattern, - CONTENT_SETTINGS_TYPE_PLUGINS, - "java_plugin", - value.get()); + owned = mock_provider.SetWebsiteSetting(pattern, pattern, + CONTENT_SETTINGS_TYPE_PLUGINS, + "java_plugin", std::move(value)); EXPECT_FALSE(owned); EXPECT_EQ(CONTENT_SETTING_ALLOW, TestUtils::GetContentSetting(&mock_provider, url, url, @@ -77,7 +74,7 @@ mock_provider.set_read_only(false); owned = mock_provider.SetWebsiteSetting( pattern, pattern, CONTENT_SETTINGS_TYPE_PLUGINS, "java_plugin", - new base::Value(CONTENT_SETTING_BLOCK)); + std::make_unique<base::Value>(CONTENT_SETTING_BLOCK)); EXPECT_TRUE(owned); EXPECT_EQ(CONTENT_SETTING_BLOCK, TestUtils::GetContentSetting(&mock_provider, url, url,
diff --git a/components/content_settings/core/browser/host_content_settings_map.cc b/components/content_settings/core/browser/host_content_settings_map.cc index bec96ef..a09ce141 100644 --- a/components/content_settings/core/browser/host_content_settings_map.cc +++ b/components/content_settings/core/browser/host_content_settings_map.cc
@@ -493,9 +493,8 @@ for (const auto& provider_pair : content_settings_providers_) { if (provider_pair.second->SetWebsiteSetting( primary_pattern, secondary_pattern, content_type, - resource_identifier, value.get())) { + resource_identifier, std::move(value))) { // If successful then ownership is passed to the provider. - ignore_result(value.release()); return; } }
diff --git a/components/content_settings/core/test/content_settings_mock_provider.cc b/components/content_settings/core/test/content_settings_mock_provider.cc index 66f1da53..62bfa469 100644 --- a/components/content_settings/core/test/content_settings_mock_provider.cc +++ b/components/content_settings/core/test/content_settings_mock_provider.cc
@@ -25,10 +25,10 @@ const ContentSettingsPattern& embedding_url_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* in_value) { + std::unique_ptr<base::Value>&& in_value) { if (read_only_) return false; - std::unique_ptr<base::Value> value(in_value); + std::unique_ptr<base::Value> value(std::move(in_value)); if (value) { value_map_.SetValue(requesting_url_pattern, embedding_url_pattern, content_type, resource_identifier, base::Time(),
diff --git a/components/content_settings/core/test/content_settings_mock_provider.h b/components/content_settings/core/test/content_settings_mock_provider.h index cb5b536..eed32bb6 100644 --- a/components/content_settings/core/test/content_settings_mock_provider.h +++ b/components/content_settings/core/test/content_settings_mock_provider.h
@@ -31,7 +31,7 @@ const ContentSettingsPattern& embedding_url_pattern, ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, - base::Value* value) override; + std::unique_ptr<base::Value>&& value) override; void ClearAllContentSettingsRules(ContentSettingsType content_type) override { }
diff --git a/components/favicon_base/BUILD.gn b/components/favicon_base/BUILD.gn index f1057b17..2e559e2 100644 --- a/components/favicon_base/BUILD.gn +++ b/components/favicon_base/BUILD.gn
@@ -11,6 +11,8 @@ "fallback_icon_style.cc", "fallback_icon_style.h", "favicon_callback.h", + "favicon_request_metrics.cc", + "favicon_request_metrics.h", "favicon_types.cc", "favicon_types.h", "favicon_url_parser.cc",
diff --git a/components/favicon_base/favicon_request_metrics.cc b/components/favicon_base/favicon_request_metrics.cc new file mode 100644 index 0000000..6fe967b --- /dev/null +++ b/components/favicon_base/favicon_request_metrics.cc
@@ -0,0 +1,30 @@ +// Copyright 2019 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 "components/favicon_base/favicon_request_metrics.h" + +#include "base/metrics/histogram_macros.h" + +void favicon::RecordFaviconRequestMetric( + favicon::FaviconRequestOrigin origin, + favicon::FaviconAvailability availability) { + switch (origin) { + case favicon::FaviconRequestOrigin::HISTORY: + UMA_HISTOGRAM_ENUMERATION("Sync.FaviconAvailability.HISTORY", + availability); + break; + case favicon::FaviconRequestOrigin::HISTORY_SYNCED_TABS: + UMA_HISTOGRAM_ENUMERATION("Sync.FaviconAvailability.SYNCED_TABS", + availability); + break; + case favicon::FaviconRequestOrigin::RECENTLY_CLOSED_TABS: + UMA_HISTOGRAM_ENUMERATION("Sync.FaviconAvailability.RECENTLY_CLOSED_TABS", + availability); + break; + case favicon::FaviconRequestOrigin::UNKNOWN: + UMA_HISTOGRAM_ENUMERATION("Sync.FaviconAvailability.UNKNOWN", + availability); + break; + } +}
diff --git a/components/favicon_base/favicon_request_metrics.h b/components/favicon_base/favicon_request_metrics.h new file mode 100644 index 0000000..53b5629 --- /dev/null +++ b/components/favicon_base/favicon_request_metrics.h
@@ -0,0 +1,35 @@ +// Copyright 2019 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 COMPONENTS_FAVICON_BASE_FAVICON_REQUEST_METRICS_H_ +#define COMPONENTS_FAVICON_BASE_FAVICON_REQUEST_METRICS_H_ + +// Header used for collecting metrics associated with favicon retrieval by UI. + +namespace favicon { +// The UI origin of an icon request. +enum class FaviconRequestOrigin { + // Unknown origin. + UNKNOWN, + // chrome://history. + HISTORY, + // chrome://history/syncedTabs. + HISTORY_SYNCED_TABS, + // Recently closed tabs menu. + RECENTLY_CLOSED_TABS, +}; + +enum class FaviconAvailability { + kLocal = 0, + kSync = 1, + kNotAvailable = 2, + kMaxValue = kNotAvailable, +}; + +void RecordFaviconRequestMetric(favicon::FaviconRequestOrigin origin, + favicon::FaviconAvailability availability); + +} // namespace favicon + +#endif // COMPONENTS_FAVICON_BASE_FAVICON_REQUEST_METRICS_H_
diff --git a/components/payments/content/service_worker_payment_instrument.cc b/components/payments/content/service_worker_payment_instrument.cc index ed50e63d..d9315c3 100644 --- a/components/payments/content/service_worker_payment_instrument.cc +++ b/components/payments/content/service_worker_payment_instrument.cc
@@ -405,8 +405,8 @@ return i < stored_payment_app_info_->capabilities.size(); } -const gfx::ImageSkia* ServiceWorkerPaymentInstrument::icon_image_skia() const { - return icon_image_.get(); +gfx::ImageSkia ServiceWorkerPaymentInstrument::icon_image_skia() const { + return icon_image_; } } // namespace payments
diff --git a/components/payments/content/service_worker_payment_instrument.h b/components/payments/content/service_worker_payment_instrument.h index 2d8559c..248b1964 100644 --- a/components/payments/content/service_worker_payment_instrument.h +++ b/components/payments/content/service_worker_payment_instrument.h
@@ -75,7 +75,7 @@ bool supported_types_specified, const std::set<autofill::CreditCard::CardType>& supported_types) const override; - const gfx::ImageSkia* icon_image_skia() const override; + gfx::ImageSkia icon_image_skia() const override; private: friend class ServiceWorkerPaymentInstrumentTest; @@ -93,7 +93,7 @@ GURL frame_origin_; const PaymentRequestSpec* spec_; std::unique_ptr<content::StoredPaymentApp> stored_payment_app_info_; - std::unique_ptr<gfx::ImageSkia> icon_image_; + gfx::ImageSkia icon_image_; // Weak pointer is fine here since the owner of this object is // PaymentRequestState which also owns PaymentResponseHelper.
diff --git a/components/payments/content/service_worker_payment_instrument_unittest.cc b/components/payments/content/service_worker_payment_instrument_unittest.cc index ced0a79..dc4af5e0 100644 --- a/components/payments/content/service_worker_payment_instrument_unittest.cc +++ b/components/payments/content/service_worker_payment_instrument_unittest.cc
@@ -60,6 +60,8 @@ ~ServiceWorkerPaymentInstrumentTest() override {} protected: + const SkBitmap* icon_bitmap() const { return icon_bitmap_; } + void OnSpecUpdated() override {} void SetUp() override { @@ -125,12 +127,16 @@ void TearDown() override {} void CreateServiceWorkerPaymentInstrument(bool with_url_method) { + constexpr int kBitmapDimension = 16; + std::unique_ptr<content::StoredPaymentApp> stored_app = std::make_unique<content::StoredPaymentApp>(); stored_app->registration_id = 123456; stored_app->scope = GURL("https://bobpay.com"); stored_app->name = "bobpay"; - stored_app->icon.reset(new SkBitmap()); + stored_app->icon = std::make_unique<SkBitmap>(); + stored_app->icon->allocN32Pixels(kBitmapDimension, kBitmapDimension); + stored_app->icon->eraseColor(SK_ColorRED); stored_app->enabled_methods.emplace_back("basic-card"); if (with_url_method) stored_app->enabled_methods.emplace_back("https://bobpay.com"); @@ -144,6 +150,7 @@ stored_app->user_hint = "Visa 4012 ... 1881"; stored_app->prefer_related_applications = false; + icon_bitmap_ = stored_app->icon.get(); instrument_ = std::make_unique<ServiceWorkerPaymentInstrument>( &browser_context_, GURL("https://testmerchant.com"), GURL("https://testmerchant.com/bobpay"), spec_.get(), @@ -167,6 +174,7 @@ std::unique_ptr<PaymentRequestSpec> spec_; std::unique_ptr<ServiceWorkerPaymentInstrument> instrument_; + const SkBitmap* icon_bitmap_; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerPaymentInstrumentTest); }; @@ -180,7 +188,10 @@ EXPECT_EQ(base::UTF16ToUTF8(GetInstrument()->GetLabel()), "bobpay"); EXPECT_EQ(base::UTF16ToUTF8(GetInstrument()->GetSublabel()), "bobpay.com"); - EXPECT_NE(GetInstrument()->icon_image_skia(), nullptr); + + const gfx::Size expected_size{icon_bitmap()->width(), + icon_bitmap()->height()}; + EXPECT_EQ(GetInstrument()->icon_image_skia().size(), expected_size); } // Test payment request event data can be correctly constructed for invoking
diff --git a/components/payments/core/payment_instrument.cc b/components/payments/core/payment_instrument.cc index 60237b6e..d53d70e 100644 --- a/components/payments/core/payment_instrument.cc +++ b/components/payments/core/payment_instrument.cc
@@ -11,8 +11,8 @@ PaymentInstrument::~PaymentInstrument() {} -const gfx::ImageSkia* PaymentInstrument::icon_image_skia() const { - return nullptr; +gfx::ImageSkia PaymentInstrument::icon_image_skia() const { + return gfx::ImageSkia(); } } // namespace payments
diff --git a/components/payments/core/payment_instrument.h b/components/payments/core/payment_instrument.h index 1098e345..abe2ec5 100644 --- a/components/payments/core/payment_instrument.h +++ b/components/payments/core/payment_instrument.h
@@ -59,7 +59,7 @@ // Return the sub/label of payment instrument, to be displayed to the user. virtual base::string16 GetLabel() const = 0; virtual base::string16 GetSublabel() const = 0; - virtual const gfx::ImageSkia* icon_image_skia() const; + virtual gfx::ImageSkia icon_image_skia() const; // Returns true if this payment instrument can be used to fulfill a request // specifying |method| as supported method of payment, false otherwise.
diff --git a/components/policy/core/common/cloud/cloud_policy_client.cc b/components/policy/core/common/cloud/cloud_policy_client.cc index 94f2c6c..f44f88d 100644 --- a/components/policy/core/common/cloud/cloud_policy_client.cc +++ b/components/policy/core/common/cloud/cloud_policy_client.cc
@@ -154,6 +154,9 @@ const std::string& machine_id, const std::string& machine_model, const std::string& brand_code, + const std::string& ethernet_mac_address, + const std::string& dock_mac_address, + const std::string& manufacture_date, DeviceManagementService* service, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, SigningService* signing_service, @@ -161,6 +164,9 @@ : machine_id_(machine_id), machine_model_(machine_model), brand_code_(brand_code), + ethernet_mac_address_(ethernet_mac_address), + dock_mac_address_(dock_mac_address), + manufacture_date_(manufacture_date), service_(service), // Can be null for unit tests. signing_service_(signing_service), device_dm_token_callback_(device_dm_token_callback), @@ -220,25 +226,10 @@ em::DeviceRegisterRequest* request = policy_fetch_request_job_->GetRequest()->mutable_register_request(); - if (!client_id.empty()) - request->set_reregister(true); + CreateDeviceRegisterRequest(type, flavor, lifetime, license_type, client_id, + requisition, current_state_key, request); if (requires_reregistration()) request->set_reregistration_dm_token(reregistration_dm_token_); - request->set_type(type); - if (!machine_id_.empty()) - request->set_machine_id(machine_id_); - if (!machine_model_.empty()) - request->set_machine_model(machine_model_); - if (!brand_code_.empty()) - request->set_brand_code(brand_code_); - if (!requisition.empty()) - request->set_requisition(requisition); - if (!current_state_key.empty()) - request->set_server_backed_state_key(current_state_key); - request->set_flavor(flavor); - if (license_type != em::LicenseType::UNDEFINED) - request->mutable_license_type()->set_license_type(license_type); - request->set_lifetime(lifetime); policy_fetch_request_job_->SetRetryCallback( base::Bind(&CloudPolicyClient::OnRetryRegister, @@ -272,24 +263,8 @@ data.set_device_certificate(pem_certificate_chain); em::DeviceRegisterRequest* request = data.mutable_device_register_request(); - if (!client_id.empty()) - request->set_reregister(true); - request->set_type(type); - if (!machine_id_.empty()) - request->set_machine_id(machine_id_); - if (!machine_model_.empty()) - request->set_machine_model(machine_model_); - if (!brand_code_.empty()) - request->set_brand_code(brand_code_); - if (!requisition.empty()) - request->set_requisition(requisition); - if (!current_state_key.empty()) - request->set_server_backed_state_key(current_state_key); - request->set_flavor(flavor); - if (license_type != em::LicenseType::UNDEFINED) - request->mutable_license_type()->set_license_type(license_type); - request->set_lifetime(lifetime); - + CreateDeviceRegisterRequest(type, flavor, lifetime, license_type, client_id, + requisition, current_state_key, request); if (!sub_organization.empty()) { em::DeviceRegisterConfiguration* configuration = data.mutable_device_register_configuration(); @@ -1194,4 +1169,38 @@ observer.OnClientError(this); } +void CloudPolicyClient::CreateDeviceRegisterRequest( + em::DeviceRegisterRequest::Type type, + em::DeviceRegisterRequest::Flavor flavor, + em::DeviceRegisterRequest::Lifetime lifetime, + em::LicenseType::LicenseTypeEnum license_type, + const std::string& client_id, + const std::string& requisition, + const std::string& current_state_key, + em::DeviceRegisterRequest* request) { + if (!client_id.empty()) + request->set_reregister(true); + request->set_type(type); + if (!machine_id_.empty()) + request->set_machine_id(machine_id_); + if (!machine_model_.empty()) + request->set_machine_model(machine_model_); + if (!brand_code_.empty()) + request->set_brand_code(brand_code_); + if (!ethernet_mac_address_.empty()) + request->set_ethernet_mac_address(ethernet_mac_address_); + if (!dock_mac_address_.empty()) + request->set_dock_mac_address(dock_mac_address_); + if (!manufacture_date_.empty()) + request->set_manufacture_date(manufacture_date_); + if (!requisition.empty()) + request->set_requisition(requisition); + if (!current_state_key.empty()) + request->set_server_backed_state_key(current_state_key); + request->set_flavor(flavor); + if (license_type != em::LicenseType::UNDEFINED) + request->mutable_license_type()->set_license_type(license_type); + request->set_lifetime(lifetime); +} + } // namespace policy
diff --git a/components/policy/core/common/cloud/cloud_policy_client.h b/components/policy/core/common/cloud/cloud_policy_client.h index 04dc912..b7e4f0e 100644 --- a/components/policy/core/common/cloud/cloud_policy_client.h +++ b/components/policy/core/common/cloud/cloud_policy_client.h
@@ -98,9 +98,10 @@ virtual void OnClientError(CloudPolicyClient* client) = 0; }; - // If non-empty, |machine_id|, |machine_model| and |brand_code| are passed - // to the server verbatim. As these reveal machine identity, they must only - // be used where this is appropriate (i.e. device policy, but not user + // If non-empty, |machine_id|, |machine_model|, |brand_code|, + // |ethernet_mac_address|, |dock_mac_address| and |manufacture_date| are + // passed to the server verbatim. As these reveal machine identity, they must + // only be used where this is appropriate (i.e. device policy, but not user // policy). |service| and |signing_service| are weak pointers and it's the // caller's responsibility to keep them valid for the lifetime of // CloudPolicyClient. The |signing_service| is used to sign sensitive @@ -111,6 +112,9 @@ const std::string& machine_id, const std::string& machine_model, const std::string& brand_code, + const std::string& ethernet_mac_address, + const std::string& dock_mac_address, + const std::string& manufacture_date, DeviceManagementService* service, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, SigningService* signing_service, @@ -300,6 +304,11 @@ const std::string& machine_id() const { return machine_id_; } const std::string& machine_model() const { return machine_model_; } const std::string& brand_code() const { return brand_code_; } + const std::string& ethernet_mac_address() const { + return ethernet_mac_address_; + } + const std::string& dock_mac_address() const { return dock_mac_address_; } + const std::string& manufacture_date() const { return manufacture_date_; } void set_last_policy_timestamp(const base::Time& timestamp) { last_policy_timestamp_ = timestamp; @@ -499,6 +508,9 @@ const std::string machine_id_; const std::string machine_model_; const std::string brand_code_; + const std::string ethernet_mac_address_; + const std::string dock_mac_address_; + const std::string manufacture_date_; PolicyTypeSet types_to_fetch_; std::vector<std::string> state_keys_to_upload_; @@ -554,6 +566,17 @@ private: void SetClientId(const std::string& client_id); + // Fills in the common fields of a DeviceRegisterRequest for |Register| and + // |RegisterWithCertificate|. + void CreateDeviceRegisterRequest( + enterprise_management::DeviceRegisterRequest::Type registration_type, + enterprise_management::DeviceRegisterRequest::Flavor flavor, + enterprise_management::DeviceRegisterRequest::Lifetime lifetime, + enterprise_management::LicenseType::LicenseTypeEnum license_type, + const std::string& client_id, + const std::string& requisition, + const std::string& current_state_key, + enterprise_management::DeviceRegisterRequest* request); // Used to store a copy of the previously used |dm_token_|. This is used // during re-registration, which gets triggered by a failed policy fetch with
diff --git a/components/policy/core/common/cloud/cloud_policy_client_unittest.cc b/components/policy/core/common/cloud/cloud_policy_client_unittest.cc index 378cb59..2690b4ca 100644 --- a/components/policy/core/common/cloud/cloud_policy_client_unittest.cc +++ b/components/policy/core/common/cloud/cloud_policy_client_unittest.cc
@@ -46,6 +46,9 @@ const char kMachineID[] = "fake-machine-id"; const char kMachineModel[] = "fake-machine-model"; const char kBrandCode[] = "fake-brand-code"; +const char kEthernetMacAddress[] = "fake-ethernet-mac-address"; +const char kDockMacAddress[] = "fake-dock-mac-address"; +const char kManufactureDate[] = "fake-manufacture-date"; const char kOAuthToken[] = "fake-oauth-token"; const char kDMToken[] = "fake-dm-token"; const char kDMToken2[] = "fake-dm-token-2"; @@ -125,6 +128,9 @@ register_request->set_machine_id(kMachineID); register_request->set_machine_model(kMachineModel); register_request->set_brand_code(kBrandCode); + register_request->set_ethernet_mac_address(kEthernetMacAddress); + register_request->set_dock_mac_address(kDockMacAddress); + register_request->set_manufacture_date(kManufactureDate); register_request->set_lifetime( em::DeviceRegisterRequest::LIFETIME_INDEFINITE); register_request->set_flavor( @@ -136,6 +142,9 @@ reregister_request->set_machine_id(kMachineID); reregister_request->set_machine_model(kMachineModel); reregister_request->set_brand_code(kBrandCode); + reregister_request->set_ethernet_mac_address(kEthernetMacAddress); + reregister_request->set_dock_mac_address(kDockMacAddress); + reregister_request->set_manufacture_date(kManufactureDate); reregister_request->set_lifetime( em::DeviceRegisterRequest::LIFETIME_INDEFINITE); reregister_request->set_flavor( @@ -153,6 +162,9 @@ request->set_machine_id(kMachineID); request->set_machine_model(kMachineModel); request->set_brand_code(kBrandCode); + request->set_ethernet_mac_address(kEthernetMacAddress); + request->set_dock_mac_address(kDockMacAddress); + request->set_manufacture_date(kManufactureDate); request->set_lifetime(em::DeviceRegisterRequest::LIFETIME_INDEFINITE); request->set_flavor( em::DeviceRegisterRequest::FLAVOR_ENROLLMENT_ATTESTATION); @@ -306,7 +318,8 @@ base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &url_loader_factory_); client_ = std::make_unique<CloudPolicyClient>( - kMachineID, kMachineModel, kBrandCode, &service_, + kMachineID, kMachineModel, kBrandCode, kEthernetMacAddress, + kDockMacAddress, kManufactureDate, &service_, shared_url_loader_factory_, &fake_signing_service_, base::BindRepeating( &MockDeviceDMTokenCallbackObserver::OnDeviceDMTokenRequested,
diff --git a/components/policy/core/common/cloud/mock_cloud_policy_client.cc b/components/policy/core/common/cloud/mock_cloud_policy_client.cc index cf80454..f166e38 100644 --- a/components/policy/core/common/cloud/mock_cloud_policy_client.cc +++ b/components/policy/core/common/cloud/mock_cloud_policy_client.cc
@@ -21,6 +21,9 @@ : CloudPolicyClient(std::string() /* machine_id */, std::string() /* machine_model */, std::string() /* brand_code */, + std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, nullptr /* service */, std::move(url_loader_factory), nullptr /* signing_service */,
diff --git a/components/policy/core/common/cloud/user_cloud_policy_manager.cc b/components/policy/core/common/cloud/user_cloud_policy_manager.cc index f7e0fb25..fb251368 100644 --- a/components/policy/core/common/cloud/user_cloud_policy_manager.cc +++ b/components/policy/core/common/cloud/user_cloud_policy_manager.cc
@@ -78,7 +78,9 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) { return std::make_unique<CloudPolicyClient>( std::string() /* machine_id */, std::string() /* machine_model */, - std::string() /* brand_code */, device_management_service, + std::string() /* brand_code */, std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, device_management_service, std::move(url_loader_factory), nullptr /* signing_service */, CloudPolicyClient::DeviceDMTokenCallback()); }
diff --git a/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc b/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc index 10463c1b..a550a77 100644 --- a/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc +++ b/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc
@@ -87,6 +87,9 @@ : CloudPolicyClient(std::string() /* machine_id */, std::string() /* machine_model */, std::string() /* brand_code */, + std::string() /* ethernet_mac_address */, + std::string() /* dock_mac_address */, + std::string() /* manufacture_date */, nullptr /* service */, nullptr /* url_loader_factory */, nullptr /* signing_service */,
diff --git a/components/previews/core/previews_features.cc b/components/previews/core/previews_features.cc index 4cd120c..c4927c84 100644 --- a/components/previews/core/previews_features.cc +++ b/components/previews/core/previews_features.cc
@@ -108,5 +108,11 @@ const base::Feature kOptimizationHintsFetching{ "OptimizationHintsFetching", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables the use of a pref to only trigger Offline Previews when there is a +// high chance that there is one to serve. +const base::Feature kOfflinePreviewsFalsePositivePrevention{ + "OfflinePreviewsFalsePositivePrevention", + base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace features } // namespace previews
diff --git a/components/previews/core/previews_features.h b/components/previews/core/previews_features.h index c49dc2c..25478c3 100644 --- a/components/previews/core/previews_features.h +++ b/components/previews/core/previews_features.h
@@ -26,6 +26,7 @@ extern const base::Feature kDataSaverLiteModeRebranding; extern const base::Feature kPreviewsReloadsAreSoftOptOuts; extern const base::Feature kOptimizationHintsFetching; +extern const base::Feature kOfflinePreviewsFalsePositivePrevention; } // namespace features } // namespace previews
diff --git a/components/safe_browsing/features.cc b/components/safe_browsing/features.cc index c1573f1..2d323f5 100644 --- a/components/safe_browsing/features.cc +++ b/components/safe_browsing/features.cc
@@ -77,6 +77,7 @@ bool probabilistically_enabled; } kExperimentalFeatures[]{ {&kAdSamplerTriggerFeature, false}, + {&kCaptureSafetyNetId, true}, {&kCheckByURLLoaderThrottle, true}, {&kCommittedSBInterstitials, true}, {&kPasswordProtectionForSignedInUsers, true},
diff --git a/components/signin/core/browser/BUILD.gn b/components/signin/core/browser/BUILD.gn index c08d475..462981bb 100644 --- a/components/signin/core/browser/BUILD.gn +++ b/components/signin/core/browser/BUILD.gn
@@ -134,8 +134,8 @@ "account_reconcilor_delegate.h", "chrome_connected_header_helper.cc", "chrome_connected_header_helper.h", - "consistency_cookie_manager_android.cc", - "consistency_cookie_manager_android.h", + "consistency_cookie_manager_base.cc", + "consistency_cookie_manager_base.h", "cookie_settings_util.cc", "cookie_settings_util.h", "dice_account_reconcilor_delegate.cc", @@ -210,6 +210,14 @@ ] } + if (is_android) { + sources += [ + "consistency_cookie_manager_android.cc", + "consistency_cookie_manager_android.h", + ] + deps += [ "android:jni_headers" ] + } + if (!enable_dice_support) { sources -= [ "dice_account_reconcilor_delegate.cc", @@ -263,7 +271,6 @@ "account_reconcilor_unittest.cc", "account_tracker_service_unittest.cc", "avatar_icon_util_unittest.cc", - "consistency_cookie_manager_android_unittest.cc", "device_id_helper_unittest.cc", "dice_account_reconcilor_delegate_unittest.cc", "gaia_cookie_manager_service_unittest.cc", @@ -313,6 +320,10 @@ deps += [ "//chromeos/components/account_manager" ] } + if (is_android) { + sources += [ "consistency_cookie_manager_unittest.cc" ] + } + if (!enable_dice_support) { sources -= [ "dice_account_reconcilor_delegate_unittest.cc" ] }
diff --git a/components/signin/core/browser/account_reconcilor.cc b/components/signin/core/browser/account_reconcilor.cc index 50815ae..33b7cc3 100644 --- a/components/signin/core/browser/account_reconcilor.cc +++ b/components/signin/core/browser/account_reconcilor.cc
@@ -22,6 +22,7 @@ #include "build/build_config.h" #include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" +#include "components/signin/core/browser/consistency_cookie_manager_base.h" #include "components/signin/core/browser/signin_buildflags.h" #include "components/signin/core/browser/signin_client.h" #include "components/signin/core/browser/signin_metrics.h" @@ -232,16 +233,12 @@ if (start_reconcile_if_tokens_available && IsIdentityManagerReady()) StartReconcile(); } +} -#if defined(OS_ANDROID) - // The ConsistencyCookieManager is not created earlier, because it requires - // the reconcilor state to be initialized. - if (base::FeatureList::IsEnabled(signin::kMiceFeature)) { - consistency_cookie_manager_ = - std::make_unique<signin::ConsistencyCookieManagerAndroid>(client_, - this); - } -#endif +void AccountReconcilor::SetConsistencyCookieManager( + std::unique_ptr<signin::ConsistencyCookieManagerBase> + consistency_cookie_manager) { + consistency_cookie_manager_ = std::move(consistency_cookie_manager); } #if defined(OS_IOS)
diff --git a/components/signin/core/browser/account_reconcilor.h b/components/signin/core/browser/account_reconcilor.h index 84417ca..adaad558 100644 --- a/components/signin/core/browser/account_reconcilor.h +++ b/components/signin/core/browser/account_reconcilor.h
@@ -34,10 +34,7 @@ namespace signin { class AccountReconcilorDelegate; - -#if defined(OS_ANDROID) -class ConsistencyCookieManagerAndroid; -#endif +class ConsistencyCookieManagerBase; } class SigninClient; @@ -105,6 +102,10 @@ // construction. void Initialize(bool start_reconcile_if_tokens_available); + void SetConsistencyCookieManager( + std::unique_ptr<signin::ConsistencyCookieManagerBase> + consistency_cookie_manager); + #if defined(OS_IOS) // Sets the WKHTTPSystemCookieStore flag value. void SetIsWKHTTPSystemCookieStoreEnabled(bool is_enabled); @@ -393,10 +394,8 @@ bool is_wkhttp_system_cookie_store_enabled_ = false; #endif // defined(OS_IOS) -#if defined(OS_ANDROID) - std::unique_ptr<signin::ConsistencyCookieManagerAndroid> + std::unique_ptr<signin::ConsistencyCookieManagerBase> consistency_cookie_manager_; -#endif base::WeakPtrFactory<AccountReconcilor> weak_factory_;
diff --git a/components/signin/core/browser/account_tracker_service.h b/components/signin/core/browser/account_tracker_service.h index 5bf928b49..cb61e2e4 100644 --- a/components/signin/core/browser/account_tracker_service.h +++ b/components/signin/core/browser/account_tracker_service.h
@@ -46,9 +46,8 @@ const std::string&); } -// AccountTrackerService is a KeyedService that retrieves and caches GAIA -// information about Google Accounts. -class AccountTrackerService : public KeyedService { +// Retrieves and caches GAIA information about Google Accounts. +class AccountTrackerService { public: // Clients of AccountTrackerService can implement this interface and register // with AddObserver() to learn about account information changes. @@ -72,13 +71,12 @@ }; AccountTrackerService(); - ~AccountTrackerService() override; + ~AccountTrackerService(); // Registers the preferences used by AccountTrackerService. static void RegisterPrefs(PrefRegistrySimple* registry); - // KeyedService implementation. - void Shutdown() override; + void Shutdown(); void AddObserver(Observer* observer); void RemoveObserver(Observer* observer);
diff --git a/components/signin/core/browser/android/BUILD.gn b/components/signin/core/browser/android/BUILD.gn index 791fd4ea..497cd55 100644 --- a/components/signin/core/browser/android/BUILD.gn +++ b/components/signin/core/browser/android/BUILD.gn
@@ -8,6 +8,7 @@ sources = [ "java/src/org/chromium/components/signin/AccountTrackerService.java", "java/src/org/chromium/components/signin/ChildAccountInfoFetcher.java", + "java/src/org/chromium/components/signin/ConsistencyCookieManager.java", "java/src/org/chromium/components/signin/OAuth2TokenService.java", ] jni_package = "components/signin" @@ -19,6 +20,7 @@ "$google_play_services_package:google_play_services_base_java", "$google_play_services_package:google_play_services_basement_java", "//base:base_java", + "//base:jni_java", "//net/android:net_java", "//third_party/android_deps:android_support_v4_java", "//third_party/android_deps:com_android_support_support_annotations_java", @@ -36,6 +38,7 @@ "java/src/org/chromium/components/signin/ChildAccountInfoFetcher.java", "java/src/org/chromium/components/signin/ChildAccountStatus.java", "java/src/org/chromium/components/signin/ChromeSigninController.java", + "java/src/org/chromium/components/signin/ConsistencyCookieManager.java", "java/src/org/chromium/components/signin/GmsAvailabilityException.java", "java/src/org/chromium/components/signin/GmsJustUpdatedException.java", "java/src/org/chromium/components/signin/util/PatternMatcher.java", @@ -45,6 +48,8 @@ "java/src/org/chromium/components/signin/ProfileDataSource.java", "java/src/org/chromium/components/signin/SystemAccountManagerDelegate.java", ] + + annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ] } junit_binary("components_signin_junit_tests") {
diff --git a/components/signin/core/browser/android/java/src/org/chromium/components/signin/ConsistencyCookieManager.java b/components/signin/core/browser/android/java/src/org/chromium/components/signin/ConsistencyCookieManager.java new file mode 100644 index 0000000..3fdb3acc --- /dev/null +++ b/components/signin/core/browser/android/java/src/org/chromium/components/signin/ConsistencyCookieManager.java
@@ -0,0 +1,73 @@ +// Copyright 2019 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. + +package org.chromium.components.signin; + +import android.support.annotation.MainThread; + +import org.chromium.base.ThreadUtils; +import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.annotations.NativeMethods; + +/** + * Created by native code to get status of {@link AccountManagerFacade#isUpdatePending()} and + * notifications when it changes. + */ +public class ConsistencyCookieManager implements ObservableValue.Observer { + private final long mNativeConsistencyCookieManager; + private final AccountManagerFacade mAccountManagerFacade; + private boolean mIsUpdatePending; + + private ConsistencyCookieManager(long nativeConsistencyCookieManager) { + ThreadUtils.assertOnUiThread(); + mNativeConsistencyCookieManager = nativeConsistencyCookieManager; + mAccountManagerFacade = AccountManagerFacade.get(); + + mAccountManagerFacade.isUpdatePending().addObserver(this); + // TODO(https://crbug.com/949562): Observe ongoing sign-in activities. + + mIsUpdatePending = calculateIsUpdatePending(); + } + + @Override + public void onValueChanged() { + boolean state = calculateIsUpdatePending(); + + if (mIsUpdatePending == state) return; + mIsUpdatePending = state; + ConsistencyCookieManagerJni.get().onIsUpdatePendingChanged(mNativeConsistencyCookieManager); + } + + private boolean calculateIsUpdatePending() { + // TODO(https://crbug.com/949562): Check for ongoing sign-in activities. + return mAccountManagerFacade.isUpdatePending().get(); + } + + @CalledByNative + @MainThread + private static ConsistencyCookieManager create(long nativeConsistencyCookieManager) { + return new ConsistencyCookieManager(nativeConsistencyCookieManager); + } + + @CalledByNative + @MainThread + private void destroy() { + ThreadUtils.assertOnUiThread(); + mAccountManagerFacade.isUpdatePending().removeObserver(this); + } + + @CalledByNative + @MainThread + private boolean getIsUpdatePending() { + ThreadUtils.assertOnUiThread(); + return mIsUpdatePending; + } + + @JNINamespace("signin") + @NativeMethods + interface Natives { + void onIsUpdatePendingChanged(long nativeConsistencyCookieManagerAndroid); + } +}
diff --git a/components/signin/core/browser/consistency_cookie_manager_android.cc b/components/signin/core/browser/consistency_cookie_manager_android.cc index c0e9925..ba4a56b 100644 --- a/components/signin/core/browser/consistency_cookie_manager_android.cc +++ b/components/signin/core/browser/consistency_cookie_manager_android.cc
@@ -4,82 +4,46 @@ #include "components/signin/core/browser/consistency_cookie_manager_android.h" -#include "base/logging.h" -#include "base/time/time.h" -#include "components/signin/core/browser/signin_client.h" -#include "google_apis/gaia/gaia_urls.h" -#include "net/cookies/canonical_cookie.h" -#include "net/cookies/cookie_options.h" -#include "services/network/public/mojom/cookie_manager.mojom.h" -#include "url/gurl.h" +#include "jni/ConsistencyCookieManager_jni.h" namespace signin { -namespace { - -const char kCookieName[] = "CHROME_ID_CONSISTENCY_STATE"; -const char kStateConsistent[] = "Consistent"; -const char kStateInconsistent[] = "Inconsistent"; -const char kStateUpdating[] = "Updating"; - -} // namespace - ConsistencyCookieManagerAndroid::ConsistencyCookieManagerAndroid( SigninClient* signin_client, AccountReconcilor* reconcilor) - : account_reconcilor_state_(reconcilor->GetState()), - signin_client_(signin_client), - account_reconcilor_observer_(this) { - DCHECK(signin_client_); - DCHECK(reconcilor); - account_reconcilor_observer_.Add(reconcilor); + : ConsistencyCookieManagerBase(signin_client, reconcilor) { + JNIEnv* env = base::android::AttachCurrentThread(); + base::android::ScopedJavaLocalRef<jobject> java_ref = + Java_ConsistencyCookieManager_create(env, + reinterpret_cast<intptr_t>(this)); + java_ref_.Reset(env, java_ref.obj()); + is_update_pending_in_java_ = + Java_ConsistencyCookieManager_getIsUpdatePending(env, java_ref_); + UpdateCookie(); } -ConsistencyCookieManagerAndroid::~ConsistencyCookieManagerAndroid() = default; +ConsistencyCookieManagerAndroid::~ConsistencyCookieManagerAndroid() { + JNIEnv* env = base::android::AttachCurrentThread(); + Java_ConsistencyCookieManager_destroy(env, java_ref_); +} -void ConsistencyCookieManagerAndroid::OnStateChanged( - signin_metrics::AccountReconcilorState state) { - if (state == account_reconcilor_state_) +void ConsistencyCookieManagerAndroid::OnIsUpdatePendingChanged( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& java_obj) { + bool is_update_pending_in_java = + Java_ConsistencyCookieManager_getIsUpdatePending(env, java_ref_); + if (is_update_pending_in_java == is_update_pending_in_java_) return; - account_reconcilor_state_ = state; + is_update_pending_in_java_ = is_update_pending_in_java; UpdateCookie(); } -void ConsistencyCookieManagerAndroid::UpdateCookie() { - // Compute the new cookie value. - std::string cookie_value; - switch (account_reconcilor_state_) { - case signin_metrics::ACCOUNT_RECONCILOR_OK: - cookie_value = kStateConsistent; - break; - case signin_metrics::ACCOUNT_RECONCILOR_RUNNING: - case signin_metrics::ACCOUNT_RECONCILOR_SCHEDULED: - cookie_value = kStateUpdating; - break; - case signin_metrics::ACCOUNT_RECONCILOR_ERROR: - cookie_value = kStateInconsistent; - break; - case signin_metrics::ACCOUNT_RECONCILOR_HISTOGRAM_COUNT: - NOTREACHED(); - break; +std::string ConsistencyCookieManagerAndroid::CalculateCookieValue() { + if (is_update_pending_in_java_) { + return kStateUpdating; } - DCHECK(!cookie_value.empty()); - - // Update the cookie with the new value. - network::mojom::CookieManager* cookie_manager = - signin_client_->GetCookieManager(); - base::Time now = base::Time::Now(); - base::Time expiry = now + base::TimeDelta::FromDays(2 * 365); // Two years. - net::CanonicalCookie cookie( - kCookieName, cookie_value, - "." + GaiaUrls::GetInstance()->gaia_url().host(), /*path=*/"/", - /*creation=*/now, /*expiration=*/expiry, /*last_access=*/now, - /*secure=*/true, /*httponly=*/false, net::CookieSameSite::NO_RESTRICTION, - net::COOKIE_PRIORITY_DEFAULT); - cookie_manager->SetCanonicalCookie( - cookie, "https", net::CookieOptions(), - network::mojom::CookieManager::SetCanonicalCookieCallback()); + return ConsistencyCookieManagerBase::CalculateCookieValue(); } } // namespace signin
diff --git a/components/signin/core/browser/consistency_cookie_manager_android.h b/components/signin/core/browser/consistency_cookie_manager_android.h index 265d5595..a193d21 100644 --- a/components/signin/core/browser/consistency_cookie_manager_android.h +++ b/components/signin/core/browser/consistency_cookie_manager_android.h
@@ -5,42 +5,33 @@ #ifndef COMPONENTS_SIGNIN_CORE_BROWSER_CONSISTENCY_COOKIE_MANAGER_ANDROID_H_ #define COMPONENTS_SIGNIN_CORE_BROWSER_CONSISTENCY_COOKIE_MANAGER_ANDROID_H_ +#include "base/android/scoped_java_ref.h" #include "base/macros.h" -#include "base/scoped_observer.h" -#include "components/signin/core/browser/account_reconcilor.h" -#include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/core/browser/consistency_cookie_manager_base.h" class SigninClient; namespace signin { -// The ConsistencyCookieManagerAndroid checks if: -// - the account reconcilor is running -// - the accounts on the device are updating -// - the user has started to interact with device account settings (from Chrome) -// If one of these conditions is true, then this object sets a cookie on Gaia -// with a "Updating" value. -// -// Otherwise the value of the cookie is "Consistent" if the accounts are -// consistent (web accounts match device accounts) or "Inconsistent". -class ConsistencyCookieManagerAndroid : public AccountReconcilor::Observer { +// ConsistencyCookieManagerAndroid subclasses ConsistencyCookieManagerBase to +// watch whether there are pending updates to the account list on the Java side. +class ConsistencyCookieManagerAndroid : public ConsistencyCookieManagerBase { public: ConsistencyCookieManagerAndroid(SigninClient* signin_client, AccountReconcilor* reconcilor); ~ConsistencyCookieManagerAndroid() override; + void OnIsUpdatePendingChanged( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& java_self); + + protected: + std::string CalculateCookieValue() override; + private: - // AccountReconcilor::Observer: - void OnStateChanged(signin_metrics::AccountReconcilorState state) override; - - void UpdateCookie(); - - signin_metrics::AccountReconcilorState account_reconcilor_state_ = - signin_metrics::ACCOUNT_RECONCILOR_OK; - SigninClient* signin_client_ = nullptr; - ScopedObserver<AccountReconcilor, AccountReconcilor::Observer> - account_reconcilor_observer_; + bool is_update_pending_in_java_ = false; + base::android::ScopedJavaGlobalRef<jobject> java_ref_; DISALLOW_COPY_AND_ASSIGN(ConsistencyCookieManagerAndroid); };
diff --git a/components/signin/core/browser/consistency_cookie_manager_base.cc b/components/signin/core/browser/consistency_cookie_manager_base.cc new file mode 100644 index 0000000..502127b --- /dev/null +++ b/components/signin/core/browser/consistency_cookie_manager_base.cc
@@ -0,0 +1,80 @@ +// Copyright 2019 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 "components/signin/core/browser/consistency_cookie_manager_base.h" + +#include "base/logging.h" +#include "base/time/time.h" +#include "components/signin/core/browser/signin_client.h" +#include "google_apis/gaia/gaia_urls.h" +#include "net/cookies/canonical_cookie.h" +#include "net/cookies/cookie_options.h" +#include "services/network/public/mojom/cookie_manager.mojom.h" +#include "url/gurl.h" + +namespace signin { + +const char kCookieName[] = "CHROME_ID_CONSISTENCY_STATE"; +const char ConsistencyCookieManagerBase::kStateConsistent[] = "Consistent"; +const char ConsistencyCookieManagerBase::kStateInconsistent[] = "Inconsistent"; +const char ConsistencyCookieManagerBase::kStateUpdating[] = "Updating"; + +ConsistencyCookieManagerBase::ConsistencyCookieManagerBase( + SigninClient* signin_client, + AccountReconcilor* reconcilor) + : account_reconcilor_state_(reconcilor->GetState()), + signin_client_(signin_client), + account_reconcilor_observer_(this) { + DCHECK(signin_client_); + DCHECK(reconcilor); + + account_reconcilor_observer_.Add(reconcilor); +} + +ConsistencyCookieManagerBase::~ConsistencyCookieManagerBase() = default; + +void ConsistencyCookieManagerBase::OnStateChanged( + signin_metrics::AccountReconcilorState state) { + if (state == account_reconcilor_state_) + return; + account_reconcilor_state_ = state; + UpdateCookie(); +} + +std::string ConsistencyCookieManagerBase::CalculateCookieValue() { + switch (account_reconcilor_state_) { + case signin_metrics::ACCOUNT_RECONCILOR_OK: + return kStateConsistent; + case signin_metrics::ACCOUNT_RECONCILOR_RUNNING: + case signin_metrics::ACCOUNT_RECONCILOR_SCHEDULED: + return kStateUpdating; + case signin_metrics::ACCOUNT_RECONCILOR_ERROR: + return kStateInconsistent; + case signin_metrics::ACCOUNT_RECONCILOR_HISTOGRAM_COUNT: + NOTREACHED(); + return {}; + } +} + +void ConsistencyCookieManagerBase::UpdateCookie() { + std::string cookie_value = CalculateCookieValue(); + DCHECK(!cookie_value.empty()); + + // Update the cookie with the new value. + network::mojom::CookieManager* cookie_manager = + signin_client_->GetCookieManager(); + base::Time now = base::Time::Now(); + base::Time expiry = now + base::TimeDelta::FromDays(2 * 365); // Two years. + net::CanonicalCookie cookie( + kCookieName, cookie_value, + "." + GaiaUrls::GetInstance()->gaia_url().host(), /*path=*/"/", + /*creation=*/now, /*expiration=*/expiry, /*last_access=*/now, + /*secure=*/true, /*httponly=*/false, net::CookieSameSite::NO_RESTRICTION, + net::COOKIE_PRIORITY_DEFAULT); + cookie_manager->SetCanonicalCookie( + cookie, "https", net::CookieOptions(), + network::mojom::CookieManager::SetCanonicalCookieCallback()); +} + +} // namespace signin
diff --git a/components/signin/core/browser/consistency_cookie_manager_base.h b/components/signin/core/browser/consistency_cookie_manager_base.h new file mode 100644 index 0000000..63408695 --- /dev/null +++ b/components/signin/core/browser/consistency_cookie_manager_base.h
@@ -0,0 +1,61 @@ +// Copyright 2019 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 COMPONENTS_SIGNIN_CORE_BROWSER_CONSISTENCY_COOKIE_MANAGER_BASE_H_ +#define COMPONENTS_SIGNIN_CORE_BROWSER_CONSISTENCY_COOKIE_MANAGER_BASE_H_ + +#include "base/macros.h" +#include "base/scoped_observer.h" +#include "components/signin/core/browser/account_reconcilor.h" +#include "components/signin/core/browser/signin_metrics.h" + +class SigninClient; + +namespace signin { + +// The ConsistencyCookieManagerBase checks if: +// - the account reconcilor is running +// - the accounts on the device are updating +// - the user has started to interact with device account settings (from Chrome) +// If one of these conditions is true, then this object sets a cookie on Gaia +// with a "Updating" value. +// +// Otherwise the value of the cookie is "Consistent" if the accounts are +// consistent (web accounts match device accounts) or "Inconsistent". +// +// Subclasses have to call UpdateCookie() at the end of the constructor. +class ConsistencyCookieManagerBase : public AccountReconcilor::Observer { + public: + ~ConsistencyCookieManagerBase() override; + + protected: + static const char kStateConsistent[]; + static const char kStateInconsistent[]; + static const char kStateUpdating[]; + + ConsistencyCookieManagerBase(SigninClient* signin_client, + AccountReconcilor* reconcilor); + + // Calculates the cookie value solely based on the reconcilor state. + virtual std::string CalculateCookieValue(); + + // Gets the new value using CalculateCookieValue and sets the cookie. + void UpdateCookie(); + + private: + // AccountReconcilor::Observer: + void OnStateChanged(signin_metrics::AccountReconcilorState state) override; + + signin_metrics::AccountReconcilorState account_reconcilor_state_ = + signin_metrics::ACCOUNT_RECONCILOR_OK; + SigninClient* signin_client_ = nullptr; + ScopedObserver<AccountReconcilor, AccountReconcilor::Observer> + account_reconcilor_observer_; + + DISALLOW_COPY_AND_ASSIGN(ConsistencyCookieManagerBase); +}; + +} // namespace signin + +#endif // COMPONENTS_SIGNIN_CORE_BROWSER_CONSISTENCY_COOKIE_MANAGER_BASE_H_
diff --git a/components/signin/core/browser/consistency_cookie_manager_android_unittest.cc b/components/signin/core/browser/consistency_cookie_manager_unittest.cc similarity index 82% rename from components/signin/core/browser/consistency_cookie_manager_android_unittest.cc rename to components/signin/core/browser/consistency_cookie_manager_unittest.cc index e955524..168581b1 100644 --- a/components/signin/core/browser/consistency_cookie_manager_android_unittest.cc +++ b/components/signin/core/browser/consistency_cookie_manager_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/signin/core/browser/consistency_cookie_manager_android.h" +#include "components/signin/core/browser/consistency_cookie_manager_base.h" #include <memory> #include <string> @@ -49,9 +49,19 @@ network::mojom::CookieManager::SetCanonicalCookieCallback callback)); }; -class ConsistencyCookieManagerAndroidTest : public ::testing::Test { +class FakeConsistencyCookieManager + : public signin::ConsistencyCookieManagerBase { public: - ConsistencyCookieManagerAndroidTest() + FakeConsistencyCookieManager(SigninClient* signin_client, + AccountReconcilor* reconcilor) + : ConsistencyCookieManagerBase(signin_client, reconcilor) { + UpdateCookie(); + } +}; + +class ConsistencyCookieManagerTest : public ::testing::Test { + public: + ConsistencyCookieManagerTest() : signin_client_(&pref_service_), identity_test_env_(/*test_url_loader_factory=*/nullptr, &pref_service_, @@ -65,10 +75,12 @@ reconcilor_ = std::make_unique<AccountReconcilor>( identity_test_env_.identity_manager(), &signin_client_, std::make_unique<AccountReconcilorDelegate>()); + reconcilor_->Initialize(/*start_reconcile_if_tokens_available=*/false); } - ~ConsistencyCookieManagerAndroidTest() override { reconcilor_->Shutdown(); } + ~ConsistencyCookieManagerTest() override { reconcilor_->Shutdown(); } + SigninClient* signin_client() { return &signin_client_; } AccountReconcilor* reconcilor() { return reconcilor_.get(); } MockCookieManager* mock_cookie_manager() { @@ -90,10 +102,12 @@ }; // Tests that the cookie is updated when the account reconcilor state changes. -TEST_F(ConsistencyCookieManagerAndroidTest, AccountReconcilorState) { +TEST_F(ConsistencyCookieManagerTest, AccountReconcilorState) { // AccountReconcilor::Initialize() creates the ConsistencyCookieManager. mock_cookie_manager()->ExpectSetCookieCall("Consistent"); - reconcilor()->Initialize(/*start_reconcile_if_tokens_available=*/false); + reconcilor()->SetConsistencyCookieManager( + std::make_unique<FakeConsistencyCookieManager>(signin_client(), + reconcilor())); testing::Mock::VerifyAndClearExpectations(mock_cookie_manager()); ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor()->GetState());
diff --git a/components/signin/core/browser/identity_manager_wrapper.cc b/components/signin/core/browser/identity_manager_wrapper.cc index 9281edb..fdc17e1 100644 --- a/components/signin/core/browser/identity_manager_wrapper.cc +++ b/components/signin/core/browser/identity_manager_wrapper.cc
@@ -11,7 +11,7 @@ #include "services/identity/public/cpp/primary_account_mutator.h" IdentityManagerWrapper::IdentityManagerWrapper( - AccountTrackerService* account_tracker_service, + std::unique_ptr<AccountTrackerService> account_tracker_service, std::unique_ptr<ProfileOAuth2TokenService> token_service, std::unique_ptr<GaiaCookieManagerService> gaia_cookie_manager_service, std::unique_ptr<SigninManagerBase> signin_manager, @@ -20,11 +20,11 @@ std::unique_ptr<identity::AccountsMutator> accounts_mutator, std::unique_ptr<identity::AccountsCookieMutator> accounts_cookie_mutator, std::unique_ptr<identity::DiagnosticsProvider> diagnostics_provider) - : identity::IdentityManager(std::move(token_service), + : identity::IdentityManager(std::move(account_tracker_service), + std::move(token_service), std::move(gaia_cookie_manager_service), std::move(signin_manager), std::move(account_fetcher_service), - account_tracker_service, std::move(primary_account_mutator), std::move(accounts_mutator), std::move(accounts_cookie_mutator),
diff --git a/components/signin/core/browser/identity_manager_wrapper.h b/components/signin/core/browser/identity_manager_wrapper.h index 916d196..c7d9958c 100644 --- a/components/signin/core/browser/identity_manager_wrapper.h +++ b/components/signin/core/browser/identity_manager_wrapper.h
@@ -28,7 +28,7 @@ public identity::IdentityManager { public: IdentityManagerWrapper( - AccountTrackerService* account_tracker_service, + std::unique_ptr<AccountTrackerService> account_tracker_service, std::unique_ptr<ProfileOAuth2TokenService> token_service, std::unique_ptr<GaiaCookieManagerService> gaia_cookie_manager_service, std::unique_ptr<SigninManagerBase> signin_manager,
diff --git a/components/supervised_user_error_page/gin_wrapper.cc b/components/supervised_user_error_page/gin_wrapper.cc index fe4d773..bb17510 100644 --- a/components/supervised_user_error_page/gin_wrapper.cc +++ b/components/supervised_user_error_page/gin_wrapper.cc
@@ -47,7 +47,10 @@ if (controller.IsEmpty()) return; v8::Local<v8::Object> global = context->Global(); - global->Set(gin::StringToV8(isolate, "webRestrictions"), controller.ToV8()); + global + ->Set(context, gin::StringToV8(isolate, "webRestrictions"), + controller.ToV8()) + .Check(); } void GinWrapper::Loader::OnDestruct() {
diff --git a/components/sync/BUILD.gn b/components/sync/BUILD.gn index 0606b7e..4f38698 100644 --- a/components/sync/BUILD.gn +++ b/components/sync/BUILD.gn
@@ -8,120 +8,6 @@ import("//components/sync/protocol/protocol_sources.gni") import("//testing/test.gni") -declare_args() { - # Controls the product part of the user agent calculated in sync_util.cc. - sync_user_agent_product = "Chrome" -} - -jumbo_static_library("base") { - sources = [ - "base/bind_to_task_runner.h", - "base/cancelation_observer.cc", - "base/cancelation_observer.h", - "base/cancelation_signal.cc", - "base/cancelation_signal.h", - "base/cryptographer.cc", - "base/cryptographer.h", - "base/data_type_histogram.cc", - "base/data_type_histogram.h", - "base/encryptor.h", - "base/enum_set.h", - "base/extensions_activity.cc", - "base/extensions_activity.h", - "base/get_session_name.cc", - "base/get_session_name.h", - "base/get_session_name_ios.h", - "base/get_session_name_ios.mm", - "base/get_session_name_linux.cc", - "base/get_session_name_linux.h", - "base/get_session_name_mac.h", - "base/get_session_name_mac.mm", - "base/get_session_name_win.cc", - "base/get_session_name_win.h", - "base/hash_util.cc", - "base/hash_util.h", - "base/immutable.h", - "base/invalidation_adapter.cc", - "base/invalidation_adapter.h", - "base/invalidation_helper.cc", - "base/invalidation_helper.h", - "base/invalidation_interface.cc", - "base/invalidation_interface.h", - "base/logging.cc", - "base/logging.h", - "base/model_type.cc", - "base/model_type.h", - "base/nigori.cc", - "base/nigori.h", - "base/node_ordinal.cc", - "base/node_ordinal.h", - "base/ordinal.h", - "base/passphrase_enums.cc", - "base/passphrase_enums.h", - "base/pref_names.cc", - "base/pref_names.h", - "base/progress_marker_map.cc", - "base/progress_marker_map.h", - "base/proto_value_ptr.h", - "base/report_unrecoverable_error.cc", - "base/report_unrecoverable_error.h", - "base/stop_source.h", - "base/storage_option.h", - "base/sync_base_switches.cc", - "base/sync_base_switches.h", - "base/sync_prefs.cc", - "base/sync_prefs.h", - "base/sync_stop_metadata_fate.cc", - "base/sync_stop_metadata_fate.h", - "base/syncer_error.cc", - "base/syncer_error.h", - "base/system_encryptor.cc", - "base/system_encryptor.h", - "base/time.cc", - "base/time.h", - "base/unique_position.cc", - "base/unique_position.h", - "base/unrecoverable_error_handler.h", - "base/unrecoverable_error_info.cc", - "base/unrecoverable_error_info.h", - "base/user_selectable_type.cc", - "base/user_selectable_type.h", - "base/weak_handle.cc", - "base/weak_handle.h", - ] - - configs += [ "//build/config:precompiled_headers" ] - - public_deps = [ - "//base", - "//components/invalidation/public", - "//components/sync/protocol", - ] - deps = [ - "//base:i18n", - "//components/os_crypt", - "//components/pref_registry", - "//components/prefs", - "//components/reading_list/features:reading_list_buildflags", - "//components/version_info", - "//crypto", - "//net", - "//third_party/zlib", - ] - - if (is_mac) { - libs = [ - "CoreFoundation.framework", - "SystemConfiguration.framework", # Required by get_session_name_mac.mm. - ] - } - - if (is_chromeos) { - # Required by get_session_name.cc on Chrome OS. - deps += [ "//chromeos/constants" ] - } -} - # TODO(crbug.com/947443): This target should be split up into "engine", "model", # "syncable" etc, but currently they all depend on each other. jumbo_static_library("rest_of_sync") { @@ -496,9 +382,9 @@ configs += [ "//build/config:precompiled_headers" ] public_deps = [ - ":base", - ":js", "//base", + "//components/sync/base", + "//components/sync/js", "//components/sync/protocol", "//components/sync/protocol:util", "//net", @@ -524,213 +410,10 @@ configs += [ "//build/config/compiler:wexit_time_destructors" ] } -jumbo_static_library("driver") { - sources = [ - "driver/about_sync_util.cc", - "driver/about_sync_util.h", - "driver/async_directory_type_controller.cc", - "driver/async_directory_type_controller.h", - "driver/backend_migrator.cc", - "driver/backend_migrator.h", - "driver/configure_context.h", - "driver/data_type_controller.cc", - "driver/data_type_controller.h", - "driver/data_type_encryption_handler.cc", - "driver/data_type_encryption_handler.h", - "driver/data_type_manager.cc", - "driver/data_type_manager.h", - "driver/data_type_manager_impl.cc", - "driver/data_type_manager_impl.h", - "driver/data_type_manager_observer.h", - "driver/data_type_status_table.cc", - "driver/data_type_status_table.h", - "driver/directory_data_type_controller.cc", - "driver/directory_data_type_controller.h", - "driver/frontend_data_type_controller.cc", - "driver/frontend_data_type_controller.h", - "driver/generic_change_processor.cc", - "driver/generic_change_processor.h", - "driver/generic_change_processor_factory.cc", - "driver/generic_change_processor_factory.h", - "driver/glue/sync_engine_backend.cc", - "driver/glue/sync_engine_backend.h", - "driver/glue/sync_engine_impl.cc", - "driver/glue/sync_engine_impl.h", - "driver/model_association_manager.cc", - "driver/model_association_manager.h", - "driver/model_associator.h", - "driver/model_type_controller.cc", - "driver/model_type_controller.h", - "driver/non_ui_syncable_service_based_model_type_controller.cc", - "driver/non_ui_syncable_service_based_model_type_controller.h", - "driver/profile_sync_service.cc", - "driver/profile_sync_service.h", - "driver/shared_change_processor.cc", - "driver/shared_change_processor.h", - "driver/shared_change_processor_ref.cc", - "driver/shared_change_processor_ref.h", - "driver/startup_controller.cc", - "driver/startup_controller.h", - "driver/sync_api_component_factory.cc", - "driver/sync_api_component_factory.h", - "driver/sync_auth_manager.cc", - "driver/sync_auth_manager.h", - "driver/sync_auth_util.cc", - "driver/sync_auth_util.h", - "driver/sync_client.cc", - "driver/sync_client.h", - "driver/sync_driver_switches.cc", - "driver/sync_driver_switches.h", - "driver/sync_service.cc", - "driver/sync_service.h", - "driver/sync_service_crypto.cc", - "driver/sync_service_crypto.h", - "driver/sync_service_observer.cc", - "driver/sync_service_observer.h", - "driver/sync_service_utils.cc", - "driver/sync_service_utils.h", - "driver/sync_session_durations_metrics_recorder.cc", - "driver/sync_session_durations_metrics_recorder.h", - "driver/sync_stopped_reporter.cc", - "driver/sync_stopped_reporter.h", - "driver/sync_token_status.cc", - "driver/sync_token_status.h", - "driver/sync_type_preference_provider.h", - "driver/sync_user_settings.h", - "driver/sync_user_settings_impl.cc", - "driver/sync_user_settings_impl.h", - "driver/sync_util.cc", - "driver/sync_util.h", - "driver/syncable_service_based_model_type_controller.cc", - "driver/syncable_service_based_model_type_controller.h", - ] - - configs += [ "//build/config:precompiled_headers" ] - - public_deps = [ - ":base", - ":js", - ":rest_of_sync", - "//base", - "//components/invalidation/public", - "//components/sync/protocol", - "//components/sync/protocol:util", - "//net", - "//url", - ] - deps = [ - "//base:i18n", - "//components/data_use_measurement/core", - "//components/invalidation/impl:feature_list", - "//components/keyed_service/core", - "//components/prefs", - "//components/signin/core/browser", - "//components/version_info", - "//components/version_info:generate_version_info", - "//services/identity/public/cpp", - "//services/network/public/cpp", - "//ui/base", - ] - - if (!is_ios) { - sources += [ - "driver/sync_policy_handler.cc", - "driver/sync_policy_handler.h", - ] - deps += [ - "//components/policy:generated", - "//components/policy/core/browser", - ] - } - - defines = [ "SYNC_USER_AGENT_PRODUCT=$sync_user_agent_product" ] - - configs += [ "//build/config/compiler:wexit_time_destructors" ] -} - group("sync") { public_deps = [ - ":driver", ":rest_of_sync", - ] -} - -jumbo_static_library("device_info") { - sources = [ - "device_info/device_count_metrics_provider.cc", - "device_info/device_count_metrics_provider.h", - "device_info/device_info.cc", - "device_info/device_info.h", - "device_info/device_info_sync_bridge.cc", - "device_info/device_info_sync_bridge.h", - "device_info/device_info_sync_service.cc", - "device_info/device_info_sync_service.h", - "device_info/device_info_sync_service_impl.cc", - "device_info/device_info_sync_service_impl.h", - "device_info/device_info_tracker.h", - "device_info/device_info_util.cc", - "device_info/device_info_util.h", - "device_info/local_device_info_provider.h", - "device_info/local_device_info_provider_impl.cc", - "device_info/local_device_info_provider_impl.h", - "device_info/local_device_info_util.cc", - "device_info/local_device_info_util.h", - ] - - configs += [ "//build/config:precompiled_headers" ] - - public_deps = [ - ":sync", - "//base", - "//components/sync/protocol", - ] - deps = [ - "//components/keyed_service/core", - "//components/metrics", - "//components/version_info", - "//ui/base", - ] - - configs += [ "//build/config/compiler:wexit_time_destructors" ] -} - -jumbo_static_library("js") { - sources = [ - "js/js_backend.h", - "js/js_controller.h", - "js/js_event_details.cc", - "js/js_event_details.h", - "js/js_event_handler.h", - "js/sync_js_controller.cc", - "js/sync_js_controller.h", - ] - - public_deps = [ - ":base", - ] -} - -jumbo_static_library("user_events") { - sources = [ - "user_events/no_op_user_event_service.cc", - "user_events/no_op_user_event_service.h", - "user_events/user_event_model_type_controller.cc", - "user_events/user_event_model_type_controller.h", - "user_events/user_event_service.h", - "user_events/user_event_service_impl.cc", - "user_events/user_event_service_impl.h", - "user_events/user_event_sync_bridge.cc", - "user_events/user_event_sync_bridge.h", - ] - - public_deps = [ - ":sync", - "//base", - "//components/keyed_service/core", - "//components/sync/protocol", - ] - deps = [ - "//components/signin/core/browser:shared", + "//components/sync/driver", ] } @@ -748,7 +431,7 @@ deps = [ ":sync", ":test_support_model", - ":user_events", + "//components/sync/user_events", ] } @@ -763,8 +446,6 @@ "base/model_type_test_util.h", "base/test_unrecoverable_error_handler.cc", "base/test_unrecoverable_error_handler.h", - "js/js_test_util.cc", - "js/js_test_util.h", "test/callback_counter.h", "test/mock_invalidation.cc", "test/mock_invalidation.h", @@ -777,12 +458,32 @@ public_deps = [ "//base", + "//components/sync/base", "//testing/gmock", "//testing/gtest", ] deps = [ - ":sync", + # For test_matchers.h, which should probably be split up. + ":rest_of_sync", + ] + + configs += [ "//build/config/compiler:wexit_time_destructors" ] +} + +static_library("test_support_js") { + testonly = true + sources = [ + "js/js_test_util.cc", + "js/js_test_util.h", + ] + + public_deps = [ + "//base", + "//components/sync/base", + "//components/sync/js", + "//testing/gmock", + "//testing/gtest", ] configs += [ "//build/config/compiler:wexit_time_destructors" ] @@ -795,8 +496,12 @@ "engine/fake_model_type_connector.h", "engine/fake_model_type_processor.cc", "engine/fake_model_type_processor.h", + "engine/fake_sync_engine.cc", + "engine/fake_sync_engine.h", "engine/fake_sync_manager.cc", "engine/fake_sync_manager.h", + "engine/mock_sync_engine.cc", + "engine/mock_sync_engine.h", "engine/sync_engine_host_stub.cc", "engine/sync_engine_host_stub.h", "engine/sync_manager_factory_for_profile_sync_test.cc", @@ -861,6 +566,8 @@ static_library("test_support_model") { testonly = true sources = [ + "model/change_processor_mock.cc", + "model/change_processor_mock.h", "model/data_type_error_handler_mock.cc", "model/data_type_error_handler_mock.h", "model/fake_model_type_change_processor.cc", @@ -933,12 +640,6 @@ "driver/test_sync_service.h", "driver/test_sync_user_settings.cc", "driver/test_sync_user_settings.h", - "engine/fake_sync_engine.cc", - "engine/fake_sync_engine.h", - "engine/mock_sync_engine.cc", - "engine/mock_sync_engine.h", - "model/change_processor_mock.cc", - "model/change_processor_mock.h", ] public_deps = [ @@ -946,13 +647,13 @@ ] deps = [ - ":driver", ":sync", ":test_support_engine", ":test_support_model", "//components/invalidation/impl:test_support", "//components/pref_registry", "//components/signin/core/browser:shared", + "//components/sync/driver", "//components/sync_preferences:test_support", "//components/version_info", "//components/version_info:generate_version_info", @@ -1084,21 +785,22 @@ ] deps = [ - ":device_info", - ":driver", ":sync", ":test_support_base", ":test_support_driver", ":test_support_engine", + ":test_support_js", ":test_support_model", ":test_support_user_events", - ":user_events", "//base", "//base/test:test_support", "//components/invalidation/impl", "//components/os_crypt:test_support", "//components/prefs:test_support", "//components/signin/core/browser:internals_test_support", + "//components/sync/device_info", + "//components/sync/driver", + "//components/sync/user_events", "//components/sync_preferences", "//components/sync_preferences:test_support", "//components/version_info",
diff --git a/components/sync/base/BUILD.gn b/components/sync/base/BUILD.gn new file mode 100644 index 0000000..05f5547 --- /dev/null +++ b/components/sync/base/BUILD.gn
@@ -0,0 +1,116 @@ +# Copyright 2019 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("//build/buildflag_header.gni") +import("//build/config/features.gni") +import("//build/config/jumbo.gni") + +jumbo_static_library("base") { + sources = [ + "bind_to_task_runner.h", + "cancelation_observer.cc", + "cancelation_observer.h", + "cancelation_signal.cc", + "cancelation_signal.h", + "cryptographer.cc", + "cryptographer.h", + "data_type_histogram.cc", + "data_type_histogram.h", + "encryptor.h", + "enum_set.h", + "extensions_activity.cc", + "extensions_activity.h", + "get_session_name.cc", + "get_session_name.h", + "get_session_name_ios.h", + "get_session_name_ios.mm", + "get_session_name_linux.cc", + "get_session_name_linux.h", + "get_session_name_mac.h", + "get_session_name_mac.mm", + "get_session_name_win.cc", + "get_session_name_win.h", + "hash_util.cc", + "hash_util.h", + "immutable.h", + "invalidation_adapter.cc", + "invalidation_adapter.h", + "invalidation_helper.cc", + "invalidation_helper.h", + "invalidation_interface.cc", + "invalidation_interface.h", + "logging.cc", + "logging.h", + "model_type.cc", + "model_type.h", + "nigori.cc", + "nigori.h", + "node_ordinal.cc", + "node_ordinal.h", + "ordinal.h", + "passphrase_enums.cc", + "passphrase_enums.h", + "pref_names.cc", + "pref_names.h", + "progress_marker_map.cc", + "progress_marker_map.h", + "proto_value_ptr.h", + "report_unrecoverable_error.cc", + "report_unrecoverable_error.h", + "stop_source.h", + "storage_option.h", + "sync_base_switches.cc", + "sync_base_switches.h", + "sync_prefs.cc", + "sync_prefs.h", + "sync_stop_metadata_fate.cc", + "sync_stop_metadata_fate.h", + "syncer_error.cc", + "syncer_error.h", + "system_encryptor.cc", + "system_encryptor.h", + "time.cc", + "time.h", + "unique_position.cc", + "unique_position.h", + "unrecoverable_error_handler.h", + "unrecoverable_error_info.cc", + "unrecoverable_error_info.h", + "user_selectable_type.cc", + "user_selectable_type.h", + "weak_handle.cc", + "weak_handle.h", + ] + + configs += [ "//build/config:precompiled_headers" ] + + public_deps = [ + "//base", + "//components/invalidation/public", + "//components/sync/protocol", + ] + deps = [ + "//base:i18n", + "//components/os_crypt", + "//components/pref_registry", + "//components/prefs", + "//components/reading_list/features:reading_list_buildflags", + "//components/version_info", + "//crypto", + "//net", + "//third_party/zlib", + ] + + if (is_mac) { + libs = [ + "CoreFoundation.framework", + "SystemConfiguration.framework", # Required by get_session_name_mac.mm. + ] + } + + if (is_chromeos) { + # Required by get_session_name.cc on Chrome OS. + deps += [ "//chromeos/constants" ] + } +}
diff --git a/components/sync/device_info/BUILD.gn b/components/sync/device_info/BUILD.gn new file mode 100644 index 0000000..f2989a8 --- /dev/null +++ b/components/sync/device_info/BUILD.gn
@@ -0,0 +1,46 @@ +# Copyright 2019 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("//build/buildflag_header.gni") +import("//build/config/features.gni") +import("//build/config/jumbo.gni") + +jumbo_static_library("device_info") { + sources = [ + "device_count_metrics_provider.cc", + "device_count_metrics_provider.h", + "device_info.cc", + "device_info.h", + "device_info_sync_bridge.cc", + "device_info_sync_bridge.h", + "device_info_sync_service.cc", + "device_info_sync_service.h", + "device_info_sync_service_impl.cc", + "device_info_sync_service_impl.h", + "device_info_tracker.h", + "device_info_util.cc", + "device_info_util.h", + "local_device_info_provider.h", + "local_device_info_provider_impl.cc", + "local_device_info_provider_impl.h", + "local_device_info_util.cc", + "local_device_info_util.h", + ] + + configs += [ "//build/config:precompiled_headers" ] + + public_deps = [ + "//base", + "//components/sync", + "//components/sync/protocol", + ] + deps = [ + "//components/keyed_service/core", + "//components/metrics", + "//components/version_info", + "//ui/base", + ] + + configs += [ "//build/config/compiler:wexit_time_destructors" ] +}
diff --git a/components/sync/driver/BUILD.gn b/components/sync/driver/BUILD.gn new file mode 100644 index 0000000..c5959f9 --- /dev/null +++ b/components/sync/driver/BUILD.gn
@@ -0,0 +1,136 @@ +# Copyright 2019 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("//build/buildflag_header.gni") +import("//build/config/features.gni") +import("//build/config/jumbo.gni") + +declare_args() { + # Controls the product part of the user agent calculated in sync_util.cc. + sync_user_agent_product = "Chrome" +} + +jumbo_static_library("driver") { + sources = [ + "about_sync_util.cc", + "about_sync_util.h", + "async_directory_type_controller.cc", + "async_directory_type_controller.h", + "backend_migrator.cc", + "backend_migrator.h", + "configure_context.h", + "data_type_controller.cc", + "data_type_controller.h", + "data_type_encryption_handler.cc", + "data_type_encryption_handler.h", + "data_type_manager.cc", + "data_type_manager.h", + "data_type_manager_impl.cc", + "data_type_manager_impl.h", + "data_type_manager_observer.h", + "data_type_status_table.cc", + "data_type_status_table.h", + "directory_data_type_controller.cc", + "directory_data_type_controller.h", + "frontend_data_type_controller.cc", + "frontend_data_type_controller.h", + "generic_change_processor.cc", + "generic_change_processor.h", + "generic_change_processor_factory.cc", + "generic_change_processor_factory.h", + "glue/sync_engine_backend.cc", + "glue/sync_engine_backend.h", + "glue/sync_engine_impl.cc", + "glue/sync_engine_impl.h", + "model_association_manager.cc", + "model_association_manager.h", + "model_associator.h", + "model_type_controller.cc", + "model_type_controller.h", + "non_ui_syncable_service_based_model_type_controller.cc", + "non_ui_syncable_service_based_model_type_controller.h", + "profile_sync_service.cc", + "profile_sync_service.h", + "shared_change_processor.cc", + "shared_change_processor.h", + "shared_change_processor_ref.cc", + "shared_change_processor_ref.h", + "startup_controller.cc", + "startup_controller.h", + "sync_api_component_factory.cc", + "sync_api_component_factory.h", + "sync_auth_manager.cc", + "sync_auth_manager.h", + "sync_auth_util.cc", + "sync_auth_util.h", + "sync_client.cc", + "sync_client.h", + "sync_driver_switches.cc", + "sync_driver_switches.h", + "sync_service.cc", + "sync_service.h", + "sync_service_crypto.cc", + "sync_service_crypto.h", + "sync_service_observer.cc", + "sync_service_observer.h", + "sync_service_utils.cc", + "sync_service_utils.h", + "sync_session_durations_metrics_recorder.cc", + "sync_session_durations_metrics_recorder.h", + "sync_stopped_reporter.cc", + "sync_stopped_reporter.h", + "sync_token_status.cc", + "sync_token_status.h", + "sync_type_preference_provider.h", + "sync_user_settings.h", + "sync_user_settings_impl.cc", + "sync_user_settings_impl.h", + "sync_util.cc", + "sync_util.h", + "syncable_service_based_model_type_controller.cc", + "syncable_service_based_model_type_controller.h", + ] + + configs += [ "//build/config:precompiled_headers" ] + + public_deps = [ + "//base", + "//components/invalidation/public", + "//components/sync:rest_of_sync", + "//components/sync/base", + "//components/sync/js", + "//components/sync/protocol", + "//components/sync/protocol:util", + "//net", + "//url", + ] + deps = [ + "//base:i18n", + "//components/data_use_measurement/core", + "//components/invalidation/impl:feature_list", + "//components/keyed_service/core", + "//components/prefs", + "//components/signin/core/browser", + "//components/version_info", + "//components/version_info:generate_version_info", + "//services/identity/public/cpp", + "//services/network/public/cpp", + "//ui/base", + ] + + if (!is_ios) { + sources += [ + "sync_policy_handler.cc", + "sync_policy_handler.h", + ] + deps += [ + "//components/policy:generated", + "//components/policy/core/browser", + ] + } + + defines = [ "SYNC_USER_AGENT_PRODUCT=$sync_user_agent_product" ] + + configs += [ "//build/config/compiler:wexit_time_destructors" ] +}
diff --git a/components/sync/driver/resources/index.html b/components/sync/driver/resources/index.html index 804cc0f..d03c356 100644 --- a/components/sync/driver/resources/index.html +++ b/components/sync/driver/resources/index.html
@@ -24,7 +24,6 @@ <script src="chrome://resources/js/event_tracker.js"></script> <script src="chrome://resources/js/cr.js"></script> <script src="chrome://resources/js/cr/event_target.js"></script> -<script src="chrome://resources/js/cr/ui/touch_handler.js"></script> <script src="chrome://resources/js/cr/ui.js"></script> <script src="chrome://resources/js/cr/ui/focus_outline_manager.js"></script> <script src="chrome://resources/js/cr/ui/splitter.js"></script>
diff --git a/components/sync/js/BUILD.gn b/components/sync/js/BUILD.gn new file mode 100644 index 0000000..4643289 --- /dev/null +++ b/components/sync/js/BUILD.gn
@@ -0,0 +1,23 @@ +# Copyright 2019 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("//build/buildflag_header.gni") +import("//build/config/features.gni") +import("//build/config/jumbo.gni") + +jumbo_static_library("js") { + sources = [ + "js_backend.h", + "js_controller.h", + "js_event_details.cc", + "js_event_details.h", + "js_event_handler.h", + "sync_js_controller.cc", + "sync_js_controller.h", + ] + + public_deps = [ + "//components/sync/base", + ] +}
diff --git a/components/sync/protocol/BUILD.gn b/components/sync/protocol/BUILD.gn index 9a9e42fc..297ef3c 100644 --- a/components/sync/protocol/BUILD.gn +++ b/components/sync/protocol/BUILD.gn
@@ -28,6 +28,6 @@ public_deps = [ "//base", - "//components/sync:base", + "//components/sync/base", ] }
diff --git a/components/sync/user_events/BUILD.gn b/components/sync/user_events/BUILD.gn new file mode 100644 index 0000000..424901e --- /dev/null +++ b/components/sync/user_events/BUILD.gn
@@ -0,0 +1,31 @@ +# Copyright 2019 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("//build/buildflag_header.gni") +import("//build/config/features.gni") +import("//build/config/jumbo.gni") + +jumbo_static_library("user_events") { + sources = [ + "no_op_user_event_service.cc", + "no_op_user_event_service.h", + "user_event_model_type_controller.cc", + "user_event_model_type_controller.h", + "user_event_service.h", + "user_event_service_impl.cc", + "user_event_service_impl.h", + "user_event_sync_bridge.cc", + "user_event_sync_bridge.h", + ] + + public_deps = [ + "//base", + "//components/keyed_service/core", + "//components/sync", + "//components/sync/protocol", + ] + deps = [ + "//components/signin/core/browser:shared", + ] +}
diff --git a/components/sync_sessions/BUILD.gn b/components/sync_sessions/BUILD.gn index f62161d..0a936c40 100644 --- a/components/sync_sessions/BUILD.gn +++ b/components/sync_sessions/BUILD.gn
@@ -51,7 +51,7 @@ public_deps = [ "//components/sessions", "//components/sync", - "//components/sync:device_info", + "//components/sync/device_info", ] deps = [
diff --git a/content/browser/browser_thread_unittest.cc b/content/browser/browser_thread_unittest.cc index 7763d782..37489b34 100644 --- a/content/browser/browser_thread_unittest.cc +++ b/content/browser/browser_thread_unittest.cc
@@ -32,12 +32,21 @@ class SequenceManagerTaskEnvironment : public base::Thread::TaskEnvironment { public: - SequenceManagerTaskEnvironment( - std::unique_ptr<base::sequence_manager::SequenceManager> sequence_manager, - scoped_refptr<base::SingleThreadTaskRunner> default_task_runner) - : sequence_manager_(std::move(sequence_manager)), - default_task_runner_(std::move(default_task_runner)) { + SequenceManagerTaskEnvironment() { + sequence_manager_ = + base::sequence_manager::internal::SequenceManagerImpl::CreateUnbound( + base::sequence_manager::SequenceManager::Settings()); + auto browser_ui_thread_scheduler = + BrowserUIThreadScheduler::CreateForTesting( + sequence_manager_.get(), sequence_manager_->GetRealTimeDomain()); + + default_task_runner_ = browser_ui_thread_scheduler->GetTaskRunnerForTesting( + BrowserUIThreadScheduler::QueueType::kDefault); + sequence_manager_->SetDefaultTaskRunner(default_task_runner_); + + BrowserTaskExecutor::CreateWithBrowserUIThreadSchedulerForTesting( + std::move(browser_ui_thread_scheduler)); } ~SequenceManagerTaskEnvironment() override { @@ -80,22 +89,8 @@ protected: void SetUp() override { ui_thread_ = std::make_unique<BrowserProcessSubThread>(BrowserThread::UI); - std::unique_ptr<base::sequence_manager::internal::SequenceManagerImpl> - sequence_manager = base::sequence_manager::internal:: - SequenceManagerImpl::CreateUnbound( - base::sequence_manager::SequenceManager::Settings()); - std::unique_ptr<BrowserUIThreadScheduler> browser_ui_thread_scheduler = - BrowserUIThreadScheduler::CreateForTesting( - sequence_manager.get(), sequence_manager->GetRealTimeDomain()); - base::Thread::Options ui_options; - ui_options.task_environment = new SequenceManagerTaskEnvironment( - std::move(sequence_manager), - browser_ui_thread_scheduler->GetTaskRunnerForTesting( - BrowserUIThreadScheduler::QueueType::kDefault)); - - BrowserTaskExecutor::CreateWithBrowserUIThreadSchedulerForTesting( - std::move(browser_ui_thread_scheduler)); + ui_options.task_environment = new SequenceManagerTaskEnvironment(); ui_thread_->StartWithOptions(ui_options); io_thread_ = std::make_unique<BrowserProcessSubThread>(BrowserThread::IO);
diff --git a/content/browser/devtools/devtools_session.cc b/content/browser/devtools/devtools_session.cc index 7ec5759b5..cab390b 100644 --- a/content/browser/devtools/devtools_session.cc +++ b/content/browser/devtools/devtools_session.cc
@@ -19,7 +19,6 @@ namespace cbor = inspector_protocol_encoding::cbor; using inspector_protocol_encoding::SpanFrom; -using inspector_protocol_encoding::Status; namespace content { @@ -440,8 +439,9 @@ } DCHECK(cbor::IsCBORMessage(SpanFrom(message))); std::string patched(message); - Status status = cbor::AppendString8EntryToCBORMap( - SpanFrom(kSessionId), SpanFrom(session_id), &patched); + inspector_protocol_encoding::Status status = + inspector_protocol_encoding::cbor::AppendString8EntryToCBORMap( + SpanFrom(kSessionId), SpanFrom(session_id), &patched); if (!status.ok()) { LOG(ERROR) << "cbor::AppendString8EntryToCBORMap error " << static_cast<uint32_t>(status.error) << " position "
diff --git a/content/browser/frame_host/interstitial_page_navigator_impl.cc b/content/browser/frame_host/interstitial_page_navigator_impl.cc index 3355fdd..ef977b6 100644 --- a/content/browser/frame_host/interstitial_page_navigator_impl.cc +++ b/content/browser/frame_host/interstitial_page_navigator_impl.cc
@@ -37,8 +37,8 @@ if (!enabled_) return; - navigation_request->navigation_handle()->DidCommitNavigation( - input_params, true, false, GURL(), NAVIGATION_TYPE_NEW_PAGE); + navigation_request->DidCommitNavigation(input_params, true, false, GURL(), + NAVIGATION_TYPE_NEW_PAGE); navigation_request.reset(); // TODO(nasko): Move implementation here, but for the time being call out
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index 8ef7d20..97fd3ee9 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -2674,7 +2674,6 @@ // Before navigating to the restored entry, it should have a restore_type // and no SiteInstance. - NavigationEntry* entry = our_controller.GetEntryAtIndex(0); EXPECT_EQ(RestoreType::LAST_SESSION_EXITED_CLEANLY, our_controller.GetEntryAtIndex(0)->restore_type()); EXPECT_FALSE(our_controller.GetEntryAtIndex(0)->site_instance()); @@ -2682,36 +2681,20 @@ // After navigating, we should have one entry, and it should be "pending". EXPECT_TRUE(our_controller.NeedsReload()); our_controller.LoadIfNecessary(); + auto restore_navigation = + NavigationSimulator::CreateFromPending(raw_our_contents); + restore_navigation->ReadyToCommit(); EXPECT_EQ(1, our_controller.GetEntryCount()); EXPECT_EQ(our_controller.GetEntryAtIndex(0), our_controller.GetPendingEntry()); // This pending navigation may have caused a different navigation to fail, // which causes the pending entry to be cleared. - FrameHostMsg_DidFailProvisionalLoadWithError_Params fail_load_params; - fail_load_params.error_code = net::ERR_ABORTED; - fail_load_params.error_description = base::string16(); - fail_load_params.url = url; - fail_load_params.showing_repost_interstitial = false; - main_test_rfh()->InitializeRenderFrameIfNeeded(); - main_test_rfh()->OnMessageReceived( - FrameHostMsg_DidFailProvisionalLoadWithError(0, // routing_id - fail_load_params)); + NavigationSimulator::NavigateAndFailFromDocument(url, net::ERR_ABORTED, + main_test_rfh()); // Now the pending restored entry commits. - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = entry->GetUniqueID(); - params.did_create_new_entry = false; - params.url = url; - params.transition = ui::PAGE_TRANSITION_LINK; - params.should_update_history = false; - params.gesture = NavigationGestureUser; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url); - TestRenderFrameHost* main_rfh = - static_cast<TestRenderFrameHost*>(raw_our_contents->GetMainFrame()); - main_rfh->PrepareForCommit(); - main_rfh->SendNavigateWithParams(¶ms, false); + restore_navigation->Commit(); // There should be no pending entry and one committed one. EXPECT_EQ(1, our_controller.GetEntryCount());
diff --git a/content/browser/frame_host/navigation_handle_impl.cc b/content/browser/frame_host/navigation_handle_impl.cc index 659d66d..f834c58 100644 --- a/content/browser/frame_host/navigation_handle_impl.cc +++ b/content/browser/frame_host/navigation_handle_impl.cc
@@ -59,6 +59,9 @@ // UMA_HISTOGRAM_MEDIUM_TIMES, but a custom kMinTime is used for high fidelity // near the low end of measured values. // +// TODO(zetamoo): This is duplicated in navigation_request. Never update one +// without the other. And remove this one. +// // TODO(csharrison,nasko): This macro is incorrect for subframe navigations, // which will only have subframe-specific transition types. This means that all // subframes currently are tagged as NewNavigations. @@ -128,16 +131,12 @@ : navigation_request_(navigation_request), net_error_code_(net::OK), was_redirected_(false), - did_replace_entry_(false), - should_update_history_(false), - subframe_entry_committed_(false), request_headers_(std::move(request_headers)), pending_nav_entry_id_(pending_nav_entry_id), navigation_id_(CreateUniqueHandleID()), redirect_chain_(redirect_chain), reload_type_(ReloadType::NONE), restore_type_(RestoreType::NONE), - navigation_type_(NAVIGATION_TYPE_UNKNOWN), is_same_process_(true), weak_factory_(this) { const GURL& url = navigation_request_->common_params().url; @@ -370,28 +369,19 @@ } bool NavigationHandleImpl::HasSubframeNavigationEntryCommitted() { - DCHECK(!IsInMainFrame()); - DCHECK(state() == NavigationRequest::DID_COMMIT || - state() == NavigationRequest::DID_COMMIT_ERROR_PAGE); - return subframe_entry_committed_; + return navigation_request_->subframe_entry_committed(); } bool NavigationHandleImpl::DidReplaceEntry() { - DCHECK(state() == NavigationRequest::DID_COMMIT || - state() == NavigationRequest::DID_COMMIT_ERROR_PAGE); - return did_replace_entry_; + return navigation_request_->did_replace_entry(); } bool NavigationHandleImpl::ShouldUpdateHistory() { - DCHECK(state() == NavigationRequest::DID_COMMIT || - state() == NavigationRequest::DID_COMMIT_ERROR_PAGE); - return should_update_history_; + return navigation_request_->should_update_history(); } const GURL& NavigationHandleImpl::GetPreviousURL() { - DCHECK(state() == NavigationRequest::DID_COMMIT || - state() == NavigationRequest::DID_COMMIT_ERROR_PAGE); - return previous_url_; + return navigation_request_->previous_url(); } net::IPEndPoint NavigationHandleImpl::GetSocketAddress() { @@ -615,99 +605,6 @@ GetDelegate()->ReadyToCommitNavigation(this); } -void NavigationHandleImpl::DidCommitNavigation( - const FrameHostMsg_DidCommitProvisionalLoad_Params& params, - bool navigation_entry_committed, - bool did_replace_entry, - const GURL& previous_url, - NavigationType navigation_type) { - CHECK_EQ(GetURL(), params.url); - - did_replace_entry_ = did_replace_entry; - should_update_history_ = params.should_update_history; - previous_url_ = previous_url; - base_url_ = params.base_url; - navigation_type_ = navigation_type; - - // If an error page reloads, net_error_code might be 200 but we still want to - // count it as an error page. - if (params.base_url.spec() == kUnreachableWebDataURL || - net_error_code_ != net::OK) { - TRACE_EVENT_ASYNC_STEP_INTO0("navigation", "NavigationHandle", this, - "DidCommitNavigation: error page"); - navigation_request_->set_handle_state( - NavigationRequest::DID_COMMIT_ERROR_PAGE); - } else { - TRACE_EVENT_ASYNC_STEP_INTO0("navigation", "NavigationHandle", this, - "DidCommitNavigation"); - navigation_request_->set_handle_state(NavigationRequest::DID_COMMIT); - } - - StopCommitTimeout(); - - // Record metrics for the time it took to commit the navigation if it was to - // another document without error. - if (!IsSameDocument() && !IsErrorPage()) { - base::TimeTicks now = base::TimeTicks::Now(); - base::TimeDelta delta = - now - navigation_request_->common_params().navigation_start; - ui::PageTransition transition = GetPageTransition(); - base::Optional<bool> is_background = - GetRenderFrameHost()->GetProcess()->IsProcessBackgrounded(); - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit", transition, is_background, - delta); - if (IsInMainFrame()) { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.MainFrame", transition, - is_background, delta); - } else { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.Subframe", transition, - is_background, delta); - } - if (is_same_process_) { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess", transition, - is_background, delta); - if (IsInMainFrame()) { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess.MainFrame", - transition, is_background, delta); - } else { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess.Subframe", - transition, is_background, delta); - } - } else { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess", transition, - is_background, delta); - if (IsInMainFrame()) { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess.MainFrame", - transition, is_background, delta); - } else { - LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess.Subframe", - transition, is_background, delta); - } - } - - if (!ready_to_commit_time_.is_null()) { - LOG_NAVIGATION_TIMING_HISTOGRAM("ReadyToCommitUntilCommit2", - GetPageTransition(), is_background, - now - ready_to_commit_time_); - } - } - - DCHECK(!IsInMainFrame() || navigation_entry_committed) - << "Only subframe navigations can get here without changing the " - << "NavigationEntry"; - subframe_entry_committed_ = navigation_entry_committed; - - // For successful navigations, ensure the frame owner element is no longer - // collapsed as a result of a prior navigation. - if (!IsErrorPage() && !frame_tree_node()->IsMainFrame()) { - // The last committed load in collapsed frames will be an error page with - // |kUnreachableWebDataURL|. Same-document navigation should not be - // possible. - DCHECK(!IsSameDocument() || !frame_tree_node()->is_collapsed()); - frame_tree_node()->SetCollapsed(false); - } -} - void NavigationHandleImpl::RunCompleteCallback( NavigationThrottle::ThrottleCheckResult result) { DCHECK(result.action() != NavigationThrottle::DEFER);
diff --git a/content/browser/frame_host/navigation_handle_impl.h b/content/browser/frame_host/navigation_handle_impl.h index 5dfc0dc..5564a03 100644 --- a/content/browser/frame_host/navigation_handle_impl.h +++ b/content/browser/frame_host/navigation_handle_impl.h
@@ -41,8 +41,6 @@ #include "content/browser/android/navigation_handle_proxy.h" #endif -struct FrameHostMsg_DidCommitProvisionalLoad_Params; - namespace content { class AppCacheNavigationHandle; @@ -207,18 +205,6 @@ // |state_| and inform the delegate. void ReadyToCommitNavigation(bool is_error); - // Called when the navigation was committed. This will update the |state_|. - // |navigation_entry_committed| indicates whether the navigation changed which - // NavigationEntry is current. - // |did_replace_entry| is true if the committed entry has replaced the - // existing one. A non-user initiated redirect causes such replacement. - void DidCommitNavigation( - const FrameHostMsg_DidCommitProvisionalLoad_Params& params, - bool navigation_entry_committed, - bool did_replace_entry, - const GURL& previous_url, - NavigationType navigation_type); - // Called during commit. Takes ownership of the embedder's NavigationData // instance. This NavigationData may have been cloned prior to being added // here. @@ -230,11 +216,10 @@ return navigation_request_->navigation_ui_data(); } - const GURL& base_url() { return base_url_; } + const GURL& base_url() { return navigation_request_->base_url(); } NavigationType navigation_type() { - DCHECK_GE(state(), NavigationRequest::DID_COMMIT); - return navigation_type_; + return navigation_request_->navigation_type(); } void set_response_headers_for_testing( @@ -321,6 +306,10 @@ void StopCommitTimeout(); void RestartCommitTimeout(); + // TODO(zetamoo): Remove once |ready_to_commit_time_| is owned by + // NavigationRequest. + base::TimeTicks ready_to_commit_time() const { return ready_to_commit_time_; } + // The NavigationRequest that owns this NavigationHandle. NavigationRequest* navigation_request_; @@ -328,9 +317,6 @@ Referrer sanitized_referrer_; net::Error net_error_code_; bool was_redirected_; - bool did_replace_entry_; - bool should_update_history_; - bool subframe_entry_committed_; // The headers used for the request. net::HttpRequestHeaders request_headers_; @@ -390,10 +376,6 @@ // Stores the restore type, or NONE it it's not a restore. RestoreType restore_type_; - GURL previous_url_; - GURL base_url_; - NavigationType navigation_type_; - // Which proxy server was used for this navigation, if any. net::ProxyServer proxy_server_;
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index 05336f9..49d7f2dd 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -12,6 +12,7 @@ #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" +#include "base/metrics/histogram_macros.h" #include "base/optional.h" #include "base/rand_util.h" #include "base/strings/string_util.h" @@ -339,6 +340,98 @@ return !previous_domain.empty() && previous_domain == new_domain; } +// LOG_NAVIGATION_TIMING_HISTOGRAM logs |value| for "Navigation.<histogram>" UMA +// as well as supplementary UMAs (depending on |transition| and |is_background|) +// for BackForward/Reload/NewNavigation variants. +// +// kMaxTime and kBuckets constants are consistent with +// UMA_HISTOGRAM_MEDIUM_TIMES, but a custom kMinTime is used for high fidelity +// near the low end of measured values. +// +// TODO(zetamoo): This is duplicated in navigation_handle_impl. Never update one +// without the other. +// +// TODO(csharrison,nasko): This macro is incorrect for subframe navigations, +// which will only have subframe-specific transition types. This means that all +// subframes currently are tagged as NewNavigations. +#define LOG_NAVIGATION_TIMING_HISTOGRAM(histogram, transition, is_background, \ + duration) \ + do { \ + const base::TimeDelta kMinTime = base::TimeDelta::FromMilliseconds(1); \ + const base::TimeDelta kMaxTime = base::TimeDelta::FromMinutes(3); \ + const int kBuckets = 50; \ + UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram, duration, kMinTime, \ + kMaxTime, kBuckets); \ + if (transition & ui::PAGE_TRANSITION_FORWARD_BACK) { \ + UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram ".BackForward", \ + duration, kMinTime, kMaxTime, kBuckets); \ + } else if (ui::PageTransitionCoreTypeIs(transition, \ + ui::PAGE_TRANSITION_RELOAD)) { \ + UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram ".Reload", duration, \ + kMinTime, kMaxTime, kBuckets); \ + } else if (ui::PageTransitionIsNewNavigation(transition)) { \ + UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram ".NewNavigation", \ + duration, kMinTime, kMaxTime, kBuckets); \ + } else { \ + NOTREACHED() << "Invalid page transition: " << transition; \ + } \ + if (is_background.has_value()) { \ + if (is_background.value()) { \ + UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram \ + ".BackgroundProcessPriority", \ + duration, kMinTime, kMaxTime, kBuckets); \ + } else { \ + UMA_HISTOGRAM_CUSTOM_TIMES("Navigation." histogram \ + ".ForegroundProcessPriority", \ + duration, kMinTime, kMaxTime, kBuckets); \ + } \ + } \ + } while (0) + +void RecordStartToCommitMetrics(base::TimeTicks navigation_start_time, + ui::PageTransition transition, + const base::TimeTicks& ready_to_commit_time, + base::Optional<bool> is_background, + bool is_same_process, + bool is_main_frame) { + base::TimeTicks now = base::TimeTicks::Now(); + base::TimeDelta delta = now - navigation_start_time; + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit", transition, is_background, + delta); + if (is_main_frame) { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.MainFrame", transition, + is_background, delta); + } else { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.Subframe", transition, + is_background, delta); + } + if (is_same_process) { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess", transition, + is_background, delta); + if (is_main_frame) { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess.MainFrame", + transition, is_background, delta); + } else { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.SameProcess.Subframe", + transition, is_background, delta); + } + } else { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess", transition, + is_background, delta); + if (is_main_frame) { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess.MainFrame", + transition, is_background, delta); + } else { + LOG_NAVIGATION_TIMING_HISTOGRAM("StartToCommit.CrossProcess.Subframe", + transition, is_background, delta); + } + } + if (!ready_to_commit_time.is_null()) { + LOG_NAVIGATION_TIMING_HISTOGRAM("ReadyToCommitUntilCommit2", transition, + is_background, now - ready_to_commit_time); + } +} + } // namespace // static @@ -2566,4 +2659,67 @@ return false; } +void NavigationRequest::DidCommitNavigation( + const FrameHostMsg_DidCommitProvisionalLoad_Params& params, + bool navigation_entry_committed, + bool did_replace_entry, + const GURL& previous_url, + NavigationType navigation_type) { + CHECK_EQ(common_params_.url, params.url); + + did_replace_entry_ = did_replace_entry; + should_update_history_ = params.should_update_history; + previous_url_ = previous_url; + base_url_ = params.base_url; + navigation_type_ = navigation_type; + + // If an error page reloads, net_error_code might be 200 but we still want to + // count it as an error page. + if (params.base_url.spec() == kUnreachableWebDataURL || + navigation_handle_->GetNetErrorCode() != net::OK) { + TRACE_EVENT_ASYNC_STEP_INTO0("navigation", "NavigationHandle", + navigation_handle_.get(), + "DidCommitNavigation: error page"); + handle_state_ = DID_COMMIT_ERROR_PAGE; + } else { + TRACE_EVENT_ASYNC_STEP_INTO0("navigation", "NavigationHandle", + navigation_handle_.get(), + "DidCommitNavigation"); + handle_state_ = DID_COMMIT; + } + + navigation_handle_->StopCommitTimeout(); + + // Record metrics for the time it took to commit the navigation if it was to + // another document without error. + if (!IsSameDocument() && handle_state_ != DID_COMMIT_ERROR_PAGE) { + ui::PageTransition transition = common_params_.transition; + base::Optional<bool> is_background = + render_frame_host_->GetProcess()->IsProcessBackgrounded(); + const base::TimeTicks& ready_to_commit_time = + navigation_handle_->ready_to_commit_time(); + + RecordStartToCommitMetrics(common_params_.navigation_start, transition, + ready_to_commit_time, is_background, + navigation_handle_->is_same_process_, + frame_tree_node_->IsMainFrame()); + } + + DCHECK(!frame_tree_node_->IsMainFrame() || navigation_entry_committed) + << "Only subframe navigations can get here without changing the " + << "NavigationEntry"; + subframe_entry_committed_ = navigation_entry_committed; + + // For successful navigations, ensure the frame owner element is no longer + // collapsed as a result of a prior navigation. + if (handle_state_ != DID_COMMIT_ERROR_PAGE && + !frame_tree_node()->IsMainFrame()) { + // The last committed load in collapsed frames will be an error page with + // |kUnreachableWebDataURL|. Same-document navigation should not be + // possible. + DCHECK(!IsSameDocument() || !frame_tree_node()->is_collapsed()); + frame_tree_node()->SetCollapsed(false); + } +} + } // namespace content
diff --git a/content/browser/frame_host/navigation_request.h b/content/browser/frame_host/navigation_request.h index c3c83e3..ba5a804 100644 --- a/content/browser/frame_host/navigation_request.h +++ b/content/browser/frame_host/navigation_request.h
@@ -23,6 +23,7 @@ #include "content/common/navigation_params.mojom.h" #include "content/common/navigation_subresource_loader_params.h" #include "content/public/browser/navigation_throttle.h" +#include "content/public/browser/navigation_type.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/common/previews_state.h" @@ -31,6 +32,8 @@ struct URLLoaderCompletionStatus; } +struct FrameHostMsg_DidCommitProvisionalLoad_Params; + namespace content { class FrameNavigationEntry; @@ -347,6 +350,51 @@ return throttle_runner_->GetDeferringThrottle(); } + // Called when the navigation was committed. + // This will update the |handle_state_|. + // |navigation_entry_committed| indicates whether the navigation changed which + // NavigationEntry is current. + // |did_replace_entry| is true if the committed entry has replaced the + // existing one. A non-user initiated redirect causes such replacement. + void DidCommitNavigation( + const FrameHostMsg_DidCommitProvisionalLoad_Params& params, + bool navigation_entry_committed, + bool did_replace_entry, + const GURL& previous_url, + NavigationType navigation_type); + + NavigationType navigation_type() const { + DCHECK_GE(handle_state_, DID_COMMIT); + return navigation_type_; + } + + const GURL& base_url() { return base_url_; } + + bool did_replace_entry() const { + DCHECK(handle_state_ == DID_COMMIT || + handle_state_ == DID_COMMIT_ERROR_PAGE); + return did_replace_entry_; + } + + bool should_update_history() const { + DCHECK(handle_state_ == DID_COMMIT || + handle_state_ == DID_COMMIT_ERROR_PAGE); + return should_update_history_; + } + + bool subframe_entry_committed() const { + DCHECK(!frame_tree_node_->IsMainFrame()); + DCHECK(handle_state_ == DID_COMMIT || + handle_state_ == DID_COMMIT_ERROR_PAGE); + return subframe_entry_committed_; + } + + const GURL& previous_url() const { + DCHECK(handle_state_ == DID_COMMIT || + handle_state_ == DID_COMMIT_ERROR_PAGE); + return previous_url_; + } + private: // TODO(clamy): Transform NavigationHandleImplTest into NavigationRequestTest // once NavigationHandleImpl has become a wrapper around NavigationRequest. @@ -576,6 +624,8 @@ // RenderProcessHostObserver implementation. void RenderProcessHostDestroyed(RenderProcessHost* host) override; + void RecordNavigationMetrics() const; + FrameTreeNode* frame_tree_node_; RenderFrameHostImpl* render_frame_host_ = nullptr; @@ -708,6 +758,29 @@ // responsible for notifying them about the various navigation events. std::unique_ptr<NavigationThrottleRunner> throttle_runner_; + // Indicates whether the navigation changed which NavigationEntry is current. + bool subframe_entry_committed_ = false; + + // True if the committed entry has replaced the existing one. + // A non-user initiated redirect causes such replacement. + bool did_replace_entry_ = false; + + // Set to false if we want to update the session history but not update the + // browser history. E.g., on unreachable urls. + bool should_update_history_ = false; + + // The previous main frame URL that the user was on. This may be empty if + // there was no last committed entry. + GURL previous_url_; + + // The base URL for the page's document when the frame was committed. + GURL base_url_; + + // The type of navigation that just occurred. Note that not all types of + // navigations in the enum are valid here, since some of them don't actually + // cause a "commit" and won't generate this notification. + NavigationType navigation_type_ = NAVIGATION_TYPE_UNKNOWN; + base::WeakPtrFactory<NavigationRequest> weak_factory_; DISALLOW_COPY_AND_ASSIGN(NavigationRequest);
diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc index b16bcd8..0241452 100644 --- a/content/browser/frame_host/navigator_impl.cc +++ b/content/browser/frame_host/navigator_impl.cc
@@ -280,9 +280,9 @@ if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) { DCHECK_EQ(!render_frame_host->GetParent(), did_navigate ? details.is_main_frame : false); - navigation_request->navigation_handle()->DidCommitNavigation( - params, did_navigate, details.did_replace_entry, details.previous_url, - details.type); + navigation_request->DidCommitNavigation(params, did_navigate, + details.did_replace_entry, + details.previous_url, details.type); navigation_request.reset(); }
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 6f019e32..f2bd60b 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -1375,8 +1375,6 @@ handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) - IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, - OnDidAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, @@ -1833,21 +1831,35 @@ is_audible_ = is_audible; } -void RenderFrameHostImpl::OnDidAddMessageToConsole( - int32_t level, +void RenderFrameHostImpl::DidAddMessageToConsole( + blink::mojom::ConsoleMessageLevel log_level, const base::string16& message, int32_t line_no, const base::string16& source_id) { - if (level < logging::LOG_VERBOSE || level > logging::LOG_FATAL) { - bad_message::ReceivedBadMessage( - GetProcess(), bad_message::RFH_DID_ADD_CONSOLE_MESSAGE_BAD_SEVERITY); + // TODO(https://crbug.com/786836): Update downstream code to use + // ConsoleMessageLevel everywhere to avoid this conversion. + logging::LogSeverity log_severity = logging::LOG_VERBOSE; + switch (log_level) { + case blink::mojom::ConsoleMessageLevel::kVerbose: + log_severity = logging::LOG_VERBOSE; + break; + case blink::mojom::ConsoleMessageLevel::kInfo: + log_severity = logging::LOG_INFO; + break; + case blink::mojom::ConsoleMessageLevel::kWarning: + log_severity = logging::LOG_WARNING; + break; + case blink::mojom::ConsoleMessageLevel::kError: + log_severity = logging::LOG_ERROR; + break; + } + + if (delegate_->DidAddMessageToConsole(log_severity, message, line_no, + source_id)) { return; } - if (delegate_->DidAddMessageToConsole(level, message, line_no, source_id)) - return; - - // Pass through log level only on builtin components pages to limit console + // Pass through log severity only on builtin components pages to limit console // spew. const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || @@ -1856,7 +1868,7 @@ const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); - LogConsoleMessage(level, message, line_no, is_builtin_component, + LogConsoleMessage(log_severity, message, line_no, is_builtin_component, is_off_the_record, source_id); }
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index 3186e56..bee0107 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -1049,10 +1049,6 @@ class DroppedInterfaceRequestLogger; // IPC Message handlers. - void OnDidAddMessageToConsole(int32_t level, - const base::string16& message, - int32_t line_no, - const base::string16& source_id); void OnDetach(); void OnFrameFocused(); void OnOpenURL(const FrameHostMsg_OpenURL_Params& params); @@ -1206,6 +1202,11 @@ void FullscreenStateChanged(bool is_fullscreen) override; void DocumentOnLoadCompleted() override; void UpdateActiveSchedulerTrackedFeatures(uint64_t features_mask) override; + void DidAddMessageToConsole(blink::mojom::ConsoleMessageLevel log_level, + const base::string16& message, + int32_t line_no, + const base::string16& source_id) override; + #if defined(OS_ANDROID) void UpdateUserGestureCarryoverInfo() override; #endif
diff --git a/content/browser/notifications/platform_notification_context_impl.cc b/content/browser/notifications/platform_notification_context_impl.cc index d0b32520..37c746bc 100644 --- a/content/browser/notifications/platform_notification_context_impl.cc +++ b/content/browser/notifications/platform_notification_context_impl.cc
@@ -235,7 +235,7 @@ std::set<GURL> origins; if (!initialized) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, std::move(origins))); return; @@ -257,7 +257,7 @@ DestroyDatabase(); base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), success, std::move(origins))); } @@ -303,7 +303,7 @@ DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!initialized) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, /* deleted_count= */ 0)); return; @@ -336,10 +336,9 @@ service_proxy_->CloseNotification(notification_id); } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, - base::BindOnce(std::move(callback), success, - deleted_notification_ids.size())); + base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), success, + deleted_notification_ids.size())); } void PlatformNotificationContextImpl::ReadNotificationDataAndRecordInteraction( @@ -362,7 +361,7 @@ DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!initialized) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, NotificationDatabaseData())); return; @@ -378,7 +377,7 @@ if (status == NotificationDatabase::STATUS_OK) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ true, database_data)); return; @@ -389,7 +388,7 @@ DestroyDatabase(); base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, NotificationDatabaseData())); } @@ -459,7 +458,7 @@ DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!initialized) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, blink::NotificationResources())); return; @@ -474,7 +473,7 @@ if (status == NotificationDatabase::STATUS_OK) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ true, notification_resources)); return; @@ -485,7 +484,7 @@ DestroyDatabase(); base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, blink::NotificationResources())); } @@ -543,7 +542,7 @@ DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!initialized) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, std::vector<NotificationDatabaseData>())); return; @@ -578,7 +577,7 @@ } base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ true, notification_datas)); @@ -593,7 +592,7 @@ DestroyDatabase(); base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, std::vector<NotificationDatabaseData>())); } @@ -644,7 +643,7 @@ DCHECK(database_data.notification_id.empty()); if (!initialized || !service_proxy_) { base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, /* notification_id= */ "")); return; @@ -680,7 +679,7 @@ DestroyDatabase(); base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, /* notification_id= */ "")); return; @@ -696,7 +695,7 @@ !DoCheckNotificationTriggerQuota(origin)) { // TODO(knollr): Reply with a custom error so developers can handle this. base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, /* notification_id= */ "")); return; @@ -723,7 +722,7 @@ // Respond with success as this notification got scheduled successfully. base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ true, write_database_data.notification_id)); return; @@ -742,7 +741,7 @@ DestroyDatabase(); base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), /* success= */ false, /* notification_id= */ "")); } @@ -765,9 +764,8 @@ bool initialized) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!initialized) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, - base::BindOnce(std::move(callback), false)); + base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), false)); return; } @@ -787,9 +785,8 @@ success = true; } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, - base::BindOnce(std::move(callback), success)); + base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), success)); } void PlatformNotificationContextImpl::OnRegistrationDeleted( @@ -850,7 +847,7 @@ if (!task_runner_) { task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); } task_runner_->PostTask(
diff --git a/content/browser/renderer_host/media/peer_connection_tracker_host.cc b/content/browser/renderer_host/media/peer_connection_tracker_host.cc index d42379f..fcf0db94 100644 --- a/content/browser/renderer_host/media/peer_connection_tracker_host.cc +++ b/content/browser/renderer_host/media/peer_connection_tracker_host.cc
@@ -26,7 +26,10 @@ IPC_BEGIN_MESSAGE_MAP(PeerConnectionTrackerHost, message) IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_AddPeerConnection, OnAddPeerConnection) - IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_AddStats, OnAddStats) + IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_AddStandardStats, + OnAddStandardStats) + IPC_MESSAGE_HANDLER(PeerConnectionTrackerHost_AddLegacyStats, + OnAddLegacyStats) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; @@ -143,11 +146,20 @@ base::OnceCallback<void(bool)>()); } -void PeerConnectionTrackerHost::OnAddStats(int lid, - const base::ListValue& value) { +void PeerConnectionTrackerHost::OnAddStandardStats( + int lid, + const base::ListValue& value) { WebRTCInternals* webrtc_internals = WebRTCInternals::GetInstance(); if (webrtc_internals) { - webrtc_internals->OnAddStats(peer_pid(), lid, value); + webrtc_internals->OnAddStandardStats(peer_pid(), lid, value); + } +} + +void PeerConnectionTrackerHost::OnAddLegacyStats(int lid, + const base::ListValue& value) { + WebRTCInternals* webrtc_internals = WebRTCInternals::GetInstance(); + if (webrtc_internals) { + webrtc_internals->OnAddLegacyStats(peer_pid(), lid, value); } }
diff --git a/content/browser/renderer_host/media/peer_connection_tracker_host.h b/content/browser/renderer_host/media/peer_connection_tracker_host.h index 6e4c322..e1533b3 100644 --- a/content/browser/renderer_host/media/peer_connection_tracker_host.h +++ b/content/browser/renderer_host/media/peer_connection_tracker_host.h
@@ -50,7 +50,8 @@ private: // Handlers for IPC messages coming from the renderer. void OnAddPeerConnection(const PeerConnectionInfo& info); - void OnAddStats(int lid, const base::ListValue& value); + void OnAddStandardStats(int lid, const base::ListValue& value); + void OnAddLegacyStats(int lid, const base::ListValue& value); void SendOnSuspendOnUIThread(); // mojom::PeerConnectionTrackerHost implementation.
diff --git a/content/browser/resources/media/stats_graph_helper.js b/content/browser/resources/media/stats_graph_helper.js index 14f9fc7..b8e0d3a 100644 --- a/content/browser/resources/media/stats_graph_helper.js +++ b/content/browser/resources/media/stats_graph_helper.js
@@ -97,28 +97,91 @@ 'googFingerprint': true, }; +function isStandardReportBlacklisted(report) { + // Codec stats reflect what has been negotiated. There are LOTS of them and + // they don't change over time on their own. + if (report.type == 'codec') { + return true; + } + // Unused data channels can stay in "connecting" indefinitely and their + // counters stay zero. + if (report.type == 'data-channel' && + readReportStat(report, 'state') == 'connecting') { + return true; + } + // The same is true for transports and "new". + if (report.type == 'transport' && + readReportStat(report, 'dtlsState') == 'new') { + return true; + } + // Local and remote candidates don't change over time and there are several of + // them. + if (report.type == 'local-candidate' || report.type == 'remote-candidate') { + return true; + } + return false; +} + +function readReportStat(report, stat) { + let values = report.stats.values; + for (let i = 0; i < values.length; i += 2) { + if (values[i] == stat) { + return values[i + 1]; + } + } + return undefined; +} + +function isStandardStatBlacklisted(report, statName) { + // The datachannelid is an identifier, but because it is a number it shows up + // as a graph if we don't blacklist it. + if (report.type == 'data-channel' && statName == 'datachannelid') { + return true; + } + // The priority does not change over time on its own; plotting uninteresting. + if (report.type == 'candidate-pair' && statName == 'priority') { + return true; + } + return false; +} + var graphViews = {}; +let graphElementsByPeerConnectionId = new Map(); // Returns number parsed from |value|, or NaN if the stats name is black-listed. function getNumberFromValue(name, value) { if (statsNameBlackList[name]) { return NaN; } + if (isNaN(value)) { + return NaN; + } return parseFloat(value); } // Adds the stats report |report| to the timeline graph for the given // |peerConnectionElement|. -function drawSingleReport(peerConnectionElement, report) { +function drawSingleReport(peerConnectionElement, report, isLegacyReport) { var reportType = report.type; var reportId = report.id; var stats = report.stats; if (!stats || !stats.values) { return; } + if (!isLegacyReport && isStandardReportBlacklisted(report)) { + return; + } + + const childrenBefore = peerConnectionElement.hasChildNodes() ? + Array.from(peerConnectionElement.childNodes) : + []; for (var i = 0; i < stats.values.length - 1; i = i + 2) { var rawLabel = stats.values[i]; + if (!isLegacyReport && isStandardStatBlacklisted(report, rawLabel)) { + continue; + } + // Propagation deltas are handled separately. if (rawLabel == RECEIVED_PROPAGATION_DELTA_LABEL) { drawReceivedPropagationDelta( @@ -140,7 +203,7 @@ var finalLabel = rawLabel; var finalValue = rawValue; // We need to convert the value if dataConversionConfig[rawLabel] exists. - if (dataConversionConfig[rawLabel]) { + if (isLegacyReport && dataConversionConfig[rawLabel]) { // Updates the original dataSeries before the conversion. addDataSeriesPoints( peerConnectionElement, rawDataSeriesId, rawLabel, [stats.timestamp], @@ -182,6 +245,38 @@ } graphViews[graphViewId].updateEndDate(); } + + const childrenAfter = peerConnectionElement.hasChildNodes() ? + Array.from(peerConnectionElement.childNodes) : + []; + for (let i = 0; i < childrenAfter.length; ++i) { + if (!childrenBefore.includes(childrenAfter[i])) { + let graphElements = + graphElementsByPeerConnectionId.get(peerConnectionElement.id); + if (!graphElements) { + graphElements = []; + graphElementsByPeerConnectionId.set( + peerConnectionElement.id, graphElements); + } + graphElements.push(childrenAfter[i]); + } + } +} + +function removeStatsReportGraphs(peerConnectionElement) { + const graphElements = + graphElementsByPeerConnectionId.get(peerConnectionElement.id); + if (graphElements) { + for (let i = 0; i < graphElements.length; ++i) { + peerConnectionElement.removeChild(graphElements[i]); + } + graphElementsByPeerConnectionId.delete(peerConnectionElement.id); + } + Object.keys(graphViews).forEach(key => { + if (key.startsWith(peerConnectionElement.id)) { + delete graphViews[key]; + } + }); } // Makes sure the TimelineDataSeries with id |dataSeriesId| is created,
diff --git a/content/browser/resources/media/stats_rates_calculator.js b/content/browser/resources/media/stats_rates_calculator.js new file mode 100644 index 0000000..2d85eee --- /dev/null +++ b/content/browser/resources/media/stats_rates_calculator.js
@@ -0,0 +1,300 @@ +// Copyright (c) 2019 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. + +class CalculatedMetric { + constructor(insertAtOriginalMetricName, name, value) { + this.insertAtOriginalMetricName = insertAtOriginalMetricName; + this.name = name; + this.value = value; + } +} + +class StatsReport { + constructor() { + // Represents an RTCStatsReport. It is a Map RTCStats.id -> RTCStats. + // https://w3c.github.io/webrtc-pc/#dom-rtcstatsreport + this.statsById = new Map(); + this.calculatedStatsById = new Map(); + } + + // |internalReports| is an array, each element represents an RTCStats object, + // but the format is a little different from the spec. This is the format: + // { + // id: "string", + // type: "string", + // stats: { + // timestamp: <milliseconds>, + // values: ["member1", value1, "member2", value2...] + // } + // } + static fromInternalsReportList(internalReports) { + const result = new StatsReport(); + internalReports.forEach(internalReport => { + if (!internalReport.stats || !internalReport.stats.values) { + return; // continue; + } + const stats = { + id: internalReport.id, + type: internalReport.type, + timestamp: internalReport.stats.timestamp / 1000.0 // ms -> s + }; + const values = internalReport.stats.values; + for (let i = 0; i < values.length; i += 2) { + // Metric "name: value". + stats[values[i]] = values[i + 1]; + } + result.statsById.set(stats.id, stats); + }); + return result; + } + + toInternalsReportList() { + const result = []; + for (let stats of this.statsById.values()) { + const internalReport = { + id: stats.id, + type: stats.type, + stats: { + timestamp: stats.timestamp * 1000.0, // s -> ms + values: [] + } + }; + Object.keys(stats).forEach(metricName => { + if (metricName == 'id' || metricName == 'type' || + metricName == 'timestamp') { + return; // continue; + } + internalReport.stats.values.push(metricName); + internalReport.stats.values.push(stats[metricName]); + const calculatedMetric = + this.getCalculatedMetricByOriginalName(stats.id, metricName); + if (calculatedMetric) { + internalReport.stats.values.push(calculatedMetric.name); + // Treat calculated metrics that are undefined as 0 to ensure graphs + // can be created anyway. + internalReport.stats.values.push( + calculatedMetric.value ? calculatedMetric.value : 0); + } + }); + result.push(internalReport); + } + return result; + } + + toString() { + let str = ''; + for (let stats of this.statsById.values()) { + if (str != '') { + str += ','; + } + str += JSON.stringify(stats); + } + let str2 = ''; + for (let stats of this.calculatedStatsById.values()) { + if (str2 != '') { + str2 += ','; + } + str2 += JSON.stringify(stats); + } + return '[original:' + str + '],calculated:[' + str2 + ']'; + } + + get(id) { + return this.statsById.get(id); + } + + getByType(type) { + const result = []; + for (let stats of this.statsById.values()) { + if (stats.type == type) { + result.push(stats); + } + } + return result; + } + + setCalculatedMetric(id, insertAtOriginalMetricName, name, value) { + let calculatedStats = this.calculatedStatsById.get(id); + if (!calculatedStats) { + calculatedStats = {}; + this.calculatedStatsById.set(id, calculatedStats); + } + calculatedStats[insertAtOriginalMetricName] = + new CalculatedMetric(insertAtOriginalMetricName, name, value); + } + + getCalculatedMetricByOriginalName(id, originalMetricName) { + const calculatedStats = this.calculatedStatsById.get(id); + return calculatedStats ? calculatedStats[originalMetricName] : undefined; + } +} + +class StatsRatesCalculator { + constructor() { + this.previousReport = null; + this.currentReport = null; + } + + addStatsReport(report) { + this.previousReport = this.currentReport; + this.currentReport = report; + this.updateCalculatedMetrics_(); + } + + // Updates all "calculated metrics", which are metrics derived from standard + // values, such as converting total counters (e.g. bytesSent) to rates (e.g. + // bytesSent/s). + updateCalculatedMetrics_() { + const calculatedMetrics = [ + { + type: 'data-channel', + condition: null, + names: [ + ['messagesSent', 'timestamp'], + ['messagesReceived', 'timestamp'], + ['bytesSent', 'timestamp'], + ['bytesReceived', 'timestamp'], + ], + }, + { + type: 'track', + condition: null, + names: [ + ['framesSent', 'timestamp'], + ['framesReceived', 'timestamp'], + [ + 'totalAudioEnergy', + 'totalSamplesDuration', + '[Audio_Level_in_RMS]', + (value) => { + // Calculated according to: + // https://w3c.github.io/webrtc-stats/#dom-rtcaudiohandlerstats-totalaudioenergy + return Math.sqrt(value); + }, + ], + [ + 'jitterBufferDelay', + 'jitterBufferEmittedCount', + '[jitterBufferDelay/jitterBufferEmittedCount_in_ms]', + (value) => { + return value * 1000; // s -> ms + }, + ], + ], + }, + { + type: 'outbound-rtp', + condition: null, + names: [ + ['bytesSent', 'timestamp'], + ['packetsSent', 'timestamp'], + ['framesEncoded', 'timestamp'], + ['qpSum', 'framesEncoded'], + ], + }, + { + type: 'inbound-rtp', + condition: null, + names: [ + ['bytesReceived', 'timestamp'], + ['packetsReceived', 'timestamp'], + ['framesDecoded', 'timestamp'], + ['qpSum', 'framesDecoded'], + ], + }, + { + type: 'transport', + condition: null, + names: [ + ['bytesSent', 'timestamp'], ['bytesReceived', 'timestamp'], + // TODO(https://crbug.com/webrtc/10568): Add packetsSent and + // packetsReceived once implemented. + ], + }, + { + type: 'candidate-pair', + condition: null, + names: [ + ['bytesSent', 'timestamp'], + ['bytesReceived', 'timestamp'], + // TODO(https://crbug.com/webrtc/10569): Add packetsSent and + // packetsReceived once implemented. + ['requestsSent', 'timestamp'], + ['requestsReceived', 'timestamp'], + ['responsesSent', 'timestamp'], + ['responsesReceived', 'timestamp'], + ['consentRequestsSent', 'timestamp'], + ['consentRequestsReceived', 'timestamp'], + [ + 'totalRoundTripTime', + 'responsesReceived', + '[totalRoundTripTime/responsesReceived_in_ms]', + (value) => { + return value * 1000; // s -> ms + }, + ], + ], + }, + ]; + calculatedMetrics.forEach(calculatedMetric => { + calculatedMetric.names.forEach( + ([accumulativeMetric, samplesMetric, resultName, transformation]) => { + this.currentReport.getByType(calculatedMetric.type) + .forEach(stats => { + if (!calculatedMetric.condition || + calculatedMetric.condition(stats)) { + if (!resultName) { + resultName = (samplesMetric == 'timestamp') ? + '[' + accumulativeMetric + '/s]' : + '[' + accumulativeMetric + '/' + samplesMetric + ']'; + } + let result = this.calculateAccumulativeMetricOverSamples_( + stats.id, accumulativeMetric, samplesMetric); + if (result && transformation) { + result = transformation(result); + } + this.currentReport.setCalculatedMetric( + stats.id, accumulativeMetric, resultName, result); + } + }); + }); + }); + } + + // Calculates the rate "delta accumulative / delta samples" and returns it. If + // a rate cannot be calculated, such as the metric is missing in the current + // or previous report, undefined is returned. + calculateAccumulativeMetricOverSamples_( + id, accumulativeMetric, samplesMetric) { + if (!this.previousReport || !this.currentReport) { + return undefined; + } + const previousStats = this.previousReport.get(id); + const currentStats = this.currentReport.get(id); + if (!previousStats || !currentStats) { + return undefined; + } + const deltaTime = currentStats.timestamp - previousStats.timestamp; + if (deltaTime <= 0) { + return undefined; + } + // Try to convert whatever the values are to numbers. This gets around the + // fact that some types that are not supported by base::Value (e.g. uint32, + // int64, uint64 and double) are passed as strings. + const previousValue = Number(previousStats[accumulativeMetric]); + const currentValue = Number(currentStats[accumulativeMetric]); + if (typeof previousValue != 'number' || typeof currentValue != 'number') { + return undefined; + } + const previousSamples = Number(previousStats[samplesMetric]); + const currentSamples = Number(currentStats[samplesMetric]); + if (typeof previousSamples != 'number' || + typeof currentSamples != 'number') { + return undefined; + } + const deltaValue = currentValue - previousValue; + const deltaSamples = currentSamples - previousSamples; + return deltaValue / deltaSamples; + } +}
diff --git a/content/browser/resources/media/stats_table.js b/content/browser/resources/media/stats_table.js index d4744d8..ee1e22c21 100644 --- a/content/browser/resources/media/stats_table.js +++ b/content/browser/resources/media/stats_table.js
@@ -33,6 +33,9 @@ * the value. */ addStatsReport: function(peerConnectionElement, report) { + if (report.type == 'codec') { + return; + } var statsTable = this.ensureStatsTable_(peerConnectionElement, report); if (report.stats) { @@ -41,6 +44,15 @@ } }, + clearStatsLists: function(peerConnectionElement) { + let containerId = peerConnectionElement.id + '-table-container'; + let container = $(containerId); + if (container) { + peerConnectionElement.removeChild(container); + this.ensureStatsTableContainer_(peerConnectionElement); + } + }, + /** * Ensure the DIV container for the stats tables is created as a child of * |peerConnectionElement|.
diff --git a/content/browser/resources/media/webrtc_internals.js b/content/browser/resources/media/webrtc_internals.js index c4de346..be9a430 100644 --- a/content/browser/resources/media/webrtc_internals.js +++ b/content/browser/resources/media/webrtc_internals.js
@@ -4,6 +4,11 @@ var USER_MEDIA_TAB_ID = 'user-media-tab-id'; +const OPTION_GETSTATS_STANDARD = 'Standardized (promise-based) getStats() API'; +const OPTION_GETSTATS_LEGACY = + 'Legacy Non-Standard (callback-based) getStats() API'; +let currentGetStatsMethod = OPTION_GETSTATS_STANDARD; + var tabView = null; var ssrcInfoManager = null; var peerConnectionUpdateTable = null; @@ -14,6 +19,9 @@ /** A list of getUserMedia requests. */ var userMediaRequests = []; +/** Maps from id (see getPeerConnectionId) to StatsRatesCalculator. */ +statsRatesCalculatorById = new Map(); + /** A simple class to store the updates and stats data for a peer connection. */ var PeerConnectionRecord = (function() { /** @constructor */ @@ -46,6 +54,10 @@ this.record_.constraints = constraints; }, + resetStats: function() { + this.record_.stats = {}; + }, + /** * @param {string} dataSeriesId The TimelineDataSeries identifier. * @return {!TimelineDataSeries} @@ -87,6 +99,7 @@ // <include src="data_series.js"> // <include src="ssrc_info_manager.js"> // <include src="stats_graph_helper.js"> +// <include src="stats_rates_calculator.js"> // <include src="stats_table.js"> // <include src="peer_connection_update_table.js"> // <include src="dump_creator.js"> @@ -94,6 +107,7 @@ function initialize() { dumpCreator = new DumpCreator($('content-root')); + $('content-root').appendChild(createStatsSelectionOptionElements()); tabView = new TabView($('content-root')); ssrcInfoManager = new SsrcInfoManager(); peerConnectionUpdateTable = new PeerConnectionUpdateTable(); @@ -106,14 +120,61 @@ } document.addEventListener('DOMContentLoaded', initialize); +function createStatsSelectionOptionElements() { + const p = document.createElement('p'); -/** Sends a request to the browser to get peer connection statistics. */ + const selectElement = document.createElement('select'); + selectElement.onchange = () => { + currentGetStatsMethod = selectElement.value; + Object.keys(peerConnectionDataStore).forEach(id => { + const peerConnectionElement = $(id); + statsTable.clearStatsLists(peerConnectionElement); + removeStatsReportGraphs(peerConnectionElement); + peerConnectionDataStore[id].resetStats(); + }); + }; + + [OPTION_GETSTATS_STANDARD, OPTION_GETSTATS_LEGACY].forEach(option => { + const optionElement = document.createElement('option'); + optionElement.setAttribute('value', option); + optionElement.appendChild(document.createTextNode(option)); + selectElement.appendChild(optionElement); + }); + + selectElement.value = currentGetStatsMethod; + + p.appendChild(document.createTextNode('Read Stats From: ')); + p.appendChild(selectElement); + return p; +} + function requestStats() { - if (Object.keys(peerConnectionDataStore).length > 0) { - chrome.send('getAllStats'); + if (currentGetStatsMethod == OPTION_GETSTATS_STANDARD) { + requestStandardStats(); + } else if (currentGetStatsMethod == OPTION_GETSTATS_LEGACY) { + requestLegacyStats(); } } +/** + * Sends a request to the browser to get peer connection statistics from the + * standard getStats() API (promise-based). + */ +function requestStandardStats() { + if (Object.keys(peerConnectionDataStore).length > 0) { + chrome.send('getStandardStats'); + } +} + +/** + * Sends a request to the browser to get peer connection statistics from the + * legacy getStats() API (callback-based non-standard API with goog-stats). + */ +function requestLegacyStats() { + if (Object.keys(peerConnectionDataStore).length > 0) { + chrome.send('getLegacyStats'); + } +} /** * A helper function for getting a peer connection element id. @@ -249,9 +310,8 @@ requestStats(); } - /** - * Handles the report of stats. + * Handles the report of stats originating from the standard getStats() API. * * @param {!Object} data The object containing pid, lid, and reports, where * reports is an array of stats reports. Each report contains id, type, @@ -259,7 +319,43 @@ * which is an array of strings, whose even index entry is the name of the * stat, and the odd index entry is the value. */ -function addStats(data) { +function addStandardStats(data) { + if (currentGetStatsMethod != OPTION_GETSTATS_STANDARD) { + return; // Obsolete! + } + var peerConnectionElement = $(getPeerConnectionId(data)); + if (!peerConnectionElement) { + return; + } + const pcId = getPeerConnectionId(data); + let statsRatesCalculator = statsRatesCalculatorById.get(pcId); + if (!statsRatesCalculator) { + statsRatesCalculator = new StatsRatesCalculator(); + statsRatesCalculatorById.set(pcId, statsRatesCalculator); + } + const r = StatsReport.fromInternalsReportList(data.reports); + statsRatesCalculator.addStatsReport(r); + data.reports = statsRatesCalculator.currentReport.toInternalsReportList(); + for (var i = 0; i < data.reports.length; ++i) { + var report = data.reports[i]; + statsTable.addStatsReport(peerConnectionElement, report); + drawSingleReport(peerConnectionElement, report, false); + } +} + +/** + * Handles the report of stats originating from the legacy getStats() API. + * + * @param {!Object} data The object containing pid, lid, and reports, where + * reports is an array of stats reports. Each report contains id, type, + * and stats, where stats is the object containing timestamp and values, + * which is an array of strings, whose even index entry is the name of the + * stat, and the odd index entry is the value. + */ +function addLegacyStats(data) { + if (currentGetStatsMethod != OPTION_GETSTATS_LEGACY) { + return; // Obsolete! + } var peerConnectionElement = $(getPeerConnectionId(data)); if (!peerConnectionElement) { return; @@ -268,7 +364,7 @@ for (var i = 0; i < data.reports.length; ++i) { var report = data.reports[i]; statsTable.addStatsReport(peerConnectionElement, report); - drawSingleReport(peerConnectionElement, report); + drawSingleReport(peerConnectionElement, report, true); } }
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index c4ab892..35ad6ce3 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -786,7 +786,7 @@ const GURL& source_url) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // NOTE: This differs slightly from - // RenderFrameHostImpl::OnDidAddMessageToConsole, which also asks the + // RenderFrameHostImpl::DidAddMessageToConsole, which also asks the // content embedder whether to classify the message as a builtin component. // This is called on the IO thread, though, so we can't easily get a // BrowserContext and call ContentBrowserClient::IsBuiltinComponent().
diff --git a/content/browser/web_contents/web_contents_impl_unittest.cc b/content/browser/web_contents/web_contents_impl_unittest.cc index c1bfa288..5e058fe3 100644 --- a/content/browser/web_contents/web_contents_impl_unittest.cc +++ b/content/browser/web_contents/web_contents_impl_unittest.cc
@@ -531,7 +531,6 @@ auto new_site_navigation = NavigationSimulator::CreateBrowserInitiated(url2, contents()); new_site_navigation->ReadyToCommit(); - int entry_id = controller().GetPendingEntry()->GetUniqueID(); EXPECT_TRUE(contents()->CrossProcessNavigationPending()); EXPECT_EQ(url, contents()->GetLastCommittedURL()); EXPECT_EQ(url2, contents()->GetVisibleURL()); @@ -542,9 +541,7 @@ &pending_rvh_delete_count); // DidNavigate from the pending page. - contents()->TestDidNavigateWithSequenceNumber( - pending_rfh, entry_id, true, url2, Referrer(), ui::PAGE_TRANSITION_TYPED, - false, 1, 1); + new_site_navigation->Commit(); SiteInstance* instance2 = contents()->GetSiteInstance(); // Keep the number of active frames in pending_rfh's SiteInstance @@ -560,7 +557,7 @@ EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); // We keep a proxy for the original RFH's SiteInstance. EXPECT_TRUE(contents()->GetRenderManagerForTesting()->GetRenderFrameProxyHost( - orig_rfh->GetSiteInstance())); + instance1)); EXPECT_EQ(orig_rvh_delete_count, 0); // Going back should switch SiteInstances again. The first SiteInstance is @@ -569,24 +566,20 @@ auto back_navigation = NavigationSimulator::CreateHistoryNavigation(-1, contents()); back_navigation->ReadyToCommit(); - entry_id = controller().GetPendingEntry()->GetUniqueID(); TestRenderFrameHost* goback_rfh = contents()->GetPendingMainFrame(); EXPECT_TRUE(contents()->CrossProcessNavigationPending()); // DidNavigate from the back action. - contents()->TestDidNavigateWithSequenceNumber( - goback_rfh, entry_id, false, url, Referrer(), ui::PAGE_TRANSITION_TYPED, - false, 2, 0); + back_navigation->Commit(); EXPECT_FALSE(contents()->CrossProcessNavigationPending()); EXPECT_EQ(goback_rfh, main_test_rfh()); EXPECT_EQ(url, contents()->GetLastCommittedURL()); EXPECT_EQ(url, contents()->GetVisibleURL()); EXPECT_EQ(instance1, contents()->GetSiteInstance()); // There should be a proxy for the pending RFH SiteInstance. - EXPECT_TRUE(contents()->GetRenderManagerForTesting()-> - GetRenderFrameProxyHost(pending_rfh->GetSiteInstance())); + EXPECT_TRUE(contents()->GetRenderManagerForTesting()->GetRenderFrameProxyHost( + instance2)); EXPECT_EQ(pending_rvh_delete_count, 0); - pending_rfh->OnSwappedOut(); // Close contents and ensure RVHs are deleted. DeleteContents(); @@ -657,35 +650,27 @@ // Navigate first contents to a new site. const GURL url2a("http://www.yahoo.com"); - controller().LoadURL(url2a, Referrer(), ui::PAGE_TRANSITION_LINK, - std::string()); - int entry_id = controller().GetPendingEntry()->GetUniqueID(); - contents()->GetMainFrame()->PrepareForCommit(); - TestRenderFrameHost* pending_rfh_a = contents()->GetPendingMainFrame(); - if (AreAllSitesIsolatedForTesting()) - EXPECT_TRUE(contents()->CrossProcessNavigationPending()); - contents()->TestDidNavigate(pending_rfh_a, entry_id, true, url2a, - ui::PAGE_TRANSITION_LINK); + auto navigation1 = + NavigationSimulator::CreateBrowserInitiated(url2a, contents()); + navigation1->SetTransition(ui::PAGE_TRANSITION_LINK); + navigation1->ReadyToCommit(); + EXPECT_TRUE(contents()->CrossProcessNavigationPending()); + navigation1->Commit(); SiteInstance* instance2a = contents()->GetSiteInstance(); EXPECT_NE(instance1, instance2a); // Navigate second contents to the same site as the first tab. - const GURL url2b("http://mail.yahoo.com"); - contents2->GetController().LoadURL(url2b, Referrer(), - ui::PAGE_TRANSITION_LINK, std::string()); - entry_id = contents2->GetController().GetPendingEntry()->GetUniqueID(); - TestRenderFrameHost* rfh2 = contents2->GetMainFrame(); - rfh2->PrepareForCommit(); - TestRenderFrameHost* pending_rfh_b = contents2->GetPendingMainFrame(); - EXPECT_NE(nullptr, pending_rfh_b); - if (AreAllSitesIsolatedForTesting()) - EXPECT_TRUE(contents2->CrossProcessNavigationPending()); + const GURL url2b("http://www.yahoo.com/foo"); + auto navigation2 = + NavigationSimulator::CreateBrowserInitiated(url2b, contents2.get()); + navigation2->SetTransition(ui::PAGE_TRANSITION_LINK); + navigation2->ReadyToCommit(); + EXPECT_TRUE(contents2->CrossProcessNavigationPending()); // NOTE(creis): We used to be in danger of showing a crash page here if the // second contents hadn't navigated somewhere first (bug 1145430). That case // is now covered by the CrossSiteBoundariesAfterCrash test. - contents2->TestDidNavigate(pending_rfh_b, entry_id, true, url2b, - ui::PAGE_TRANSITION_LINK); + navigation2->Commit(); SiteInstance* instance2b = contents2->GetSiteInstance(); EXPECT_NE(instance1, instance2b);
diff --git a/content/browser/webrtc/webrtc_internals.cc b/content/browser/webrtc/webrtc_internals.cc index 2b3666be..089eff19 100644 --- a/content/browser/webrtc/webrtc_internals.cc +++ b/content/browser/webrtc/webrtc_internals.cc
@@ -249,8 +249,9 @@ EnsureLogList(record)->Append(std::move(log_entry)); } -void WebRTCInternals::OnAddStats(base::ProcessId pid, int lid, - const base::ListValue& value) { +void WebRTCInternals::OnAddStandardStats(base::ProcessId pid, + int lid, + const base::ListValue& value) { if (!observers_.might_have_observers()) return; @@ -260,7 +261,22 @@ dict->SetKey("reports", value.Clone()); - SendUpdate("addStats", std::move(dict)); + SendUpdate("addStandardStats", std::move(dict)); +} + +void WebRTCInternals::OnAddLegacyStats(base::ProcessId pid, + int lid, + const base::ListValue& value) { + if (!observers_.might_have_observers()) + return; + + auto dict = std::make_unique<base::DictionaryValue>(); + dict->SetInteger("pid", static_cast<int>(pid)); + dict->SetInteger("lid", lid); + + dict->SetKey("reports", value.Clone()); + + SendUpdate("addLegacyStats", std::move(dict)); } void WebRTCInternals::OnGetUserMedia(int rid,
diff --git a/content/browser/webrtc/webrtc_internals.h b/content/browser/webrtc/webrtc_internals.h index bf6256af..3098a67 100644 --- a/content/browser/webrtc/webrtc_internals.h +++ b/content/browser/webrtc/webrtc_internals.h
@@ -80,10 +80,16 @@ const std::string& type, const std::string& value); - // This method is called when results from PeerConnectionInterface::GetStats - // are available. |pid| is the renderer process id, |lid| is the renderer - // local id, |value| is the list of stats reports. - void OnAddStats(base::ProcessId pid, int lid, const base::ListValue& value); + // These methods are called when results from + // PeerConnectionInterface::GetStats (legacy or standard API) are available. + // |pid| is the renderer process id, |lid| is the renderer local id, |value| + // is the list of stats reports. + void OnAddStandardStats(base::ProcessId pid, + int lid, + const base::ListValue& value); + void OnAddLegacyStats(base::ProcessId pid, + int lid, + const base::ListValue& value); // This method is called when getUserMedia is called. |render_process_id| is // the id of the render process (not OS pid), which is needed because we might
diff --git a/content/browser/webrtc/webrtc_internals_browsertest.cc b/content/browser/webrtc/webrtc_internals_browsertest.cc index 2cd0a8d7..a8d2d8ae 100644 --- a/content/browser/webrtc/webrtc_internals_browsertest.cc +++ b/content/browser/webrtc/webrtc_internals_browsertest.cc
@@ -327,11 +327,13 @@ pc.stats_[id][iter->first].push_back(iter->second); } std::stringstream ss; - ss << "{pid:" << pc.pid_ << ", lid:" << pc.lid_ << "," - "reports:[" << "{id:'" << id << "', type:'" << type << "', " - "stats:" << stats.GetString() << "}]}"; - - ASSERT_TRUE(ExecuteJavascript("addStats(" + ss.str() + ")")); + ss << "(() => {\n"; + ss << " currentGetStatsMethod = OPTION_GETSTATS_LEGACY;\n"; + ss << " addLegacyStats({pid:" << pc.pid_ << ", lid:" << pc.lid_ + << ", reports:[{id:'" << id << "', type:'" << type + << "', stats:" << stats.GetString() << "}]});\n"; + ss << "})()"; + ASSERT_TRUE(ExecuteJavascript(ss.str())); VerifyStatsTable(pc, entry); }
diff --git a/content/browser/webrtc/webrtc_internals_message_handler.cc b/content/browser/webrtc/webrtc_internals_message_handler.cc index 80580be3..62fa8da 100644 --- a/content/browser/webrtc/webrtc_internals_message_handler.cc +++ b/content/browser/webrtc/webrtc_internals_message_handler.cc
@@ -33,8 +33,12 @@ void WebRTCInternalsMessageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "getAllStats", - base::BindRepeating(&WebRTCInternalsMessageHandler::OnGetAllStats, + "getStandardStats", + base::BindRepeating(&WebRTCInternalsMessageHandler::OnGetStandardStats, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "getLegacyStats", + base::BindRepeating(&WebRTCInternalsMessageHandler::OnGetLegacyStats, base::Unretained(this))); web_ui()->RegisterMessageCallback( @@ -84,12 +88,21 @@ return host; } -void WebRTCInternalsMessageHandler::OnGetAllStats( +void WebRTCInternalsMessageHandler::OnGetStandardStats( + const base::ListValue* /* unused_list */) { + for (RenderProcessHost::iterator i( + content::RenderProcessHost::AllHostsIterator()); + !i.IsAtEnd(); i.Advance()) { + i.GetCurrentValue()->Send(new PeerConnectionTracker_GetStandardStats()); + } +} + +void WebRTCInternalsMessageHandler::OnGetLegacyStats( const base::ListValue* /* unused_list */) { for (RenderProcessHost::iterator i( content::RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { - i.GetCurrentValue()->Send(new PeerConnectionTracker_GetAllStats()); + i.GetCurrentValue()->Send(new PeerConnectionTracker_GetLegacyStats()); } }
diff --git a/content/browser/webrtc/webrtc_internals_message_handler.h b/content/browser/webrtc/webrtc_internals_message_handler.h index b353617..4e5943d9 100644 --- a/content/browser/webrtc/webrtc_internals_message_handler.h +++ b/content/browser/webrtc/webrtc_internals_message_handler.h
@@ -43,7 +43,8 @@ RenderFrameHost* GetWebRTCInternalsHost() const; // Javascript message handler. - void OnGetAllStats(const base::ListValue* list); + void OnGetStandardStats(const base::ListValue* list); + void OnGetLegacyStats(const base::ListValue* list); void OnSetAudioDebugRecordingsEnabled(bool enable, const base::ListValue* list); void OnSetEventLogRecordingsEnabled(bool enable, const base::ListValue* list);
diff --git a/content/browser/webrtc/webrtc_internals_unittest.cc b/content/browser/webrtc/webrtc_internals_unittest.cc index ac7ffcc..6fb9ab0 100644 --- a/content/browser/webrtc/webrtc_internals_unittest.cc +++ b/content/browser/webrtc/webrtc_internals_unittest.cc
@@ -407,7 +407,7 @@ base::RunLoop().RunUntilIdle(); } -TEST_F(WebRtcInternalsTest, OnAddStats) { +TEST_F(WebRtcInternalsTest, OnAddStandardStats) { const int rid = 0, pid = 1, lid = 2; base::RunLoop loop; MockWebRtcInternalsProxy observer(&loop); @@ -419,11 +419,40 @@ base::ListValue list; list.AppendString("xxx"); list.AppendString("yyy"); - webrtc_internals.OnAddStats(pid, lid, list); + webrtc_internals.OnAddStandardStats(pid, lid, list); loop.Run(); - EXPECT_EQ("addStats", observer.command()); + EXPECT_EQ("addStandardStats", observer.command()); + ASSERT_TRUE(observer.value()); + + base::DictionaryValue* dict = nullptr; + EXPECT_TRUE(observer.value()->GetAsDictionary(&dict)); + + VerifyInt(dict, "pid", pid); + VerifyInt(dict, "lid", lid); + VerifyList(dict, "reports", list); + + base::RunLoop().RunUntilIdle(); +} + +TEST_F(WebRtcInternalsTest, OnAddLegacyStats) { + const int rid = 0, pid = 1, lid = 2; + base::RunLoop loop; + MockWebRtcInternalsProxy observer(&loop); + WebRTCInternalsForTest webrtc_internals; + webrtc_internals.AddObserver(&observer); + webrtc_internals.OnAddPeerConnection(rid, pid, lid, kUrl, kRtcConfiguration, + kContraints); + + base::ListValue list; + list.AppendString("xxx"); + list.AppendString("yyy"); + webrtc_internals.OnAddLegacyStats(pid, lid, list); + + loop.Run(); + + EXPECT_EQ("addLegacyStats", observer.command()); ASSERT_TRUE(observer.value()); base::DictionaryValue* dict = nullptr;
diff --git a/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc b/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc index 8fc71d6..77c35f1 100644 --- a/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc +++ b/content/browser/webrtc/webrtc_video_capture_shared_device_browsertest.cc
@@ -16,8 +16,6 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/video_capture/public/cpp/mock_receiver.h" #include "services/video_capture/public/mojom/constants.mojom.h" -#include "services/video_capture/public/mojom/device.mojom.h" -#include "services/video_capture/public/mojom/device_factory.mojom.h" #include "services/video_capture/public/mojom/device_factory_provider.mojom.h" #include "services/video_capture/public/mojom/video_source.mojom.h" #include "services/video_capture/public/mojom/video_source_provider.mojom.h" @@ -33,26 +31,6 @@ namespace { -enum class ServiceApi { kSingleClient, kMultiClient }; - -struct TestParams { - ServiceApi api_to_use; - media::VideoCaptureBufferType buffer_type_to_request; - - media::mojom::VideoBufferHandle::Tag GetExpectedBufferHandleTag() const { - switch (buffer_type_to_request) { - case media::VideoCaptureBufferType::kSharedMemory: - return media::mojom::VideoBufferHandle::Tag::SHARED_BUFFER_HANDLE; - case media::VideoCaptureBufferType::kSharedMemoryViaRawFileDescriptor: - return media::mojom::VideoBufferHandle::Tag:: - SHARED_MEMORY_VIA_RAW_FILE_DESCRIPTOR; - case media::VideoCaptureBufferType::kMailboxHolder: - NOTREACHED(); - return media::mojom::VideoBufferHandle::Tag::SHARED_BUFFER_HANDLE; - } - } -}; - static const char kVideoCaptureHtmlFile[] = "/media/video_capture_test.html"; static const char kStartVideoCaptureAndVerify[] = "startVideoCaptureAndVerifySize(%d, %d)"; @@ -65,9 +43,7 @@ // opens the device from clients. One client is the test calling into the // video capture service directly. The second client is the Browser, which the // test exercises through JavaScript. -class WebRtcVideoCaptureSharedDeviceBrowserTest - : public ContentBrowserTest, - public testing::WithParamInterface<TestParams> { +class WebRtcVideoCaptureSharedDeviceBrowserTest : public ContentBrowserTest { public: WebRtcVideoCaptureSharedDeviceBrowserTest() : weak_factory_(this) { scoped_feature_list_.InitAndEnableFeature(features::kMojoVideoCapture); @@ -75,27 +51,18 @@ ~WebRtcVideoCaptureSharedDeviceBrowserTest() override {} - void OpenDeviceViaService(base::OnceClosure done_cb) { + void OpenDeviceViaService( + media::VideoCaptureBufferType buffer_type_to_request, + base::OnceClosure done_cb) { connector_->BindInterface(video_capture::mojom::kServiceName, &device_factory_provider_); - switch (GetParam().api_to_use) { - case ServiceApi::kSingleClient: - device_factory_provider_->ConnectToDeviceFactory( - mojo::MakeRequest(&device_factory_)); - device_factory_->GetDeviceInfos(base::BindOnce( - &WebRtcVideoCaptureSharedDeviceBrowserTest::OnDeviceInfosReceived, - weak_factory_.GetWeakPtr(), GetParam().buffer_type_to_request, - std::move(done_cb))); - break; - case ServiceApi::kMultiClient: - device_factory_provider_->ConnectToVideoSourceProvider( - mojo::MakeRequest(&video_source_provider_)); - video_source_provider_->GetSourceInfos(base::BindOnce( - &WebRtcVideoCaptureSharedDeviceBrowserTest::OnSourceInfosReceived, - weak_factory_.GetWeakPtr(), GetParam().buffer_type_to_request, - std::move(done_cb))); - break; - } + device_factory_provider_->ConnectToVideoSourceProvider( + mojo::MakeRequest(&video_source_provider_)); + + video_source_provider_->GetSourceInfos(base::BindOnce( + &WebRtcVideoCaptureSharedDeviceBrowserTest::OnSourceInfosReceived, + weak_factory_.GetWeakPtr(), buffer_type_to_request, + std::move(done_cb))); } void OpenDeviceInRendererAndWaitForPlaying() { @@ -145,38 +112,6 @@ std::unique_ptr<video_capture::MockReceiver> mock_receiver_; private: - void OnDeviceInfosReceived( - media::VideoCaptureBufferType buffer_type_to_request, - base::OnceClosure done_cb, - const std::vector<media::VideoCaptureDeviceInfo>& infos) { - ASSERT_FALSE(infos.empty()); - device_factory_->CreateDevice( - infos[0].descriptor.device_id, mojo::MakeRequest(&device_), - base::BindOnce( - &WebRtcVideoCaptureSharedDeviceBrowserTest::OnCreateDeviceCallback, - weak_factory_.GetWeakPtr(), infos, buffer_type_to_request, - std::move(done_cb))); - } - - void OnCreateDeviceCallback( - const std::vector<media::VideoCaptureDeviceInfo>& infos, - media::VideoCaptureBufferType buffer_type_to_request, - base::OnceClosure done_cb, - video_capture::mojom::DeviceAccessResultCode result_code) { - ASSERT_EQ(video_capture::mojom::DeviceAccessResultCode::SUCCESS, - result_code); - - media::VideoCaptureParams requestable_settings; - ASSERT_FALSE(infos[0].supported_formats.empty()); - requestable_settings.requested_format = infos[0].supported_formats[0]; - requestable_settings.requested_format.frame_size = kVideoSize; - requestable_settings.buffer_type = buffer_type_to_request; - - device_->Start(requestable_settings, std::move(receiver_proxy_)); - - std::move(done_cb).Run(); - } - void OnSourceInfosReceived( media::VideoCaptureBufferType buffer_type_to_request, base::OnceClosure done_cb, @@ -213,16 +148,9 @@ base::test::ScopedFeatureList scoped_feature_list_; video_capture::mojom::DeviceFactoryProviderPtr device_factory_provider_; - - // For single-client API case only - video_capture::mojom::DeviceFactoryPtr device_factory_; - video_capture::mojom::DevicePtr device_; - - // For multi-client API case only video_capture::mojom::VideoSourceProviderPtr video_source_provider_; video_capture::mojom::VideoSourcePtr video_source_; video_capture::mojom::PushVideoStreamSubscriptionPtr subscription_; - video_capture::mojom::ReceiverPtr receiver_proxy_; base::WeakPtrFactory<WebRtcVideoCaptureSharedDeviceBrowserTest> weak_factory_; @@ -232,18 +160,18 @@ // Tests that a single fake video capture device can be opened via JavaScript // by the Renderer while it is already in use by a direct client of the // video capture service. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( WebRtcVideoCaptureSharedDeviceBrowserTest, ReceiveFrameInRendererWhileDeviceAlreadyInUseViaDirectServiceClient) { Initialize(); base::RunLoop receive_frame_from_service_wait_loop; - auto expected_buffer_handle_tag = GetParam().GetExpectedBufferHandleTag(); ON_CALL(*mock_receiver_, DoOnNewBuffer(_, _)) .WillByDefault(Invoke( - [expected_buffer_handle_tag]( - int32_t, media::mojom::VideoBufferHandlePtr* buffer_handle) { - ASSERT_EQ(expected_buffer_handle_tag, (*buffer_handle)->which()); + [](int32_t, media::mojom::VideoBufferHandlePtr* buffer_handle) { + ASSERT_EQ( + media::mojom::VideoBufferHandle::Tag::SHARED_BUFFER_HANDLE, + (*buffer_handle)->which()); })); EXPECT_CALL(*mock_receiver_, DoOnFrameReadyInBuffer(_, _, _, _)) .WillOnce(InvokeWithoutArgs([&receive_frame_from_service_wait_loop]() { @@ -252,7 +180,43 @@ .WillRepeatedly(Return()); base::RunLoop open_device_via_service_run_loop; - OpenDeviceViaService(open_device_via_service_run_loop.QuitClosure()); + OpenDeviceViaService(media::VideoCaptureBufferType::kSharedMemory, + open_device_via_service_run_loop.QuitClosure()); + open_device_via_service_run_loop.Run(); + + OpenDeviceInRendererAndWaitForPlaying(); + + receive_frame_from_service_wait_loop.Run(); +} + +#if defined(OS_LINUX) + +// Tests that a single fake video capture device can be opened via JavaScript +// by the Renderer while it is already in use by a direct client of the +// video capture service that requested to get buffers as raw file handles. +IN_PROC_BROWSER_TEST_F( + WebRtcVideoCaptureSharedDeviceBrowserTest, + ReceiveFrameInRendererWhileDeviceAlreadyInUseUsingRawFileHandleBuffers) { + Initialize(); + + base::RunLoop receive_frame_from_service_wait_loop; + ON_CALL(*mock_receiver_, DoOnNewBuffer(_, _)) + .WillByDefault(Invoke( + [](int32_t, media::mojom::VideoBufferHandlePtr* buffer_handle) { + ASSERT_EQ(media::mojom::VideoBufferHandle::Tag:: + SHARED_MEMORY_VIA_RAW_FILE_DESCRIPTOR, + (*buffer_handle)->which()); + })); + EXPECT_CALL(*mock_receiver_, DoOnFrameReadyInBuffer(_, _, _, _)) + .WillOnce(InvokeWithoutArgs([&receive_frame_from_service_wait_loop]() { + receive_frame_from_service_wait_loop.Quit(); + })) + .WillRepeatedly(Return()); + + base::RunLoop open_device_via_service_run_loop; + OpenDeviceViaService( + media::VideoCaptureBufferType::kSharedMemoryViaRawFileDescriptor, + open_device_via_service_run_loop.QuitClosure()); open_device_via_service_run_loop.Run(); OpenDeviceInRendererAndWaitForPlaying(); @@ -261,20 +225,22 @@ } // Tests that a single fake video capture device can be opened by a direct -// client of the video capture service while it is already in use via JavaScript -// by the Renderer. -IN_PROC_BROWSER_TEST_P( +// client of the video capture service that requests to get buffers as raw +// file handles while it is already in use via JavaScript by the Renderer. +IN_PROC_BROWSER_TEST_F( WebRtcVideoCaptureSharedDeviceBrowserTest, - ReceiveFrameViaDirectServiceClientWhileDeviceAlreadyInUseViaRenderer) { + ReceiveFrameFromServiceViaRawFileHandlesWhileDeviceAlreadyInUseByRenderer) { Initialize(); + OpenDeviceInRendererAndWaitForPlaying(); + base::RunLoop receive_frame_from_service_wait_loop; - auto expected_buffer_handle_tag = GetParam().GetExpectedBufferHandleTag(); ON_CALL(*mock_receiver_, DoOnNewBuffer(_, _)) .WillByDefault(Invoke( - [expected_buffer_handle_tag]( - int32_t, media::mojom::VideoBufferHandlePtr* buffer_handle) { - ASSERT_EQ(expected_buffer_handle_tag, (*buffer_handle)->which()); + [](int32_t, media::mojom::VideoBufferHandlePtr* buffer_handle) { + ASSERT_EQ(media::mojom::VideoBufferHandle::Tag:: + SHARED_MEMORY_VIA_RAW_FILE_DESCRIPTOR, + (*buffer_handle)->which()); })); EXPECT_CALL(*mock_receiver_, DoOnFrameReadyInBuffer(_, _, _, _)) .WillOnce(InvokeWithoutArgs([&receive_frame_from_service_wait_loop]() { @@ -282,34 +248,15 @@ })) .WillRepeatedly(Return()); - OpenDeviceInRendererAndWaitForPlaying(); - base::RunLoop open_device_via_service_run_loop; - OpenDeviceViaService(open_device_via_service_run_loop.QuitClosure()); + OpenDeviceViaService( + media::VideoCaptureBufferType::kSharedMemoryViaRawFileDescriptor, + open_device_via_service_run_loop.QuitClosure()); open_device_via_service_run_loop.Run(); receive_frame_from_service_wait_loop.Run(); } -INSTANTIATE_TEST_SUITE_P( - , - WebRtcVideoCaptureSharedDeviceBrowserTest, - ::testing::Values( - TestParams{ServiceApi::kSingleClient, - media::VideoCaptureBufferType::kSharedMemory}, - TestParams { - ServiceApi::kMultiClient, media::VideoCaptureBufferType::kSharedMemory - } -#if defined(OS_LINUX) - , - TestParams{ - ServiceApi::kSingleClient, - media::VideoCaptureBufferType::kSharedMemoryViaRawFileDescriptor}, - TestParams { - ServiceApi::kMultiClient, - media::VideoCaptureBufferType::kSharedMemoryViaRawFileDescriptor - } #endif // defined(OS_LINUX) - )); } // namespace content
diff --git a/content/browser/worker_host/worker_script_fetch_initiator.cc b/content/browser/worker_host/worker_script_fetch_initiator.cc index 33693a1..58e2c08 100644 --- a/content/browser/worker_host/worker_script_fetch_initiator.cc +++ b/content/browser/worker_host/worker_script_fetch_initiator.cc
@@ -40,7 +40,7 @@ #include "services/network/loader_util.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/shared_url_loader_factory.h" -#include "third_party/blink/public/common/loader//url_loader_factory_bundle.h" +#include "third_party/blink/public/common/loader/url_loader_factory_bundle.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom.h" #include "url/origin.h"
diff --git a/content/common/frame.mojom b/content/common/frame.mojom index 7deab3e..88471bc4 100644 --- a/content/common/frame.mojom +++ b/content/common/frame.mojom
@@ -21,6 +21,7 @@ import "services/viz/public/interfaces/compositing/surface_id.mojom"; import "third_party/blink/public/mojom/blob/blob_url_store.mojom"; import "third_party/blink/public/mojom/commit_result/commit_result.mojom"; +import "third_party/blink/public/mojom/devtools/console_message.mojom"; import "third_party/blink/public/mojom/feature_policy/feature_policy.mojom"; import "third_party/blink/public/mojom/frame/lifecycle.mojom"; import "third_party/blink/public/mojom/frame/navigation_initiator.mojom"; @@ -473,4 +474,12 @@ // of the individual bits. // TODO(altimin): Move into a separate scheduling interface. UpdateActiveSchedulerTrackedFeatures(uint64 features_mask); + + // Blink and JavaScript error messages to log to the console or debugger UI. + DidAddMessageToConsole( + blink.mojom.ConsoleMessageLevel log_level, + mojo_base.mojom.BigString16 msg, + int32 line_number, + mojo_base.mojom.String16 source_id); + };
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 8673d658..aa3530d 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -1098,14 +1098,6 @@ // ----------------------------------------------------------------------------- // Messages sent from the renderer to the browser. -// Blink and JavaScript error messages to log to the console -// or debugger UI. -IPC_MESSAGE_ROUTED4(FrameHostMsg_DidAddMessageToConsole, - int32_t, /* log level */ - base::string16, /* msg */ - int32_t, /* line number */ - base::string16 /* source id */) - // Sent by the renderer when a child frame is created in the renderer. // // Each of these messages will have a corresponding FrameHostMsg_Detach message
diff --git a/content/common/media/peer_connection_tracker_messages.h b/content/common/media/peer_connection_tracker_messages.h index 6d1455f4..231725e 100644 --- a/content/common/media/peer_connection_tracker_messages.h +++ b/content/common/media/peer_connection_tracker_messages.h
@@ -29,12 +29,16 @@ // Messages sent from PeerConnectionTracker to PeerConnectionTrackerHost. IPC_MESSAGE_CONTROL1(PeerConnectionTrackerHost_AddPeerConnection, PeerConnectionInfo /* info */) -IPC_MESSAGE_CONTROL2(PeerConnectionTrackerHost_AddStats, +IPC_MESSAGE_CONTROL2(PeerConnectionTrackerHost_AddStandardStats, + int /* lid */, + base::ListValue /* value */) +IPC_MESSAGE_CONTROL2(PeerConnectionTrackerHost_AddLegacyStats, int /* lid */, base::ListValue /* value */) // Messages sent to PeerConnectionTracker. -IPC_MESSAGE_CONTROL0(PeerConnectionTracker_GetAllStats) +IPC_MESSAGE_CONTROL0(PeerConnectionTracker_GetStandardStats) +IPC_MESSAGE_CONTROL0(PeerConnectionTracker_GetLegacyStats) IPC_MESSAGE_CONTROL0(PeerConnectionTracker_OnSuspend) IPC_MESSAGE_CONTROL2(PeerConnectionTracker_StartEventLog, int /* peer_connection_local_id */,
diff --git a/content/public/browser/browser_thread.h b/content/public/browser/browser_thread.h index 247c7405..319cc88 100644 --- a/content/public/browser/browser_thread.h +++ b/content/public/browser/browser_thread.h
@@ -103,6 +103,12 @@ // // TODO(crbug.com/887407): Replace callsites with PostTaskWithTraits and // appropriate traits (TBD). + // + // DEPRECATED(carlscab): This method is deprecated and will go away soon, + // consider posting the task with priority BEST_EFFORT. For example: + // base::PostTaskWithTraits( + // FROM_HERE, {content::BrowserThread::UI, base::TaskPriority::BEST_EFFORT}, + // base::BindOnce(...)); static void PostAfterStartupTask( const base::Location& from_here, const scoped_refptr<base::TaskRunner>& task_runner,
diff --git a/content/public/common/common_param_traits_macros.h b/content/public/common/common_param_traits_macros.h index 24bded9..247b7f0 100644 --- a/content/public/common/common_param_traits_macros.h +++ b/content/public/common/common_param_traits_macros.h
@@ -123,7 +123,6 @@ IPC_STRUCT_TRAITS_MEMBER(allow_scripts_to_close_windows) IPC_STRUCT_TRAITS_MEMBER(remote_fonts_enabled) IPC_STRUCT_TRAITS_MEMBER(javascript_can_access_clipboard) - IPC_STRUCT_TRAITS_MEMBER(xslt_enabled) IPC_STRUCT_TRAITS_MEMBER(xss_auditor_enabled) IPC_STRUCT_TRAITS_MEMBER(dns_prefetching_enabled) IPC_STRUCT_TRAITS_MEMBER(data_saver_enabled)
diff --git a/content/public/common/web_preferences.cc b/content/public/common/web_preferences.cc index 1822036..1691690d 100644 --- a/content/public/common/web_preferences.cc +++ b/content/public/common/web_preferences.cc
@@ -78,7 +78,6 @@ allow_scripts_to_close_windows(false), remote_fonts_enabled(true), javascript_can_access_clipboard(false), - xslt_enabled(true), xss_auditor_enabled(true), dns_prefetching_enabled(true), data_saver_enabled(false),
diff --git a/content/public/common/web_preferences.h b/content/public/common/web_preferences.h index a83015f3..63f9611 100644 --- a/content/public/common/web_preferences.h +++ b/content/public/common/web_preferences.h
@@ -93,7 +93,6 @@ bool allow_scripts_to_close_windows; bool remote_fonts_enabled; bool javascript_can_access_clipboard; - bool xslt_enabled; bool xss_auditor_enabled; // We don't use dns_prefetching_enabled to disable DNS prefetching. Instead, // we disable the feature at a lower layer so that we catch non-WebKit uses
diff --git a/content/public/renderer/render_view_observer.h b/content/public/renderer/render_view_observer.h index 3eb08a310..4119177 100644 --- a/content/public/renderer/render_view_observer.h +++ b/content/public/renderer/render_view_observer.h
@@ -11,12 +11,9 @@ #include "ipc/ipc_listener.h" #include "ipc/ipc_sender.h" -class GURL; - namespace blink { class WebGestureEvent; class WebLocalFrame; -struct WebURLError; } namespace content { @@ -35,10 +32,6 @@ virtual void OnDestruct() = 0; // These match the WebKit API notifications - virtual void DidFailProvisionalLoad(blink::WebLocalFrame* frame, - const blink::WebURLError& error) {} - virtual void DidCommitProvisionalLoad(blink::WebLocalFrame* frame, - bool is_new_navigation) {} virtual void DidClearWindowObject(blink::WebLocalFrame* frame) {} virtual void DidCommitCompositorFrame() {} virtual void DidUpdateMainFrameLayout() {} @@ -46,9 +39,6 @@ // These match the RenderView methods. virtual void DidHandleGestureEvent(const blink::WebGestureEvent& event) {} - // These match incoming IPCs. - virtual void Navigate(const GURL& url) {} - virtual void OnZoomLevelChanged() {} // IPC::Listener implementation.
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index 758b43d..b4a6c7f3 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -1796,6 +1796,8 @@ ->GetCookieManager(mojo::MakeRequest(&cookie_manager)); net::CookieOptions options; options.set_include_httponly(); + options.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); std::unique_ptr<net::CanonicalCookie> cc( net::CanonicalCookie::Create(url, value, base::Time::Now(), options)); DCHECK(cc.get());
diff --git a/content/renderer/java/gin_java_bridge_object.cc b/content/renderer/java/gin_java_bridge_object.cc index 03af04d..6afc798 100644 --- a/content/renderer/java/gin_java_bridge_object.cc +++ b/content/renderer/java/gin_java_bridge_object.cc
@@ -38,7 +38,9 @@ if (controller.IsEmpty()) return NULL; - global->Set(gin::StringToV8(isolate, object_name), controller.ToV8()); + global->Set(context, gin::StringToV8(isolate, object_name), controller.ToV8()) + .Check(); + return object; }
diff --git a/content/renderer/media/webrtc/peer_connection_tracker.cc b/content/renderer/media/webrtc/peer_connection_tracker.cc index f2f2b0b1..c21bed75 100644 --- a/content/renderer/media/webrtc/peer_connection_tracker.cc +++ b/content/renderer/media/webrtc/peer_connection_tracker.cc
@@ -433,10 +433,16 @@ return result; } -class InternalStatsObserver : public webrtc::StatsObserver { +// chrome://webrtc-internals displays stats and stats graphs. The call path +// involves thread and process hops (IPC). This is the webrtc::StatsObserver +// that is used when webrtc-internals wants legacy stats. It starts in +// webrtc_internals.js performing requestLegacyStats and the result gets +// asynchronously delivered to webrtc_internals.js at addLegacyStats. +class InternalLegacyStatsObserver : public webrtc::StatsObserver { public: - InternalStatsObserver(int lid, - scoped_refptr<base::SingleThreadTaskRunner> main_thread) + InternalLegacyStatsObserver( + int lid, + scoped_refptr<base::SingleThreadTaskRunner> main_thread) : lid_(lid), main_thread_(std::move(main_thread)) {} void OnComplete(const StatsReports& reports) override { @@ -450,13 +456,14 @@ if (!list->empty()) { main_thread_->PostTask( - FROM_HERE, base::BindOnce(&InternalStatsObserver::OnCompleteImpl, - std::move(list), lid_)); + FROM_HERE, + base::BindOnce(&InternalLegacyStatsObserver::OnCompleteImpl, + std::move(list), lid_)); } } protected: - ~InternalStatsObserver() override { + ~InternalLegacyStatsObserver() override { // Will be destructed on libjingle's signaling thread. // The signaling thread is where libjingle's objects live and from where // libjingle makes callbacks. This may or may not be the same thread as @@ -469,7 +476,107 @@ static void OnCompleteImpl(std::unique_ptr<base::ListValue> list, int lid) { DCHECK(!list->empty()); RenderThreadImpl::current()->Send( - new PeerConnectionTrackerHost_AddStats(lid, *list.get())); + new PeerConnectionTrackerHost_AddLegacyStats(lid, *list.get())); + } + + const int lid_; + const scoped_refptr<base::SingleThreadTaskRunner> main_thread_; +}; + +// chrome://webrtc-internals displays stats and stats graphs. The call path +// involves thread and process hops (IPC). This is the ----webrtc::StatsObserver +// that is used when webrtc-internals wants standard stats. It starts in +// webrtc_internals.js performing requestStandardStats and the result gets +// asynchronously delivered to webrtc_internals.js at addStandardStats. +class InternalStandardStatsObserver : public webrtc::RTCStatsCollectorCallback { + public: + InternalStandardStatsObserver( + int lid, + scoped_refptr<base::SingleThreadTaskRunner> main_thread) + : lid_(lid), main_thread_(std::move(main_thread)) {} + + void OnStatsDelivered( + const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report) override { + // We're on the signaling thread. + DCHECK(!main_thread_->BelongsToCurrentThread()); + main_thread_->PostTask( + FROM_HERE, + base::BindOnce( + &InternalStandardStatsObserver::OnStatsDeliveredOnMainThread, + scoped_refptr<InternalStandardStatsObserver>(this), report)); + } + + protected: + ~InternalStandardStatsObserver() override {} + + private: + void OnStatsDeliveredOnMainThread( + rtc::scoped_refptr<const webrtc::RTCStatsReport> report) { + auto list = ReportToList(report); + RenderThreadImpl::current()->Send( + new PeerConnectionTrackerHost_AddStandardStats(lid_, *list.get())); + } + + std::unique_ptr<base::ListValue> ReportToList( + const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report) { + std::unique_ptr<base::ListValue> result_list(new base::ListValue()); + for (const auto& stats : *report) { + // The format of "stats_subdictionary" is: + // {timestamp:<milliseconds>, values: [<key-value pairs>]} + auto stats_subdictionary = std::make_unique<base::DictionaryValue>(); + // Timestamp is reported in milliseconds. + stats_subdictionary->SetDouble("timestamp", + stats.timestamp_us() / 1000.0); + // Values are reported as + // "values": ["member1", value, "member2", value...] + auto name_value_pairs = std::make_unique<base::ListValue>(); + for (const auto* member : stats.Members()) { + if (!member->is_defined()) + continue; + name_value_pairs->AppendString(member->name()); + name_value_pairs->Append(MemberToValue(*member)); + } + stats_subdictionary->Set("values", std::move(name_value_pairs)); + + // The format of "stats_dictionary" is: + // {id:<string>, stats:<stats_subdictionary>, type:<string>} + auto stats_dictionary = std::make_unique<base::DictionaryValue>(); + stats_dictionary->Set("stats", std::move(stats_subdictionary)); + stats_dictionary->SetString("id", stats.id()); + stats_dictionary->SetString("type", stats.type()); + result_list->Append(std::move(stats_dictionary)); + } + return result_list; + } + + std::unique_ptr<base::Value> MemberToValue( + const webrtc::RTCStatsMemberInterface& member) { + switch (member.type()) { + // Types supported by base::Value are passed as the appropriate type. + case webrtc::RTCStatsMemberInterface::Type::kBool: + return std::make_unique<base::Value>( + *member.cast_to<webrtc::RTCStatsMember<bool>>()); + case webrtc::RTCStatsMemberInterface::Type::kInt32: + return std::make_unique<base::Value>( + *member.cast_to<webrtc::RTCStatsMember<int32_t>>()); + case webrtc::RTCStatsMemberInterface::Type::kString: + return std::make_unique<base::Value>( + *member.cast_to<webrtc::RTCStatsMember<std::string>>()); + // Types not supported by base::Value are converted to string. + case webrtc::RTCStatsMemberInterface::Type::kUint32: + case webrtc::RTCStatsMemberInterface::Type::kInt64: + case webrtc::RTCStatsMemberInterface::Type::kUint64: + case webrtc::RTCStatsMemberInterface::Type::kDouble: + case webrtc::RTCStatsMemberInterface::Type::kSequenceBool: + case webrtc::RTCStatsMemberInterface::Type::kSequenceInt32: + case webrtc::RTCStatsMemberInterface::Type::kSequenceUint32: + case webrtc::RTCStatsMemberInterface::Type::kSequenceInt64: + case webrtc::RTCStatsMemberInterface::Type::kSequenceUint64: + case webrtc::RTCStatsMemberInterface::Type::kSequenceDouble: + case webrtc::RTCStatsMemberInterface::Type::kSequenceString: + default: + return std::make_unique<base::Value>(member.ValueToString()); + } } const int lid_; @@ -497,7 +604,9 @@ const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PeerConnectionTracker, message) - IPC_MESSAGE_HANDLER(PeerConnectionTracker_GetAllStats, OnGetAllStats) + IPC_MESSAGE_HANDLER(PeerConnectionTracker_GetStandardStats, + OnGetStandardStats) + IPC_MESSAGE_HANDLER(PeerConnectionTracker_GetLegacyStats, OnGetLegacyStats) IPC_MESSAGE_HANDLER(PeerConnectionTracker_OnSuspend, OnSuspend) IPC_MESSAGE_HANDLER(PeerConnectionTracker_StartEventLog, OnStartEventLog) IPC_MESSAGE_HANDLER(PeerConnectionTracker_StopEventLog, OnStopEventLog) @@ -506,19 +615,30 @@ return handled; } -void PeerConnectionTracker::OnGetAllStats() { +void PeerConnectionTracker::OnGetStandardStats() { DCHECK_CALLED_ON_VALID_THREAD(main_thread_); const std::string empty_track_id; - for (auto it = peer_connection_local_id_map_.begin(); - it != peer_connection_local_id_map_.end(); ++it) { - rtc::scoped_refptr<InternalStatsObserver> observer( - new rtc::RefCountedObject<InternalStatsObserver>( - it->second, main_thread_task_runner_)); + for (const auto& pair : peer_connection_local_id_map_) { + scoped_refptr<InternalStandardStatsObserver> observer( + new rtc::RefCountedObject<InternalStandardStatsObserver>( + pair.second, main_thread_task_runner_)); + pair.first->GetStandardStatsForTracker(observer); + } +} - it->first->GetStats(observer, - webrtc::PeerConnectionInterface::kStatsOutputLevelDebug, - nullptr); +void PeerConnectionTracker::OnGetLegacyStats() { + DCHECK_CALLED_ON_VALID_THREAD(main_thread_); + + const std::string empty_track_id; + for (const auto& pair : peer_connection_local_id_map_) { + rtc::scoped_refptr<InternalLegacyStatsObserver> observer( + new rtc::RefCountedObject<InternalLegacyStatsObserver>( + pair.second, main_thread_task_runner_)); + + pair.first->GetStats( + observer, webrtc::PeerConnectionInterface::kStatsOutputLevelDebug, + nullptr); } }
diff --git a/content/renderer/media/webrtc/peer_connection_tracker.h b/content/renderer/media/webrtc/peer_connection_tracker.h index aafaf03..ee33830 100644 --- a/content/renderer/media/webrtc/peer_connection_tracker.h +++ b/content/renderer/media/webrtc/peer_connection_tracker.h
@@ -221,7 +221,8 @@ size_t transceiver_index); // IPC Message handler for getting all stats. - void OnGetAllStats(); + void OnGetStandardStats(); + void OnGetLegacyStats(); // Called when the browser process reports a suspend event from the OS. void OnSuspend();
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc index 0781bb4..390c837 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -1505,6 +1505,11 @@ return webkit_request.RequestSucceeded(); } +void RTCPeerConnectionHandler::GetStandardStatsForTracker( + scoped_refptr<webrtc::RTCStatsCollectorCallback> observer) { + native_peer_connection_->GetStats(observer.get()); +} + void RTCPeerConnectionHandler::GetStats( const blink::WebRTCStatsRequest& request) { DCHECK(task_runner_->RunsTasksInCurrentSequence());
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.h b/content/renderer/media/webrtc/rtc_peer_connection_handler.h index ffc6f6e..69c3fb11 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.h +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.h
@@ -31,6 +31,7 @@ #include "third_party/blink/public/platform/web_rtc_stats_request.h" #include "third_party/blink/public/platform/web_rtc_stats_response.h" #include "third_party/webrtc/api/stats/rtc_stats.h" +#include "third_party/webrtc/api/stats/rtc_stats_collector_callback.h" namespace blink { class WebLocalFrame; @@ -185,6 +186,8 @@ // Asynchronously calls native_peer_connection_->getStats on the signaling // thread. + void GetStandardStatsForTracker( + scoped_refptr<webrtc::RTCStatsCollectorCallback> observer); void GetStats(webrtc::StatsObserver* observer, webrtc::PeerConnectionInterface::StatsOutputLevel level, rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> selector);
diff --git a/content/renderer/media_recorder/media_recorder_handler.cc b/content/renderer/media_recorder/media_recorder_handler.cc index 1146447..3aecc41 100644 --- a/content/renderer/media_recorder/media_recorder_handler.cc +++ b/content/renderer/media_recorder/media_recorder_handler.cc
@@ -343,7 +343,8 @@ video_recorder->Resume(); for (const auto& audio_recorder : audio_recorders_) audio_recorder->Resume(); - webm_muxer_->Resume(); + if (webm_muxer_) + webm_muxer_->Resume(); } void MediaRecorderHandler::EncodingInfo(
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index c75b617..3d94c35 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -2919,8 +2919,6 @@ void RenderFrameImpl::NotifyObserversOfFailedProvisionalLoad( const blink::WebURLError& error) { - for (auto& observer : render_view_->observers()) - observer.DidFailProvisionalLoad(frame_, error); for (auto& observer : observers_) observer.DidFailProvisionalLoad(error); } @@ -4545,9 +4543,9 @@ } } - Send(new FrameHostMsg_DidAddMessageToConsole( - routing_id_, static_cast<int32_t>(log_severity), message.text.Utf16(), - static_cast<int32_t>(source_line), source_name.Utf16())); + GetFrameHost()->DidAddMessageToConsole(message.level, message.text.Utf16(), + static_cast<int32_t>(source_line), + source_name.Utf16()); } void RenderFrameImpl::DownloadURL( @@ -6061,8 +6059,6 @@ bool is_new_navigation, bool is_same_document, ui::PageTransition transition) { - for (auto& observer : render_view_->observers_) - observer.DidCommitProvisionalLoad(frame_, is_new_navigation); for (auto& observer : observers_) observer.DidCommitProvisionalLoad(is_same_document, transition); } @@ -7026,11 +7022,6 @@ const CommitNavigationParams& commit_params) { DCHECK(render_view_->webview()); - if (is_main_frame_) { - for (auto& observer : render_view_->observers_) - observer.Navigate(url); - } - render_view_->history_list_offset_ = commit_params.current_history_list_offset; render_view_->history_list_length_ =
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 68fbc8d..2c754dc 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -4,6 +4,7 @@ #include <stddef.h> #include <stdint.h> + #include <tuple> #include "base/bind.h" @@ -17,6 +18,7 @@ #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/bind_test_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/values.h" @@ -2486,35 +2488,6 @@ view()->HistoryForwardListCount() + 1); } -// IPC Listener that runs a callback when a console.log() is executed from -// javascript. -class ConsoleCallbackFilter : public IPC::Listener { - public: - explicit ConsoleCallbackFilter( - base::Callback<void(const base::string16&)> callback) - : callback_(callback) {} - - bool OnMessageReceived(const IPC::Message& msg) override { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(ConsoleCallbackFilter, msg) - IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, - OnDidAddMessageToConsole) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; - } - - void OnDidAddMessageToConsole(int32_t, - const base::string16& message, - int32_t, - const base::string16&) { - callback_.Run(message); - } - - private: - base::Callback<void(const base::string16&)> callback_; -}; - // Tests that there's no UaF after dispatchBeforeUnloadEvent. // See https://crbug.com/666714. TEST_F(RenderViewImplTest, DispatchBeforeUnloadCanDetachFrame) { @@ -2522,26 +2495,29 @@ "<script>window.onbeforeunload = function() { " "window.console.log('OnBeforeUnload called'); }</script>"); - // Creates a callback that swaps the frame when the 'OnBeforeUnload called' + // Create a callback that swaps the frame when the 'OnBeforeUnload called' // log is printed from the beforeunload handler. - std::unique_ptr<ConsoleCallbackFilter> callback_filter( - new ConsoleCallbackFilter(base::Bind( - [](RenderFrameImpl* frame, const base::string16& msg) { - // Makes sure this happens during the beforeunload handler. - EXPECT_EQ(base::UTF8ToUTF16("OnBeforeUnload called"), msg); + base::RunLoop run_loop; + bool was_callback_run = false; + frame()->SetDidAddMessageToConsoleCallback( + base::BindOnce(base::BindLambdaForTesting([&](const base::string16& msg) { + // Makes sure this happens during the beforeunload handler. + EXPECT_EQ(base::UTF8ToUTF16("OnBeforeUnload called"), msg); - // Swaps the main frame. - frame->OnMessageReceived(FrameMsg_SwapOut( - frame->GetRoutingID(), 1, false, FrameReplicationState())); - }, - base::Unretained(frame())))); - render_thread_->sink().AddFilter(callback_filter.get()); + // Swaps the main frame. + frame()->OnMessageReceived(FrameMsg_SwapOut( + frame()->GetRoutingID(), 1, false, FrameReplicationState())); - // Simulates a BeforeUnload IPC received from the browser. + was_callback_run = true; + run_loop.Quit(); + }))); + + // Simulate a BeforeUnload IPC received from the browser. frame()->OnMessageReceived( FrameMsg_BeforeUnload(frame()->GetRoutingID(), false)); - render_thread_->sink().RemoveFilter(callback_filter.get()); + run_loop.Run(); + ASSERT_TRUE(was_callback_run); } // IPC Listener that runs a callback when a javascript modal dialog is
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 3e328da..3c144ca 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -687,7 +687,6 @@ settings->SetDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled); settings->SetJavaScriptCanAccessClipboard( prefs.javascript_can_access_clipboard); - WebRuntimeFeatures::EnableXSLT(prefs.xslt_enabled); settings->SetXSSAuditorEnabled(prefs.xss_auditor_enabled); settings->SetDNSPrefetchingEnabled(prefs.dns_prefetching_enabled); blink::WebNetworkStateNotifier::SetSaveDataEnabled(prefs.data_saver_enabled);
diff --git a/content/shell/browser/web_test/web_test_bluetooth_adapter_provider.cc b/content/shell/browser/web_test/web_test_bluetooth_adapter_provider.cc index 8f7d6559..f4b9ac0f 100644 --- a/content/shell/browser/web_test/web_test_bluetooth_adapter_provider.cc +++ b/content/shell/browser/web_test/web_test_bluetooth_adapter_provider.cc
@@ -107,14 +107,14 @@ ACTION_TEMPLATE(RunCallback, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - return ::testing::get<k>(args).Run(); + return std::move(std::get<k>(args)).Run(); } // Invokes Run() on the k-th argument of the function with 1 argument. ACTION_TEMPLATE(RunCallback, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(p0)) { - return ::testing::get<k>(args).Run(p0); + return std::move(std::get<k>(args)).Run(p0); } // Invokes Run() on the k-th argument of the function with the result @@ -122,7 +122,7 @@ ACTION_TEMPLATE(RunCallbackWithResult, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(func)) { - return ::testing::get<k>(args).Run(func()); + return std::move(std::get<k>(args)).Run(func()); } // Function to iterate over the adapter's devices and return the one @@ -672,17 +672,17 @@ BluetoothUUID(kUserDescriptionUUID), false /* is_local */, device::BluetoothRemoteGattCharacteristic::PROPERTY_READ); - ON_CALL(*user_description, ReadRemoteDescriptor(_, _)) + ON_CALL(*user_description, ReadRemoteDescriptor_(_, _)) .WillByDefault(Invoke( [descriptorName]( const BluetoothRemoteGattDescriptor::ValueCallback& callback, - const BluetoothRemoteGattDescriptor::ErrorCallback&) { + BluetoothRemoteGattDescriptor::ErrorCallback&) { std::vector<uint8_t> value(descriptorName.begin(), descriptorName.end()); callback.Run(value); })); - ON_CALL(*user_description, WriteRemoteDescriptor(_, _, _)) + ON_CALL(*user_description, WriteRemoteDescriptor_(_, _, _)) .WillByDefault(RunCallback<1 /* success_callback */>()); auto client_config = std::make_unique<NiceMockBluetoothGattDescriptor>( @@ -694,10 +694,10 @@ // Crash if WriteRemoteDescriptor called. Not using GoogleMock's Expect // because this is used in web tests that may not report a mock // expectation. - ON_CALL(*client_config, WriteRemoteDescriptor(_, _, _)) + ON_CALL(*client_config, WriteRemoteDescriptor_(_, _, _)) .WillByDefault( Invoke([](const std::vector<uint8_t>&, const base::Closure&, - const BluetoothRemoteGattDescriptor::ErrorCallback&) { + BluetoothRemoteGattDescriptor::ErrorCallback&) { NOTREACHED(); })); @@ -711,10 +711,10 @@ // because this is used in web tests that may not report a mock // expectation // error correctly as a web test failure. - ON_CALL(*no_read_descriptor, ReadRemoteDescriptor(_, _)) + ON_CALL(*no_read_descriptor, ReadRemoteDescriptor_(_, _)) .WillByDefault( Invoke([](const BluetoothRemoteGattDescriptor::ValueCallback&, - const BluetoothRemoteGattDescriptor::ErrorCallback&) { + BluetoothRemoteGattDescriptor::ErrorCallback&) { NOTREACHED(); })); @@ -1037,19 +1037,18 @@ BluetoothUUID(kUserDescriptionUUID), false, device::BluetoothRemoteGattCharacteristic::PROPERTY_READ); - ON_CALL(*user_descriptor, ReadRemoteDescriptor(_, _)) + ON_CALL(*user_descriptor, ReadRemoteDescriptor_(_, _)) .WillByDefault(Invoke( [adapter_ptr, device_ptr, disconnect, succeeds]( const BluetoothRemoteGattDescriptor::ValueCallback& callback, - const BluetoothRemoteGattDescriptor::ErrorCallback& - error_callback) { - base::Closure pending; + BluetoothRemoteGattDescriptor::ErrorCallback& error_callback) { + base::OnceClosure pending; if (succeeds) { pending = base::Bind(callback, std::vector<uint8_t>({1})); } else { pending = - base::Bind(error_callback, - BluetoothRemoteGattService::GATT_ERROR_FAILED); + base::BindOnce(std::move(error_callback), + BluetoothRemoteGattService::GATT_ERROR_FAILED); } device_ptr->PushPendingCallback(std::move(pending)); if (disconnect) { @@ -1061,19 +1060,18 @@ } })); - ON_CALL(*user_descriptor, WriteRemoteDescriptor(_, _, _)) + ON_CALL(*user_descriptor, WriteRemoteDescriptor_(_, _, _)) .WillByDefault(Invoke( [adapter_ptr, device_ptr, disconnect, succeeds]( const std::vector<uint8_t>& value, const base::Closure& callback, - const BluetoothRemoteGattDescriptor::ErrorCallback& - error_callback) { - base::Closure pending; + BluetoothRemoteGattDescriptor::ErrorCallback& error_callback) { + base::OnceClosure pending; if (succeeds) { pending = callback; } else { pending = - base::Bind(error_callback, - BluetoothRemoteGattService::GATT_ERROR_FAILED); + base::BindOnce(std::move(error_callback), + BluetoothRemoteGattService::GATT_ERROR_FAILED); } device_ptr->PushPendingCallback(std::move(pending)); if (disconnect) { @@ -1643,10 +1641,10 @@ BluetoothUUID(kUserDescriptionUUID), false, device::BluetoothRemoteGattCharacteristic::PROPERTY_READ); - ON_CALL(*error_descriptor, ReadRemoteDescriptor(_, _)) + ON_CALL(*error_descriptor, ReadRemoteDescriptor_(_, _)) .WillByDefault(RunCallback<1 /* error_callback */>(error_code)); - ON_CALL(*error_descriptor, WriteRemoteDescriptor(_, _, _)) + ON_CALL(*error_descriptor, WriteRemoteDescriptor_(_, _, _)) .WillByDefault(RunCallback<2 /* error_callback */>(error_code)); characteristic->AddMockDescriptor(std::move(error_descriptor));
diff --git a/content/shell/renderer/web_test/blink_test_helpers.cc b/content/shell/renderer/web_test/blink_test_helpers.cc index 40b58ed1d..786f175e 100644 --- a/content/shell/renderer/web_test/blink_test_helpers.cc +++ b/content/shell/renderer/web_test/blink_test_helpers.cc
@@ -105,7 +105,6 @@ prefs->allow_universal_access_from_file_urls = true; prefs->dom_paste_enabled = true; prefs->javascript_can_access_clipboard = true; - prefs->xslt_enabled = true; prefs->xss_auditor_enabled = false; #if defined(OS_MACOSX) prefs->editing_behavior = EDITING_BEHAVIOR_MAC;
diff --git a/content/shell/renderer/web_test/blink_test_runner.cc b/content/shell/renderer/web_test/blink_test_runner.cc index 7d1f5097..86c728a 100644 --- a/content/shell/renderer/web_test/blink_test_runner.cc +++ b/content/shell/renderer/web_test/blink_test_runner.cc
@@ -170,8 +170,7 @@ : RenderViewObserver(render_view), RenderViewObserverTracker<BlinkTestRunner>(render_view), test_config_(mojom::ShellTestConfiguration::New()), - is_main_window_(false), - focus_on_next_commit_(false) {} + is_main_window_(false) {} BlinkTestRunner::~BlinkTestRunner() {} @@ -698,28 +697,6 @@ return handled; } -void BlinkTestRunner::Navigate(const GURL& url) { - focus_on_next_commit_ = true; -} - -void BlinkTestRunner::DidCommitProvisionalLoad(WebLocalFrame* frame, - bool is_new_navigation) { - if (waiting_for_reset_ && frame == render_view()->GetWebView()->MainFrame() && - GURL(frame->GetDocumentLoader()->GetUrl()).IsAboutBlank()) { - waiting_for_reset_ = false; - Send(new BlinkTestHostMsg_ResetDone(routing_id())); - } - if (!focus_on_next_commit_) - return; - focus_on_next_commit_ = false; - render_view()->GetWebView()->SetFocusedFrame(frame); -} - -void BlinkTestRunner::DidFailProvisionalLoad(WebLocalFrame* frame, - const WebURLError& error) { - focus_on_next_commit_ = false; -} - // Public methods - ----------------------------------------------------------- void BlinkTestRunner::Reset(bool for_new_test) { @@ -757,6 +734,17 @@ CaptureDumpComplete(); } +void BlinkTestRunner::DidCommitNavigationInMainFrame() { + WebFrame* main_frame = render_view()->GetWebView()->MainFrame(); + if (!waiting_for_reset_ || !main_frame->IsWebLocalFrame()) + return; + GURL url = main_frame->ToWebLocalFrame()->GetDocumentLoader()->GetUrl(); + if (!url.IsAboutBlank()) + return; + waiting_for_reset_ = false; + Send(new BlinkTestHostMsg_ResetDone(routing_id())); +} + // Private methods ----------------------------------------------------------- mojom::WebTestBluetoothFakeAdapterSetter&
diff --git a/content/shell/renderer/web_test/blink_test_runner.h b/content/shell/renderer/web_test/blink_test_runner.h index b08e36fc..ec8220f 100644 --- a/content/shell/renderer/web_test/blink_test_runner.h +++ b/content/shell/renderer/web_test/blink_test_runner.h
@@ -52,11 +52,6 @@ // RenderViewObserver implementation. bool OnMessageReceived(const IPC::Message& message) override; void DidClearWindowObject(blink::WebLocalFrame* frame) override; - void Navigate(const GURL& url) override; - void DidCommitProvisionalLoad(blink::WebLocalFrame* frame, - bool is_new_navigation) override; - void DidFailProvisionalLoad(blink::WebLocalFrame* frame, - const blink::WebURLError& error) override; // WebTestDelegate implementation. void ClearEditCommand() override; @@ -155,6 +150,7 @@ void OnReplicateTestConfiguration(mojom::ShellTestConfigurationPtr params); void OnSetupSecondaryRenderer(); void CaptureDump(mojom::WebTestControl::CaptureDumpCallback callback); + void DidCommitNavigationInMainFrame(); private: // Message handlers. @@ -193,7 +189,6 @@ bool is_main_window_; - bool focus_on_next_commit_; bool waiting_for_reset_ = false; std::unique_ptr<test_runner::AppBannerService> app_banner_service_;
diff --git a/content/shell/renderer/web_test/web_test_render_frame_observer.cc b/content/shell/renderer/web_test/web_test_render_frame_observer.cc index 02166c6..ae614472 100644 --- a/content/shell/renderer/web_test/web_test_render_frame_observer.cc +++ b/content/shell/renderer/web_test/web_test_render_frame_observer.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "content/public/renderer/render_frame.h" +#include "content/public/renderer/render_view.h" #include "content/shell/renderer/web_test/blink_test_runner.h" #include "content/shell/renderer/web_test/web_test_render_thread_observer.h" #include "content/shell/test_runner/web_test_interfaces.h" @@ -44,6 +45,34 @@ blink::scheduler::GetSingleThreadTaskRunnerForTesting()); } +void WebTestRenderFrameObserver::ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) { + if (!render_frame()->IsMainFrame()) + return; + focus_on_next_commit_ = true; +} + +void WebTestRenderFrameObserver::DidCommitProvisionalLoad( + bool is_same_document_navigation, + ui::PageTransition transition) { + if (!render_frame()->IsMainFrame()) + return; + if (focus_on_next_commit_) { + focus_on_next_commit_ = false; + render_frame()->GetRenderView()->GetWebView()->SetFocusedFrame( + render_frame()->GetWebFrame()); + } + BlinkTestRunner::Get(render_frame()->GetRenderView()) + ->DidCommitNavigationInMainFrame(); +} + +void WebTestRenderFrameObserver::DidFailProvisionalLoad( + const blink::WebURLError& error) { + if (!render_frame()->IsMainFrame()) + return; + focus_on_next_commit_ = false; +} + void WebTestRenderFrameObserver::OnDestruct() { delete this; }
diff --git a/content/shell/renderer/web_test/web_test_render_frame_observer.h b/content/shell/renderer/web_test/web_test_render_frame_observer.h index b3a1e36..9489f2b4 100644 --- a/content/shell/renderer/web_test/web_test_render_frame_observer.h +++ b/content/shell/renderer/web_test/web_test_render_frame_observer.h
@@ -20,6 +20,11 @@ private: // RenderFrameObserver implementation. + void ReadyToCommitNavigation( + blink::WebDocumentLoader* document_loader) override; + void DidCommitProvisionalLoad(bool is_same_document_navigation, + ui::PageTransition transition) override; + void DidFailProvisionalLoad(const blink::WebURLError& error) override; void OnDestruct() override; void CaptureDump(CaptureDumpCallback callback) override; @@ -32,6 +37,7 @@ void BindRequest(mojom::WebTestControlAssociatedRequest request); mojo::AssociatedBinding<mojom::WebTestControl> binding_; + bool focus_on_next_commit_ = false; DISALLOW_COPY_AND_ASSIGN(WebTestRenderFrameObserver); };
diff --git a/content/test/test_render_frame.cc b/content/test/test_render_frame.cc index c3b28a34..bdedd20f 100644 --- a/content/test/test_render_frame.cc +++ b/content/test/test_render_frame.cc
@@ -47,6 +47,11 @@ return std::move(last_document_interface_broker_request_); } + void SetDidAddMessageToConsoleCallback( + base::OnceCallback<void(const base::string16& msg)> callback) { + did_add_message_to_console_callback_ = std::move(callback); + } + // Holds on to the request end of the InterfaceProvider interface whose client // end is bound to the corresponding RenderFrame's |remote_interfaces_| to // facilitate retrieving the most recent |interface_provider_request| in @@ -156,6 +161,15 @@ void UpdateActiveSchedulerTrackedFeatures(uint64_t features_mask) override {} + void DidAddMessageToConsole(blink::mojom::ConsoleMessageLevel log_level, + const base::string16& msg, + int32_t line_number, + const base::string16& source_id) override { + if (did_add_message_to_console_callback_) { + std::move(did_add_message_to_console_callback_).Run(msg); + } + } + #if defined(OS_ANDROID) void UpdateUserGestureCarryoverInfo() override {} #endif @@ -168,6 +182,9 @@ blink::mojom::DocumentInterfaceBrokerRequest last_document_interface_broker_request_; + base::OnceCallback<void(const base::string16& msg)> + did_add_message_to_console_callback_; + DISALLOW_COPY_AND_ASSIGN(MockFrameHost); }; @@ -331,6 +348,11 @@ return mock_frame_host_->TakeLastCommitParams(); } +void TestRenderFrame::SetDidAddMessageToConsoleCallback( + base::OnceCallback<void(const base::string16& msg)> callback) { + mock_frame_host_->SetDidAddMessageToConsoleCallback(std::move(callback)); +} + service_manager::mojom::InterfaceProviderRequest TestRenderFrame::TakeLastInterfaceProviderRequest() { return mock_frame_host_->TakeLastInterfaceProviderRequest();
diff --git a/content/test/test_render_frame.h b/content/test/test_render_frame.h index 97c787c..7d719b24 100644 --- a/content/test/test_render_frame.h +++ b/content/test/test_render_frame.h
@@ -68,6 +68,11 @@ std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> TakeLastCommitParams(); + // Sets a callback to be run the next time DidAddMessageToConsole + // is called (e.g. window.console.log() is called). + void SetDidAddMessageToConsoleCallback( + base::OnceCallback<void(const base::string16& msg)> callback); + service_manager::mojom::InterfaceProviderRequest TakeLastInterfaceProviderRequest();
diff --git a/device/bluetooth/bluetooth_gatt_descriptor.h b/device/bluetooth/bluetooth_gatt_descriptor.h index b47b4a1..7442ff26 100644 --- a/device/bluetooth/bluetooth_gatt_descriptor.h +++ b/device/bluetooth/bluetooth_gatt_descriptor.h
@@ -24,8 +24,8 @@ class DEVICE_BLUETOOTH_EXPORT BluetoothGattDescriptor { public: // The ErrorCallback is used by methods to asynchronously report errors. - typedef base::Callback<void(BluetoothGattService::GattErrorCode)> - ErrorCallback; + using ErrorCallback = + base::OnceCallback<void(BluetoothGattService::GattErrorCode)>; // The Bluetooth Specification declares several predefined descriptors that // profiles can use. The following are definitions for the list of UUIDs
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor.h b/device/bluetooth/bluetooth_remote_gatt_descriptor.h index 816d140..b5fd813 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor.h +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor.h
@@ -49,7 +49,7 @@ // value. |callback| is called to return the read value on success and // |error_callback| is called for failures. virtual void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) = 0; + ErrorCallback error_callback) = 0; // Sends a write request to a remote characteristic descriptor, to modify the // value of the descriptor with the new value |new_value|. |callback| is @@ -58,7 +58,7 @@ // hosted. virtual void WriteRemoteDescriptor(const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) = 0; + ErrorCallback error_callback) = 0; protected: BluetoothRemoteGattDescriptor();
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_android.cc b/device/bluetooth/bluetooth_remote_gatt_descriptor_android.cc index 65211d0..589449d 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_android.cc +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_android.cc
@@ -81,11 +81,11 @@ void BluetoothRemoteGattDescriptorAndroid::ReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { if (read_pending_ || write_pending_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); return; } @@ -94,24 +94,24 @@ AttachCurrentThread(), j_descriptor_)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattServiceAndroid::GATT_ERROR_FAILED)); return; } read_pending_ = true; read_callback_ = callback; - read_error_callback_ = error_callback; + read_error_callback_ = std::move(error_callback); } void BluetoothRemoteGattDescriptorAndroid::WriteRemoteDescriptor( const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { if (read_pending_ || write_pending_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); return; } @@ -121,14 +121,14 @@ env, j_descriptor_, base::android::ToJavaByteArray(env, new_value))) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattServiceAndroid::GATT_ERROR_FAILED)); return; } write_pending_ = true; write_callback_ = callback; - write_error_callback_ = error_callback; + write_error_callback_ = std::move(error_callback); } void BluetoothRemoteGattDescriptorAndroid::OnRead( @@ -140,9 +140,8 @@ // Clear callbacks before calling to avoid reentrancy issues. ValueCallback read_callback = read_callback_; - ErrorCallback read_error_callback = read_error_callback_; + ErrorCallback read_error_callback = std::move(read_error_callback_); read_callback_.Reset(); - read_error_callback_.Reset(); if (status == 0 // android.bluetooth.BluetoothGatt.GATT_SUCCESS && !read_callback.is_null()) { @@ -150,8 +149,8 @@ read_callback.Run(value_); // TODO(https://crbug.com/584369): Call GattDescriptorValueChanged. } else if (!read_error_callback.is_null()) { - read_error_callback.Run( - BluetoothRemoteGattServiceAndroid::GetGattErrorCode(status)); + std::move(read_error_callback) + .Run(BluetoothRemoteGattServiceAndroid::GetGattErrorCode(status)); } } @@ -163,17 +162,16 @@ // Clear callbacks before calling to avoid reentrancy issues. base::Closure write_callback = write_callback_; - ErrorCallback write_error_callback = write_error_callback_; + ErrorCallback write_error_callback = std::move(write_error_callback_); write_callback_.Reset(); - write_error_callback_.Reset(); if (status == 0 // android.bluetooth.BluetoothGatt.GATT_SUCCESS && !write_callback.is_null()) { write_callback.Run(); // TODO(https://crbug.com/584369): Call GattDescriptorValueChanged. } else if (!write_error_callback.is_null()) { - write_error_callback.Run( - BluetoothRemoteGattServiceAndroid::GetGattErrorCode(status)); + std::move(write_error_callback) + .Run(BluetoothRemoteGattServiceAndroid::GetGattErrorCode(status)); } }
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_android.h b/device/bluetooth/bluetooth_remote_gatt_descriptor_android.h index f8fb862..322a2c4 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_android.h +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_android.h
@@ -48,10 +48,10 @@ BluetoothRemoteGattCharacteristic::Permissions GetPermissions() const override; void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteRemoteDescriptor(const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; // Called when Read operation completes. void OnRead(JNIEnv* env,
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h index e7c10354..f558a66 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h
@@ -38,10 +38,10 @@ const std::vector<uint8_t>& GetValue() const override; BluetoothRemoteGattCharacteristic* GetCharacteristic() const override; void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteRemoteDescriptor(const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; private: friend class BluetoothLowEnergyDeviceMac;
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm index c6b09e1..a8f10f0 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm
@@ -75,14 +75,12 @@ BluetoothRemoteGattDescriptorMac::~BluetoothRemoteGattDescriptorMac() { if (!read_value_callbacks_.first.is_null()) { - std::pair<ValueCallback, ErrorCallback> callbacks; - callbacks.swap(read_value_callbacks_); - callbacks.second.Run(BluetoothGattService::GATT_ERROR_FAILED); + std::move(read_value_callbacks_) + .second.Run(BluetoothGattService::GATT_ERROR_FAILED); } if (!write_value_callbacks_.first.is_null()) { - std::pair<base::Closure, ErrorCallback> callbacks; - callbacks.swap(write_value_callbacks_); - callbacks.second.Run(BluetoothGattService::GATT_ERROR_FAILED); + std::move(write_value_callbacks_) + .second.Run(BluetoothGattService::GATT_ERROR_FAILED); } } @@ -96,36 +94,36 @@ // |error_callback| is called for failures. void BluetoothRemoteGattDescriptorMac::ReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { if (value_read_or_write_in_progress_) { VLOG(1) << *this << ": Read failed, already in progress."; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); return; } VLOG(1) << *this << ": Read value."; value_read_or_write_in_progress_ = true; - read_value_callbacks_ = std::make_pair(callback, error_callback); + read_value_callbacks_ = std::make_pair(callback, std::move(error_callback)); [GetCBPeripheral() readValueForDescriptor:cb_descriptor_]; } void BluetoothRemoteGattDescriptorMac::WriteRemoteDescriptor( const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { if (value_read_or_write_in_progress_) { VLOG(1) << *this << ": Write failed, already in progress."; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); return; } VLOG(1) << *this << ": Write value."; value_read_or_write_in_progress_ = true; - write_value_callbacks_ = std::make_pair(callback, error_callback); + write_value_callbacks_ = std::make_pair(callback, std::move(error_callback)); base::scoped_nsobject<NSData> nsdata_value( [[NSData alloc] initWithBytes:value.data() length:value.size()]); [GetCBPeripheral() writeValue:nsdata_value forDescriptor:GetCBDescriptor()]; @@ -147,7 +145,7 @@ VLOG(1) << *this << ": Read value failed with error: " << BluetoothAdapterMac::String(error) << ", converted to error code: " << error_code; - callbacks.second.Run(error_code); + std::move(callbacks.second).Run(error_code); return; } VLOG(1) << *this << ": Value read."; @@ -171,7 +169,7 @@ VLOG(1) << *this << ": Write value failed with error: " << BluetoothAdapterMac::String(error) << ", converted to error code: " << error_code; - callbacks.second.Run(error_code); + std::move(callbacks.second).Run(error_code); return; } VLOG(1) << *this << ": Value written.";
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_win.cc b/device/bluetooth/bluetooth_remote_gatt_descriptor_win.cc index 4829188a..5006f9f3 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_win.cc +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_win.cc
@@ -71,21 +71,23 @@ void BluetoothRemoteGattDescriptorWin::ReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); NOTIMPLEMENTED(); - error_callback.Run(BluetoothRemoteGattService::GATT_ERROR_NOT_SUPPORTED); + std::move(error_callback) + .Run(BluetoothRemoteGattService::GATT_ERROR_NOT_SUPPORTED); } void BluetoothRemoteGattDescriptorWin::WriteRemoteDescriptor( const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); NOTIMPLEMENTED(); - error_callback.Run(BluetoothRemoteGattService::GATT_ERROR_NOT_SUPPORTED); + std::move(error_callback) + .Run(BluetoothRemoteGattService::GATT_ERROR_NOT_SUPPORTED); } uint16_t BluetoothRemoteGattDescriptorWin::GetAttributeHandle() const {
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_win.h b/device/bluetooth/bluetooth_remote_gatt_descriptor_win.h index c4c2c51..98ad74a 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_win.h +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_win.h
@@ -39,10 +39,10 @@ BluetoothRemoteGattCharacteristic::Permissions GetPermissions() const override; void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteRemoteDescriptor(const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; uint16_t GetAttributeHandle() const; PBTH_LE_GATT_DESCRIPTOR GetWinDescriptorInfo() const {
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.cc b/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.cc index 33efac1..ca05ae7 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.cc +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.cc
@@ -99,11 +99,11 @@ void BluetoothRemoteGattDescriptorWinrt::ReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { if (pending_read_callbacks_ || pending_write_callbacks_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); return; } @@ -116,7 +116,7 @@ << logging::SystemErrorCodeToString(hr); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_FAILED)); return; } @@ -131,23 +131,23 @@ << logging::SystemErrorCodeToString(hr); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_FAILED)); return; } - pending_read_callbacks_ = - std::make_unique<PendingReadCallbacks>(callback, error_callback); + pending_read_callbacks_ = std::make_unique<PendingReadCallbacks>( + callback, std::move(error_callback)); } void BluetoothRemoteGattDescriptorWinrt::WriteRemoteDescriptor( const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { if (pending_read_callbacks_ || pending_write_callbacks_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); return; } @@ -159,7 +159,7 @@ << logging::SystemErrorCodeToString(hr); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_FAILED)); return; } @@ -171,7 +171,7 @@ << logging::SystemErrorCodeToString(hr); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_FAILED)); return; } @@ -183,7 +183,7 @@ << logging::SystemErrorCodeToString(hr); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_FAILED)); return; } @@ -199,13 +199,13 @@ << logging::SystemErrorCodeToString(hr); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(error_callback, + base::BindOnce(std::move(error_callback), BluetoothRemoteGattService::GATT_ERROR_FAILED)); return; } - pending_write_callbacks_ = - std::make_unique<PendingWriteCallbacks>(callback, error_callback); + pending_write_callbacks_ = std::make_unique<PendingWriteCallbacks>( + callback, std::move(error_callback)); } IGattDescriptor* BluetoothRemoteGattDescriptorWinrt::GetDescriptorForTesting() { @@ -252,8 +252,8 @@ auto pending_read_callbacks = std::move(pending_read_callbacks_); if (!read_result) { - pending_read_callbacks->error_callback.Run( - BluetoothGattService::GATT_ERROR_FAILED); + std::move(pending_read_callbacks->error_callback) + .Run(BluetoothGattService::GATT_ERROR_FAILED); return; } @@ -262,8 +262,8 @@ if (FAILED(hr)) { VLOG(2) << "Getting GATT Communication Status failed: " << logging::SystemErrorCodeToString(hr); - pending_read_callbacks->error_callback.Run( - BluetoothGattService::GATT_ERROR_FAILED); + std::move(pending_read_callbacks->error_callback) + .Run(BluetoothGattService::GATT_ERROR_FAILED); return; } @@ -274,13 +274,14 @@ if (FAILED(hr)) { VLOG(2) << "As IGattReadResult2 failed: " << logging::SystemErrorCodeToString(hr); - pending_read_callbacks->error_callback.Run( - BluetoothGattService::GATT_ERROR_FAILED); + std::move(pending_read_callbacks->error_callback) + .Run(BluetoothGattService::GATT_ERROR_FAILED); return; } - pending_read_callbacks->error_callback.Run( - BluetoothRemoteGattServiceWinrt::GetGattErrorCode(read_result_2.Get())); + std::move(pending_read_callbacks->error_callback) + .Run(BluetoothRemoteGattServiceWinrt::GetGattErrorCode( + read_result_2.Get())); return; } @@ -289,8 +290,8 @@ if (FAILED(hr)) { VLOG(2) << "Getting Descriptor Value failed: " << logging::SystemErrorCodeToString(hr); - pending_read_callbacks->error_callback.Run( - BluetoothGattService::GATT_ERROR_FAILED); + std::move(pending_read_callbacks->error_callback) + .Run(BluetoothGattService::GATT_ERROR_FAILED); return; } @@ -300,8 +301,8 @@ if (FAILED(hr)) { VLOG(2) << "Getting Pointer To Buffer Data failed: " << logging::SystemErrorCodeToString(hr); - pending_read_callbacks->error_callback.Run( - BluetoothGattService::GATT_ERROR_FAILED); + std::move(pending_read_callbacks->error_callback) + .Run(BluetoothGattService::GATT_ERROR_FAILED); return; } @@ -315,8 +316,8 @@ auto pending_write_callbacks = std::move(pending_write_callbacks_); if (!write_result) { - pending_write_callbacks->error_callback.Run( - BluetoothGattService::GATT_ERROR_FAILED); + std::move(pending_write_callbacks->error_callback) + .Run(BluetoothGattService::GATT_ERROR_FAILED); return; } @@ -325,15 +326,16 @@ if (FAILED(hr)) { VLOG(2) << "Getting GATT Communication Status failed: " << logging::SystemErrorCodeToString(hr); - pending_write_callbacks->error_callback.Run( - BluetoothGattService::GATT_ERROR_FAILED); + std::move(pending_write_callbacks->error_callback) + .Run(BluetoothGattService::GATT_ERROR_FAILED); return; } if (status != GattCommunicationStatus_Success) { VLOG(2) << "Unexpected GattCommunicationStatus: " << status; - pending_write_callbacks->error_callback.Run( - BluetoothRemoteGattServiceWinrt::GetGattErrorCode(write_result.Get())); + std::move(pending_write_callbacks->error_callback) + .Run(BluetoothRemoteGattServiceWinrt::GetGattErrorCode( + write_result.Get())); return; }
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.h b/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.h index 1f3324b0..9d541fb 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.h +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_winrt.h
@@ -43,10 +43,10 @@ const std::vector<uint8_t>& GetValue() const override; BluetoothRemoteGattCharacteristic* GetCharacteristic() const override; void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteRemoteDescriptor(const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; ABI::Windows::Devices::Bluetooth::GenericAttributeProfile::IGattDescriptor* GetDescriptorForTesting();
diff --git a/device/bluetooth/bluez/bluetooth_gatt_descriptor_bluez.h b/device/bluetooth/bluez/bluetooth_gatt_descriptor_bluez.h index ac73948..d55e1ff 100644 --- a/device/bluetooth/bluez/bluetooth_gatt_descriptor_bluez.h +++ b/device/bluetooth/bluez/bluetooth_gatt_descriptor_bluez.h
@@ -31,7 +31,7 @@ private: // Called by dbus:: on unsuccessful completion of a request to read or write // the descriptor value. - void OnError(const ErrorCallback& error_callback, + void OnError(ErrorCallback error_callback, const std::string& error_name, const std::string& error_message);
diff --git a/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.cc b/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.cc index 7efbbd5..a0f50caf 100644 --- a/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.cc +++ b/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.cc
@@ -83,21 +83,22 @@ void BluetoothRemoteGattDescriptorBlueZ::ReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { VLOG(1) << "Sending GATT characteristic descriptor read request to " << "descriptor: " << GetIdentifier() << ", UUID: " << GetUUID().canonical_value(); bluez::BluezDBusManager::Get()->GetBluetoothGattDescriptorClient()->ReadValue( object_path(), callback, - base::Bind(&BluetoothRemoteGattDescriptorBlueZ::OnError, - weak_ptr_factory_.GetWeakPtr(), error_callback)); + base::BindOnce(&BluetoothRemoteGattDescriptorBlueZ::OnError, + weak_ptr_factory_.GetWeakPtr(), + std::move(error_callback))); } void BluetoothRemoteGattDescriptorBlueZ::WriteRemoteDescriptor( const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { VLOG(1) << "Sending GATT characteristic descriptor write request to " << "characteristic: " << GetIdentifier() << ", UUID: " << GetUUID().canonical_value() @@ -106,19 +107,20 @@ bluez::BluezDBusManager::Get() ->GetBluetoothGattDescriptorClient() ->WriteValue(object_path(), new_value, callback, - base::Bind(&BluetoothRemoteGattDescriptorBlueZ::OnError, - weak_ptr_factory_.GetWeakPtr(), error_callback)); + base::BindOnce(&BluetoothRemoteGattDescriptorBlueZ::OnError, + weak_ptr_factory_.GetWeakPtr(), + std::move(error_callback))); } void BluetoothRemoteGattDescriptorBlueZ::OnError( - const ErrorCallback& error_callback, + ErrorCallback error_callback, const std::string& error_name, const std::string& error_message) { VLOG(1) << "Operation failed: " << error_name << ", message: " << error_message; - error_callback.Run( - BluetoothGattServiceBlueZ::DBusErrorToServiceError(error_name)); + std::move(error_callback) + .Run(BluetoothGattServiceBlueZ::DBusErrorToServiceError(error_name)); } } // namespace bluez
diff --git a/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.h b/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.h index b68e12b..6b77dbe 100644 --- a/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.h +++ b/device/bluetooth/bluez/bluetooth_remote_gatt_descriptor_bluez.h
@@ -36,10 +36,10 @@ device::BluetoothRemoteGattCharacteristic::Permissions GetPermissions() const override; void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteRemoteDescriptor(const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; private: friend class BluetoothRemoteGattCharacteristicBlueZ; @@ -50,7 +50,7 @@ // Called by dbus:: on unsuccessful completion of a request to read or write // the descriptor value. - void OnError(const ErrorCallback& error_callback, + void OnError(ErrorCallback error_callback, const std::string& error_name, const std::string& error_message);
diff --git a/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.cc b/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.cc index e33002c..1f53f9f1 100644 --- a/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.cc +++ b/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.cc
@@ -51,26 +51,27 @@ void BluetoothRemoteGattDescriptorCast::ReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback) { - remote_descriptor_->Read( - base::BindOnce(&BluetoothRemoteGattDescriptorCast::OnReadRemoteDescriptor, - weak_factory_.GetWeakPtr(), callback, error_callback)); + ErrorCallback error_callback) { + remote_descriptor_->Read(base::BindOnce( + &BluetoothRemoteGattDescriptorCast::OnReadRemoteDescriptor, + weak_factory_.GetWeakPtr(), callback, std::move(error_callback))); } void BluetoothRemoteGattDescriptorCast::WriteRemoteDescriptor( const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { remote_descriptor_->Write( new_value, base::BindOnce( &BluetoothRemoteGattDescriptorCast::OnWriteRemoteDescriptor, - weak_factory_.GetWeakPtr(), new_value, callback, error_callback)); + weak_factory_.GetWeakPtr(), new_value, callback, + std::move(error_callback))); } void BluetoothRemoteGattDescriptorCast::OnReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback, + ErrorCallback error_callback, bool success, const std::vector<uint8_t>& result) { if (success) { @@ -78,20 +79,20 @@ callback.Run(result); return; } - error_callback.Run(BluetoothGattService::GATT_ERROR_FAILED); + std::move(error_callback).Run(BluetoothGattService::GATT_ERROR_FAILED); } void BluetoothRemoteGattDescriptorCast::OnWriteRemoteDescriptor( const std::vector<uint8_t>& written_value, const base::Closure& callback, - const ErrorCallback& error_callback, + ErrorCallback error_callback, bool success) { if (success) { value_ = written_value; callback.Run(); return; } - error_callback.Run(BluetoothGattService::GATT_ERROR_FAILED); + std::move(error_callback).Run(BluetoothGattService::GATT_ERROR_FAILED); } } // namespace device
diff --git a/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.h b/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.h index 0c74564..e1561a6 100644 --- a/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.h +++ b/device/bluetooth/cast/bluetooth_remote_gatt_descriptor_cast.h
@@ -41,10 +41,10 @@ const std::vector<uint8_t>& GetValue() const override; BluetoothRemoteGattCharacteristic* GetCharacteristic() const override; void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteRemoteDescriptor(const std::vector<uint8_t>& new_value, const base::Closure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; private: // Called when the remote descriptor has been read or the operation has @@ -53,7 +53,7 @@ // |result|. If |success| is false, |result| is ignored and |error_callback| // is run. void OnReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback, + ErrorCallback error_callback, bool success, const std::vector<uint8_t>& result); @@ -63,7 +63,7 @@ // If successful, |value_| will be updated. void OnWriteRemoteDescriptor(const std::vector<uint8_t>& written_value, const base::Closure& callback, - const ErrorCallback& error_callback, + ErrorCallback error_callback, bool success); BluetoothRemoteGattCharacteristicCast* const characteristic_; @@ -76,4 +76,4 @@ } // namespace device -#endif // DEVICE_BLUETOOTH_CAST_BLUETOOTH_REMOTE_GATT_DESCRIPTOR_CAST_H_ \ No newline at end of file +#endif // DEVICE_BLUETOOTH_CAST_BLUETOOTH_REMOTE_GATT_DESCRIPTOR_CAST_H_
diff --git a/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.cc b/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.cc index a203429..520259a 100644 --- a/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.cc +++ b/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.cc
@@ -89,11 +89,11 @@ // BluetoothGattDescriptorClientImpl override. void ReadValue(const dbus::ObjectPath& object_path, const ValueCallback& callback, - const ErrorCallback& error_callback) override { + ErrorCallback error_callback) override { dbus::ObjectProxy* object_proxy = object_manager_->GetObjectProxy(object_path); if (!object_proxy) { - error_callback.Run(kUnknownDescriptorError, ""); + std::move(error_callback).Run(kUnknownDescriptorError, ""); return; } @@ -111,18 +111,19 @@ base::BindOnce(&BluetoothGattDescriptorClientImpl::OnValueSuccess, weak_ptr_factory_.GetWeakPtr(), callback), base::BindOnce(&BluetoothGattDescriptorClientImpl::OnError, - weak_ptr_factory_.GetWeakPtr(), error_callback)); + weak_ptr_factory_.GetWeakPtr(), + std::move(error_callback))); } // BluetoothGattDescriptorClientImpl override. void WriteValue(const dbus::ObjectPath& object_path, const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) override { + ErrorCallback error_callback) override { dbus::ObjectProxy* object_proxy = object_manager_->GetObjectProxy(object_path); if (!object_proxy) { - error_callback.Run(kUnknownDescriptorError, ""); + std::move(error_callback).Run(kUnknownDescriptorError, ""); return; } @@ -141,7 +142,8 @@ base::BindOnce(&BluetoothGattDescriptorClientImpl::OnSuccess, weak_ptr_factory_.GetWeakPtr(), callback), base::BindOnce(&BluetoothGattDescriptorClientImpl::OnError, - weak_ptr_factory_.GetWeakPtr(), error_callback)); + weak_ptr_factory_.GetWeakPtr(), + std::move(error_callback))); } // dbus::ObjectManager::Interface override. @@ -223,8 +225,7 @@ } // Called when a response for a failed method call is received. - void OnError(const ErrorCallback& error_callback, - dbus::ErrorResponse* response) { + void OnError(ErrorCallback error_callback, dbus::ErrorResponse* response) { // Error response has optional error message argument. std::string error_name; std::string error_message; @@ -236,7 +237,7 @@ error_name = kNoResponseError; error_message = ""; } - error_callback.Run(error_name, error_message); + std::move(error_callback).Run(error_name, error_message); } dbus::ObjectManager* object_manager_;
diff --git a/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.h b/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.h index 2ba7f16..cf424f6 100644 --- a/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.h +++ b/device/bluetooth/dbus/bluetooth_gatt_descriptor_client.h
@@ -65,8 +65,9 @@ }; // Callbacks used to report the result of asynchronous methods. - typedef base::Callback<void(const std::string& error_name, - const std::string& error_message)> ErrorCallback; + using ErrorCallback = + base::OnceCallback<void(const std::string& error_name, + const std::string& error_message)>; typedef base::Callback<void(const std::vector<uint8_t>& value)> ValueCallback; ~BluetoothGattDescriptorClient() override; @@ -89,7 +90,7 @@ // invokes |error_callback|. virtual void ReadValue(const dbus::ObjectPath& object_path, const ValueCallback& callback, - const ErrorCallback& error_callback) = 0; + ErrorCallback error_callback) = 0; // Issues a request to write the value of GATT descriptor with object path // |object_path| with value |value|. Invokes |callback| on success and @@ -97,7 +98,7 @@ virtual void WriteValue(const dbus::ObjectPath& object_path, const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) = 0; + ErrorCallback error_callback) = 0; // Creates the instance. static BluetoothGattDescriptorClient* Create();
diff --git a/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.cc b/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.cc index cce7db84..dd804f8 100644 --- a/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.cc +++ b/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.cc
@@ -97,10 +97,10 @@ void FakeBluetoothGattDescriptorClient::ReadValue( const dbus::ObjectPath& object_path, const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { auto iter = properties_.find(object_path); if (iter == properties_.end()) { - error_callback.Run(kUnknownDescriptorError, ""); + std::move(error_callback).Run(kUnknownDescriptorError, ""); return; } @@ -129,17 +129,18 @@ const dbus::ObjectPath& object_path, const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { if (properties_.find(object_path) == properties_.end()) { - error_callback.Run(kUnknownDescriptorError, ""); + std::move(error_callback).Run(kUnknownDescriptorError, ""); return; } // Since the only fake descriptor is "Client Characteristic Configuration" // and BlueZ doesn't allow writing to it, return failure. - error_callback.Run(bluetooth_gatt_service::kErrorNotPermitted, - "Writing to the Client Characteristic Configuration " - "descriptor not allowed"); + std::move(error_callback) + .Run(bluetooth_gatt_service::kErrorNotPermitted, + "Writing to the Client Characteristic Configuration " + "descriptor not allowed"); } dbus::ObjectPath FakeBluetoothGattDescriptorClient::ExposeDescriptor(
diff --git a/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.h b/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.h index 4f22a68..43cc07b 100644 --- a/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.h +++ b/device/bluetooth/dbus/fake_bluetooth_gatt_descriptor_client.h
@@ -51,11 +51,11 @@ Properties* GetProperties(const dbus::ObjectPath& object_path) override; void ReadValue(const dbus::ObjectPath& object_path, const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteValue(const dbus::ObjectPath& object_path, const std::vector<uint8_t>& value, const base::Closure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; // Makes the descriptor with the UUID |uuid| visible under the characteristic // with object path |characteristic_path|. Descriptor object paths are
diff --git a/device/bluetooth/test/fake_remote_gatt_descriptor.cc b/device/bluetooth/test/fake_remote_gatt_descriptor.cc index aab0061e..406464b 100644 --- a/device/bluetooth/test/fake_remote_gatt_descriptor.cc +++ b/device/bluetooth/test/fake_remote_gatt_descriptor.cc
@@ -65,27 +65,27 @@ void FakeRemoteGattDescriptor::ReadRemoteDescriptor( const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&FakeRemoteGattDescriptor::DispatchReadResponse, - weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); + FROM_HERE, base::BindOnce(&FakeRemoteGattDescriptor::DispatchReadResponse, + weak_ptr_factory_.GetWeakPtr(), callback, + std::move(error_callback))); } void FakeRemoteGattDescriptor::WriteRemoteDescriptor( const std::vector<uint8_t>& value, const base::RepeatingClosure& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindRepeating(&FakeRemoteGattDescriptor::DispatchWriteResponse, - weak_ptr_factory_.GetWeakPtr(), callback, - error_callback, value)); + base::BindOnce(&FakeRemoteGattDescriptor::DispatchWriteResponse, + weak_ptr_factory_.GetWeakPtr(), callback, + std::move(error_callback), value)); } void FakeRemoteGattDescriptor::DispatchReadResponse( const ValueCallback& callback, - const ErrorCallback& error_callback) { + ErrorCallback error_callback) { DCHECK(next_read_response_); uint16_t gatt_code = next_read_response_->gatt_code(); base::Optional<std::vector<uint8_t>> value = next_read_response_->value(); @@ -98,14 +98,15 @@ return; } else if (gatt_code == mojom::kGATTInvalidHandle) { DCHECK(!value); - error_callback.Run(device::BluetoothGattService::GATT_ERROR_FAILED); + std::move(error_callback) + .Run(device::BluetoothGattService::GATT_ERROR_FAILED); return; } } void FakeRemoteGattDescriptor::DispatchWriteResponse( const base::RepeatingClosure& callback, - const ErrorCallback& error_callback, + ErrorCallback error_callback, const std::vector<uint8_t>& value) { DCHECK(next_write_response_); uint16_t gatt_code = next_write_response_.value(); @@ -117,7 +118,8 @@ callback.Run(); break; case mojom::kGATTInvalidHandle: - error_callback.Run(device::BluetoothGattService::GATT_ERROR_FAILED); + std::move(error_callback) + .Run(device::BluetoothGattService::GATT_ERROR_FAILED); break; default: NOTREACHED();
diff --git a/device/bluetooth/test/fake_remote_gatt_descriptor.h b/device/bluetooth/test/fake_remote_gatt_descriptor.h index f12770f..5bfa694 100644 --- a/device/bluetooth/test/fake_remote_gatt_descriptor.h +++ b/device/bluetooth/test/fake_remote_gatt_descriptor.h
@@ -58,17 +58,17 @@ const std::vector<uint8_t>& GetValue() const override; device::BluetoothRemoteGattCharacteristic* GetCharacteristic() const override; void ReadRemoteDescriptor(const ValueCallback& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; void WriteRemoteDescriptor(const std::vector<uint8_t>& value, const base::RepeatingClosure& callback, - const ErrorCallback& error_callback) override; + ErrorCallback error_callback) override; private: void DispatchReadResponse(const ValueCallback& callback, - const ErrorCallback& error_callback); + ErrorCallback error_callback); void DispatchWriteResponse(const base::RepeatingClosure& callback, - const ErrorCallback& error_callback, + ErrorCallback error_callback, const std::vector<uint8_t>& value); const std::string descriptor_id_;
diff --git a/device/bluetooth/test/mock_bluetooth_device.cc b/device/bluetooth/test/mock_bluetooth_device.cc index 5684e5c..48036ba 100644 --- a/device/bluetooth/test/mock_bluetooth_device.cc +++ b/device/bluetooth/test/mock_bluetooth_device.cc
@@ -88,13 +88,13 @@ return nullptr; } -void MockBluetoothDevice::PushPendingCallback(const base::Closure& callback) { - pending_callbacks_.push(callback); +void MockBluetoothDevice::PushPendingCallback(base::OnceClosure callback) { + pending_callbacks_.push(std::move(callback)); } void MockBluetoothDevice::RunPendingCallbacks() { while (!pending_callbacks_.empty()) { - pending_callbacks_.front().Run(); + std::move(pending_callbacks_.front()).Run(); pending_callbacks_.pop(); } }
diff --git a/device/bluetooth/test/mock_bluetooth_device.h b/device/bluetooth/test/mock_bluetooth_device.h index a68a8d0..50823e7 100644 --- a/device/bluetooth/test/mock_bluetooth_device.h +++ b/device/bluetooth/test/mock_bluetooth_device.h
@@ -133,7 +133,7 @@ // trying to run callbacks in response to other actions e.g. run a read // value callback in response to a connection request. // Appends callback to the end of the callbacks queue. - void PushPendingCallback(const base::Closure& callback); + void PushPendingCallback(base::OnceClosure callback); // Runs all pending callbacks. void RunPendingCallbacks(); @@ -147,7 +147,7 @@ bool connected_; // Used by tests to save callbacks that will be run in the future. - base::queue<base::Closure> pending_callbacks_; + base::queue<base::OnceClosure> pending_callbacks_; std::vector<std::unique_ptr<MockBluetoothGattService>> mock_services_; };
diff --git a/device/bluetooth/test/mock_bluetooth_gatt_descriptor.h b/device/bluetooth/test/mock_bluetooth_gatt_descriptor.h index 1ae5d29..2ef1141 100644 --- a/device/bluetooth/test/mock_bluetooth_gatt_descriptor.h +++ b/device/bluetooth/test/mock_bluetooth_gatt_descriptor.h
@@ -38,12 +38,20 @@ MOCK_CONST_METHOD0(GetCharacteristic, BluetoothRemoteGattCharacteristic*()); MOCK_CONST_METHOD0(GetPermissions, BluetoothRemoteGattCharacteristic::Permissions()); - MOCK_METHOD2(ReadRemoteDescriptor, - void(const ValueCallback&, const ErrorCallback&)); - MOCK_METHOD3(WriteRemoteDescriptor, + void ReadRemoteDescriptor(const ValueCallback& c, ErrorCallback ec) override { + ReadRemoteDescriptor_(c, ec); + } + MOCK_METHOD2(ReadRemoteDescriptor_, + void(const ValueCallback&, ErrorCallback&)); + void WriteRemoteDescriptor(const std::vector<uint8_t>& v, + const base::Closure& c, + ErrorCallback ec) override { + WriteRemoteDescriptor_(v, c, ec); + } + MOCK_METHOD3(WriteRemoteDescriptor_, void(const std::vector<uint8_t>&, const base::Closure&, - const ErrorCallback&)); + ErrorCallback&)); private: DISALLOW_COPY_AND_ASSIGN(MockBluetoothGattDescriptor);
diff --git a/device/fido/device_response_converter.cc b/device/fido/device_response_converter.cc index 45d0ef15..e92f63c 100644 --- a/device/fido/device_response_converter.cc +++ b/device/fido/device_response_converter.cc
@@ -339,11 +339,11 @@ switch (state) { case base::StreamingUtf8Validator::VALID_ENDPOINT: - // This shouldn't happen because this callback should only be called - // when the UTF-8 was found to be invalid. Thus reaching this point - // suggests a divergence between |StreamingUtf8Validator| and - // |base::IsStringUTF8|, which the CBOR code uses. - NOTREACHED(); + // |base::IsStringUTF8|, which the CBOR code uses, is stricter than + // |StreamingUtf8Validator| in that the former rejects ranges of code + // points that should never appear. Therefore, if this case occurs, the + // string is structurally valid as UTF-8, but includes invalid code points + // and thus we reject it. return base::nullopt; case base::StreamingUtf8Validator::INVALID:
diff --git a/device/gamepad/public/cpp/BUILD.gn b/device/gamepad/public/cpp/BUILD.gn index 18a0da7..b380d1a 100644 --- a/device/gamepad/public/cpp/BUILD.gn +++ b/device/gamepad/public/cpp/BUILD.gn
@@ -13,14 +13,19 @@ # stay that way due to their above-described purpose). # Consult {platform-architecture-dev, services-dev}@chromium.org in the case # of any uncertainty. -source_set("shared_with_blink") { +component("shared_with_blink") { sources = [ "gamepad.cc", "gamepad.h", "gamepads.cc", "gamepads.h", ] + # Do not add deps here per the above comment. + defines = [ "IS_GAMEPAD_PUBLIC_IMPL" ] + public_deps = [ + "//base", + ] } # Normally typemap traits sources should be build directly into mojom targets
diff --git a/device/gamepad/public/cpp/gamepad.h b/device/gamepad/public/cpp/gamepad.h index 231b031..c59c3e46 100644 --- a/device/gamepad/public/cpp/gamepad.h +++ b/device/gamepad/public/cpp/gamepad.h
@@ -8,6 +8,8 @@ #include <stddef.h> #include <cstdint> +#include "base/component_export.h" + namespace device { #pragma pack(push, 4) @@ -100,7 +102,7 @@ // This structure is intentionally POD and fixed size so that it can be shared // memory between hardware polling threads and the rest of the browser. See // also gamepads.h. -class Gamepad { +class COMPONENT_EXPORT(GAMEPAD_PUBLIC) Gamepad { public: static constexpr size_t kIdLengthCap = 128; static constexpr size_t kMappingLengthCap = 16;
diff --git a/device/gamepad/public/cpp/gamepads.h b/device/gamepad/public/cpp/gamepads.h index e5ebebf..58681fd 100644 --- a/device/gamepad/public/cpp/gamepads.h +++ b/device/gamepad/public/cpp/gamepads.h
@@ -5,6 +5,8 @@ #ifndef DEVICE_GAMEPAD_PUBLIC_CPP_GAMEPADS_H_ #define DEVICE_GAMEPAD_PUBLIC_CPP_GAMEPADS_H_ +#include "base/component_export.h" + #include "device/gamepad/public/cpp/gamepad.h" namespace device { @@ -14,7 +16,7 @@ // This structure is intentionally POD and fixed size so that it can be stored // in shared memory between hardware polling threads and the rest of the // browser. -class Gamepads { +class COMPONENT_EXPORT(GAMEPAD_PUBLIC) Gamepads { public: static constexpr size_t kItemsLengthCap = 4;
diff --git a/device/vr/public/mojom/vr_service.mojom b/device/vr/public/mojom/vr_service.mojom index 3966e54..dbc09a1 100644 --- a/device/vr/public/mojom/vr_service.mojom +++ b/device/vr/public/mojom/vr_service.mojom
@@ -4,6 +4,7 @@ module device.mojom; +import "device/gamepad/public/mojom/gamepad.mojom"; import "mojo/public/mojom/base/time.mojom"; import "gpu/ipc/common/mailbox_holder.mojom"; import "gpu/ipc/common/sync_token.mojom"; @@ -112,6 +113,13 @@ // the space of a single frame, so it may not have been preceeded by a // primary_input_pressed = true; bool primary_input_clicked; + + // Contains information about advanced input state such as additional buttons, + // triggers, touch sensors, joysticks, touchpads, and vibration actuators. If + // the controller has none of these capabilities, then this field will be + // null. The information is a snapshot of the controller state that was taken + // at the time corresponding to the timestamp field's value. + Gamepad? gamepad; }; //
diff --git a/docs/android_emulator.md b/docs/android_emulator.md index 394fac5..9a72634 100644 --- a/docs/android_emulator.md +++ b/docs/android_emulator.md
@@ -2,6 +2,13 @@ Always use x86 emulators (or x86\_64 for testing 64-bit APKs). Although arm emulators exist, they are so slow that they are not worth your time. +*** note +**Note:** apps with native code must be compiled specifically for the device +architecture, so make sure your copy of the app supports x86. Also, be aware the +Play Store may not display ARM-only applications for an x86 emulator. The steps +below show how to locally compile chromium-based apps for x86. +*** + ## Building for Emulation You need to target the correct architecture via GN args: ```gn @@ -27,14 +34,15 @@ ### Choosing an Image Android Studio's image labels roughly translate to the following: -| AVD "Target" | GMS? | Build Properties | -| --- | --- | --- | -| Google Play | This has GMS | `user`/`release-keys` | -| Google APIs | This has GMS | `userdebug`/`dev-keys` | -| No label | AOSP image, does not have GMS | `eng`/`test-keys` | +| AVD "Target" | Virtual Device Configuration tab | GMS? | Build Properties | +| --- | --- | --- | --- | +| Google Play | "Recommended" (the default tab) | This has GMS | `user`/`release-keys` | +| Google APIs | "x86 Images" | This has GMS | `userdebug`/`dev-keys` | +| No label | "x86 Images" | AOSP image, does not have GMS | `eng`/`test-keys` | *** promo -If you're not sure which to use, **choose Google APIs**. +**Tip:** if you're not sure which to use, choose **Google APIs** under the **x86 +Images** tab in the Virtual Device Configuration wizard. *** ### Configuration
diff --git a/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc b/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc index b507570..431509747 100644 --- a/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc +++ b/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc
@@ -156,7 +156,7 @@ ACTION_TEMPLATE(InvokeCallbackArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - std::get<k>(args).Run(); + std::move(std::get<k>(args)).Run(); } IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, SetAdapterState) {
diff --git a/extensions/browser/api/bluetooth_socket/bluetooth_socket_apitest.cc b/extensions/browser/api/bluetooth_socket/bluetooth_socket_apitest.cc index 79b3015..e22e225 100644 --- a/extensions/browser/api/bluetooth_socket/bluetooth_socket_apitest.cc +++ b/extensions/browser/api/bluetooth_socket/bluetooth_socket_apitest.cc
@@ -81,19 +81,19 @@ ACTION_TEMPLATE(InvokeCallbackArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - std::get<k>(args).Run(); + std::move(std::get<k>(args)).Run(); } ACTION_TEMPLATE(InvokeCallbackArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(p0)) { - std::get<k>(args).Run(p0); + std::move(std::get<k>(args)).Run(p0); } ACTION_TEMPLATE(InvokeCallbackArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_2_VALUE_PARAMS(p0, p1)) { - std::get<k>(args).Run(p0, p1); + std::move(std::get<k>(args)).Run(p0, p1); } } // namespace
diff --git a/gpu/ipc/in_process_gpu_thread_holder.cc b/gpu/ipc/in_process_gpu_thread_holder.cc index d07fa5c9..f2fd2a0 100644 --- a/gpu/ipc/in_process_gpu_thread_holder.cc +++ b/gpu/ipc/in_process_gpu_thread_holder.cc
@@ -27,8 +27,8 @@ gpu::GPUInfo gpu_info; gpu::CollectGraphicsInfoForTesting(&gpu_info); - gpu::GpuFeatureInfo gpu_feature_info = gpu::ComputeGpuFeatureInfo( - gpu_info, gpu_preferences_, command_line, nullptr); + gpu_feature_info_ = gpu::ComputeGpuFeatureInfo(gpu_info, gpu_preferences_, + command_line, nullptr); Start(); }
diff --git a/ios/chrome/app/BUILD.gn b/ios/chrome/app/BUILD.gn index 124a920..cc1e2fd4 100644 --- a/ios/chrome/app/BUILD.gn +++ b/ios/chrome/app/BUILD.gn
@@ -207,7 +207,6 @@ "//ios/chrome/browser/suggestions", "//ios/chrome/browser/sync", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/authentication", "//ios/chrome/browser/ui/browser_view",
diff --git a/ios/chrome/app/application_delegate/BUILD.gn b/ios/chrome/app/application_delegate/BUILD.gn index e99d1fb7..e0e51ce 100644 --- a/ios/chrome/app/application_delegate/BUILD.gn +++ b/ios/chrome/app/application_delegate/BUILD.gn
@@ -128,12 +128,12 @@ "//ios/chrome/browser/payments", "//ios/chrome/browser/tabs", "//ios/chrome/browser/u2f", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication", "//ios/chrome/browser/ui/browser_view", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/main", "//ios/chrome/browser/ui/safe_mode", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/url_loading", "//ios/chrome/browser/web:tab_id_tab_helper", "//ios/chrome/browser/web_state_list",
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 39ccf6dd..fdccecf 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -453,9 +453,6 @@ - (void)lastIncognitoTabClosed; // Called when the last regular tab was closed. - (void)lastRegularTabClosed; -// Post a notification with name |notificationName| on the first available -// run loop cycle. -- (void)postNotificationOnNextRunLoopCycle:(NSString*)notificationName; // Opens a tab in the target BVC, and switches to it in a way that's appropriate // to the current UI, based on the |dismissModals| flag: // - If a modal dialog is showing and |dismissModals| is NO, the selected tab of @@ -2481,21 +2478,6 @@ ios::GetChromeBrowserProvider()->LogIfModalViewsArePresented(); } -// iOS does not guarantee the order in which the observers are notified by -// the notification center. There are different parts of the application that -// register for UIApplication notifications so recording them in order to -// measure the performance of the app being moved to the foreground / background -// is not reliable. Instead we prefer using designated notifications that are -// posted to the observers on the first available run loop cycle, which -// guarantees that they are delivered to the observer only after UIApplication -// notifications have been treated. -- (void)postNotificationOnNextRunLoopCycle:(NSString*)notificationName { - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:notificationName - object:self]; - }); -} - - (bool)mustShowRestoreInfobar { if ([self isFirstLaunchAfterUpgrade]) return false;
diff --git a/ios/chrome/browser/autofill/BUILD.gn b/ios/chrome/browser/autofill/BUILD.gn index 3bb6bbc..18f1600 100644 --- a/ios/chrome/browser/autofill/BUILD.gn +++ b/ios/chrome/browser/autofill/BUILD.gn
@@ -66,9 +66,10 @@ "//ios/chrome/browser/history", "//ios/chrome/browser/passwords:passwords_generation_utils", "//ios/chrome/browser/signin", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill/manual_fill:manual_fill_ui", "//ios/chrome/browser/ui/image_util", + "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/web", "//third_party/leveldatabase", "//third_party/libaddressinput", @@ -91,7 +92,7 @@ "//base", "//components/autofill/core/browser", "//components/autofill/ios/browser", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", ] libs = [ "UIKit.framework" ] } @@ -156,10 +157,10 @@ "//ios/chrome/browser/browser_state:test_support", "//ios/chrome/browser/infobars", "//ios/chrome/browser/ssl", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/settings:test_support", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web:test_support", "//ios/chrome/browser/web:web_internal", "//ios/chrome/test/base", @@ -504,7 +505,7 @@ "//components/autofill/ios/browser:browser", "//ios/chrome/app/strings", "//ios/chrome/browser/autofill:autofill_shared", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/testing/earl_grey:earl_grey_support",
diff --git a/ios/chrome/browser/context_menu/BUILD.gn b/ios/chrome/browser/context_menu/BUILD.gn index 9be41b12..835d157 100644 --- a/ios/chrome/browser/context_menu/BUILD.gn +++ b/ios/chrome/browser/context_menu/BUILD.gn
@@ -13,7 +13,7 @@ "//base/test:test_support", "//components/strings", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/public/provider/chrome/browser",
diff --git a/ios/chrome/browser/device_sharing/BUILD.gn b/ios/chrome/browser/device_sharing/BUILD.gn index 0e6c625..fbfb9b68 100644 --- a/ios/chrome/browser/device_sharing/BUILD.gn +++ b/ios/chrome/browser/device_sharing/BUILD.gn
@@ -47,7 +47,7 @@ deps = [ ":device_sharing", "//components/handoff", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/third_party/earl_grey:earl_grey+link",
diff --git a/ios/chrome/browser/memory/BUILD.gn b/ios/chrome/browser/memory/BUILD.gn index 0673e33a..e11599c 100644 --- a/ios/chrome/browser/memory/BUILD.gn +++ b/ios/chrome/browser/memory/BUILD.gn
@@ -16,6 +16,6 @@ "//base", "//components/prefs", "//ios/chrome/browser", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", ] }
diff --git a/ios/chrome/browser/metrics/BUILD.gn b/ios/chrome/browser/metrics/BUILD.gn index c50555d..3c7421ce 100644 --- a/ios/chrome/browser/metrics/BUILD.gn +++ b/ios/chrome/browser/metrics/BUILD.gn
@@ -62,7 +62,7 @@ "//components/rappor", "//components/signin/core/browser", "//components/sync", - "//components/sync:device_info", + "//components/sync/device_info", "//components/ukm", "//components/ukm:observers", "//components/variations", @@ -140,7 +140,7 @@ "//ios/chrome/browser/browser_state", "//ios/chrome/browser/prerender", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list", "//ios/web", "//ui/base", @@ -162,7 +162,7 @@ ":metrics_internal", "//base", "//base/test:test_support", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list", "//ios/chrome/browser/web_state_list:test_support", "//ios/testing:ocmock_support", @@ -196,7 +196,6 @@ "//ios/chrome/browser/metrics", "//ios/chrome/browser/signin", "//ios/chrome/browser/sync", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication", "//ios/chrome/browser/ui/authentication:eg_test_support", "//ios/chrome/browser/ui/authentication/cells", @@ -205,6 +204,7 @@ "//ios/chrome/browser/ui/tab_grid:egtest_support", "//ios/chrome/browser/ui/toolbar/buttons", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/public/provider/chrome/browser/signin:test_support", @@ -229,10 +229,10 @@ "//ios/chrome/app:app_internal", "//ios/chrome/app/strings", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/main", "//ios/chrome/browser/ui/popup_menu:constants", "//ios/chrome/browser/ui/tab_grid:egtest_support", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support",
diff --git a/ios/chrome/browser/omaha/BUILD.gn b/ios/chrome/browser/omaha/BUILD.gn index becd3ec..6fcc9a09 100644 --- a/ios/chrome/browser/omaha/BUILD.gn +++ b/ios/chrome/browser/omaha/BUILD.gn
@@ -18,7 +18,7 @@ "//ios/chrome/browser", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/browser_state_metrics", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/upgrade", "//ios/chrome/common", "//ios/public/provider/chrome/browser",
diff --git a/ios/chrome/browser/passwords/BUILD.gn b/ios/chrome/browser/passwords/BUILD.gn index 5bd2ca1..58a89b9b 100644 --- a/ios/chrome/browser/passwords/BUILD.gn +++ b/ios/chrome/browser/passwords/BUILD.gn
@@ -75,14 +75,15 @@ "//ios/chrome/browser/ssl", "//ios/chrome/browser/sync/glue", "//ios/chrome/browser/translate:translate", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/elements", "//ios/chrome/browser/ui/infobars:feature_flags", "//ios/chrome/browser/ui/infobars:infobars_ui", "//ios/chrome/browser/ui/infobars/coordinators", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/ui", "//ios/third_party/material_components_ios:material_components_ios", @@ -135,7 +136,6 @@ ] deps = [ "//base:i18n", - "//ios/chrome/browser/ui", ] libs = [ "CoreGraphics.framework" ] }
diff --git a/ios/chrome/browser/prerender/BUILD.gn b/ios/chrome/browser/prerender/BUILD.gn index 88ce54b..60ab091 100644 --- a/ios/chrome/browser/prerender/BUILD.gn +++ b/ios/chrome/browser/prerender/BUILD.gn
@@ -32,7 +32,6 @@ "//ios/chrome/browser/sessions:serialisation", "//ios/chrome/browser/signin", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/ntp:util", "//ios/chrome/browser/web", "//ios/chrome/browser/web_state_list",
diff --git a/ios/chrome/browser/providers/signin/BUILD.gn b/ios/chrome/browser/providers/signin/BUILD.gn index d7427bd0..2b7303f3 100644 --- a/ios/chrome/browser/providers/signin/BUILD.gn +++ b/ios/chrome/browser/providers/signin/BUILD.gn
@@ -9,7 +9,7 @@ ] deps = [ "//base", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/public/provider/chrome/browser/signin", ] libs = [ "UIKit.framework" ]
diff --git a/ios/chrome/browser/signin/BUILD.gn b/ios/chrome/browser/signin/BUILD.gn index cdedefc..71baf9e8 100644 --- a/ios/chrome/browser/signin/BUILD.gn +++ b/ios/chrome/browser/signin/BUILD.gn
@@ -11,8 +11,6 @@ "account_consistency_service_factory.mm", "account_reconcilor_factory.cc", "account_reconcilor_factory.h", - "account_tracker_service_factory.cc", - "account_tracker_service_factory.h", "authentication_service.h", "authentication_service.mm", "authentication_service_delegate.h",
diff --git a/ios/chrome/browser/signin/account_tracker_service_factory.cc b/ios/chrome/browser/signin/account_tracker_service_factory.cc deleted file mode 100644 index 091c835f..0000000 --- a/ios/chrome/browser/signin/account_tracker_service_factory.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// 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. - -#include "ios/chrome/browser/signin/account_tracker_service_factory.h" - -#include <utility> - -#include "base/no_destructor.h" -#include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" - -namespace ios { - -AccountTrackerServiceFactory::AccountTrackerServiceFactory() - : BrowserStateKeyedServiceFactory( - "AccountTrackerService", - BrowserStateDependencyManager::GetInstance()) { -} - -AccountTrackerServiceFactory::~AccountTrackerServiceFactory() {} - -// static -AccountTrackerService* AccountTrackerServiceFactory::GetForBrowserState( - ios::ChromeBrowserState* browser_state) { - return static_cast<AccountTrackerService*>( - GetInstance()->GetServiceForBrowserState(browser_state, true)); -} - -// static -AccountTrackerServiceFactory* AccountTrackerServiceFactory::GetInstance() { - static base::NoDestructor<AccountTrackerServiceFactory> instance; - return instance.get(); -} - -void AccountTrackerServiceFactory::RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) { - AccountTrackerService::RegisterPrefs(registry); -} - -std::unique_ptr<KeyedService> -AccountTrackerServiceFactory::BuildServiceInstanceFor( - web::BrowserState* context) const { - ios::ChromeBrowserState* chrome_browser_state = - ios::ChromeBrowserState::FromBrowserState(context); - std::unique_ptr<AccountTrackerService> service(new AccountTrackerService()); - service->Initialize(chrome_browser_state->GetPrefs(), base::FilePath()); - return service; -} - -} // namespace ios
diff --git a/ios/chrome/browser/signin/account_tracker_service_factory.h b/ios/chrome/browser/signin/account_tracker_service_factory.h deleted file mode 100644 index 305712d5..0000000 --- a/ios/chrome/browser/signin/account_tracker_service_factory.h +++ /dev/null
@@ -1,51 +0,0 @@ -// 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_SIGNIN_ACCOUNT_TRACKER_SERVICE_FACTORY_H_ -#define IOS_CHROME_BROWSER_SIGNIN_ACCOUNT_TRACKER_SERVICE_FACTORY_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/no_destructor.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" - -class AccountTrackerService; - -namespace ios { - -class ChromeBrowserState; - -// Singleton that owns all AccountTrackerServices and associates them with -// ios::ChromeBrowserState. -class AccountTrackerServiceFactory : public BrowserStateKeyedServiceFactory { - public: - // Returns the instance of AccountTrackerService associated with this - // browser state (creating one if none exists). Returns nullptr if this - // browser state cannot have a AccountTrackerService (for example, if - // |browser_state| is incognito). - static AccountTrackerService* GetForBrowserState( - ios::ChromeBrowserState* browser_state); - - // Returns the instance of the AccountTrackerServiceFactory singleton. - static AccountTrackerServiceFactory* GetInstance(); - - private: - friend class base::NoDestructor<AccountTrackerServiceFactory>; - - AccountTrackerServiceFactory(); - ~AccountTrackerServiceFactory() override; - - // BrowserStateKeyedServiceFactory implementation. - void RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - std::unique_ptr<KeyedService> BuildServiceInstanceFor( - web::BrowserState* context) const override; - - DISALLOW_COPY_AND_ASSIGN(AccountTrackerServiceFactory); -}; - -} // namespace ios - -#endif // IOS_CHROME_BROWSER_SIGNIN_ACCOUNT_TRACKER_SERVICE_FACTORY_H_
diff --git a/ios/chrome/browser/signin/authentication_service.h b/ios/chrome/browser/signin/authentication_service.h index 923d883..c6fc25b 100644 --- a/ios/chrome/browser/signin/authentication_service.h +++ b/ios/chrome/browser/signin/authentication_service.h
@@ -79,10 +79,6 @@ // managed. virtual bool IsAuthenticatedIdentityManaged(); - // Returns the email of the authenticated user, or |nil| if the user is not - // authenticated. - virtual NSString* GetAuthenticatedUserEmail(); - // Retrieves the identity of the currently authenticated user or |nil| if // either the user is not authenticated, or is authenticated through // ClientLogin.
diff --git a/ios/chrome/browser/signin/authentication_service.mm b/ios/chrome/browser/signin/authentication_service.mm index e3a29a2..f4c3b716 100644 --- a/ios/chrome/browser/signin/authentication_service.mm +++ b/ios/chrome/browser/signin/authentication_service.mm
@@ -252,42 +252,42 @@ } std::vector<std::string> account_ids = GetAccountsInPrefs(); - base::ListValue accounts_pref_value; + std::vector<base::Value> accounts_pref_value; for (const std::string& account_id : account_ids) { if (identity_manager_->HasAccountWithRefreshToken(account_id)) { - accounts_pref_value.AppendString(account_id); + accounts_pref_value.emplace_back(account_id); } else { // The account for |email| was removed since the last application cold // start. Insert |kFakeAccountIdForRemovedAccount| to ensure // |have_accounts_changed_| will be set to true and the removal won't be // silently ignored. - accounts_pref_value.AppendString(kFakeAccountIdForRemovedAccount); + accounts_pref_value.emplace_back(kFakeAccountIdForRemovedAccount); } } - pref_service_->Set(prefs::kSigninLastAccounts, accounts_pref_value); + pref_service_->Set(prefs::kSigninLastAccounts, + base::Value(std::move(accounts_pref_value))); pref_service_->SetBoolean(prefs::kSigninLastAccountsMigrated, true); } void AuthenticationService::StoreAccountsInPrefs() { std::vector<CoreAccountInfo> accounts( identity_manager_->GetAccountsWithRefreshTokens()); - base::ListValue accounts_pref_value; + std::vector<base::Value> accounts_pref_value; for (const CoreAccountInfo& account_info : accounts) - accounts_pref_value.AppendString(account_info.account_id); - pref_service_->Set(prefs::kSigninLastAccounts, accounts_pref_value); + accounts_pref_value.emplace_back(account_info.account_id); + pref_service_->Set(prefs::kSigninLastAccounts, + base::Value(std::move(accounts_pref_value))); } std::vector<std::string> AuthenticationService::GetAccountsInPrefs() { - std::vector<std::string> accounts; - const base::ListValue* accounts_pref = + const base::Value* accounts_pref = pref_service_->GetList(prefs::kSigninLastAccounts); - for (size_t i = 0; i < accounts_pref->GetSize(); ++i) { - std::string account; - if (accounts_pref->GetString(i, &account) && !account.empty()) { - accounts.push_back(account); - } else { - NOTREACHED(); - } + + std::vector<std::string> accounts; + for (const auto& value : accounts_pref->GetList()) { + DCHECK(value.is_string()); + DCHECK(!value.GetString().empty()); + accounts.push_back(value.GetString()); } return accounts; } @@ -571,15 +571,6 @@ return identity_manager_->HasPrimaryAccount(); } -NSString* AuthenticationService::GetAuthenticatedUserEmail() { - if (!IsAuthenticated()) - return nil; - std::string authenticated_username = - identity_manager_->GetPrimaryAccountInfo().email; - DCHECK_LT(0U, authenticated_username.length()); - return base::SysUTF8ToNSString(authenticated_username); -} - bool AuthenticationService::IsAuthenticatedIdentityManaged() { base::Optional<AccountInfo> primary_account_info = identity_manager_->FindExtendedAccountInfoForAccount(
diff --git a/ios/chrome/browser/signin/authentication_service_fake.h b/ios/chrome/browser/signin/authentication_service_fake.h index 8cbdc80..fcc6acfc 100644 --- a/ios/chrome/browser/signin/authentication_service_fake.h +++ b/ios/chrome/browser/signin/authentication_service_fake.h
@@ -40,8 +40,6 @@ ChromeIdentity* GetAuthenticatedIdentity() override; - NSString* GetAuthenticatedUserEmail() override; - private: AuthenticationServiceFake(PrefService* pref_service, SyncSetupService* sync_setup_service,
diff --git a/ios/chrome/browser/signin/authentication_service_fake.mm b/ios/chrome/browser/signin/authentication_service_fake.mm index f3566eb..6613f5e 100644 --- a/ios/chrome/browser/signin/authentication_service_fake.mm +++ b/ios/chrome/browser/signin/authentication_service_fake.mm
@@ -65,10 +65,6 @@ return authenticated_identity_; } -NSString* AuthenticationServiceFake::GetAuthenticatedUserEmail() { - return [authenticated_identity_ userEmail]; -} - std::unique_ptr<KeyedService> AuthenticationServiceFake::CreateAuthenticationService( web::BrowserState* context) {
diff --git a/ios/chrome/browser/signin/authentication_service_unittest.mm b/ios/chrome/browser/signin/authentication_service_unittest.mm index f4123fa..65de372 100644 --- a/ios/chrome/browser/signin/authentication_service_unittest.mm +++ b/ios/chrome/browser/signin/authentication_service_unittest.mm
@@ -295,8 +295,6 @@ EXPECT_EQ(base::SysNSStringToUTF8([identity_ userEmail]), identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_NSEQ([identity_ userEmail], - authentication_service_->GetAuthenticatedUserEmail()); EXPECT_EQ(identity_, authentication_service_->GetAuthenticatedIdentity()); } @@ -316,8 +314,6 @@ EXPECT_EQ(base::SysNSStringToUTF8([identity_ userEmail]), identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_NSEQ([identity_ userEmail], - authentication_service_->GetAuthenticatedUserEmail()); EXPECT_EQ(identity_, authentication_service_->GetAuthenticatedIdentity()); } @@ -335,7 +331,6 @@ CreateAuthenticationService(); EXPECT_EQ("", identity_manager()->GetPrimaryAccountInfo().email); - EXPECT_NSEQ(nil, authentication_service_->GetAuthenticatedUserEmail()); EXPECT_FALSE(authentication_service_->GetAuthenticatedIdentity()); }
diff --git a/ios/chrome/browser/signin/identity_manager_factory.cc b/ios/chrome/browser/signin/identity_manager_factory.cc index 7588899..de376f56 100644 --- a/ios/chrome/browser/signin/identity_manager_factory.cc +++ b/ios/chrome/browser/signin/identity_manager_factory.cc
@@ -18,7 +18,6 @@ #include "components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/signin/account_tracker_service_factory.h" #include "ios/chrome/browser/signin/identity_manager_factory_observer.h" #include "ios/chrome/browser/signin/profile_oauth2_token_service_ios_provider_impl.h" #include "ios/chrome/browser/signin/signin_client_factory.h" @@ -31,16 +30,24 @@ namespace { std::unique_ptr<ProfileOAuth2TokenService> BuildTokenService( - ios::ChromeBrowserState* chrome_browser_state) { + ios::ChromeBrowserState* chrome_browser_state, + AccountTrackerService* account_tracker_service) { auto delegate = std::make_unique<ProfileOAuth2TokenServiceIOSDelegate>( SigninClientFactory::GetForBrowserState(chrome_browser_state), std::make_unique<ProfileOAuth2TokenServiceIOSProviderImpl>(), - ios::AccountTrackerServiceFactory::GetForBrowserState( - chrome_browser_state)); + account_tracker_service); return std::make_unique<ProfileOAuth2TokenService>( chrome_browser_state->GetPrefs(), std::move(delegate)); } +std::unique_ptr<AccountTrackerService> BuildAccountTrackerService( + ios::ChromeBrowserState* chrome_browser_state) { + auto account_tracker_service = std::make_unique<AccountTrackerService>(); + account_tracker_service->Initialize(chrome_browser_state->GetPrefs(), + base::FilePath()); + return account_tracker_service; +} + std::unique_ptr<AccountFetcherService> BuildAccountFetcherService( SigninClient* signin_client, ProfileOAuth2TokenService* token_service, @@ -54,14 +61,13 @@ std::unique_ptr<SigninManager> BuildSigninManager( ios::ChromeBrowserState* chrome_browser_state, + AccountTrackerService* account_tracker_service, ProfileOAuth2TokenService* token_service, GaiaCookieManagerService* gaia_cookie_manager_service) { std::unique_ptr<SigninManager> service = std::make_unique<SigninManager>( SigninClientFactory::GetForBrowserState(chrome_browser_state), - token_service, - ios::AccountTrackerServiceFactory::GetForBrowserState( - chrome_browser_state), - gaia_cookie_manager_service, signin::AccountConsistencyMethod::kMirror); + token_service, account_tracker_service, gaia_cookie_manager_service, + signin::AccountConsistencyMethod::kMirror); service->Initialize(GetApplicationContext()->GetLocalState()); return service; } @@ -76,7 +82,6 @@ : BrowserStateKeyedServiceFactory( "IdentityManager", BrowserStateDependencyManager::GetInstance()) { - DependsOn(ios::AccountTrackerServiceFactory::GetInstance()); DependsOn(SigninClientFactory::GetInstance()); } @@ -105,7 +110,6 @@ // static void IdentityManagerFactory::EnsureFactoryAndDependeeFactoriesBuilt() { IdentityManagerFactory::GetInstance(); - ios::AccountTrackerServiceFactory::GetInstance(); SigninClientFactory::GetInstance(); } @@ -125,22 +129,23 @@ ios::ChromeBrowserState::FromBrowserState(context); // Construct the dependencies that IdentityManager will own. + std::unique_ptr<AccountTrackerService> account_tracker_service = + BuildAccountTrackerService(browser_state); + std::unique_ptr<ProfileOAuth2TokenService> token_service = - BuildTokenService(browser_state); + BuildTokenService(browser_state, account_tracker_service.get()); auto gaia_cookie_manager_service = std::make_unique<GaiaCookieManagerService>( token_service.get(), SigninClientFactory::GetForBrowserState(browser_state)); std::unique_ptr<SigninManager> signin_manager = BuildSigninManager( - browser_state, token_service.get(), gaia_cookie_manager_service.get()); - - AccountTrackerService* account_tracker_service = - ios::AccountTrackerServiceFactory::GetForBrowserState(browser_state); + browser_state, account_tracker_service.get(), token_service.get(), + gaia_cookie_manager_service.get()); auto primary_account_mutator = std::make_unique<identity::PrimaryAccountMutatorImpl>( - account_tracker_service, signin_manager.get()); + account_tracker_service.get(), signin_manager.get()); auto accounts_cookie_mutator = std::make_unique<identity::AccountsCookieMutatorImpl>( @@ -153,10 +158,10 @@ std::unique_ptr<AccountFetcherService> account_fetcher_service = BuildAccountFetcherService( SigninClientFactory::GetForBrowserState(browser_state), - token_service.get(), account_tracker_service); + token_service.get(), account_tracker_service.get()); auto identity_manager = std::make_unique<IdentityManagerWrapper>( - account_tracker_service, std::move(token_service), + std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(signin_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), /*accounts_mutator=*/nullptr, std::move(accounts_cookie_mutator),
diff --git a/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc b/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc index bc9bab8a..c93784a 100644 --- a/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc +++ b/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc
@@ -8,12 +8,9 @@ #include "base/bind.h" #include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/fake_profile_oauth2_token_service.h" #include "components/signin/core/browser/identity_manager_wrapper.h" #include "components/signin/core/browser/test_signin_client.h" -#include "components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/signin/account_tracker_service_factory.h" #include "ios/chrome/browser/signin/identity_manager_factory.h" #include "ios/chrome/browser/signin/profile_oauth2_token_service_ios_provider_impl.h" #include "ios/chrome/browser/signin/signin_client_factory.h" @@ -93,14 +90,10 @@ ios::ChromeBrowserState* chrome_browser_state = ios::ChromeBrowserState::FromBrowserState(browser_state); - auto fake_token_service = std::make_unique<FakeProfileOAuth2TokenService>( - chrome_browser_state->GetPrefs()); - return identity::IdentityTestEnvironment::BuildIdentityManagerForTests( SigninClientFactory::GetForBrowserState(chrome_browser_state), - chrome_browser_state->GetPrefs(), std::move(fake_token_service), - ios::AccountTrackerServiceFactory::GetForBrowserState( - chrome_browser_state), + chrome_browser_state->GetPrefs(), base::FilePath(), + std::unique_ptr<ProfileOAuth2TokenServiceIOSProvider>(), signin::AccountConsistencyMethod::kMirror); } @@ -111,21 +104,10 @@ ios::ChromeBrowserState* chrome_browser_state = ios::ChromeBrowserState::FromBrowserState(browser_state); - std::unique_ptr<OAuth2TokenServiceDelegate> delegate = - std::make_unique<ProfileOAuth2TokenServiceIOSDelegate>( - SigninClientFactory::GetForBrowserState(chrome_browser_state), - std::make_unique<ProfileOAuth2TokenServiceIOSProviderImpl>(), - ios::AccountTrackerServiceFactory::GetForBrowserState( - chrome_browser_state)); - - auto fake_token_service = std::make_unique<FakeProfileOAuth2TokenService>( - chrome_browser_state->GetPrefs(), std::move(delegate)); - return identity::IdentityTestEnvironment::BuildIdentityManagerForTests( SigninClientFactory::GetForBrowserState(chrome_browser_state), - chrome_browser_state->GetPrefs(), std::move(fake_token_service), - ios::AccountTrackerServiceFactory::GetForBrowserState( - chrome_browser_state), + chrome_browser_state->GetPrefs(), base::FilePath(), + std::make_unique<ProfileOAuth2TokenServiceIOSProviderImpl>(), signin::AccountConsistencyMethod::kMirror); }
diff --git a/ios/chrome/browser/snapshots/BUILD.gn b/ios/chrome/browser/snapshots/BUILD.gn index a35f0093..4812e7e 100644 --- a/ios/chrome/browser/snapshots/BUILD.gn +++ b/ios/chrome/browser/snapshots/BUILD.gn
@@ -36,8 +36,8 @@ "//ios/chrome/browser/infobars", "//ios/chrome/browser/ntp", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web:tab_id_tab_helper", "//ios/chrome/browser/web_state_list", "//ios/web/public", @@ -77,8 +77,8 @@ ":test_utils", "//base", "//ios/chrome/browser/browser_state:test_support", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/image_util", + "//ios/chrome/browser/ui/util", "//ios/web", "//ios/web/public/test", "//ios/web/public/test/fakes:fakes",
diff --git a/ios/chrome/browser/sync/BUILD.gn b/ios/chrome/browser/sync/BUILD.gn index 03d3fd0b..6c6c2ca 100644 --- a/ios/chrome/browser/sync/BUILD.gn +++ b/ios/chrome/browser/sync/BUILD.gn
@@ -54,8 +54,8 @@ "//components/sessions", "//components/signin/core/browser", "//components/sync", - "//components/sync:device_info", - "//components/sync:user_events", + "//components/sync/device_info", + "//components/sync/user_events", "//components/sync_preferences", "//components/sync_sessions", "//components/unified_consent",
diff --git a/ios/chrome/browser/tabs/BUILD.gn b/ios/chrome/browser/tabs/BUILD.gn index 15bf9d4..b2976024 100644 --- a/ios/chrome/browser/tabs/BUILD.gn +++ b/ios/chrome/browser/tabs/BUILD.gn
@@ -121,7 +121,6 @@ "//ios/chrome/browser/sync", "//ios/chrome/browser/translate", "//ios/chrome/browser/u2f", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/commands",
diff --git a/ios/chrome/browser/ui/BUILD.gn b/ios/chrome/browser/ui/BUILD.gn index f0e83df..5ac87f4a 100644 --- a/ios/chrome/browser/ui/BUILD.gn +++ b/ios/chrome/browser/ui/BUILD.gn
@@ -4,25 +4,6 @@ import("//build/config/ios/rules.gni") -# TODO(crbug.com/944008): This source set is now empty, remove in followup. -source_set("ui") { - sources = [] - public_deps = [ - "//ios/chrome/browser/ui/util", - "//ios/chrome/common/ui_util", - ] - deps = [ - "//base", - "//base:i18n", - "//components/sessions", - "//ios/chrome/browser", - "//ios/chrome/browser/ui/commands", - "//ui/base", - ] - allow_circular_includes_from = [ "//ios/chrome/browser/ui/commands" ] - configs += [ "//build/config/compiler:enable_arc" ] -} - source_set("feature_flags") { configs += [ "//build/config/compiler:enable_arc" ] sources = [ @@ -33,74 +14,3 @@ "//base", ] } - -# TODO(crbug.com/944008): This source set is now empty, remove in followup. -source_set("unit_tests") { - configs += [ "//build/config/compiler:enable_arc" ] - testonly = true - sources = [] - deps = [ - ":resources_unit_tests", - ":ui", - "//base", - "//base/test:test_support", - "//components/bookmarks/browser", - "//components/bookmarks/test", - "//components/omnibox/browser:test_support", - "//components/payments/core", - "//components/prefs:test_support", - "//components/search_engines", - "//components/sessions", - "//ios/chrome/app/strings", - "//ios/chrome/browser", - "//ios/chrome/browser/bookmarks", - "//ios/chrome/browser/browser_state", - "//ios/chrome/browser/browser_state:test_support", - "//ios/chrome/browser/favicon", - "//ios/chrome/browser/find_in_page", - "//ios/chrome/browser/main:test_support", - "//ios/chrome/browser/search_engines", - "//ios/chrome/browser/sessions", - "//ios/chrome/browser/snapshots", - "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui:feature_flags", - "//ios/chrome/browser/ui/activity_services", - "//ios/chrome/browser/ui/alert_coordinator", - "//ios/chrome/browser/ui/browser_container:ui", - "//ios/chrome/browser/ui/commands", - "//ios/chrome/browser/ui/toolbar/public", - "//ios/chrome/browser/ui/toolbar/test", - "//ios/chrome/browser/url_loading", - "//ios/chrome/browser/web", - "//ios/chrome/browser/web:web_internal", - "//ios/chrome/browser/web_state_list", - "//ios/chrome/browser/web_state_list:test_support", - "//ios/chrome/browser/web_state_list/web_usage_enabler", - "//ios/chrome/test:test_support", - "//ios/net", - "//ios/testing:ocmock_support", - "//ios/web/public/test", - "//ios/web/public/test/fakes", - "//net", - "//net:test_support", - "//services/network:test_support", - "//testing/gmock", - "//testing/gtest", - "//third_party/ocmock", - "//ui/base", - "//ui/base:test_support", - "//url", - ] -} - -bundle_data("resources_unit_tests") { - visibility = [ ":unit_tests" ] - testonly = true - sources = [ - "//ios/chrome/test/data/testbadpass.pkpass", - "//ios/chrome/test/data/testpass.pkpass", - ] - outputs = [ - "{{bundle_resources_dir}}/ios/chrome/test/data/{{source_file_part}}", - ] -}
diff --git a/ios/chrome/browser/ui/activity_services/BUILD.gn b/ios/chrome/browser/ui/activity_services/BUILD.gn index d35b35bb..3c97561 100644 --- a/ios/chrome/browser/ui/activity_services/BUILD.gn +++ b/ios/chrome/browser/ui/activity_services/BUILD.gn
@@ -35,10 +35,10 @@ "//ios/chrome/browser/passwords", "//ios/chrome/browser/snapshots", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/activity_services/activities", "//ios/chrome/browser/ui/activity_services/requirements", "//ios/chrome/browser/ui/commands", + "//ios/chrome/browser/ui/util", "//ios/web", "//net", "//ui/base", @@ -125,7 +125,7 @@ "//base", "//components/strings", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/third_party/material_components_ios",
diff --git a/ios/chrome/browser/ui/alert_coordinator/BUILD.gn b/ios/chrome/browser/ui/alert_coordinator/BUILD.gn index c66a8158..5ecde50 100644 --- a/ios/chrome/browser/ui/alert_coordinator/BUILD.gn +++ b/ios/chrome/browser/ui/alert_coordinator/BUILD.gn
@@ -40,7 +40,7 @@ "//base", "//base/test:test_support", "//components/strings", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test:test_support", "//ios/web/public/test/fakes", "//testing/gtest", @@ -60,9 +60,10 @@ "//base", "//components/strings", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/material_components", + "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/third_party/material_components_ios", "//ios/third_party/material_roboto_font_loader_ios", "//ui/base",
diff --git a/ios/chrome/browser/ui/authentication/BUILD.gn b/ios/chrome/browser/ui/authentication/BUILD.gn index c0388b4..cf578b6 100644 --- a/ios/chrome/browser/ui/authentication/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/BUILD.gn
@@ -50,7 +50,6 @@ "//ios/chrome/browser/signin", "//ios/chrome/browser/sync", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/collection_view/cells", @@ -59,8 +58,10 @@ "//ios/chrome/browser/ui/material_components", "//ios/chrome/browser/ui/settings:settings_root", "//ios/chrome/browser/ui/signin_interaction/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/unified_consent", "//ios/chrome/common", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/images", "//ios/public/provider/chrome/browser/signin",
diff --git a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm index 98181c5..e368358 100644 --- a/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm +++ b/ios/chrome/browser/ui/authentication/authentication_flow_performer.mm
@@ -287,7 +287,7 @@ - (void)clearData:(ios::ChromeBrowserState*)browserState dispatcher:(id<BrowsingDataCommands>)dispatcher { DCHECK(!AuthenticationServiceFactory::GetForBrowserState(browserState) - ->GetAuthenticatedUserEmail()); + ->IsAuthenticated()); [dispatcher removeBrowsingDataForBrowserState:browserState
diff --git a/ios/chrome/browser/ui/authentication/cells/BUILD.gn b/ios/chrome/browser/ui/authentication/cells/BUILD.gn index 7286007..72bf9216 100644 --- a/ios/chrome/browser/ui/authentication/cells/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/cells/BUILD.gn
@@ -28,13 +28,13 @@ "//components/unified_consent", "//ios/chrome/app/strings", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/settings/cells:public", "//ios/chrome/browser/ui/table_view:styler", "//ios/chrome/browser/ui/table_view/cells", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/signin", "//ui/base",
diff --git a/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm b/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm index b136267..7fad463 100644 --- a/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm +++ b/ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.mm
@@ -73,7 +73,7 @@ if (!authService->ShouldPromptForSignIn()) return nullptr; // Returns null if user has already signed in via some other path. - if ([authService->GetAuthenticatedUserEmail() length]) { + if (authService->IsAuthenticated()) { authService->ResetPromptForSignIn(); return nullptr; }
diff --git a/ios/chrome/browser/ui/autofill/BUILD.gn b/ios/chrome/browser/ui/autofill/BUILD.gn index 264bf28a..341cb76 100644 --- a/ios/chrome/browser/ui/autofill/BUILD.gn +++ b/ios/chrome/browser/ui/autofill/BUILD.gn
@@ -45,13 +45,13 @@ "//ios/chrome/browser/ssl", "//ios/chrome/browser/sync", "//ios/chrome/browser/translate:translate", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill/cells", "//ios/chrome/browser/ui/autofill/manual_fill:manual_fill", "//ios/chrome/browser/ui/autofill/manual_fill:manual_fill_ui", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list:web_state_list", "//ios/chrome/common", "//ios/public/provider/chrome/browser", @@ -77,10 +77,10 @@ "//base", "//components/autofill/core/browser", "//components/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill/cells", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/colors", + "//ios/chrome/browser/ui/util", "//ios/third_party/material_components_ios", "//ios/third_party/material_roboto_font_loader_ios", "//ios/web", @@ -113,12 +113,12 @@ "//ios/chrome/browser", "//ios/chrome/browser/infobars", "//ios/chrome/browser/infobars:public", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/image_util", "//ios/chrome/browser/ui/infobars:infobars_ui", "//ios/chrome/browser/ui/util", "//ios/chrome/common", + "//ios/chrome/common/ui_util", "//ios/third_party/material_components_ios", "//ios/third_party/material_roboto_font_loader_ios", "//ui/base:base",
diff --git a/ios/chrome/browser/ui/autofill/cells/BUILD.gn b/ios/chrome/browser/ui/autofill/cells/BUILD.gn index 23fee9c..b8f427a 100644 --- a/ios/chrome/browser/ui/autofill/cells/BUILD.gn +++ b/ios/chrome/browser/ui/autofill/cells/BUILD.gn
@@ -20,7 +20,6 @@ "//ios/chrome/app/strings", "//ios/chrome/app/theme", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/autofill:autofill_ui", "//ios/chrome/browser/ui/collection_view/cells",
diff --git a/ios/chrome/browser/ui/bookmarks/BUILD.gn b/ios/chrome/browser/ui/bookmarks/BUILD.gn index 7c16ccb..f980bfc 100644 --- a/ios/chrome/browser/ui/bookmarks/BUILD.gn +++ b/ios/chrome/browser/ui/bookmarks/BUILD.gn
@@ -76,7 +76,6 @@ "//ios/chrome/browser/signin", "//ios/chrome/browser/sync", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/authentication", "//ios/chrome/browser/ui/authentication/cells", @@ -98,6 +97,7 @@ "//ios/chrome/browser/url_loading", "//ios/chrome/browser/web_state_list", "//ios/chrome/common/favicon", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/ui", "//ios/third_party/material_roboto_font_loader_ios", @@ -168,7 +168,6 @@ "//ios/chrome/browser/bookmarks", "//ios/chrome/browser/bookmarks:bookmarks_utils", "//ios/chrome/browser/browser_state", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication:eg_test_support", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/bookmarks:bookmarks", @@ -177,6 +176,7 @@ "//ios/chrome/browser/ui/table_view", "//ios/chrome/browser/ui/toolbar/buttons", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/public/provider/chrome/browser/signin:test_support",
diff --git a/ios/chrome/browser/ui/bookmarks/cells/BUILD.gn b/ios/chrome/browser/ui/bookmarks/cells/BUILD.gn index 476e481..2d59545f 100644 --- a/ios/chrome/browser/ui/bookmarks/cells/BUILD.gn +++ b/ios/chrome/browser/ui/bookmarks/cells/BUILD.gn
@@ -27,7 +27,6 @@ "//components/unified_consent", "//ios/chrome/app/strings", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/bookmarks:bookmarks_ui", @@ -35,6 +34,7 @@ "//ios/chrome/browser/ui/icons", "//ios/chrome/browser/ui/table_view:styler", "//ios/chrome/browser/ui/table_view/cells", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/ui", "//ios/third_party/material_components_ios",
diff --git a/ios/chrome/browser/ui/bubble/BUILD.gn b/ios/chrome/browser/ui/bubble/BUILD.gn index 98f3f21..68927677 100644 --- a/ios/chrome/browser/ui/bubble/BUILD.gn +++ b/ios/chrome/browser/ui/bubble/BUILD.gn
@@ -25,7 +25,6 @@ "//ios/chrome/browser", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/feature_engagement", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/util", @@ -49,7 +48,7 @@ ":bubble", "//base", "//base:i18n", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//testing/gtest", ] libs = [ "CoreGraphics.framework" ]
diff --git a/ios/chrome/browser/ui/content_suggestions/BUILD.gn b/ios/chrome/browser/ui/content_suggestions/BUILD.gn index 7379481..43f7222 100644 --- a/ios/chrome/browser/ui/content_suggestions/BUILD.gn +++ b/ios/chrome/browser/ui/content_suggestions/BUILD.gn
@@ -46,7 +46,6 @@ "//ios/chrome/browser/reading_list", "//ios/chrome/browser/search_engines", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/commands", @@ -70,6 +69,7 @@ "//ios/chrome/browser/web_state_list", "//ios/chrome/common/app_group", "//ios/chrome/common/favicon", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/images", "//ios/public/provider/chrome/browser/ui", @@ -113,7 +113,6 @@ "resources:ntp_search_icon", "//base", "//components/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/collection_view", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions/cells:cells_ui", @@ -128,6 +127,7 @@ "//ios/chrome/browser/ui/toolbar/public", "//ios/chrome/browser/ui/util:util", "//ios/chrome/common/favicon", + "//ios/chrome/common/ui_util", "//ios/web/common", "//ui/base", ] @@ -159,13 +159,13 @@ "//base:i18n", "//components/strings", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions/cells:cells_ui", "//ios/chrome/browser/ui/location_bar:constants", "//ios/chrome/browser/ui/ntp", "//ios/chrome/browser/ui/ntp_tile_views:constants", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/third_party/material_components_ios", "//ios/web/common", "//ui/base", @@ -192,8 +192,6 @@ "//ios/chrome/browser/browser_state:test_support", "//ios/chrome/browser/ntp_snippets", "//ios/chrome/browser/search_engines", - "//ios/chrome/browser/ui", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/collection_view", "//ios/chrome/browser/ui/collection_view", "//ios/chrome/browser/ui/commands", @@ -203,6 +201,7 @@ "//ios/chrome/browser/ui/content_suggestions/identifier", "//ios/chrome/browser/ui/location_bar:notifications", "//ios/chrome/browser/ui/toolbar/test", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/url_loading", "//ios/chrome/browser/web_state_list", "//ios/chrome/browser/web_state_list:test_support", @@ -246,13 +245,13 @@ "//ios/chrome/browser/ntp_snippets", "//ios/chrome/browser/reading_list", "//ios/chrome/browser/search_engines", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/content_suggestions/cells:cells_ui", "//ios/chrome/browser/ui/location_bar:location_bar", "//ios/chrome/browser/ui/settings", "//ios/chrome/browser/ui/tab_grid:egtest_support", "//ios/chrome/browser/ui/toolbar/buttons", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/test:eg_test_support", "//ios/chrome/test:test_support", "//ios/chrome/test/app:test_support",
diff --git a/ios/chrome/browser/ui/content_suggestions/cells/BUILD.gn b/ios/chrome/browser/ui/content_suggestions/cells/BUILD.gn index e54fb8fe..7b4f0ed4 100644 --- a/ios/chrome/browser/ui/content_suggestions/cells/BUILD.gn +++ b/ios/chrome/browser/ui/content_suggestions/cells/BUILD.gn
@@ -54,7 +54,6 @@ deps = [ "//base", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/collection_view", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/content_suggestions/identifier", @@ -64,6 +63,7 @@ "//ios/chrome/browser/ui/util", "//ios/chrome/common", "//ios/chrome/common/favicon", + "//ios/chrome/common/ui_util", "//ui/base", ] public_deps = [ @@ -87,8 +87,8 @@ ":cells_ui", "//base", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/collection_view", + "//ios/chrome/browser/ui/util", "//ios/chrome/common/favicon", "//testing/gtest", "//third_party/ocmock",
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm index 88861126..82f8403 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view.mm
@@ -292,13 +292,14 @@ self.fakeLocationBarTrailingConstraint.constant = 0; self.fakeLocationBarTopConstraint.constant = 0; + self.separator.alpha = 0; + return; } else { self.alpha = 1; + self.separator.alpha = percent; } - self.separator.alpha = percent; - // Grow the blur to cover the safeArea top. self.fakeToolbarTopConstraint.constant = -safeAreaInsets.top * percent;
diff --git a/ios/chrome/browser/ui/dialogs/BUILD.gn b/ios/chrome/browser/ui/dialogs/BUILD.gn index 3e7e7f6e..1a2ef8cd 100644 --- a/ios/chrome/browser/ui/dialogs/BUILD.gn +++ b/ios/chrome/browser/ui/dialogs/BUILD.gn
@@ -65,10 +65,10 @@ "//components/strings", "//components/url_formatter", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/dialogs/non_modal", + "//ios/chrome/browser/ui/util", "//ios/web", "//ui/base", "//url", @@ -112,7 +112,7 @@ "//components/strings", "//components/url_formatter", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/testing/earl_grey:earl_grey_support",
diff --git a/ios/chrome/browser/ui/download/BUILD.gn b/ios/chrome/browser/ui/download/BUILD.gn index 2440ba3e4..c9d047a 100644 --- a/ios/chrome/browser/ui/download/BUILD.gn +++ b/ios/chrome/browser/ui/download/BUILD.gn
@@ -38,7 +38,6 @@ "//ios/chrome/browser/download", "//ios/chrome/browser/infobars", "//ios/chrome/browser/store_kit", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", @@ -46,6 +45,7 @@ "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web:web_internal", "//ios/chrome/browser/web_state_list:web_state_list", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/images", "//ios/third_party/material_components_ios",
diff --git a/ios/chrome/browser/ui/elements/BUILD.gn b/ios/chrome/browser/ui/elements/BUILD.gn index 0213e73..149eb7f 100644 --- a/ios/chrome/browser/ui/elements/BUILD.gn +++ b/ios/chrome/browser/ui/elements/BUILD.gn
@@ -63,9 +63,10 @@ deps = [ "//base", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/material_components", + "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/third_party/material_components_ios", ] libs = [ "UIKit.framework" ]
diff --git a/ios/chrome/browser/ui/find_bar/BUILD.gn b/ios/chrome/browser/ui/find_bar/BUILD.gn index 83aa9b1..ba157e3 100644 --- a/ios/chrome/browser/ui/find_bar/BUILD.gn +++ b/ios/chrome/browser/ui/find_bar/BUILD.gn
@@ -20,11 +20,12 @@ "//components/strings", "//ios/chrome/app/strings", "//ios/chrome/browser/find_in_page", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/image_util", "//ios/chrome/browser/ui/resources:menu_shadow", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/third_party/material_components_ios", "//ui/base", "//ui/gfx",
diff --git a/ios/chrome/browser/ui/first_run/BUILD.gn b/ios/chrome/browser/ui/first_run/BUILD.gn index ea141d7..74baffb 100644 --- a/ios/chrome/browser/ui/first_run/BUILD.gn +++ b/ios/chrome/browser/ui/first_run/BUILD.gn
@@ -34,7 +34,6 @@ "//ios/chrome/browser/first_run", "//ios/chrome/browser/signin", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/fancy_ui", @@ -75,8 +74,8 @@ "//components/prefs:test_support", "//ios/chrome/browser/browser_state:test_support", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/fancy_ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test:test_support", "//ios/web/public/test", "//testing/gtest",
diff --git a/ios/chrome/browser/ui/history/BUILD.gn b/ios/chrome/browser/ui/history/BUILD.gn index dbe170d4..4470a67a 100644 --- a/ios/chrome/browser/ui/history/BUILD.gn +++ b/ios/chrome/browser/ui/history/BUILD.gn
@@ -24,10 +24,10 @@ "//ios/chrome/browser/favicon", "//ios/chrome/browser/history", "//ios/chrome/browser/sync", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/context_menu", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/table_view", + "//ios/chrome/browser/ui/util", ] libs = [ "MobileCoreServices.framework", @@ -74,7 +74,6 @@ "//ios/chrome/browser/browser_state", "//ios/chrome/browser/metrics:metrics_internal", "//ios/chrome/browser/sync", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/context_menu", @@ -86,6 +85,7 @@ "//ios/chrome/browser/ui/util", "//ios/chrome/browser/url_loading", "//ios/chrome/common/favicon", + "//ios/chrome/common/ui_util", "//ui/base", ] } @@ -99,7 +99,6 @@ deps = [ ":history_ui", "//base", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/history/public", @@ -123,7 +122,6 @@ "//base", "//base/test:test_support", "//components/history/core/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/list_model", "//ios/chrome/test:test_support", "//testing/gtest", @@ -148,7 +146,6 @@ "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/browser_state", - "//ios/chrome/browser/ui:ui", "//ios/chrome/browser/ui/authentication:eg_test_support", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/popup_menu:constants",
diff --git a/ios/chrome/browser/ui/infobars/BUILD.gn b/ios/chrome/browser/ui/infobars/BUILD.gn index c0cd12d..b1639ad 100644 --- a/ios/chrome/browser/ui/infobars/BUILD.gn +++ b/ios/chrome/browser/ui/infobars/BUILD.gn
@@ -70,7 +70,6 @@ "//components/strings", "//ios/chrome/app/theme:theme", "//ios/chrome/app/theme:theme_grit", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/fancy_ui", "//ios/chrome/browser/ui/fullscreen",
diff --git a/ios/chrome/browser/ui/location_bar/BUILD.gn b/ios/chrome/browser/ui/location_bar/BUILD.gn index 40702c59..32f1ebd77 100644 --- a/ios/chrome/browser/ui/location_bar/BUILD.gn +++ b/ios/chrome/browser/ui/location_bar/BUILD.gn
@@ -42,7 +42,6 @@ "//ios/chrome/browser/ntp", "//ios/chrome/browser/search_engines", "//ios/chrome/browser/ssl", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/elements", @@ -66,6 +65,7 @@ "//ios/chrome/browser/web", "//ios/chrome/browser/web_state_list", "//ios/chrome/common:timing", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser:browser", "//ios/public/provider/chrome/browser/voice", "//ios/third_party/material_components_ios",
diff --git a/ios/chrome/browser/ui/main/BUILD.gn b/ios/chrome/browser/ui/main/BUILD.gn index 843a722..6a01406 100644 --- a/ios/chrome/browser/ui/main/BUILD.gn +++ b/ios/chrome/browser/ui/main/BUILD.gn
@@ -68,7 +68,6 @@ ] deps = [ "//base", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ui/base", "//url",
diff --git a/ios/chrome/browser/ui/ntp/BUILD.gn b/ios/chrome/browser/ui/ntp/BUILD.gn index f5e137e..309dc92 100644 --- a/ios/chrome/browser/ui/ntp/BUILD.gn +++ b/ios/chrome/browser/ui/ntp/BUILD.gn
@@ -98,7 +98,6 @@ "//ios/chrome/browser/search_engines", "//ios/chrome/browser/suggestions", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/bookmarks", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", @@ -109,12 +108,14 @@ "//ios/chrome/browser/ui/overscroll_actions", "//ios/chrome/browser/ui/toolbar/buttons", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/url_loading", "//ios/chrome/browser/web_state_list", "//ios/chrome/common", "//ios/chrome/common/app_group", "//ios/chrome/common/favicon", "//ios/chrome/common/ntp_tile", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/images", "//ios/public/provider/chrome/browser/ui", @@ -166,7 +167,6 @@ "//ios/chrome/browser/sessions", "//ios/chrome/browser/sessions:test_support", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_ui", @@ -198,9 +198,9 @@ "//components/strings", "//ios/chrome/app/strings", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/testing/earl_grey:earl_grey_support",
diff --git a/ios/chrome/browser/ui/omnibox/BUILD.gn b/ios/chrome/browser/ui/omnibox/BUILD.gn index f791d27..d4f2a9f 100644 --- a/ios/chrome/browser/ui/omnibox/BUILD.gn +++ b/ios/chrome/browser/ui/omnibox/BUILD.gn
@@ -96,7 +96,6 @@ "//ios/chrome/browser/prerender", "//ios/chrome/browser/search_engines", "//ios/chrome/browser/sessions", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/fullscreen",
diff --git a/ios/chrome/browser/ui/omnibox/popup/BUILD.gn b/ios/chrome/browser/ui/omnibox/popup/BUILD.gn index 8be77173..788b9e54 100644 --- a/ios/chrome/browser/ui/omnibox/popup/BUILD.gn +++ b/ios/chrome/browser/ui/omnibox/popup/BUILD.gn
@@ -26,7 +26,6 @@ "//ios/chrome/browser", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/favicon", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/ntp:util", @@ -34,8 +33,10 @@ "//ios/chrome/browser/ui/omnibox/popup/shortcuts", "//ios/chrome/browser/ui/toolbar/buttons", "//ios/chrome/browser/ui/toolbar/public:feature_flags", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list:web_state_list", "//ios/chrome/common/favicon", + "//ios/chrome/common/ui_util", "//ios/web/public:public", "//net", "//ui/base",
diff --git a/ios/chrome/browser/ui/omnibox/popup/shortcuts/BUILD.gn b/ios/chrome/browser/ui/omnibox/popup/shortcuts/BUILD.gn index 1c45ca14..f6c50ef 100644 --- a/ios/chrome/browser/ui/omnibox/popup/shortcuts/BUILD.gn +++ b/ios/chrome/browser/ui/omnibox/popup/shortcuts/BUILD.gn
@@ -46,7 +46,6 @@ "//components/reading_list/core", "//components/reading_list/ios", "//ios/chrome/browser/ntp_tiles", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands:commands", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/favicon", @@ -88,7 +87,6 @@ "//components/strings", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/reading_list", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", "//ios/chrome/browser/ui/omnibox:omnibox_popup_shared",
diff --git a/ios/chrome/browser/ui/overscroll_actions/BUILD.gn b/ios/chrome/browser/ui/overscroll_actions/BUILD.gn index 73d2858..f2fa8c1 100644 --- a/ios/chrome/browser/ui/overscroll_actions/BUILD.gn +++ b/ios/chrome/browser/ui/overscroll_actions/BUILD.gn
@@ -23,7 +23,6 @@ "//ios/chrome/app/strings:ios_chromium_strings_grit", "//ios/chrome/app/strings:ios_strings_grit", "//ios/chrome/app/theme", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", "//ios/chrome/browser/ui/fullscreen",
diff --git a/ios/chrome/browser/ui/page_info/BUILD.gn b/ios/chrome/browser/ui/page_info/BUILD.gn index 8438426..5d23fc2d 100644 --- a/ios/chrome/browser/ui/page_info/BUILD.gn +++ b/ios/chrome/browser/ui/page_info/BUILD.gn
@@ -23,11 +23,11 @@ "//ios/chrome/app/theme", "//ios/chrome/browser", "//ios/chrome/browser/browser_state", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/fancy_ui", "//ios/chrome/browser/ui/page_info/requirements", "//ios/chrome/browser/ui/popup_menu", + "//ios/chrome/browser/ui/util", "//ios/chrome/common", "//ios/web", "//ui/base", @@ -50,7 +50,6 @@ "//ios/chrome/browser/browser_state", "//ios/chrome/browser/reading_list", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/fullscreen:coordinators",
diff --git a/ios/chrome/browser/ui/payments/BUILD.gn b/ios/chrome/browser/ui/payments/BUILD.gn index 4d39046..57a483d 100644 --- a/ios/chrome/browser/ui/payments/BUILD.gn +++ b/ios/chrome/browser/ui/payments/BUILD.gn
@@ -78,7 +78,6 @@ "//ios/chrome/browser/browser_state", "//ios/chrome/browser/payments", "//ios/chrome/browser/signin", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill", "//ios/chrome/browser/ui/autofill:autofill_ui", "//ios/chrome/browser/ui/autofill/cells", @@ -89,6 +88,7 @@ "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/icons", "//ios/chrome/browser/ui/payments/cells", + "//ios/chrome/browser/ui/util", "//ios/third_party/material_roboto_font_loader_ios", "//ios/web", "//third_party/libaddressinput", @@ -155,7 +155,6 @@ "//components/strings", "//ios/chrome/app/strings:ios_strings_grit", "//ios/chrome/app/theme", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill:autofill_ui", "//ios/chrome/browser/ui/autofill/cells", "//ios/chrome/browser/ui/collection_view", @@ -164,6 +163,7 @@ "//ios/chrome/browser/ui/list_model", "//ios/chrome/browser/ui/material_components", "//ios/chrome/browser/ui/payments/cells", + "//ios/chrome/browser/ui/util", "//ios/third_party/material_components_ios", "//third_party/libaddressinput:strings_grit", "//ui/base",
diff --git a/ios/chrome/browser/ui/payments/cells/BUILD.gn b/ios/chrome/browser/ui/payments/cells/BUILD.gn index 176a4dc4..4dbfeae 100644 --- a/ios/chrome/browser/ui/payments/cells/BUILD.gn +++ b/ios/chrome/browser/ui/payments/cells/BUILD.gn
@@ -25,10 +25,11 @@ deps = [ "//ios/chrome/app/theme", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill:autofill_ui", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/colors", + "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/third_party/material_components_ios", "//ios/third_party/material_roboto_font_loader_ios", "//url/",
diff --git a/ios/chrome/browser/ui/popup_menu/BUILD.gn b/ios/chrome/browser/ui/popup_menu/BUILD.gn index f06e19b..eddff42 100644 --- a/ios/chrome/browser/ui/popup_menu/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/BUILD.gn
@@ -53,7 +53,6 @@ "//ios/chrome/browser/reading_list", "//ios/chrome/browser/search_engines", "//ios/chrome/browser/translate", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/activity_services", "//ios/chrome/browser/ui/bookmarks",
diff --git a/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn b/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn index 95f5d3cc..90a2c85c 100644 --- a/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/cells/BUILD.gn
@@ -12,7 +12,6 @@ ] deps = [ "//base", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/favicon/resources:default_favicon", "//ios/chrome/browser/ui/popup_menu/public:ui_constants", "//ios/chrome/browser/ui/popup_menu/public/cells",
diff --git a/ios/chrome/browser/ui/popup_menu/public/BUILD.gn b/ios/chrome/browser/ui/popup_menu/public/BUILD.gn index 6350c66..9cbdc1ce 100644 --- a/ios/chrome/browser/ui/popup_menu/public/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/public/BUILD.gn
@@ -32,7 +32,6 @@ ":ui_constants", "//base", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/image_util", "//ios/chrome/browser/ui/popup_menu/public/", "//ios/chrome/browser/ui/popup_menu/public/cells", @@ -42,6 +41,7 @@ "//ios/chrome/browser/ui/table_view:styler", "//ios/chrome/browser/ui/util", "//ios/chrome/common", + "//ios/chrome/common/ui_util", "//ui/base", ] libs = [
diff --git a/ios/chrome/browser/ui/print/BUILD.gn b/ios/chrome/browser/ui/print/BUILD.gn index 0a26766e..08e502d 100644 --- a/ios/chrome/browser/ui/print/BUILD.gn +++ b/ios/chrome/browser/ui/print/BUILD.gn
@@ -31,7 +31,7 @@ ] deps = [ "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/testing/earl_grey:earl_grey_support",
diff --git a/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm b/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm index a36e713757..5065b65 100644 --- a/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm +++ b/ios/chrome/browser/ui/promos/signin_promo_view_controller.mm
@@ -185,7 +185,7 @@ AuthenticationService* authService = AuthenticationServiceFactory::GetForBrowserState(browserState); // Do not show the SSO promo if the user is already logged in. - if (authService->GetAuthenticatedUserEmail()) + if (authService->IsAuthenticated()) return NO; // Show the promo at most every two major versions.
diff --git a/ios/chrome/browser/ui/qr_scanner/BUILD.gn b/ios/chrome/browser/ui/qr_scanner/BUILD.gn index 2644bfe..7644148 100644 --- a/ios/chrome/browser/ui/qr_scanner/BUILD.gn +++ b/ios/chrome/browser/ui/qr_scanner/BUILD.gn
@@ -67,13 +67,13 @@ "//ios/chrome/app:app_internal", "//ios/chrome/app/strings", "//ios/chrome/browser", - "//ios/chrome/browser/ui:ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/icons", "//ios/chrome/browser/ui/location_bar", "//ios/chrome/browser/ui/omnibox", "//ios/chrome/browser/ui/toolbar", "//ios/chrome/browser/ui/toolbar/public:feature_flags", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/url_loading", "//ios/chrome/test/app:test_support", "//ios/chrome/test/base",
diff --git a/ios/chrome/browser/ui/reading_list/BUILD.gn b/ios/chrome/browser/ui/reading_list/BUILD.gn index a9157fdb..c8dd505 100644 --- a/ios/chrome/browser/ui/reading_list/BUILD.gn +++ b/ios/chrome/browser/ui/reading_list/BUILD.gn
@@ -42,7 +42,6 @@ "//ios/chrome/browser/metrics:metrics_internal", "//ios/chrome/browser/reading_list", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", @@ -103,7 +102,6 @@ "//components/url_formatter", "//ios/chrome/app/strings", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/keyboard", "//ios/chrome/browser/ui/list_model", @@ -147,7 +145,6 @@ "//ios/chrome/browser/feature_engagement", "//ios/chrome/browser/reading_list", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/static_content", "//ios/chrome/test/fakes", "//ios/web", @@ -174,7 +171,6 @@ "//ios/chrome/app/theme:theme_grit", "//ios/chrome/browser", "//ios/chrome/browser/reading_list", - "//ios/chrome/browser/ui:ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/popup_menu:constants", "//ios/chrome/browser/ui/table_view",
diff --git a/ios/chrome/browser/ui/recent_tabs/BUILD.gn b/ios/chrome/browser/ui/recent_tabs/BUILD.gn index 18dec54..d5a7fec 100644 --- a/ios/chrome/browser/ui/recent_tabs/BUILD.gn +++ b/ios/chrome/browser/ui/recent_tabs/BUILD.gn
@@ -68,7 +68,6 @@ "//ios/chrome/browser/sessions", "//ios/chrome/browser/sessions:serialisation", "//ios/chrome/browser/sync", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/commands", @@ -127,10 +126,10 @@ "//base/test:test_support", "//components/strings", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication:eg_test_support", "//ios/chrome/browser/ui/history:history_ui", "//ios/chrome/browser/ui/table_view", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/public/provider/chrome/browser/signin:test_support",
diff --git a/ios/chrome/browser/ui/sad_tab/BUILD.gn b/ios/chrome/browser/ui/sad_tab/BUILD.gn index 6193e4d..a030ec7 100644 --- a/ios/chrome/browser/ui/sad_tab/BUILD.gn +++ b/ios/chrome/browser/ui/sad_tab/BUILD.gn
@@ -16,11 +16,11 @@ "//components/strings", "//components/ui_metrics", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/overscroll_actions", "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/third_party/material_components_ios", "//ios/third_party/material_roboto_font_loader_ios", "//ios/web",
diff --git a/ios/chrome/browser/ui/safe_mode/BUILD.gn b/ios/chrome/browser/ui/safe_mode/BUILD.gn index 8bd15874..902dfa3 100644 --- a/ios/chrome/browser/ui/safe_mode/BUILD.gn +++ b/ios/chrome/browser/ui/safe_mode/BUILD.gn
@@ -19,8 +19,8 @@ "//ios/chrome/browser", "//ios/chrome/browser/crash_report", "//ios/chrome/browser/safe_mode", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/fancy_ui", + "//ios/chrome/browser/ui/util", "//ui/gfx", ]
diff --git a/ios/chrome/browser/ui/settings/BUILD.gn b/ios/chrome/browser/ui/settings/BUILD.gn index 45cb9df..a4733ae 100644 --- a/ios/chrome/browser/ui/settings/BUILD.gn +++ b/ios/chrome/browser/ui/settings/BUILD.gn
@@ -136,7 +136,6 @@ "//ios/chrome/browser/signin", "//ios/chrome/browser/sync", "//ios/chrome/browser/translate", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/alert_coordinator", "//ios/chrome/browser/ui/authentication", @@ -173,6 +172,7 @@ "//ios/chrome/browser/web:web", "//ios/chrome/common", "//ios/chrome/common/favicon", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/images", "//ios/public/provider/chrome/browser/mailto",
diff --git a/ios/chrome/browser/ui/settings/cells/BUILD.gn b/ios/chrome/browser/ui/settings/cells/BUILD.gn index 88f3b8e96..6decd0d 100644 --- a/ios/chrome/browser/ui/settings/cells/BUILD.gn +++ b/ios/chrome/browser/ui/settings/cells/BUILD.gn
@@ -46,13 +46,14 @@ "//components/strings", "//ios/chrome/app/strings", "//ios/chrome/browser/browsing_data", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/icons", "//ios/chrome/browser/ui/table_view:styler", "//ios/chrome/browser/ui/table_view/cells", + "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/signin", "//ios/third_party/material_roboto_font_loader_ios",
diff --git a/ios/chrome/browser/ui/settings/cells/legacy/BUILD.gn b/ios/chrome/browser/ui/settings/cells/legacy/BUILD.gn index f050c516..8fbee99 100644 --- a/ios/chrome/browser/ui/settings/cells/legacy/BUILD.gn +++ b/ios/chrome/browser/ui/settings/cells/legacy/BUILD.gn
@@ -11,10 +11,11 @@ deps = [ "//components/strings", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/collection_view/cells", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/icons", + "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/third_party/material_roboto_font_loader_ios", "//ui/base", ]
diff --git a/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm b/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm index feab597..039e03c 100644 --- a/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/sync/sync_encryption_passphrase_table_view_controller.mm
@@ -81,8 +81,8 @@ self.shouldHideDoneButton = YES; browserState_ = browserState; NSString* userEmail = - AuthenticationServiceFactory::GetForBrowserState(browserState_) - ->GetAuthenticatedUserEmail(); + [AuthenticationServiceFactory::GetForBrowserState(browserState_) + ->GetAuthenticatedIdentity() userEmail]; DCHECK(userEmail); syncer::SyncService* service = ProfileSyncServiceFactory::GetForBrowserState(browserState_);
diff --git a/ios/chrome/browser/ui/side_swipe/BUILD.gn b/ios/chrome/browser/ui/side_swipe/BUILD.gn index 3a7827d..c9907e2f 100644 --- a/ios/chrome/browser/ui/side_swipe/BUILD.gn +++ b/ios/chrome/browser/ui/side_swipe/BUILD.gn
@@ -29,7 +29,6 @@ "//ios/chrome/browser/reading_list", "//ios/chrome/browser/snapshots", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/elements", "//ios/chrome/browser/ui/fullscreen", @@ -38,9 +37,11 @@ "//ios/chrome/browser/ui/tab_grid/grid:grid_ui", "//ios/chrome/browser/ui/tabs/requirements", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web", "//ios/chrome/browser/web_state_list", "//ios/chrome/common", + "//ios/chrome/common/ui_util", "//ios/web/common", "//ui/base", "//url",
diff --git a/ios/chrome/browser/ui/signin_interaction/BUILD.gn b/ios/chrome/browser/ui/signin_interaction/BUILD.gn index a922c7d..4c10906f 100644 --- a/ios/chrome/browser/ui/signin_interaction/BUILD.gn +++ b/ios/chrome/browser/ui/signin_interaction/BUILD.gn
@@ -41,12 +41,12 @@ "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/signin", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication:eg_test_support", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", "//ios/chrome/browser/ui/settings", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/public/provider/chrome/browser/signin:test_support",
diff --git a/ios/chrome/browser/ui/static_content/BUILD.gn b/ios/chrome/browser/ui/static_content/BUILD.gn index d0a03523..432873f 100644 --- a/ios/chrome/browser/ui/static_content/BUILD.gn +++ b/ios/chrome/browser/ui/static_content/BUILD.gn
@@ -13,7 +13,6 @@ deps = [ "//base", "//ios/chrome/browser/browser_state", - "//ios/chrome/browser/ui", "//ios/chrome/browser/url_loading", "//ios/web", "//net", @@ -34,7 +33,6 @@ "//base/test:test_support", "//ios/chrome/app/strings", "//ios/chrome/browser/browser_state:test_support", - "//ios/chrome/browser/ui", "//ios/chrome/browser/url_loading", "//ios/testing:ocmock_support", "//ios/web",
diff --git a/ios/chrome/browser/ui/tab_grid/BUILD.gn b/ios/chrome/browser/ui/tab_grid/BUILD.gn index d790322..9d94b75 100644 --- a/ios/chrome/browser/ui/tab_grid/BUILD.gn +++ b/ios/chrome/browser/ui/tab_grid/BUILD.gn
@@ -28,7 +28,6 @@ "//ios/chrome/browser/sessions:serialisation", "//ios/chrome/browser/snapshots", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/history",
diff --git a/ios/chrome/browser/ui/table_view/BUILD.gn b/ios/chrome/browser/ui/table_view/BUILD.gn index 69a9ebfd..ffe51bf 100644 --- a/ios/chrome/browser/ui/table_view/BUILD.gn +++ b/ios/chrome/browser/ui/table_view/BUILD.gn
@@ -71,9 +71,9 @@ ] deps = [ "//base", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/material_components", + "//ios/chrome/browser/ui/util", "//ios/third_party/material_components_ios", ] }
diff --git a/ios/chrome/browser/ui/tabs/BUILD.gn b/ios/chrome/browser/ui/tabs/BUILD.gn index 9e695206..9b5ffed 100644 --- a/ios/chrome/browser/ui/tabs/BUILD.gn +++ b/ios/chrome/browser/ui/tabs/BUILD.gn
@@ -45,7 +45,6 @@ "//ios/chrome/browser/browser_state", "//ios/chrome/browser/drag_and_drop", "//ios/chrome/browser/snapshots", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/bubble", "//ios/chrome/browser/ui/colors", "//ios/chrome/browser/ui/commands", @@ -62,6 +61,7 @@ "//ios/chrome/browser/web_state_list", "//ios/chrome/common", "//ios/chrome/common:common_extension", + "//ios/chrome/common/ui_util", "//ios/third_party/material_components_ios", "//ios/web", "//third_party/google_toolbox_for_mac", @@ -100,7 +100,7 @@ "//ios/chrome/browser/browser_state:test_support", "//ios/chrome/browser/sessions:test_support", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list", "//ios/chrome/browser/web_state_list:test_support", "//ios/web/public", @@ -121,7 +121,7 @@ ":tabs", "//ios/chrome/app/strings", "//ios/chrome/browser", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", "//ios/third_party/earl_grey:earl_grey+link",
diff --git a/ios/chrome/browser/ui/toolbar/BUILD.gn b/ios/chrome/browser/ui/toolbar/BUILD.gn index 3fb3028..b75aa7e1 100644 --- a/ios/chrome/browser/ui/toolbar/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/BUILD.gn
@@ -33,7 +33,6 @@ "//ios/chrome/browser/browser_state", "//ios/chrome/browser/reading_list", "//ios/chrome/browser/search_engines", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/bookmarks", "//ios/chrome/browser/ui/broadcaster", "//ios/chrome/browser/ui/commands", @@ -50,6 +49,7 @@ "//ios/chrome/browser/ui/toolbar/buttons", "//ios/chrome/browser/ui/toolbar/keyboard_assist", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/ui/voice", "//ios/chrome/browser/web_state_list", "//ios/chrome/common", @@ -84,7 +84,6 @@ deps = [ "//base", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui:ui", "//ios/chrome/browser/ui/activity_services/requirements", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/fullscreen:ui", @@ -160,7 +159,6 @@ "//components/strings", "//ios/chrome/app/strings", "//ios/chrome/browser/infobars", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", "//ios/chrome/browser/ui/infobars:test_support",
diff --git a/ios/chrome/browser/ui/toolbar/buttons/BUILD.gn b/ios/chrome/browser/ui/toolbar/buttons/BUILD.gn index 5697cda..3883d92 100644 --- a/ios/chrome/browser/ui/toolbar/buttons/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/buttons/BUILD.gn
@@ -36,12 +36,12 @@ "//components/strings", "//ios/chrome/app/strings", "//ios/chrome/app/theme", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_constant", "//ios/chrome/browser/ui/toolbar/public", "//ios/chrome/browser/ui/toolbar/public:feature_flags", "//ios/chrome/browser/ui/util", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/images", "//ios/third_party/material_components_ios",
diff --git a/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn b/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn index 92410e0..115b4894 100644 --- a/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn
@@ -49,9 +49,9 @@ "//ios/chrome/browser/bookmarks", "//ios/chrome/browser/browser_state:test_support", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/broadcaster", "//ios/chrome/browser/ui/toolbar/test", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web_state_list", "//ios/chrome/browser/web_state_list:test_support", "//ios/chrome/test:test_support",
diff --git a/ios/chrome/browser/ui/toolbar/keyboard_assist/BUILD.gn b/ios/chrome/browser/ui/toolbar/keyboard_assist/BUILD.gn index 951b9e3b..69c4f779 100644 --- a/ios/chrome/browser/ui/toolbar/keyboard_assist/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/keyboard_assist/BUILD.gn
@@ -25,12 +25,12 @@ "//base:i18n", "//ios/chrome/app/strings:ios_strings_grit", "//ios/chrome/browser", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/location_bar:constants", "//ios/chrome/browser/ui/omnibox:omnibox_internal", "//ios/chrome/browser/ui/toolbar/public", "//ios/chrome/browser/ui/util/", + "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/voice", "//ui/base",
diff --git a/ios/chrome/browser/ui/toolbar/public/BUILD.gn b/ios/chrome/browser/ui/toolbar/public/BUILD.gn index 3556fc9..093250ca 100644 --- a/ios/chrome/browser/ui/toolbar/public/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/public/BUILD.gn
@@ -19,11 +19,11 @@ deps = [ ":feature_flags", "//base", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/activity_services/requirements", "//ios/chrome/browser/ui/bubble", "//ios/chrome/browser/ui/fullscreen:ui", "//ios/chrome/browser/ui/ntp", + "//ios/chrome/browser/ui/util", "//ios/public/provider/chrome/browser/voice", ] }
diff --git a/ios/chrome/browser/ui/webui/BUILD.gn b/ios/chrome/browser/ui/webui/BUILD.gn index 9191715..5e5866af 100644 --- a/ios/chrome/browser/ui/webui/BUILD.gn +++ b/ios/chrome/browser/ui/webui/BUILD.gn
@@ -63,7 +63,7 @@ "//ios/chrome/browser/passwords", "//ios/chrome/browser/suggestions", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/util", "//ios/chrome/browser/ui/util:terms_util", "//ios/chrome/browser/web:java_script_console", "//ios/chrome/browser/web_state_list",
diff --git a/ios/chrome/browser/url_loading/BUILD.gn b/ios/chrome/browser/url_loading/BUILD.gn index ffb5bf3..6d03f8e 100644 --- a/ios/chrome/browser/url_loading/BUILD.gn +++ b/ios/chrome/browser/url_loading/BUILD.gn
@@ -39,7 +39,6 @@ "//ios/chrome/browser/sessions", "//ios/chrome/browser/snapshots", "//ios/chrome/browser/tabs", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/ntp:util", "//ios/chrome/browser/web",
diff --git a/ios/chrome/browser/web/BUILD.gn b/ios/chrome/browser/web/BUILD.gn index 1372a0cf..cda71ae 100644 --- a/ios/chrome/browser/web/BUILD.gn +++ b/ios/chrome/browser/web/BUILD.gn
@@ -40,7 +40,6 @@ "//ios/chrome/browser/browser_state", "//ios/chrome/browser/ntp", "//ios/chrome/browser/snapshots", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands:commands", "//ios/chrome/browser/ui/fullscreen", "//ios/chrome/browser/ui/util:util", @@ -298,7 +297,6 @@ "//ios/chrome/browser/find_in_page", "//ios/chrome/browser/infobars", "//ios/chrome/browser/passwords", - "//ios/chrome/browser/ui", "//ios/chrome/browser/web", "//ios/chrome/test/fakes", "//ios/web", @@ -340,9 +338,9 @@ "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/browser_state", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/popup_menu:constants", + "//ios/chrome/browser/ui/util", "//ios/chrome/test:test_support", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support",
diff --git a/ios/chrome/test/app/BUILD.gn b/ios/chrome/test/app/BUILD.gn index 354baee..2bc463a 100644 --- a/ios/chrome/test/app/BUILD.gn +++ b/ios/chrome/test/app/BUILD.gn
@@ -45,8 +45,8 @@ "//components/metrics", "//components/prefs", "//components/signin/core/browser", - "//components/sync:device_info", "//components/sync:test_support_fake_server", + "//components/sync/device_info", "//google_apis", "//ios/chrome/app:app_internal", "//ios/chrome/app/application_delegate:application_delegate_internal",
diff --git a/ios/chrome/test/data/testbadpass.pkpass b/ios/chrome/test/data/testbadpass.pkpass deleted file mode 100644 index 3f59060b..0000000 --- a/ios/chrome/test/data/testbadpass.pkpass +++ /dev/null
@@ -1 +0,0 @@ -This isn't even a zip file, it's so bad!
diff --git a/ios/chrome/test/data/testpass.pkpass b/ios/chrome/test/data/testpass.pkpass deleted file mode 100644 index 098e4cd..0000000 --- a/ios/chrome/test/data/testpass.pkpass +++ /dev/null Binary files differ
diff --git a/ios/chrome/test/earl_grey/BUILD.gn b/ios/chrome/test/earl_grey/BUILD.gn index 2280ac2..9a82b3f4 100644 --- a/ios/chrome/test/earl_grey/BUILD.gn +++ b/ios/chrome/test/earl_grey/BUILD.gn
@@ -247,7 +247,6 @@ "//components/strings", "//components/unified_consent", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication:authentication", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/bookmarks:bookmarks_ui", @@ -268,6 +267,7 @@ "//ios/chrome/browser/ui/table_view/cells", "//ios/chrome/browser/ui/toolbar/buttons", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/testing/earl_grey:earl_grey_support", "//ios/third_party/material_components_ios", @@ -329,7 +329,6 @@ "//components/strings", "//components/unified_consent", "//ios/chrome/app/strings", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/bookmarks:bookmarks_ui", "//ios/chrome/browser/ui/content_suggestions:content_suggestions_ui", @@ -344,6 +343,7 @@ "//ios/chrome/browser/ui/settings/sync", "//ios/chrome/browser/ui/static_content", "//ios/chrome/browser/ui/toolbar/public", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/testing/earl_grey:eg_app_support+eg2", "//ios/testing/earl_grey:eg_app_support+eg2",
diff --git a/ios/chrome/test/fakes/BUILD.gn b/ios/chrome/test/fakes/BUILD.gn index f3210934..3359c4c 100644 --- a/ios/chrome/test/fakes/BUILD.gn +++ b/ios/chrome/test/fakes/BUILD.gn
@@ -37,7 +37,6 @@ "//components/translate/core/common", "//ios/chrome/browser/download", "//ios/chrome/browser/store_kit", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/commands", "//ios/chrome/browser/ui/download", "//ios/chrome/browser/ui/overscroll_actions",
diff --git a/ios/showcase/payments/BUILD.gn b/ios/showcase/payments/BUILD.gn index f9429bd..1bd8577 100644 --- a/ios/showcase/payments/BUILD.gn +++ b/ios/showcase/payments/BUILD.gn
@@ -37,10 +37,10 @@ "//base", "//components/strings", "//ios/chrome/app/strings:ios_strings_grit", - "//ios/chrome/browser/ui", "//ios/chrome/browser/ui/autofill:autofill_ui", "//ios/chrome/browser/ui/payments:payments_ui", "//ios/chrome/browser/ui/settings", + "//ios/chrome/browser/ui/util", "//ios/chrome/test/earl_grey:test_support", "//ios/showcase/test", "//ios/third_party/earl_grey:earl_grey+link",
diff --git a/ios/web_view/BUILD.gn b/ios/web_view/BUILD.gn index af9e161..65b5f17 100644 --- a/ios/web_view/BUILD.gn +++ b/ios/web_view/BUILD.gn
@@ -162,8 +162,6 @@ "internal/pref_names.mm", "internal/signin/ios_web_view_signin_client.h", "internal/signin/ios_web_view_signin_client.mm", - "internal/signin/web_view_account_tracker_service_factory.h", - "internal/signin/web_view_account_tracker_service_factory.mm", "internal/signin/web_view_identity_manager_factory.h", "internal/signin/web_view_identity_manager_factory.mm", "internal/signin/web_view_profile_oauth2_token_service_ios_provider_impl.h", @@ -290,8 +288,8 @@ "//components/signin/ios/browser:active_state_manager", "//components/strings:components_strings_grit", "//components/sync", - "//components/sync:device_info", - "//components/sync:user_events", + "//components/sync/device_info", + "//components/sync/user_events", "//components/language/ios/browser", "//components/sync_sessions", "//components/translate/core/browser",
diff --git a/ios/web_view/internal/signin/web_view_account_tracker_service_factory.h b/ios/web_view/internal/signin/web_view_account_tracker_service_factory.h deleted file mode 100644 index 3118aa4..0000000 --- a/ios/web_view/internal/signin/web_view_account_tracker_service_factory.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2017 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_WEB_VIEW_INTERNAL_SIGNIN_WEB_VIEW_ACCOUNT_TRACKER_SERVICE_FACTORY_H_ -#define IOS_WEB_VIEW_INTERNAL_SIGNIN_WEB_VIEW_ACCOUNT_TRACKER_SERVICE_FACTORY_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/no_destructor.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" - -class AccountTrackerService; - -namespace ios_web_view { - -class WebViewBrowserState; - -// Singleton that owns all AccountTrackerServices and associates them with a -// browser state. -class WebViewAccountTrackerServiceFactory - : public BrowserStateKeyedServiceFactory { - public: - // Returns the instance of AccountTrackerService associated with this - // browser state (creating one if none exists). Returns nullptr if this - // browser state cannot have a AccountTrackerService (for example, if - // |browser_state| is incognito). - static AccountTrackerService* GetForBrowserState( - ios_web_view::WebViewBrowserState* browser_state); - - // Returns the instance of the AccountTrackerServiceFactory singleton. - static WebViewAccountTrackerServiceFactory* GetInstance(); - - private: - friend class base::NoDestructor<WebViewAccountTrackerServiceFactory>; - - WebViewAccountTrackerServiceFactory(); - ~WebViewAccountTrackerServiceFactory() override = default; - - // BrowserStateKeyedServiceFactory implementation. - void RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - std::unique_ptr<KeyedService> BuildServiceInstanceFor( - web::BrowserState* context) const override; - - DISALLOW_COPY_AND_ASSIGN(WebViewAccountTrackerServiceFactory); -}; - -} // namespace ios_web_view - -#endif // IOS_WEB_VIEW_INTERNAL_SIGNIN_WEB_VIEW_ACCOUNT_TRACKER_SERVICE_FACTORY_H_
diff --git a/ios/web_view/internal/signin/web_view_account_tracker_service_factory.mm b/ios/web_view/internal/signin/web_view_account_tracker_service_factory.mm deleted file mode 100644 index 6cbc331..0000000 --- a/ios/web_view/internal/signin/web_view_account_tracker_service_factory.mm +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2017 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 "ios/web_view/internal/signin/web_view_account_tracker_service_factory.h" - -#include <utility> - -#include "base/no_destructor.h" -#include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "ios/web_view/internal/web_view_browser_state.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -namespace ios_web_view { - -WebViewAccountTrackerServiceFactory::WebViewAccountTrackerServiceFactory() - : BrowserStateKeyedServiceFactory( - "AccountTrackerService", - BrowserStateDependencyManager::GetInstance()) { -} - -// static -AccountTrackerService* WebViewAccountTrackerServiceFactory::GetForBrowserState( - ios_web_view::WebViewBrowserState* browser_state) { - return static_cast<AccountTrackerService*>( - GetInstance()->GetServiceForBrowserState(browser_state, true)); -} - -// static -WebViewAccountTrackerServiceFactory* -WebViewAccountTrackerServiceFactory::GetInstance() { - static base::NoDestructor<WebViewAccountTrackerServiceFactory> instance; - return instance.get(); -} - -void WebViewAccountTrackerServiceFactory::RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) { - AccountTrackerService::RegisterPrefs(registry); -} - -std::unique_ptr<KeyedService> -WebViewAccountTrackerServiceFactory::BuildServiceInstanceFor( - web::BrowserState* context) const { - WebViewBrowserState* browser_state = - WebViewBrowserState::FromBrowserState(context); - std::unique_ptr<AccountTrackerService> service = - std::make_unique<AccountTrackerService>(); - service->Initialize(browser_state->GetPrefs(), base::FilePath()); - return service; -} - -} // namespace ios_web_view
diff --git a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm index 78b767f..e0dd681 100644 --- a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm +++ b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm
@@ -19,7 +19,6 @@ #include "components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h" #include "ios/web_view/internal/app/application_context.h" #include "ios/web_view/internal/signin/ios_web_view_signin_client.h" -#include "ios/web_view/internal/signin/web_view_account_tracker_service_factory.h" #include "ios/web_view/internal/signin/web_view_profile_oauth2_token_service_ios_provider_impl.h" #include "ios/web_view/internal/signin/web_view_signin_client_factory.h" #include "ios/web_view/internal/web_view_browser_state.h" @@ -38,7 +37,8 @@ namespace { std::unique_ptr<ProfileOAuth2TokenService> BuildTokenService( - WebViewBrowserState* browser_state) { + WebViewBrowserState* browser_state, + AccountTrackerService* account_tracker_service) { IOSWebViewSigninClient* signin_client = WebViewSigninClientFactory::GetForBrowserState(browser_state); auto token_service_provider = @@ -46,11 +46,19 @@ signin_client); auto delegate = std::make_unique<ProfileOAuth2TokenServiceIOSDelegate>( signin_client, std::move(token_service_provider), - WebViewAccountTrackerServiceFactory::GetForBrowserState(browser_state)); + account_tracker_service); return std::make_unique<ProfileOAuth2TokenService>(browser_state->GetPrefs(), std::move(delegate)); } +std::unique_ptr<AccountTrackerService> BuildAccountTrackerService( + WebViewBrowserState* browser_state) { + auto account_tracker_service = std::make_unique<AccountTrackerService>(); + account_tracker_service->Initialize(browser_state->GetPrefs(), + base::FilePath()); + return account_tracker_service; +} + std::unique_ptr<AccountFetcherService> BuildAccountFetcherService( SigninClient* signin_client, ProfileOAuth2TokenService* token_service, @@ -64,6 +72,7 @@ std::unique_ptr<SigninManager> BuildSigninManager( WebViewBrowserState* browser_state, + AccountTrackerService* account_tracker_service, ProfileOAuth2TokenService* token_service, GaiaCookieManagerService* gaia_cookie_manager_service) { // Clearing the sign in state on start up greatly simplifies the management of @@ -75,9 +84,8 @@ std::unique_ptr<SigninManager> service = std::make_unique<SigninManager>( WebViewSigninClientFactory::GetForBrowserState(browser_state), - token_service, - WebViewAccountTrackerServiceFactory::GetForBrowserState(browser_state), - gaia_cookie_manager_service, signin::AccountConsistencyMethod::kDisabled); + token_service, account_tracker_service, gaia_cookie_manager_service, + signin::AccountConsistencyMethod::kDisabled); service->Initialize(ApplicationContext::GetInstance()->GetLocalState()); return service; } @@ -92,7 +100,6 @@ : BrowserStateKeyedServiceFactory( "IdentityManager", BrowserStateDependencyManager::GetInstance()) { - DependsOn(WebViewAccountTrackerServiceFactory::GetInstance()); DependsOn(WebViewSigninClientFactory::GetInstance()); } @@ -114,7 +121,6 @@ // static void WebViewIdentityManagerFactory::EnsureFactoryAndDependeeFactoriesBuilt() { WebViewIdentityManagerFactory::GetInstance(); - WebViewAccountTrackerServiceFactory::GetInstance(); WebViewSigninClientFactory::GetInstance(); } @@ -125,22 +131,23 @@ WebViewBrowserState::FromBrowserState(context); // Construct the dependencies that IdentityManager will own. + std::unique_ptr<AccountTrackerService> account_tracker_service = + BuildAccountTrackerService(browser_state); + std::unique_ptr<ProfileOAuth2TokenService> token_service = - BuildTokenService(browser_state); + BuildTokenService(browser_state, account_tracker_service.get()); auto gaia_cookie_manager_service = std::make_unique<GaiaCookieManagerService>( token_service.get(), WebViewSigninClientFactory::GetForBrowserState(browser_state)); std::unique_ptr<SigninManager> signin_manager = BuildSigninManager( - browser_state, token_service.get(), gaia_cookie_manager_service.get()); - - AccountTrackerService* account_tracker_service = - WebViewAccountTrackerServiceFactory::GetForBrowserState(browser_state); + browser_state, account_tracker_service.get(), token_service.get(), + gaia_cookie_manager_service.get()); auto primary_account_mutator = std::make_unique<identity::PrimaryAccountMutatorImpl>( - account_tracker_service, signin_manager.get()); + account_tracker_service.get(), signin_manager.get()); auto accounts_cookie_mutator = std::make_unique<identity::AccountsCookieMutatorImpl>( @@ -153,10 +160,10 @@ std::unique_ptr<AccountFetcherService> account_fetcher_service = BuildAccountFetcherService( WebViewSigninClientFactory::GetForBrowserState(browser_state), - token_service.get(), account_tracker_service); + token_service.get(), account_tracker_service.get()); return std::make_unique<IdentityManagerWrapper>( - account_tracker_service, std::move(token_service), + std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(signin_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), /*accounts_mutator=*/nullptr, std::move(accounts_cookie_mutator),
diff --git a/net/cert/cert_verify_proc_unittest.cc b/net/cert/cert_verify_proc_unittest.cc index 4386d91f0..e23943c 100644 --- a/net/cert/cert_verify_proc_unittest.cc +++ b/net/cert/cert_verify_proc_unittest.cc
@@ -2667,7 +2667,8 @@ #if defined(USE_NSS_CERTS) SetURLRequestContextForNSSHttpIO(context->get()); #endif - SetGlobalCertNetFetcherForTesting(CreateCertNetFetcher(context->get())); + SetGlobalCertNetFetcherForTesting( + base::MakeRefCounted<CertNetFetcherImpl>(context->get())); initialization_complete_event->Signal(); }
diff --git a/net/cert_net/cert_net_fetcher_impl.cc b/net/cert_net/cert_net_fetcher_impl.cc index e2f2083..bda452a 100644 --- a/net/cert_net/cert_net_fetcher_impl.cc +++ b/net/cert_net/cert_net_fetcher_impl.cc
@@ -99,8 +99,6 @@ // The default timeout in seconds for fetch requests. const int kTimeoutSeconds = 15; -class RequestCore; -struct RequestParams; class Job; struct JobToRequestParamsComparator; @@ -113,13 +111,15 @@ // owned types doesn't come until C++17. using JobSet = std::map<Job*, std::unique_ptr<Job>, JobComparator>; +} // namespace + // AsyncCertNetFetcherImpl manages URLRequests in an async fashion on the // URLRequestContexts's task runner thread. // // * Schedules // * De-duplicates requests // * Handles timeouts -class AsyncCertNetFetcherImpl { +class CertNetFetcherImpl::AsyncCertNetFetcherImpl { public: // Initializes AsyncCertNetFetcherImpl using the specified URLRequestContext // for issuing requests. |context| must remain valid until Shutdown() is @@ -162,6 +162,8 @@ DISALLOW_COPY_AND_ASSIGN(AsyncCertNetFetcherImpl); }; +namespace { + // Policy for which URLs are allowed to be fetched. This is called both for the // initial URL and for each redirect. Returns OK on success or a net error // code on failure. @@ -196,9 +198,12 @@ HTTP_METHOD_POST, }; +} // namespace + // RequestCore tracks an outstanding call to Fetch(). It is // reference-counted for ease of sharing between threads. -class RequestCore : public base::RefCountedThreadSafe<RequestCore> { +class CertNetFetcherImpl::RequestCore + : public base::RefCountedThreadSafe<RequestCore> { public: explicit RequestCore(scoped_refptr<base::SingleThreadTaskRunner> task_runner) : completion_event_(base::WaitableEvent::ResetPolicy::MANUAL, @@ -273,7 +278,7 @@ DISALLOW_COPY_AND_ASSIGN(RequestCore); }; -struct RequestParams { +struct CertNetFetcherImpl::RequestParams { RequestParams(); bool operator<(const RequestParams& other) const; @@ -291,31 +296,36 @@ DISALLOW_COPY_AND_ASSIGN(RequestParams); }; -RequestParams::RequestParams() +CertNetFetcherImpl::RequestParams::RequestParams() : http_method(HTTP_METHOD_GET), max_response_bytes(0) {} -bool RequestParams::operator<(const RequestParams& other) const { +bool CertNetFetcherImpl::RequestParams::operator<( + const RequestParams& other) const { return std::tie(url, http_method, max_response_bytes, timeout) < std::tie(other.url, other.http_method, other.max_response_bytes, other.timeout); } +namespace { + // Job tracks an outstanding URLRequest as well as all of the pending requests // for it. class Job : public URLRequest::Delegate { public: - Job(std::unique_ptr<RequestParams> request_params, - AsyncCertNetFetcherImpl* parent); + Job(std::unique_ptr<CertNetFetcherImpl::RequestParams> request_params, + CertNetFetcherImpl::AsyncCertNetFetcherImpl* parent); ~Job() override; - const RequestParams& request_params() const { return *request_params_; } + const CertNetFetcherImpl::RequestParams& request_params() const { + return *request_params_; + } // Creates a request and attaches it to the job. When the job completes it // will notify the request of completion through OnJobCompleted. - void AttachRequest(scoped_refptr<RequestCore> request); + void AttachRequest(scoped_refptr<CertNetFetcherImpl::RequestCore> request); // Removes |request| from the job. - void DetachRequest(RequestCore* request); + void DetachRequest(CertNetFetcherImpl::RequestCore* request); // Creates and starts a URLRequest for the job. After the URLRequest has // completed, OnJobCompleted() will be invoked and all the registered requests @@ -363,10 +373,10 @@ void FailRequest(Error error); // The requests attached to this job. - std::vector<scoped_refptr<RequestCore>> requests_; + std::vector<scoped_refptr<CertNetFetcherImpl::RequestCore>> requests_; // The input parameters for starting a URLRequest. - std::unique_ptr<RequestParams> request_params_; + std::unique_ptr<CertNetFetcherImpl::RequestParams> request_params_; // The URLRequest response information. std::vector<uint8_t> response_body_; @@ -379,12 +389,14 @@ base::OneShotTimer timer_; // Non-owned pointer to the AsyncCertNetFetcherImpl that created this job. - AsyncCertNetFetcherImpl* parent_; + CertNetFetcherImpl::AsyncCertNetFetcherImpl* parent_; DISALLOW_COPY_AND_ASSIGN(Job); }; -void RequestCore::CancelJob() { +} // namespace + +void CertNetFetcherImpl::RequestCore::CancelJob() { if (!task_runner_->RunsTasksInCurrentSequence()) { task_runner_->PostTask(FROM_HERE, base::BindOnce(&RequestCore::CancelJob, this)); @@ -400,7 +412,7 @@ SignalImmediateError(); } -void RequestCore::SignalImmediateError() { +void CertNetFetcherImpl::RequestCore::SignalImmediateError() { // These data members are normally only written on the network thread, but it // is safe to write here from either thread. This is because // SignalImmediateError is only to be called before this request is attached @@ -416,8 +428,10 @@ completion_event_.Signal(); } -Job::Job(std::unique_ptr<RequestParams> request_params, - AsyncCertNetFetcherImpl* parent) +namespace { + +Job::Job(std::unique_ptr<CertNetFetcherImpl::RequestParams> request_params, + CertNetFetcherImpl::AsyncCertNetFetcherImpl* parent) : request_params_(std::move(request_params)), parent_(parent) {} Job::~Job() { @@ -425,12 +439,13 @@ Stop(); } -void Job::AttachRequest(scoped_refptr<RequestCore> request) { +void Job::AttachRequest( + scoped_refptr<CertNetFetcherImpl::RequestCore> request) { request->AttachedToJob(this); requests_.push_back(std::move(request)); } -void Job::DetachRequest(RequestCore* request) { +void Job::DetachRequest(CertNetFetcherImpl::RequestCore* request) { std::unique_ptr<Job> delete_this; auto it = std::find(requests_.begin(), requests_.end(), request); @@ -610,13 +625,16 @@ OnUrlRequestCompleted(result); } -AsyncCertNetFetcherImpl::AsyncCertNetFetcherImpl(URLRequestContext* context) +} // namespace + +CertNetFetcherImpl::AsyncCertNetFetcherImpl::AsyncCertNetFetcherImpl( + URLRequestContext* context) : context_(context) { // Allow creation to happen from another thread. thread_checker_.DetachFromThread(); } -AsyncCertNetFetcherImpl::~AsyncCertNetFetcherImpl() { +CertNetFetcherImpl::AsyncCertNetFetcherImpl::~AsyncCertNetFetcherImpl() { DCHECK(thread_checker_.CalledOnValidThread()); jobs_.clear(); } @@ -625,7 +643,7 @@ return job1->request_params() < job2->request_params(); } -void AsyncCertNetFetcherImpl::Fetch( +void CertNetFetcherImpl::AsyncCertNetFetcherImpl::Fetch( std::unique_ptr<RequestParams> request_params, scoped_refptr<RequestCore> request) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -647,7 +665,7 @@ job->StartURLRequest(context_); } -void AsyncCertNetFetcherImpl::Shutdown() { +void CertNetFetcherImpl::AsyncCertNetFetcherImpl::Shutdown() { DCHECK(thread_checker_.CalledOnValidThread()); for (const auto& job : jobs_) { job.first->Cancel(); @@ -655,14 +673,19 @@ jobs_.clear(); } +namespace { + struct JobToRequestParamsComparator { bool operator()(const JobSet::value_type& job, - const RequestParams& value) const { + const CertNetFetcherImpl::RequestParams& value) const { return job.first->request_params() < value; } }; -Job* AsyncCertNetFetcherImpl::FindJob(const RequestParams& params) { +} // namespace + +Job* CertNetFetcherImpl::AsyncCertNetFetcherImpl::FindJob( + const RequestParams& params) { DCHECK(thread_checker_.CalledOnValidThread()); // The JobSet is kept in sorted order so items can be found using binary @@ -674,7 +697,8 @@ return nullptr; } -std::unique_ptr<Job> AsyncCertNetFetcherImpl::RemoveJob(Job* job) { +std::unique_ptr<Job> CertNetFetcherImpl::AsyncCertNetFetcherImpl::RemoveJob( + Job* job) { DCHECK(thread_checker_.CalledOnValidThread()); auto it = jobs_.find(job); CHECK(it != jobs_.end()); @@ -683,9 +707,12 @@ return owned_job; } +namespace { + class CertNetFetcherRequestImpl : public CertNetFetcher::Request { public: - explicit CertNetFetcherRequestImpl(scoped_refptr<RequestCore> core) + explicit CertNetFetcherRequestImpl( + scoped_refptr<CertNetFetcherImpl::RequestCore> core) : core_(std::move(core)) { DCHECK(core_); } @@ -703,121 +730,110 @@ } private: - scoped_refptr<RequestCore> core_; -}; - -class CertNetFetcherImpl : public CertNetFetcher { - public: - explicit CertNetFetcherImpl(URLRequestContext* context) - : task_runner_(base::ThreadTaskRunnerHandle::Get()), context_(context) {} - - void Shutdown() override { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - if (impl_) { - impl_->Shutdown(); - impl_.reset(); - } - context_ = nullptr; - } - - std::unique_ptr<Request> FetchCaIssuers(const GURL& url, - int timeout_milliseconds, - int max_response_bytes) override { - std::unique_ptr<RequestParams> request_params(new RequestParams); - - request_params->url = url; - request_params->http_method = HTTP_METHOD_GET; - request_params->timeout = GetTimeout(timeout_milliseconds); - request_params->max_response_bytes = - GetMaxResponseBytes(max_response_bytes, kMaxResponseSizeInBytesForAia); - - return DoFetch(std::move(request_params)); - } - - std::unique_ptr<Request> FetchCrl(const GURL& url, - int timeout_milliseconds, - int max_response_bytes) override { - std::unique_ptr<RequestParams> request_params(new RequestParams); - - request_params->url = url; - request_params->http_method = HTTP_METHOD_GET; - request_params->timeout = GetTimeout(timeout_milliseconds); - request_params->max_response_bytes = - GetMaxResponseBytes(max_response_bytes, kMaxResponseSizeInBytesForCrl); - - return DoFetch(std::move(request_params)); - } - - WARN_UNUSED_RESULT std::unique_ptr<Request> FetchOcsp( - const GURL& url, - int timeout_milliseconds, - int max_response_bytes) override { - std::unique_ptr<RequestParams> request_params(new RequestParams); - - request_params->url = url; - request_params->http_method = HTTP_METHOD_GET; - request_params->timeout = GetTimeout(timeout_milliseconds); - request_params->max_response_bytes = - GetMaxResponseBytes(max_response_bytes, kMaxResponseSizeInBytesForAia); - - return DoFetch(std::move(request_params)); - } - - private: - ~CertNetFetcherImpl() override { - // The fetcher must be shutdown (at which point |context_| will be set to - // null) before destruction. - DCHECK(!context_); - } - - void DoFetchOnNetworkSequence(std::unique_ptr<RequestParams> request_params, - scoped_refptr<RequestCore> request) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - - if (!context_) { - // The fetcher might have been shutdown between when this task was posted - // and when it is running. In this case, signal the request and do not - // start a network request. - request->SignalImmediateError(); - return; - } - - if (!impl_) { - impl_.reset(new AsyncCertNetFetcherImpl(context_)); - } - - impl_->Fetch(std::move(request_params), request); - } - - std::unique_ptr<Request> DoFetch( - std::unique_ptr<RequestParams> request_params) { - scoped_refptr<RequestCore> request_core = new RequestCore(task_runner_); - - // If the fetcher has already been shutdown, DoFetchOnNetworkSequence will - // signal the request with an error. However, if the fetcher shuts down - // before DoFetchOnNetworkSequence runs and PostTask still returns true, - // then the request will hang (that is, WaitForResult will not return). - if (!task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&CertNetFetcherImpl::DoFetchOnNetworkSequence, this, - std::move(request_params), request_core))) { - request_core->SignalImmediateError(); - } - - return std::make_unique<CertNetFetcherRequestImpl>(std::move(request_core)); - } - - private: - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - // Not owned. |context_| must stay valid until Shutdown() is called. - URLRequestContext* context_ = nullptr; - std::unique_ptr<AsyncCertNetFetcherImpl> impl_; + scoped_refptr<CertNetFetcherImpl::RequestCore> core_; }; } // namespace -scoped_refptr<CertNetFetcher> CreateCertNetFetcher(URLRequestContext* context) { - return base::MakeRefCounted<CertNetFetcherImpl>(context); +CertNetFetcherImpl::CertNetFetcherImpl(URLRequestContext* context) + : task_runner_(base::ThreadTaskRunnerHandle::Get()), context_(context) {} + +CertNetFetcherImpl::~CertNetFetcherImpl() { + // The fetcher must be shutdown (at which point |context_| will be set to + // null) before destruction. + DCHECK(!context_); +} + +void CertNetFetcherImpl::Shutdown() { + DCHECK(task_runner_->RunsTasksInCurrentSequence()); + if (impl_) { + impl_->Shutdown(); + impl_.reset(); + } + context_ = nullptr; +} + +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchCaIssuers( + const GURL& url, + int timeout_milliseconds, + int max_response_bytes) { + std::unique_ptr<RequestParams> request_params(new RequestParams); + + request_params->url = url; + request_params->http_method = HTTP_METHOD_GET; + request_params->timeout = GetTimeout(timeout_milliseconds); + request_params->max_response_bytes = + GetMaxResponseBytes(max_response_bytes, kMaxResponseSizeInBytesForAia); + + return DoFetch(std::move(request_params)); +} + +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchCrl( + const GURL& url, + int timeout_milliseconds, + int max_response_bytes) { + std::unique_ptr<RequestParams> request_params(new RequestParams); + + request_params->url = url; + request_params->http_method = HTTP_METHOD_GET; + request_params->timeout = GetTimeout(timeout_milliseconds); + request_params->max_response_bytes = + GetMaxResponseBytes(max_response_bytes, kMaxResponseSizeInBytesForCrl); + + return DoFetch(std::move(request_params)); +} + +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchOcsp( + const GURL& url, + int timeout_milliseconds, + int max_response_bytes) { + std::unique_ptr<RequestParams> request_params(new RequestParams); + + request_params->url = url; + request_params->http_method = HTTP_METHOD_GET; + request_params->timeout = GetTimeout(timeout_milliseconds); + request_params->max_response_bytes = + GetMaxResponseBytes(max_response_bytes, kMaxResponseSizeInBytesForAia); + + return DoFetch(std::move(request_params)); +} + +void CertNetFetcherImpl::DoFetchOnNetworkSequence( + std::unique_ptr<RequestParams> request_params, + scoped_refptr<RequestCore> request) { + DCHECK(task_runner_->RunsTasksInCurrentSequence()); + + if (!context_) { + // The fetcher might have been shutdown between when this task was posted + // and when it is running. In this case, signal the request and do not + // start a network request. + request->SignalImmediateError(); + return; + } + + if (!impl_) { + impl_.reset(new AsyncCertNetFetcherImpl(context_)); + } + + impl_->Fetch(std::move(request_params), request); +} + +std::unique_ptr<CertNetFetcherImpl::Request> CertNetFetcherImpl::DoFetch( + std::unique_ptr<RequestParams> request_params) { + scoped_refptr<RequestCore> request_core = new RequestCore(task_runner_); + + // If the fetcher has already been shutdown, DoFetchOnNetworkSequence will + // signal the request with an error. However, if the fetcher shuts down + // before DoFetchOnNetworkSequence runs and PostTask still returns true, + // then the request will hang (that is, WaitForResult will not return). + if (!task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&CertNetFetcherImpl::DoFetchOnNetworkSequence, this, + std::move(request_params), request_core))) { + request_core->SignalImmediateError(); + } + + return std::make_unique<CertNetFetcherRequestImpl>(std::move(request_core)); } } // namespace net
diff --git a/net/cert_net/cert_net_fetcher_impl.h b/net/cert_net/cert_net_fetcher_impl.h index 42a53c2..efb2bed7 100644 --- a/net/cert_net/cert_net_fetcher_impl.h +++ b/net/cert_net/cert_net_fetcher_impl.h
@@ -7,19 +7,56 @@ #include "base/memory/ref_counted.h" #include "net/base/net_export.h" +#include "net/cert/cert_net_fetcher.h" + +namespace base { +class SingleThreadTaskRunner; +} namespace net { -class CertNetFetcher; class URLRequestContext; -// Creates a CertNetFetcher that issues requests through the provided +// A CertNetFetcher that issues requests through the provided // URLRequestContext. The URLRequestContext must stay valid until the returned // CertNetFetcher's Shutdown method is called. The CertNetFetcher is to be // created and shutdown on the network thread. Its Fetch methods are to be used // on a *different* thread, since it gives a blocking interface to URL fetching. -NET_EXPORT scoped_refptr<CertNetFetcher> CreateCertNetFetcher( - URLRequestContext* context); +class NET_EXPORT CertNetFetcherImpl : public CertNetFetcher { + public: + class AsyncCertNetFetcherImpl; + class RequestCore; + struct RequestParams; + + explicit CertNetFetcherImpl(URLRequestContext* context); + + // CertNetFetcher impl: + void Shutdown() override; + std::unique_ptr<Request> FetchCaIssuers(const GURL& url, + int timeout_milliseconds, + int max_response_bytes) override; + std::unique_ptr<Request> FetchCrl(const GURL& url, + int timeout_milliseconds, + int max_response_bytes) override; + WARN_UNUSED_RESULT std::unique_ptr<Request> FetchOcsp( + const GURL& url, + int timeout_milliseconds, + int max_response_bytes) override; + + private: + ~CertNetFetcherImpl() override; + + void DoFetchOnNetworkSequence(std::unique_ptr<RequestParams> request_params, + scoped_refptr<RequestCore> request); + + std::unique_ptr<Request> DoFetch( + std::unique_ptr<RequestParams> request_params); + + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + // Not owned. |context_| must stay valid until Shutdown() is called. + URLRequestContext* context_ = nullptr; + std::unique_ptr<AsyncCertNetFetcherImpl> impl_; +}; } // namespace net
diff --git a/net/cert_net/cert_net_fetcher_impl_unittest.cc b/net/cert_net/cert_net_fetcher_impl_unittest.cc index 87bfddf..0523cb0 100644 --- a/net/cert_net/cert_net_fetcher_impl_unittest.cc +++ b/net/cert_net/cert_net_fetcher_impl_unittest.cc
@@ -134,7 +134,7 @@ CertNetFetcher* fetcher() const { return fetcher_.get(); } void CreateFetcherOnNetworkThread(base::WaitableEvent* done) { - fetcher_ = CreateCertNetFetcher(&state_->context); + fetcher_ = base::MakeRefCounted<CertNetFetcherImpl>(&state_->context); done->Signal(); }
diff --git a/net/cookies/canonical_cookie.cc b/net/cookies/canonical_cookie.cc index f75dc14..327d9d8 100644 --- a/net/cookies/canonical_cookie.cc +++ b/net/cookies/canonical_cookie.cc
@@ -211,13 +211,6 @@ return nullptr; } - if (options.exclude_httponly() && parsed_cookie.IsHttpOnly()) { - DVLOG(net::cookie_util::kVlogSetCookies) - << "Create() is not creating a httponly cookie"; - *status = CookieInclusionStatus::EXCLUDE_HTTP_ONLY; - return nullptr; - } - std::string cookie_domain; if (!GetCookieDomain(url, parsed_cookie, &cookie_domain)) { DVLOG(net::cookie_util::kVlogSetCookies) @@ -264,8 +257,12 @@ creation_time, cookie_expires, creation_time, parsed_cookie.IsSecure(), parsed_cookie.IsHttpOnly(), parsed_cookie.SameSite(), parsed_cookie.Priority())); + + *status = cc->IsSetPermittedInContext(options); + if (*status != CookieInclusionStatus::INCLUDE) + return nullptr; + DCHECK(cc->IsCanonical()); - *status = CookieInclusionStatus::INCLUDE; return cc; } @@ -427,6 +424,50 @@ return CanonicalCookie::CookieInclusionStatus::INCLUDE; } +CanonicalCookie::CookieInclusionStatus CanonicalCookie::IsSetPermittedInContext( + const CookieOptions& options) const { + if (options.exclude_httponly() && IsHttpOnly()) { + DVLOG(net::cookie_util::kVlogSetCookies) + << "HttpOnly cookie not permitted in script context."; + return CookieInclusionStatus::EXCLUDE_HTTP_ONLY; + } + + switch (GetEffectiveSameSite()) { + case CookieSameSite::STRICT_MODE: + // This intentionally checks for `< SAME_SITE_LAX`, as we allow + // `SameSite=Strict` cookies to be set for top-level navigations that + // qualify for receipt of `SameSite=Lax` cookies. + if (options.same_site_cookie_context() < + CookieOptions::SameSiteCookieContext::SAME_SITE_LAX) { + DVLOG(net::cookie_util::kVlogSetCookies) + << "Trying to set a `SameSite=Strict` cookie from a " + "cross-site URL."; + return CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT; + } + break; + case CookieSameSite::LAX_MODE: + if (options.same_site_cookie_context() < + CookieOptions::SameSiteCookieContext::SAME_SITE_LAX) { + if (SameSite() == CookieSameSite::UNSPECIFIED) { + DVLOG(net::cookie_util::kVlogSetCookies) + << "Cookies with no known SameSite attribute being treated as " + "lax; attempt to set from a cross-site URL denied."; + return CanonicalCookie::CookieInclusionStatus:: + EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX; + } else { + DVLOG(net::cookie_util::kVlogSetCookies) + << "Trying to set a `SameSite=Lax` cookie from a cross-site URL."; + return CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_LAX; + } + } + break; + default: + break; + } + + return CookieInclusionStatus::INCLUDE; +} + std::string CanonicalCookie::DebugString() const { return base::StringPrintf( "name: %s value: %s domain: %s path: %s creation: %" PRId64,
diff --git a/net/cookies/canonical_cookie.h b/net/cookies/canonical_cookie.h index 97a74305..560918f 100644 --- a/net/cookies/canonical_cookie.h +++ b/net/cookies/canonical_cookie.h
@@ -197,6 +197,14 @@ const GURL& url, const CookieOptions& options) const; + // Returns if the cookie with given attributes can be set in context described + // by |options|, and if no, describes why. + // WARNING: this does not cover checking whether secure cookies are set in + // a secure schema, since whether the schema is secure isn't part of + // |options|. + CookieInclusionStatus IsSetPermittedInContext( + const CookieOptions& options) const; + std::string DebugString() const; static std::string CanonPathWithString(const GURL& url,
diff --git a/net/cookies/canonical_cookie_unittest.cc b/net/cookies/canonical_cookie_unittest.cc index 62c40fda3..df20ce59 100644 --- a/net/cookies/canonical_cookie_unittest.cc +++ b/net/cookies/canonical_cookie_unittest.cc
@@ -191,6 +191,69 @@ EXPECT_EQ(CookieSameSite::UNSPECIFIED, cookie->SameSite()); } +TEST(CanonicalCookieTest, CreateSameSiteInCrossSiteContexts) { + GURL url("http://www.example.com/test/foo.html"); + base::Time now = base::Time::Now(); + std::unique_ptr<CanonicalCookie> cookie; + CookieOptions options; + + // In SAME_SITE_STRICT contexts, any `SameSite` value can be set: + options.set_same_site_cookie_context( + CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Strict", now, options); + EXPECT_TRUE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Lax", now, options); + EXPECT_TRUE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2;", now, options); + EXPECT_TRUE(cookie.get()); + + // In SAME_SITE_LAX contexts, any `SameSite` value can be set: + options.set_same_site_cookie_context( + CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Strict", now, options); + EXPECT_TRUE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Lax", now, options); + EXPECT_TRUE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2;", now, options); + EXPECT_TRUE(cookie.get()); + + { + // In CROSS_SITE contexts, the `SameSite` attribute must be omitted, + // or none --- if the experiment requiring explicit none isn't on. + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(features::kSameSiteByDefaultCookies); + + options.set_same_site_cookie_context( + CookieOptions::SameSiteCookieContext::CROSS_SITE); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Strict", now, options); + EXPECT_FALSE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Lax", now, options); + EXPECT_FALSE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=None", now, options); + EXPECT_TRUE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2;", now, options); + EXPECT_TRUE(cookie.get()); + } + + { + // With the kSameSiteByDefaultCookies experiments, an explicit + // SameSite=None is required in a cross-site environment. + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(features::kSameSiteByDefaultCookies); + + options.set_same_site_cookie_context( + CookieOptions::SameSiteCookieContext::CROSS_SITE); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Strict", now, options); + EXPECT_FALSE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Lax", now, options); + EXPECT_FALSE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=None", now, options); + EXPECT_TRUE(cookie.get()); + cookie = CanonicalCookie::Create(url, "A=2;", now, options); + EXPECT_FALSE(cookie.get()); + } +} + TEST(CanonicalCookieTest, CreateInvalidHttpOnly) { GURL url("http://www.example.com/test/foo.html"); base::Time now = base::Time::Now(); @@ -541,43 +604,47 @@ TEST(CanonicalCookieTest, IncludeSameSiteForSameSiteURL) { GURL url("https://example.test"); base::Time creation_time = base::Time::Now(); - CookieOptions options; + CookieOptions creation_options; + creation_options.set_same_site_cookie_context( + CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); + + CookieOptions request_options; std::unique_ptr<CanonicalCookie> cookie; // `SameSite=Strict` cookies are included for a URL only if the options' // SameSiteCookieMode is SAME_SITE_STRICT. cookie = CanonicalCookie::Create(url, "A=2; SameSite=Strict", creation_time, - options); + creation_options); EXPECT_EQ(CookieSameSite::STRICT_MODE, cookie->SameSite()); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::CROSS_SITE); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); // `SameSite=Lax` cookies are included for a URL only if the options' // SameSiteCookieMode is SAME_SITE_STRICT or SAME_SITE_LAX. - cookie = - CanonicalCookie::Create(url, "A=2; SameSite=Lax", creation_time, options); + cookie = CanonicalCookie::Create(url, "A=2; SameSite=Lax", creation_time, + creation_options); EXPECT_EQ(CookieSameSite::LAX_MODE, cookie->SameSite()); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::CROSS_SITE); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_LAX); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); // `SameSite=Extended` cookies are included for a URL only if the options' @@ -585,58 +652,58 @@ // TODO(crbug.com/953995): Right now Extended behaves the same as Lax. // Implement Extended. cookie = CanonicalCookie::Create(url, "A=2; SameSite=Extended", creation_time, - options); + creation_options); EXPECT_EQ(CookieSameSite::EXTENDED_MODE, cookie->SameSite()); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::CROSS_SITE); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_LAX); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); // `SameSite=None` cookies are included for all URLs. cookie = CanonicalCookie::Create(url, "A=2; SameSite=None", creation_time, - options); + creation_options); EXPECT_EQ(CookieSameSite::NO_RESTRICTION, cookie->SameSite()); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::CROSS_SITE); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); // Cookies with no SameSite attribute are parsed as // CookieSameSite::UNSPECIFIED, and inclusion depends on the FeatureList. - cookie = CanonicalCookie::Create(url, "A=2", creation_time, options); + cookie = CanonicalCookie::Create(url, "A=2", creation_time, creation_options); EXPECT_EQ(CookieSameSite::UNSPECIFIED, cookie->SameSite()); { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kSameSiteByDefaultCookies); // With SameSiteByDefault disabled, the cookie is included for all requests. - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::CROSS_SITE); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); } { @@ -645,18 +712,18 @@ // With SameSiteByDefault enabled, the cookie is included for a URL only if // the options' SameSiteCookieMode is SAME_SITE_STRICT or SAME_SITE_LAX. - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::CROSS_SITE); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus:: EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); - options.set_same_site_cookie_context( + request_options.set_same_site_cookie_context( CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - EXPECT_EQ(cookie->IncludeForRequestURL(url, options), + EXPECT_EQ(cookie->IncludeForRequestURL(url, request_options), CanonicalCookie::CookieInclusionStatus::INCLUDE); } } @@ -738,7 +805,9 @@ status); EXPECT_FALSE(CanonicalCookie::Create(https_url, "__Secure-A=B; httponly", creation_time, options, &status)); - EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, status); + // (EXCLUDE_HTTP_ONLY would be fine, too) + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + status); // A typoed prefix does not have to be Secure. EXPECT_TRUE(CanonicalCookie::Create(https_url, "__secure-A=B; Secure", @@ -1413,4 +1482,129 @@ EXPECT_EQ("/foo%7F", cc->Path()); } +TEST(CanonicalCookieTest, IsSetPermittedInContext) { + GURL url("http://www.example.com/test"); + base::Time current_time = base::Time::Now(); + + CanonicalCookie cookie_scriptable( + "A", "2", "www.example.com", "/test", current_time, base::Time(), + base::Time(), true /*secure*/, false /*httponly*/, + CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT); + CanonicalCookie cookie_httponly( + "A", "2", "www.example.com", "/test", current_time, base::Time(), + base::Time(), true /*secure*/, true /*httponly*/, + CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT); + + CookieOptions context_script; + CookieOptions context_network; + context_network.set_include_httponly(); + + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_scriptable.IsSetPermittedInContext(context_network)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_scriptable.IsSetPermittedInContext(context_script)); + + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_httponly.IsSetPermittedInContext(context_network)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, + cookie_httponly.IsSetPermittedInContext(context_script)); + + CookieOptions context_cross_site; + CookieOptions context_same_site_lax; + context_same_site_lax.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); + CookieOptions context_same_site_strict; + context_same_site_strict.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); + + { + CanonicalCookie cookie_same_site_unrestricted( + "A", "2", "www.example.com", "/test", current_time, base::Time(), + base::Time(), true /*secure*/, false /*httponly*/, + CookieSameSite::NO_RESTRICTION, COOKIE_PRIORITY_DEFAULT); + + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unrestricted.IsSetPermittedInContext( + context_cross_site)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unrestricted.IsSetPermittedInContext( + context_same_site_lax)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unrestricted.IsSetPermittedInContext( + context_same_site_strict)); + } + + { + CanonicalCookie cookie_same_site_lax( + "A", "2", "www.example.com", "/test", current_time, base::Time(), + base::Time(), true /*secure*/, false /*httponly*/, + CookieSameSite::LAX_MODE, COOKIE_PRIORITY_DEFAULT); + + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_LAX, + cookie_same_site_lax.IsSetPermittedInContext(context_cross_site)); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_lax.IsSetPermittedInContext(context_same_site_lax)); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_lax.IsSetPermittedInContext(context_same_site_strict)); + } + + { + CanonicalCookie cookie_same_site_strict( + "A", "2", "www.example.com", "/test", current_time, base::Time(), + base::Time(), true /*secure*/, false /*httponly*/, + CookieSameSite::STRICT_MODE, COOKIE_PRIORITY_DEFAULT); + + // TODO(morlovich): Do compatibility testing on whether set of strict in lax + // context really should be accepted. + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT, + cookie_same_site_strict.IsSetPermittedInContext(context_cross_site)); + EXPECT_EQ( + CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_strict.IsSetPermittedInContext(context_same_site_lax)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_strict.IsSetPermittedInContext( + context_same_site_strict)); + } + + // Behavior of UNSPECIFIED depends on an experiment. + CanonicalCookie cookie_same_site_unspecified( + "A", "2", "www.example.com", "/test", current_time, base::Time(), + base::Time(), true /*secure*/, false /*httponly*/, + CookieSameSite::UNSPECIFIED, COOKIE_PRIORITY_DEFAULT); + + { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(features::kSameSiteByDefaultCookies); + + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unspecified.IsSetPermittedInContext( + context_cross_site)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unspecified.IsSetPermittedInContext( + context_same_site_lax)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unspecified.IsSetPermittedInContext( + context_same_site_strict)); + } + + { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(features::kSameSiteByDefaultCookies); + + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus:: + EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX, + cookie_same_site_unspecified.IsSetPermittedInContext( + context_cross_site)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unspecified.IsSetPermittedInContext( + context_same_site_lax)); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::INCLUDE, + cookie_same_site_unspecified.IsSetPermittedInContext( + context_same_site_strict)); + } +} + } // namespace net
diff --git a/net/cookies/cookie_monster.cc b/net/cookies/cookie_monster.cc index e7ad8df..1241126 100644 --- a/net/cookies/cookie_monster.cc +++ b/net/cookies/cookie_monster.cc
@@ -1194,10 +1194,12 @@ return; } - if (cc->IsHttpOnly() && options.exclude_httponly()) { - MaybeRunCookieCallback( - std::move(callback), - CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY); + CanonicalCookie::CookieInclusionStatus status = + cc->IsSetPermittedInContext(options); + if (status != CanonicalCookie::CookieInclusionStatus::INCLUDE) { + // IsSetPermittedInContext already logs if it rejects a cookie, so + // CookieMonster doesn't need to. + MaybeRunCookieCallback(std::move(callback), status); return; } @@ -1219,7 +1221,7 @@ base::Time creation_date_to_inherit; - CanonicalCookie::CookieInclusionStatus status = DeleteAnyEquivalentCookie( + status = DeleteAnyEquivalentCookie( key, *cc, secure_source, options.exclude_httponly(), already_expired, &creation_date_to_inherit);
diff --git a/net/cookies/cookie_monster_unittest.cc b/net/cookies/cookie_monster_unittest.cc index 3256a998..80d8e592 100644 --- a/net/cookies/cookie_monster_unittest.cc +++ b/net/cookies/cookie_monster_unittest.cc
@@ -3224,6 +3224,34 @@ EXPECT_EQ(1U, delete_callback.result()); } +TEST_F(CookieMonsterTest, NoSmuggling) { + GURL url("http://www.example.com"); + std::string cookie_line = "foo=bar; SameSite=Lax"; + + CookieMonster cm(nullptr, nullptr); + CookieOptions env_same_site; + env_same_site.set_same_site_cookie_context( + CookieOptions::SameSiteCookieContext::SAME_SITE_LAX); + + CookieOptions env_cross_site; + env_cross_site.set_same_site_cookie_context( + CookieOptions::SameSiteCookieContext::CROSS_SITE); + + // Cookie can be created successfully, since environment permits it. + auto cookie = CanonicalCookie::Create(url, cookie_line, base::Time::Now(), + env_same_site); + ASSERT_TRUE(cookie != nullptr); + + // ... but the environment is re-checked on set, so if it's different, this + // may be rejected then. + ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback; + cm.SetCanonicalCookieAsync(std::move(cookie), "http", env_cross_site, + callback.MakeCallback()); + callback.WaitUntilDone(); + EXPECT_EQ(CanonicalCookie::CookieInclusionStatus::EXCLUDE_SAMESITE_LAX, + callback.result()); +} + class CookieMonsterNotificationTest : public CookieMonsterTest { public: CookieMonsterNotificationTest()
diff --git a/net/cookies/cookie_store_unittest.h b/net/cookies/cookie_store_unittest.h index 67892c3..ed7c0d8 100644 --- a/net/cookies/cookie_store_unittest.h +++ b/net/cookies/cookie_store_unittest.h
@@ -206,6 +206,8 @@ CookieOptions options; if (can_modify_httponly) options.set_include_httponly(); + options.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); cs->SetCanonicalCookieAsync(std::move(cookie), std::move(source_scheme), options, callback.MakeCallback()); callback.WaitUntilDone(); @@ -258,6 +260,8 @@ CookieOptions options; if (can_modify_httponly) options.set_include_httponly(); + options.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); cs->SetCanonicalCookieAsync(std::move(cookie), std::move(source_scheme), options, callback.MakeCallback()); callback.WaitUntilDone();
diff --git a/net/http/http_stream_factory_unittest.cc b/net/http/http_stream_factory_unittest.cc index 17336429..9a4f9450 100644 --- a/net/http/http_stream_factory_unittest.cc +++ b/net/http/http_stream_factory_unittest.cc
@@ -2000,24 +2000,21 @@ // Create some HTTP/2 sockets. std::vector<std::unique_ptr<ClientSocketHandle>> handles; for (size_t i = 0; i < kNumIdleSockets; i++) { - scoped_refptr<TransportSocketParams> transport_params( - new TransportSocketParams(host_port_pair, OnHostResolutionCallback())); - auto connection = std::make_unique<ClientSocketHandle>(); TestCompletionCallback callback; - SSLConfig ssl_config; - scoped_refptr<SSLSocketParams> ssl_params( - new SSLSocketParams(transport_params, nullptr, nullptr, host_port_pair, - ssl_config, PRIVACY_MODE_DISABLED)); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + std::make_unique<SSLConfig>() /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); ClientSocketPool::GroupId group_id(host_port_pair, ClientSocketPool::SocketType::kSsl, PrivacyMode::PRIVACY_MODE_DISABLED); int rv = connection->Init( - group_id, - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(ssl_params), - MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), + group_id, socket_params, MEDIUM, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL, ProxyServer::Direct()), NetLogWithSource());
diff --git a/net/socket/client_socket_pool.cc b/net/socket/client_socket_pool.cc index 98c1b6a..ac9f1a9 100644 --- a/net/socket/client_socket_pool.cc +++ b/net/socket/client_socket_pool.cc
@@ -24,93 +24,27 @@ // The maximum duration, in seconds, to keep used idle persistent sockets alive. int64_t g_used_idle_socket_timeout_s = 300; // 5 minutes -// TODO(mmenke): Once the socket pool arguments are no longer needed, remove -// this method and use TransportConnectJob::CreateTransportConnectJob() -// directly. -std::unique_ptr<ConnectJob> CreateTransportConnectJob( - scoped_refptr<TransportSocketParams> transport_socket_params, - RequestPriority priority, - const SocketTag& socket_tag, - const CommonConnectJobParams* common_connect_job_params, - ConnectJob::Delegate* delegate) { - return TransportConnectJob::CreateTransportConnectJob( - std::move(transport_socket_params), priority, socket_tag, - common_connect_job_params, delegate, nullptr /* net_log */); -} - -std::unique_ptr<ConnectJob> CreateSOCKSConnectJob( - scoped_refptr<SOCKSSocketParams> socks_socket_params, - RequestPriority priority, - const SocketTag& socket_tag, - const CommonConnectJobParams* common_connect_job_params, - ConnectJob::Delegate* delegate) { - return std::make_unique<SOCKSConnectJob>( - priority, socket_tag, common_connect_job_params, - std::move(socks_socket_params), delegate, nullptr /* net_log */); -} - -std::unique_ptr<ConnectJob> CreateSSLConnectJob( - scoped_refptr<SSLSocketParams> ssl_socket_params, - RequestPriority priority, - const SocketTag& socket_tag, - const CommonConnectJobParams* common_connect_job_params, - ConnectJob::Delegate* delegate) { - return std::make_unique<SSLConnectJob>( - priority, socket_tag, common_connect_job_params, - std::move(ssl_socket_params), delegate, nullptr /* net_log */); -} - -std::unique_ptr<ConnectJob> CreateHttpProxyConnectJob( - scoped_refptr<HttpProxySocketParams> http_proxy_socket_params, - RequestPriority priority, - const SocketTag& socket_tag, - const CommonConnectJobParams* common_connect_job_params, - ConnectJob::Delegate* delegate) { - return std::make_unique<HttpProxyConnectJob>( - priority, socket_tag, common_connect_job_params, - std::move(http_proxy_socket_params), delegate, nullptr /* net_log */); -} - } // namespace ClientSocketPool::SocketParams::SocketParams( - const CreateConnectJobCallback& create_connect_job_callback) - : create_connect_job_callback_(create_connect_job_callback) {} - -scoped_refptr<ClientSocketPool::SocketParams> -ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - scoped_refptr<TransportSocketParams> transport_client_params) { - CreateConnectJobCallback callback = base::BindRepeating( - &CreateTransportConnectJob, std::move(transport_client_params)); - return base::MakeRefCounted<SocketParams>(callback); -} - -scoped_refptr<ClientSocketPool::SocketParams> -ClientSocketPool::SocketParams::CreateFromSOCKSSocketParams( - scoped_refptr<SOCKSSocketParams> socks_socket_params) { - CreateConnectJobCallback callback = base::BindRepeating( - &CreateSOCKSConnectJob, std::move(socks_socket_params)); - return base::MakeRefCounted<SocketParams>(callback); -} - -scoped_refptr<ClientSocketPool::SocketParams> -ClientSocketPool::SocketParams::CreateFromSSLSocketParams( - scoped_refptr<SSLSocketParams> ssl_socket_params) { - CreateConnectJobCallback callback = - base::BindRepeating(&CreateSSLConnectJob, std::move(ssl_socket_params)); - return base::MakeRefCounted<SocketParams>(callback); -} - -scoped_refptr<ClientSocketPool::SocketParams> -ClientSocketPool::SocketParams::CreateFromHttpProxySocketParams( - scoped_refptr<HttpProxySocketParams> http_proxy_socket_params) { - CreateConnectJobCallback callback = base::BindRepeating( - &CreateHttpProxyConnectJob, std::move(http_proxy_socket_params)); - return base::MakeRefCounted<SocketParams>(callback); -} + MutableNetworkTrafficAnnotationTag proxy_annotation_tag, + std::unique_ptr<SSLConfig> ssl_config_for_origin, + std::unique_ptr<SSLConfig> ssl_config_for_proxy, + const OnHostResolutionCallback& resolution_callback) + : proxy_annotation_tag_(proxy_annotation_tag), + ssl_config_for_origin_(std::move(ssl_config_for_origin)), + ssl_config_for_proxy_(std::move(ssl_config_for_proxy)), + resolution_callback_(resolution_callback) {} ClientSocketPool::SocketParams::~SocketParams() = default; +scoped_refptr<ClientSocketPool::SocketParams> +ClientSocketPool::SocketParams::CreateForHttpForTesting() { + return base::MakeRefCounted<SocketParams>( + MutableNetworkTrafficAnnotationTag(), nullptr /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); +} + ClientSocketPool::GroupId::GroupId() : socket_type_(SocketType::kHttp), privacy_mode_(PrivacyMode::PRIVACY_MODE_DISABLED) {} @@ -199,7 +133,16 @@ RequestPriority request_priority, SocketTag socket_tag, ConnectJob::Delegate* delegate) { - return socket_params->create_connect_job_callback().Run( + bool using_ssl = + (group_id.socket_type() == ClientSocketPool::SocketType::kSsl || + group_id.socket_type() == + ClientSocketPool::SocketType::kSslVersionInterferenceProbe); + return ConnectJob::CreateConnectJob( + using_ssl, group_id.destination(), proxy_server, + socket_params->proxy_annotation_tag(), + socket_params->ssl_config_for_origin(), + socket_params->ssl_config_for_proxy(), is_for_websockets, + group_id.privacy_mode(), socket_params->resolution_callback(), request_priority, socket_tag, common_connect_job_params, delegate); }
diff --git a/net/socket/client_socket_pool.h b/net/socket/client_socket_pool.h index 0e17b3b..5658c61 100644 --- a/net/socket/client_socket_pool.h +++ b/net/socket/client_socket_pool.h
@@ -21,6 +21,7 @@ #include "net/log/net_log_capture_mode.h" #include "net/socket/connect_job.h" #include "net/socket/socket_tag.h" +#include "net/traffic_annotation/network_traffic_annotation.h" namespace base { class DictionaryValue; @@ -35,14 +36,11 @@ class ClientSocketHandle; struct CommonConnectJobParams; class HttpAuthController; -class HttpProxySocketParams; class HttpResponseInfo; class NetLogWithSource; class ProxyServer; -class SOCKSSocketParams; -class SSLSocketParams; +struct SSLConfig; class StreamSocket; -class TransportSocketParams; // ClientSocketPools are layered. This defines an interface for lower level // socket pools to communicate with higher layer pools. @@ -169,35 +167,52 @@ const CommonConnectJobParams* common_connect_job_params, ConnectJob::Delegate* delegate)>; - // "Parameters" that own a single callback for creating a ConnectJob that can - // be of any type. + // Parameters that, in combination with GroupId, proxy, websocket information, + // and global state, are sufficient to create a ConnectJob. + // + // DO NOT ADD ANY FIELDS TO THIS CLASS. + // + // TODO(https://crbug.com/921369) In order to resolve longstanding issues + // related to pooling distinguishable sockets together, remove this class + // entirely. class NET_EXPORT_PRIVATE SocketParams : public base::RefCounted<SocketParams> { public: - explicit SocketParams( - const CreateConnectJobCallback& create_connect_job_callback); + // For non-SSL requests / non-HTTPS proxies, the corresponding SSLConfig + // argument may be nullptr. + SocketParams(MutableNetworkTrafficAnnotationTag proxy_annotation_tag, + std::unique_ptr<SSLConfig> ssl_config_for_origin, + std::unique_ptr<SSLConfig> ssl_config_for_proxy, + const OnHostResolutionCallback& resolution_callback); - const CreateConnectJobCallback& create_connect_job_callback() { - return create_connect_job_callback_; + // Creates a SocketParams object with none of the fields populated. This + // works for the HTTP case only. + static scoped_refptr<SocketParams> CreateForHttpForTesting(); + + MutableNetworkTrafficAnnotationTag proxy_annotation_tag() const { + return proxy_annotation_tag_; } - static scoped_refptr<SocketParams> CreateFromTransportSocketParams( - scoped_refptr<TransportSocketParams> transport_client_params); + const SSLConfig* ssl_config_for_origin() const { + return ssl_config_for_origin_.get(); + } - static scoped_refptr<SocketParams> CreateFromSOCKSSocketParams( - scoped_refptr<SOCKSSocketParams> socks_socket_params); + const SSLConfig* ssl_config_for_proxy() const { + return ssl_config_for_proxy_.get(); + } - static scoped_refptr<SocketParams> CreateFromSSLSocketParams( - scoped_refptr<SSLSocketParams> ssl_socket_params); - - static scoped_refptr<SocketParams> CreateFromHttpProxySocketParams( - scoped_refptr<HttpProxySocketParams> http_proxy_socket_params); + const OnHostResolutionCallback& resolution_callback() const { + return resolution_callback_; + } private: friend class base::RefCounted<SocketParams>; ~SocketParams(); - const CreateConnectJobCallback create_connect_job_callback_; + MutableNetworkTrafficAnnotationTag proxy_annotation_tag_; + std::unique_ptr<SSLConfig> ssl_config_for_origin_; + std::unique_ptr<SSLConfig> ssl_config_for_proxy_; + const OnHostResolutionCallback resolution_callback_; DISALLOW_COPY_AND_ASSIGN(SocketParams); };
diff --git a/net/socket/client_socket_pool_base_unittest.cc b/net/socket/client_socket_pool_base_unittest.cc index fc04510c..efb74e2dc 100644 --- a/net/socket/client_socket_pool_base_unittest.cc +++ b/net/socket/client_socket_pool_base_unittest.cc
@@ -81,14 +81,6 @@ privacy_mode); } -// Returns a ClientSocketPool::SocketParams that will never be used to -// create a real TreansportConnectJob. -scoped_refptr<ClientSocketPool::SocketParams> CreateDummyParams() { - return ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>(HostPortPair("ignored", 80), - OnHostResolutionCallback())); -} - // Make sure |handle| sets load times correctly when it has been assigned a // reused socket. void TestLoadTimingInfoConnectedReused(const ClientSocketHandle& handle) { @@ -632,7 +624,7 @@ ClientSocketPoolBaseTest() : TestWithScopedTaskEnvironment( base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME), - params_(CreateDummyParams()) { + params_(ClientSocketPool::SocketParams::CreateForHttpForTesting()) { connect_backup_jobs_enabled_ = TransportClientSocketPool::connect_backup_jobs_enabled(); TransportClientSocketPool::set_connect_backup_jobs_enabled(true); @@ -1562,9 +1554,11 @@ TestCompletionCallback callback; int rv = handle->Init( - TestGroupId("a"), CreateDummyParams(), LOWEST, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, nested_callback->callback(), - ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); + TestGroupId("a"), + ClientSocketPool::SocketParams::CreateForHttpForTesting(), LOWEST, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + nested_callback->callback(), ClientSocketPool::ProxyAuthCallback(), pool, + NetLogWithSource()); if (rv != ERR_IO_PENDING) { DCHECK_EQ(TestConnectJob::kMockJob, next_job_type); nested_callback->callback().Run(rv); @@ -2660,11 +2654,12 @@ EXPECT_EQ( expected_result_, - handle2_.Init(TestGroupId("a"), CreateDummyParams(), DEFAULT_PRIORITY, - SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), - ClientSocketPool::ProxyAuthCallback(), pool_, - NetLogWithSource())); + handle2_.Init( + TestGroupId("a"), + ClientSocketPool::SocketParams::CreateForHttpForTesting(), + DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), pool_, NetLogWithSource())); } TransportClientSocketPool* const pool_; @@ -4510,14 +4505,16 @@ int RequestSocket(TransportClientSocketPool* pool) { return handle_.Init( - group_id_, CreateDummyParams(), DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, callback_.callback(), - ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); + group_id_, ClientSocketPool::SocketParams::CreateForHttpForTesting(), + DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + callback_.callback(), ClientSocketPool::ProxyAuthCallback(), pool, + NetLogWithSource()); } int RequestSocketWithoutLimits(TransportClientSocketPool* pool) { return handle_.Init( - group_id_, CreateDummyParams(), MAXIMUM_PRIORITY, SocketTag(), + group_id_, ClientSocketPool::SocketParams::CreateForHttpForTesting(), + MAXIMUM_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::DISABLED, callback_.callback(), ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); }
diff --git a/net/socket/client_socket_pool_manager.cc b/net/socket/client_socket_pool_manager.cc index 5d6045e..405d61d8 100644 --- a/net/socket/client_socket_pool_manager.cc +++ b/net/socket/client_socket_pool_manager.cc
@@ -12,14 +12,11 @@ #include "base/strings/stringprintf.h" #include "net/base/features.h" #include "net/base/load_flags.h" -#include "net/http/http_proxy_connect_job.h" #include "net/http/http_stream_factory.h" #include "net/proxy_resolution/proxy_info.h" #include "net/socket/client_socket_handle.h" #include "net/socket/client_socket_pool.h" -#include "net/socket/socks_connect_job.h" -#include "net/socket/ssl_connect_job.h" -#include "net/socket/transport_connect_job.h" +#include "net/socket/connect_job.h" #include "net/ssl/ssl_config.h" namespace net { @@ -90,114 +87,27 @@ return ClientSocketPool::GroupId(endpoint, socket_type, privacy_mode); } -// The meat of the implementation for the InitSocketHandleForHttpRequest, -// InitSocketHandleForRawConnect and PreconnectSocketsForHttpRequest methods. -scoped_refptr<ClientSocketPool::SocketParams> CreateSocketParams( - bool using_ssl, - const HostPortPair& endpoint, - const ProxyServer& proxy_server, - MutableNetworkTrafficAnnotationTag proxy_annotation_tag, - const SSLConfig& ssl_config_for_origin, - const SSLConfig& ssl_config_for_proxy, - bool force_tunnel, - PrivacyMode privacy_mode, - const OnHostResolutionCallback& resolution_callback) { - scoped_refptr<HttpProxySocketParams> http_proxy_params; - scoped_refptr<SOCKSSocketParams> socks_params; - - if (!proxy_server.is_direct()) { - scoped_refptr<TransportSocketParams> proxy_tcp_params = - base::MakeRefCounted<TransportSocketParams>( - proxy_server.host_port_pair(), resolution_callback); - - if (proxy_server.is_http() || proxy_server.is_https() || - proxy_server.is_quic()) { - scoped_refptr<SSLSocketParams> ssl_params; - if (!proxy_server.is_http()) { - // Set ssl_params, and unset proxy_tcp_params - ssl_params = base::MakeRefCounted<SSLSocketParams>( - std::move(proxy_tcp_params), nullptr, nullptr, - proxy_server.host_port_pair(), ssl_config_for_proxy, - PRIVACY_MODE_DISABLED); - proxy_tcp_params = nullptr; - } - - http_proxy_params = base::MakeRefCounted<HttpProxySocketParams>( - std::move(proxy_tcp_params), std::move(ssl_params), - proxy_server.is_quic(), endpoint, proxy_server.is_trusted_proxy(), - force_tunnel || using_ssl, - NetworkTrafficAnnotationTag(proxy_annotation_tag)); - } else { - DCHECK(proxy_server.is_socks()); - socks_params = base::MakeRefCounted<SOCKSSocketParams>( - std::move(proxy_tcp_params), - proxy_server.scheme() == ProxyServer::SCHEME_SOCKS5, endpoint, - NetworkTrafficAnnotationTag(proxy_annotation_tag)); - } - } - - // Deal with SSL - which layers on top of any given proxy. - if (using_ssl) { - scoped_refptr<TransportSocketParams> ssl_tcp_params; - if (proxy_server.is_direct()) { - ssl_tcp_params = base::MakeRefCounted<TransportSocketParams>( - endpoint, resolution_callback); - } - scoped_refptr<SSLSocketParams> ssl_params = - base::MakeRefCounted<SSLSocketParams>( - std::move(ssl_tcp_params), std::move(socks_params), - std::move(http_proxy_params), endpoint, ssl_config_for_origin, - privacy_mode); - return ClientSocketPool::SocketParams::CreateFromSSLSocketParams( - std::move(ssl_params)); - } - - if (proxy_server.is_http() || proxy_server.is_https()) { - return ClientSocketPool::SocketParams::CreateFromHttpProxySocketParams( - std::move(http_proxy_params)); - } - - if (proxy_server.is_socks()) { - return ClientSocketPool::SocketParams::CreateFromSOCKSSocketParams( - std::move(socks_params)); - } - - DCHECK(proxy_server.is_direct()); - scoped_refptr<TransportSocketParams> tcp_params = - base::MakeRefCounted<TransportSocketParams>(endpoint, - resolution_callback); - return ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - std::move(tcp_params)); -} - -// DO NOT ADD ANY ARGUMENTS TO THIS METHOD. -// // TODO(https://crbug.com/921369) In order to resolve longstanding issues -// related to pooling distinguishable sockets together, reduce the arguments to -// just |group_id|. -scoped_refptr<ClientSocketPool::SocketParams> CreateSocketParamsForGroup( +// related to pooling distinguishable sockets together, get rid of SocketParams +// entirely. +scoped_refptr<ClientSocketPool::SocketParams> CreateSocketParams( const ClientSocketPool::GroupId& group_id, - // This argument should be removed. const ProxyServer& proxy_server, - // This argument should be removed. MutableNetworkTrafficAnnotationTag proxy_annotation_tag, - // This argument should be removed. const SSLConfig& ssl_config_for_origin, - // This argument should be removed. const SSLConfig& ssl_config_for_proxy, - // This argument should be removed. - bool is_for_websockets, - // TODO(https://crbug.com/912727): This argument should be removed. const OnHostResolutionCallback& resolution_callback) { bool using_ssl = (group_id.socket_type() == ClientSocketPool::SocketType::kSsl || group_id.socket_type() == ClientSocketPool::SocketType::kSslVersionInterferenceProbe); - bool force_tunnel = is_for_websockets; - return CreateSocketParams(using_ssl, group_id.destination(), proxy_server, - proxy_annotation_tag, ssl_config_for_origin, - ssl_config_for_proxy, force_tunnel, - group_id.privacy_mode(), resolution_callback); + bool using_proxy_ssl = proxy_server.is_http_like() && !proxy_server.is_http(); + return base::MakeRefCounted<ClientSocketPool::SocketParams>( + proxy_annotation_tag, + using_ssl ? std::make_unique<SSLConfig>(ssl_config_for_origin) : nullptr, + using_proxy_ssl ? std::make_unique<SSLConfig>(ssl_config_for_proxy) + : nullptr, + resolution_callback); } int InitSocketPoolHelper( @@ -232,10 +142,9 @@ CreateGroupId(group_type, origin_host_port, proxy_info, ssl_config_for_origin, privacy_mode); scoped_refptr<ClientSocketPool::SocketParams> socket_params = - CreateSocketParamsForGroup(connection_group, proxy_info.proxy_server(), - proxy_info.traffic_annotation(), - ssl_config_for_origin, ssl_config_for_proxy, - is_for_websockets, resolution_callback); + CreateSocketParams(connection_group, proxy_info.proxy_server(), + proxy_info.traffic_annotation(), ssl_config_for_origin, + ssl_config_for_proxy, resolution_callback); ClientSocketPool* pool = session->GetSocketPool(socket_pool_type, proxy_info.proxy_server()); @@ -396,15 +305,12 @@ // QUIC proxies are currently not supported through this method. DCHECK(!proxy_info.is_quic()); - scoped_refptr<ClientSocketPool::SocketParams> socket_params = - CreateSocketParams(use_tls, host_port_pair, proxy_info.proxy_server(), - proxy_info.traffic_annotation(), ssl_config_for_origin, - ssl_config_for_proxy, true /* force_tunnel */, - net::PRIVACY_MODE_DISABLED, - OnHostResolutionCallback()); - return socket_params->create_connect_job_callback().Run( - request_priority, SocketTag(), common_connect_job_params, - connect_job_delegate); + return ConnectJob::CreateConnectJob( + use_tls, host_port_pair, proxy_info.proxy_server(), + proxy_info.traffic_annotation(), &ssl_config_for_origin, + &ssl_config_for_proxy, true /* force_tunnel */, + net::PRIVACY_MODE_DISABLED, OnHostResolutionCallback(), request_priority, + SocketTag(), common_connect_job_params, connect_job_delegate); } int PreconnectSocketsForHttpRequest(
diff --git a/net/socket/connect_job.cc b/net/socket/connect_job.cc index 1102ac1..85790b0e 100644 --- a/net/socket/connect_job.cc +++ b/net/socket/connect_job.cc
@@ -10,10 +10,16 @@ #include "net/base/net_errors.h" #include "net/base/trace_constants.h" #include "net/http/http_auth_controller.h" +#include "net/http/http_proxy_connect_job.h" #include "net/log/net_log.h" #include "net/log/net_log_event_type.h" #include "net/socket/client_socket_handle.h" +#include "net/socket/socket_tag.h" +#include "net/socket/socks_connect_job.h" +#include "net/socket/ssl_connect_job.h" #include "net/socket/stream_socket.h" +#include "net/socket/transport_connect_job.h" +#include "net/ssl/ssl_config.h" namespace net { @@ -91,6 +97,91 @@ net_log().EndEvent(NetLogEventType::CONNECT_JOB); } +std::unique_ptr<ConnectJob> ConnectJob::CreateConnectJob( + bool using_ssl, + const HostPortPair& endpoint, + const ProxyServer& proxy_server, + MutableNetworkTrafficAnnotationTag proxy_annotation_tag, + const SSLConfig* ssl_config_for_origin, + const SSLConfig* ssl_config_for_proxy, + bool force_tunnel, + PrivacyMode privacy_mode, + const OnHostResolutionCallback& resolution_callback, + RequestPriority request_priority, + SocketTag socket_tag, + const CommonConnectJobParams* common_connect_job_params, + ConnectJob::Delegate* delegate) { + scoped_refptr<HttpProxySocketParams> http_proxy_params; + scoped_refptr<SOCKSSocketParams> socks_params; + + if (!proxy_server.is_direct()) { + auto proxy_tcp_params = base::MakeRefCounted<TransportSocketParams>( + proxy_server.host_port_pair(), resolution_callback); + + if (proxy_server.is_http() || proxy_server.is_https() || + proxy_server.is_quic()) { + scoped_refptr<SSLSocketParams> ssl_params; + if (!proxy_server.is_http()) { + DCHECK(ssl_config_for_proxy); + // Set ssl_params, and unset proxy_tcp_params + ssl_params = base::MakeRefCounted<SSLSocketParams>( + std::move(proxy_tcp_params), nullptr, nullptr, + proxy_server.host_port_pair(), *ssl_config_for_proxy, + PRIVACY_MODE_DISABLED); + proxy_tcp_params = nullptr; + } + + http_proxy_params = base::MakeRefCounted<HttpProxySocketParams>( + std::move(proxy_tcp_params), std::move(ssl_params), + proxy_server.is_quic(), endpoint, proxy_server.is_trusted_proxy(), + force_tunnel || using_ssl, + NetworkTrafficAnnotationTag(proxy_annotation_tag)); + } else { + DCHECK(proxy_server.is_socks()); + socks_params = base::MakeRefCounted<SOCKSSocketParams>( + std::move(proxy_tcp_params), + proxy_server.scheme() == ProxyServer::SCHEME_SOCKS5, endpoint, + NetworkTrafficAnnotationTag(proxy_annotation_tag)); + } + } + + // Deal with SSL - which layers on top of any given proxy. + if (using_ssl) { + DCHECK(ssl_config_for_origin); + scoped_refptr<TransportSocketParams> ssl_tcp_params; + if (proxy_server.is_direct()) { + ssl_tcp_params = base::MakeRefCounted<TransportSocketParams>( + endpoint, resolution_callback); + } + auto ssl_params = base::MakeRefCounted<SSLSocketParams>( + std::move(ssl_tcp_params), std::move(socks_params), + std::move(http_proxy_params), endpoint, *ssl_config_for_origin, + privacy_mode); + return std::make_unique<SSLConnectJob>( + request_priority, socket_tag, common_connect_job_params, + std::move(ssl_params), delegate, nullptr /* net_log */); + } + + if (proxy_server.is_http() || proxy_server.is_https()) { + return std::make_unique<HttpProxyConnectJob>( + request_priority, socket_tag, common_connect_job_params, + std::move(http_proxy_params), delegate, nullptr /* net_log */); + } + + if (proxy_server.is_socks()) { + return std::make_unique<SOCKSConnectJob>( + request_priority, socket_tag, common_connect_job_params, + std::move(socks_params), delegate, nullptr /* net_log */); + } + + DCHECK(proxy_server.is_direct()); + auto tcp_params = base::MakeRefCounted<TransportSocketParams>( + endpoint, resolution_callback); + return TransportConnectJob::CreateTransportConnectJob( + std::move(tcp_params), request_priority, socket_tag, + common_connect_job_params, delegate, nullptr /* net_log */); +} + std::unique_ptr<StreamSocket> ConnectJob::PassSocket() { return std::move(socket_); }
diff --git a/net/socket/connect_job.h b/net/socket/connect_job.h index 2d9883bb..e23df86d 100644 --- a/net/socket/connect_job.h +++ b/net/socket/connect_job.h
@@ -13,6 +13,7 @@ #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "base/timer/timer.h" +#include "net/base/address_list.h" #include "net/base/load_states.h" #include "net/base/load_timing_info.h" #include "net/base/net_export.h" @@ -23,10 +24,12 @@ #include "net/socket/socket_tag.h" #include "net/socket/ssl_client_socket.h" #include "net/third_party/quiche/src/quic/core/quic_versions.h" +#include "net/traffic_annotation/network_traffic_annotation.h" namespace net { class ClientSocketFactory; +class HostPortPair; class HostResolver; class HttpAuthCache; class HttpAuthController; @@ -34,12 +37,16 @@ class HttpResponseInfo; class HttpUserAgentSettings; class NetLog; +class NetLogWithSource; class NetworkQualityEstimator; class ProxyDelegate; +class ProxyServer; class SocketPerformanceWatcherFactory; +struct SSLConfig; class StreamSocket; class WebSocketEndpointLockManager; class QuicStreamFactory; +class SocketTag; class SpdySessionPool; class SSLCertRequestInfo; @@ -89,6 +96,10 @@ WebSocketEndpointLockManager* websocket_endpoint_lock_manager; }; +using OnHostResolutionCallback = + base::RepeatingCallback<int(const AddressList&, + const NetLogWithSource& net_log)>; + // ConnectJob provides an abstract interface for "connecting" a socket. // The connection may involve host resolution, tcp connection, ssl connection, // etc. @@ -143,6 +154,24 @@ NetLogEventType net_log_connect_event_type); virtual ~ConnectJob(); + // Creates a ConnectJob with the specified parameters. + // |common_connect_job_params| and |delegate| must outlive the returned + // ConnectJob. + static std::unique_ptr<ConnectJob> CreateConnectJob( + bool using_ssl, + const HostPortPair& endpoint, + const ProxyServer& proxy_server, + MutableNetworkTrafficAnnotationTag proxy_annotation_tag, + const SSLConfig* ssl_config_for_origin, + const SSLConfig* ssl_config_for_proxy, + bool force_tunnel, + PrivacyMode privacy_mode, + const OnHostResolutionCallback& resolution_callback, + RequestPriority request_priority, + SocketTag socket_tag, + const CommonConnectJobParams* common_connect_job_params, + ConnectJob::Delegate* delegate); + // Accessors const NetLogWithSource& net_log() { return net_log_; } RequestPriority priority() const { return priority_; }
diff --git a/net/socket/transport_client_socket_pool_unittest.cc b/net/socket/transport_client_socket_pool_unittest.cc index 3fde6459..fb85532 100644 --- a/net/socket/transport_client_socket_pool_unittest.cc +++ b/net/socket/transport_client_socket_pool_unittest.cc
@@ -109,10 +109,7 @@ group_id_(HostPortPair("www.google.com", 80), ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED), - params_(ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), - OnHostResolutionCallback()))), + params_(ClientSocketPool::SocketParams::CreateForHttpForTesting()), client_socket_factory_(&net_log_) { std::unique_ptr<MockCertVerifier> cert_verifier = std::make_unique<MockCertVerifier>(); @@ -163,13 +160,10 @@ ClientSocketPool::GroupId group_id(HostPortPair(host_name, 80), ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED); - scoped_refptr<ClientSocketPool::SocketParams> params( - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - group_id.destination(), OnHostResolutionCallback()))); return test_base_.StartRequestUsingPool( pool_.get(), group_id, priority, - ClientSocketPool::RespectLimits::ENABLED, params); + ClientSocketPool::RespectLimits::ENABLED, + ClientSocketPool::SocketParams::CreateForHttpForTesting()); } int GetOrderOfRequest(size_t index) { @@ -189,9 +183,9 @@ } size_t completion_count() const { return test_base_.completion_count(); } - SSLConfig GetSSLConfig() const { - SSLConfig ssl_config; - session_deps_.ssl_config_service->GetSSLConfig(&ssl_config); + std::unique_ptr<SSLConfig> GetSSLConfig() const { + std::unique_ptr<SSLConfig> ssl_config = std::make_unique<SSLConfig>(); + session_deps_.ssl_config_service->GetSSLConfig(ssl_config.get()); return ssl_config; } @@ -874,10 +868,6 @@ TEST_F(TransportClientSocketPoolTest, RequestTwice) { ClientSocketHandle handle; RequestSocketCallback callback(group_id_, params_, &handle, pool_.get()); - scoped_refptr<ClientSocketPool::SocketParams> dest( - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), OnHostResolutionCallback()))); int rv = handle.Init( group_id_, params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), @@ -1011,23 +1001,22 @@ const HostPortPair kHostPortPair("ssl.server.test", 443); - scoped_refptr<TransportSocketParams> tcp_params = - base::MakeRefCounted<TransportSocketParams>(kHostPortPair, - OnHostResolutionCallback()); - scoped_refptr<SSLSocketParams> params( - new SSLSocketParams(tcp_params, nullptr, nullptr, kHostPortPair, - GetSSLConfig(), PRIVACY_MODE_DISABLED)); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + GetSSLConfig() /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); ClientSocketHandle handle; TestCompletionCallback callback; - int rv = handle.Init( - ClientSocketPool::GroupId(kHostPortPair, - ClientSocketPool::SocketType::kSsl, - PrivacyMode::PRIVACY_MODE_DISABLED), - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(params), MEDIUM, - SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + int rv = + handle.Init(ClientSocketPool::GroupId(kHostPortPair, + ClientSocketPool::SocketType::kSsl, + PrivacyMode::PRIVACY_MODE_DISABLED), + socket_params, MEDIUM, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), + NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -1273,30 +1262,34 @@ // Test the case that SOCKSSocketParams are provided. TEST_F(TransportClientSocketPoolTest, SOCKS) { - const HostPortPair kDesination("host", 80); + const HostPortPair kDestination("host", 80); + + TransportClientSocketPool proxy_pool( + kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, + ProxyServer::FromURI("socks5://foopy", + ProxyServer::SCHEME_HTTP /* default_scheme */), + false /* is_for_websockets */, tagging_common_connect_job_params_.get(), + session_deps_.ssl_config_service.get()); + for (IoMode socket_io_mode : {SYNCHRONOUS, ASYNC}) { - scoped_refptr<TransportSocketParams> tcp_params = - base::MakeRefCounted<TransportSocketParams>(HostPortPair("proxy", 80), - OnHostResolutionCallback()); - scoped_refptr<ClientSocketPool::SocketParams> socks_params( - ClientSocketPool::SocketParams::CreateFromSOCKSSocketParams( - base::MakeRefCounted<SOCKSSocketParams>( - tcp_params, true /* socks_v5 */, kDesination, - TRAFFIC_ANNOTATION_FOR_TESTS))); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + nullptr /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); SOCKS5MockData data(socket_io_mode); data.data_provider()->set_connect_data(MockConnect(socket_io_mode, OK)); tagging_client_socket_factory_.AddSocketDataProvider(data.data_provider()); ClientSocketHandle handle; TestCompletionCallback callback; - int rv = - handle.Init(ClientSocketPool::GroupId( - kDesination, ClientSocketPool::SocketType::kSsl, - PrivacyMode::PRIVACY_MODE_DISABLED), - socks_params, LOW, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + int rv = handle.Init( + ClientSocketPool::GroupId(kDestination, + ClientSocketPool::SocketType::kHttp, + PrivacyMode::PRIVACY_MODE_DISABLED), + socket_params, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(callback.GetResult(rv), IsOk()); EXPECT_TRUE(handle.is_initialized()); EXPECT_TRUE(handle.socket()); @@ -1312,13 +1305,14 @@ // See https://crbug.com/940848 TEST_F(TransportClientSocketPoolTest, SpdyOneConnectJobTwoRequestsError) { const HostPortPair kEndpoint("unresolvable.host.name", 443); - const HostPortPair kProxy("unresolvable.proxy.name", 443); session_deps_.host_resolver->set_synchronous_mode(true); // Create a socket pool which only allows a single connection at a time. TransportClientSocketPool pool( - 1, 1, kUnusedIdleSocketTimeout, ProxyServer::Direct(), + 1, 1, kUnusedIdleSocketTimeout, + ProxyServer::FromURI("https://unresolvable.proxy.name", + ProxyServer::SCHEME_HTTP /* default_scheme */), false /* is_for_websockets */, tagging_common_connect_job_params_.get(), session_deps_.ssl_config_service.get()); @@ -1352,29 +1346,12 @@ SSLSocketDataProvider ssl_data2(SYNCHRONOUS, OK); tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data2); - scoped_refptr<TransportSocketParams> transport_params = - base::MakeRefCounted<TransportSocketParams>(kProxy, - OnHostResolutionCallback()); - - scoped_refptr<SSLSocketParams> proxy_ssl_params = - base::MakeRefCounted<SSLSocketParams>( - transport_params, nullptr /* socks_proxy_params */, - nullptr /* http_proxy_params */, kProxy, GetSSLConfig(), - PRIVACY_MODE_DISABLED); - - scoped_refptr<HttpProxySocketParams> http_proxy_params = - base::MakeRefCounted<HttpProxySocketParams>( - nullptr /* transport_params */, proxy_ssl_params, false /* is_quic */, - kEndpoint, false /* is_trusted_proxy */, true /* tunnel */, - TRAFFIC_ANNOTATION_FOR_TESTS); - scoped_refptr<SSLSocketParams> endpoint_ssl_params = - base::MakeRefCounted<SSLSocketParams>( - nullptr /* direct_params */, nullptr /* socks_proxy_params */, - http_proxy_params, kEndpoint, GetSSLConfig(), PRIVACY_MODE_DISABLED); - - scoped_refptr<ClientSocketPool::SocketParams> pool_params = - ClientSocketPool::SocketParams::CreateFromSSLSocketParams( - endpoint_ssl_params); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + GetSSLConfig() /* ssl_config_for_origin */, + GetSSLConfig() /* ssl_config_for_proxy */, + OnHostResolutionCallback()); ClientSocketPool::GroupId group_id(kEndpoint, ClientSocketPool::SocketType::kSsl, @@ -1384,7 +1361,7 @@ TestCompletionCallback callback1; ClientSocketHandle handle1; int rv1 = handle1.Init( - group_id, pool_params, HIGHEST, SocketTag(), + group_id, socket_params, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); ASSERT_THAT(rv1, IsError(ERR_IO_PENDING)); @@ -1393,7 +1370,7 @@ TestCompletionCallback callback2; ClientSocketHandle handle2; int rv2 = handle2.Init( - group_id, pool_params, LOWEST, SocketTag(), + group_id, socket_params, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); ASSERT_THAT(rv2, IsError(ERR_IO_PENDING)); @@ -1424,7 +1401,9 @@ // Create a socket pool which only allows a single connection at a time. TransportClientSocketPool pool( - 1, 1, kUnusedIdleSocketTimeout, ProxyServer::Direct(), + 1, 1, kUnusedIdleSocketTimeout, + ProxyServer::FromURI("https://unresolvable.proxy.name", + ProxyServer::SCHEME_HTTP /* default_scheme */), false /* is_for_websockets */, tagging_common_connect_job_params_.get(), session_deps_.ssl_config_service.get()); @@ -1471,29 +1450,12 @@ SSLSocketDataProvider ssl_data2(SYNCHRONOUS, OK); tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data2); - scoped_refptr<TransportSocketParams> transport_params = - base::MakeRefCounted<TransportSocketParams>(kProxy, - OnHostResolutionCallback()); - - scoped_refptr<SSLSocketParams> proxy_ssl_params = - base::MakeRefCounted<SSLSocketParams>( - transport_params, nullptr /* socks_proxy_params */, - nullptr /* http_proxy_params */, kProxy, GetSSLConfig(), - PRIVACY_MODE_DISABLED); - - scoped_refptr<HttpProxySocketParams> http_proxy_params = - base::MakeRefCounted<HttpProxySocketParams>( - nullptr /* transport_params */, proxy_ssl_params, false /* is_quic */, - kEndpoint, false /* is_trusted_proxy */, true /* tunnel */, - TRAFFIC_ANNOTATION_FOR_TESTS); - scoped_refptr<SSLSocketParams> endpoint_ssl_params = - base::MakeRefCounted<SSLSocketParams>( - nullptr /* direct_params */, nullptr /* socks_proxy_params */, - http_proxy_params, kEndpoint, GetSSLConfig(), PRIVACY_MODE_DISABLED); - - scoped_refptr<ClientSocketPool::SocketParams> pool_params = - ClientSocketPool::SocketParams::CreateFromSSLSocketParams( - endpoint_ssl_params); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + GetSSLConfig() /* ssl_config_for_origin */, + GetSSLConfig() /* ssl_config_for_proxy */, + OnHostResolutionCallback()); ClientSocketPool::GroupId group_id(kEndpoint, ClientSocketPool::SocketType::kSsl, @@ -1503,7 +1465,7 @@ TestCompletionCallback callback1; ClientSocketHandle handle1; base::RunLoop run_loop; - int rv1 = handle1.Init(group_id, pool_params, HIGHEST, SocketTag(), + int rv1 = handle1.Init(group_id, socket_params, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), base::BindLambdaForTesting( @@ -1519,7 +1481,7 @@ TestCompletionCallback callback2; ClientSocketHandle handle2; int rv2 = handle2.Init( - group_id, pool_params, LOWEST, SocketTag(), + group_id, socket_params, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); ASSERT_THAT(rv2, IsError(ERR_IO_PENDING)); @@ -1540,7 +1502,6 @@ TEST_F(TransportClientSocketPoolTest, HttpTunnelSetupRedirect) { const HostPortPair kEndpoint("host.test", 443); - const HostPortPair kProxy("proxy.test", 443); const std::string kRedirectTarget = "https://some.other.host.test/"; @@ -1558,6 +1519,16 @@ for (bool use_https_proxy : {false, true}) { SCOPED_TRACE(use_https_proxy); + + TransportClientSocketPool proxy_pool( + kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, + ProxyServer::FromURI( + use_https_proxy ? "https://proxy.test" : "http://proxy.test", + ProxyServer::SCHEME_HTTP /* default_scheme */), + false /* is_for_websockets */, + tagging_common_connect_job_params_.get(), + session_deps_.ssl_config_service.get()); + MockWrite writes[] = { MockWrite(ASYNC, 0, "CONNECT host.test:443 HTTP/1.1\r\n" @@ -1576,42 +1547,21 @@ ClientSocketHandle handle; TestCompletionCallback callback; - scoped_refptr<TransportSocketParams> transport_params = - base::MakeRefCounted<TransportSocketParams>( - kProxy, OnHostResolutionCallback()); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + GetSSLConfig() /* ssl_config_for_origin */, + GetSSLConfig() /* ssl_config_for_proxy */, + OnHostResolutionCallback()); - scoped_refptr<SSLSocketParams> proxy_ssl_params = - base::MakeRefCounted<SSLSocketParams>( - transport_params, nullptr /* socks_proxy_params */, - nullptr /* http_proxy_params */, kProxy, GetSSLConfig(), - PRIVACY_MODE_DISABLED); - - scoped_refptr<HttpProxySocketParams> http_proxy_params = - base::MakeRefCounted<HttpProxySocketParams>( - use_https_proxy ? nullptr : transport_params, - use_https_proxy ? proxy_ssl_params : nullptr, false /* is_quic */, - kEndpoint, false /* is_trusted_proxy */, true /* tunnel */, - TRAFFIC_ANNOTATION_FOR_TESTS); - scoped_refptr<SSLSocketParams> endpoint_ssl_params = - base::MakeRefCounted<SSLSocketParams>( - nullptr /* direct_params */, nullptr /* socks_proxy_params */, - http_proxy_params, kEndpoint, GetSSLConfig(), - PRIVACY_MODE_DISABLED); - - // Whether the proxy is HTTPS or not, always connecting to an HTTPS site - // through it. - scoped_refptr<ClientSocketPool::SocketParams> pool_params = - ClientSocketPool::SocketParams::CreateFromSSLSocketParams( - endpoint_ssl_params); - - int rv = handle.Init( - ClientSocketPool::GroupId(kEndpoint, - ClientSocketPool::SocketType::kSsl, - PrivacyMode::PRIVACY_MODE_DISABLED), - pool_params, LOW, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, callback.callback(), - ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), - NetLogWithSource()); + int rv = handle.Init(ClientSocketPool::GroupId( + kEndpoint, ClientSocketPool::SocketType::kSsl, + PrivacyMode::PRIVACY_MODE_DISABLED), + socket_params, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, + NetLogWithSource()); rv = callback.GetResult(rv); if (!use_https_proxy) { @@ -1671,12 +1621,10 @@ // Test socket is tagged before connected. uint64_t old_traffic = GetTaggedBytes(tag_val1); const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), - ClientSocketPool::SocketType::kSsl, + ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED); scoped_refptr<ClientSocketPool::SocketParams> params = - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - test_server.host_port_pair(), OnHostResolutionCallback())); + ClientSocketPool::SocketParams::CreateForHttpForTesting(); TestCompletionCallback callback; int rv = handle.Init( kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, @@ -1787,20 +1735,24 @@ TEST_F(TransportClientSocketPoolTest, TagSOCKSProxy) { session_deps_.host_resolver->set_synchronous_mode(true); + TransportClientSocketPool proxy_pool( + kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, + ProxyServer::FromURI("socks5://proxy", + ProxyServer::SCHEME_HTTP /* default_scheme */), + false /* is_for_websockets */, tagging_common_connect_job_params_.get(), + session_deps_.ssl_config_service.get()); + SocketTag tag1(SocketTag::UNSET_UID, 0x12345678); SocketTag tag2(getuid(), 0x87654321); const HostPortPair kDestination("host", 80); const ClientSocketPool::GroupId kGroupId(kDestination, ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED); - scoped_refptr<TransportSocketParams> tcp_params = - base::MakeRefCounted<TransportSocketParams>(HostPortPair("proxy", 80), - OnHostResolutionCallback()); - scoped_refptr<ClientSocketPool::SocketParams> socks_params( - ClientSocketPool::SocketParams::CreateFromSOCKSSocketParams( - base::MakeRefCounted<SOCKSSocketParams>( - tcp_params, true /* socks_v5 */, kDestination, - TRAFFIC_ANNOTATION_FOR_TESTS))); + scoped_refptr<ClientSocketPool::SocketParams> socks_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + nullptr /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); // Test socket is tagged when created synchronously. SOCKS5MockData data_sync(SYNCHRONOUS); @@ -1808,11 +1760,10 @@ tagging_client_socket_factory_.AddSocketDataProvider( data_sync.data_provider()); ClientSocketHandle handle; - int rv = handle.Init(kGroupId, socks_params, LOW, tag1, - ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), - ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + int rv = handle.Init( + kGroupId, socks_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.is_initialized()); EXPECT_TRUE(handle.socket()); @@ -1824,11 +1775,10 @@ // Test socket is tagged when reused synchronously. StreamSocket* socket = handle.socket(); handle.Reset(); - rv = handle.Init(kGroupId, socks_params, LOW, tag2, - ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), - ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), - NetLogWithSource()); + rv = handle.Init( + kGroupId, socks_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -1846,7 +1796,7 @@ rv = handle.Init(kGroupId, socks_params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_TRUE(handle.is_initialized()); @@ -1859,11 +1809,10 @@ // Test socket is tagged when reused after being created asynchronously. socket = handle.socket(); handle.Reset(); - rv = handle.Init(kGroupId, socks_params, LOW, tag2, - ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), - ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), - NetLogWithSource()); + rv = handle.Init( + kGroupId, socks_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -1887,8 +1836,8 @@ // TLS 1.3 sockets aren't reused until the read side has been pumped. // TODO(crbug.com/906668): Support pumping the read side and setting the // socket to be reusable. - SSLConfig ssl_config = GetSSLConfig(); - ssl_config.version_max = SSL_PROTOCOL_VERSION_TLS1_2; + std::unique_ptr<SSLConfig> ssl_config = GetSSLConfig(); + ssl_config->version_max = SSL_PROTOCOL_VERSION_TLS1_2; TestCompletionCallback callback; ClientSocketHandle handle; @@ -1899,21 +1848,20 @@ const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), ClientSocketPool::SocketType::kSsl, PrivacyMode::PRIVACY_MODE_DISABLED); - scoped_refptr<TransportSocketParams> tcp_params = - base::MakeRefCounted<TransportSocketParams>(test_server.host_port_pair(), - OnHostResolutionCallback()); - scoped_refptr<SSLSocketParams> params(new SSLSocketParams( - tcp_params, nullptr, nullptr, test_server.host_port_pair(), ssl_config, - PRIVACY_MODE_DISABLED)); + + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + std::move(ssl_config) /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); // Test socket is tagged before connected. uint64_t old_traffic = GetTaggedBytes(tag_val1); - int rv = handle.Init( - kGroupId, - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(params), LOW, - tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), - NetLogWithSource()); + int rv = + handle.Init(kGroupId, socket_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), + pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(callback.GetResult(rv), IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -1924,12 +1872,10 @@ handle.Reset(); old_traffic = GetTaggedBytes(tag_val2); TestCompletionCallback callback2; - rv = handle.Init( - kGroupId, - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(params), LOW, - tag2, ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), - NetLogWithSource()); + rv = handle.Init(kGroupId, socket_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, + callback2.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -1972,32 +1918,28 @@ const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), ClientSocketPool::SocketType::kSsl, PrivacyMode::PRIVACY_MODE_DISABLED); - scoped_refptr<TransportSocketParams> tcp_params = - base::MakeRefCounted<TransportSocketParams>(test_server.host_port_pair(), - OnHostResolutionCallback()); - scoped_refptr<SSLSocketParams> params(new SSLSocketParams( - tcp_params, nullptr, nullptr, test_server.host_port_pair(), - GetSSLConfig(), PRIVACY_MODE_DISABLED)); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + GetSSLConfig() /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); // Test connect jobs that are orphaned and then adopted, appropriately apply // new tag. Request socket with |tag1|. TestCompletionCallback callback; - int rv = handle.Init( - kGroupId, - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(params), LOW, - tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), - NetLogWithSource()); + int rv = + handle.Init(kGroupId, socket_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), + pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv; // Abort and request socket with |tag2|. handle.Reset(); TestCompletionCallback callback2; - rv = handle.Init( - kGroupId, - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(params), LOW, - tag2, ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), - NetLogWithSource()); + rv = handle.Init(kGroupId, socket_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, + callback2.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(callback2.GetResult(rv), IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -2039,12 +1981,11 @@ const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), ClientSocketPool::SocketType::kSsl, PrivacyMode::PRIVACY_MODE_DISABLED); - scoped_refptr<TransportSocketParams> tcp_params = - base::MakeRefCounted<TransportSocketParams>(test_server.host_port_pair(), - OnHostResolutionCallback()); - scoped_refptr<SSLSocketParams> params(new SSLSocketParams( - tcp_params, nullptr, nullptr, test_server.host_port_pair(), - GetSSLConfig(), PRIVACY_MODE_DISABLED)); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + GetSSLConfig() /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); // Test that sockets paused by a full underlying socket pool are properly // connected and tagged when underlying pool is freed up. @@ -2052,13 +1993,11 @@ ClientSocketHandle tcp_handles[kMaxSocketsPerGroup]; int rv; for (auto& tcp_handle : tcp_handles) { - rv = tcp_handle.Init( - kGroupId, - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - tcp_params), - LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), - pool_for_real_sockets_.get(), NetLogWithSource()); + rv = tcp_handle.Init(kGroupId, socket_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), + ClientSocketPool::ProxyAuthCallback(), + pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(callback.GetResult(rv), IsOk()); EXPECT_TRUE(tcp_handle.socket()); EXPECT_TRUE(tcp_handle.socket()->IsConnected()); @@ -2066,18 +2005,15 @@ // Request two SSL sockets. ClientSocketHandle handle_to_be_canceled; rv = handle_to_be_canceled.Init( - kGroupId, - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(params), LOW, - tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + kGroupId, socket_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - rv = handle.Init( - kGroupId, - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(params), LOW, - tag2, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), - NetLogWithSource()); + rv = handle.Init(kGroupId, socket_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); // Cancel first request. handle_to_be_canceled.Reset(); @@ -2109,6 +2045,13 @@ SocketTag tag1(SocketTag::UNSET_UID, 0x12345678); SocketTag tag2(getuid(), 0x87654321); + TransportClientSocketPool proxy_pool( + kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, + ProxyServer::FromURI("http://proxy", + ProxyServer::SCHEME_HTTP /* default_scheme */), + false /* is_for_websockets */, tagging_common_connect_job_params_.get(), + session_deps_.ssl_config_service.get()); + session_deps_.host_resolver->set_synchronous_mode(true); SequencedSocketData socket_data; socket_data.set_connect_data(MockConnect(SYNCHRONOUS, OK)); @@ -2116,24 +2059,20 @@ const HostPortPair kDestination("www.google.com", 80); const ClientSocketPool::GroupId kGroupId(kDestination, - ClientSocketPool::SocketType::kSsl, + ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED); - scoped_refptr<ClientSocketPool::SocketParams> params = - ClientSocketPool::SocketParams::CreateFromHttpProxySocketParams( - base::MakeRefCounted<HttpProxySocketParams>( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("http.proxy.host", 80), - OnHostResolutionCallback()), - nullptr /* ssl_params */, false /* is_quic */, kDestination, - false /* is_trusted_proxy */, false /* tunnel */, - TRAFFIC_ANNOTATION_FOR_TESTS)); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + nullptr /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); // Verify requested socket is tagged properly. ClientSocketHandle handle; int rv = handle.Init( - kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + kGroupId, socket_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.is_initialized()); ASSERT_TRUE(handle.socket()); @@ -2147,9 +2086,9 @@ StreamSocket* socket = handle.socket(); handle.Reset(); rv = handle.Init( - kGroupId, params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + kGroupId, socket_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -2167,6 +2106,13 @@ SocketTag tag1(SocketTag::UNSET_UID, 0x12345678); SocketTag tag2(getuid(), 0x87654321); + TransportClientSocketPool proxy_pool( + kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, + ProxyServer::FromURI("http://proxy", + ProxyServer::SCHEME_HTTP /* default_scheme */), + false /* is_for_websockets */, tagging_common_connect_job_params_.get(), + session_deps_.ssl_config_service.get()); + session_deps_.host_resolver->set_synchronous_mode(true); std::string request = @@ -2182,27 +2128,26 @@ SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes); tagging_client_socket_factory_.AddSocketDataProvider(&socket_data); + SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK); + tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data); const HostPortPair kDestination("www.google.com", 443); const ClientSocketPool::GroupId kGroupId(kDestination, ClientSocketPool::SocketType::kSsl, PrivacyMode::PRIVACY_MODE_DISABLED); - scoped_refptr<ClientSocketPool::SocketParams> params = - ClientSocketPool::SocketParams::CreateFromHttpProxySocketParams( - base::MakeRefCounted<HttpProxySocketParams>( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("http.proxy.host", 80), - OnHostResolutionCallback()), - nullptr /* ssl_params */, quic::QUIC_VERSION_UNSUPPORTED, - kDestination, false /* is_trusted_proxy */, true /* tunnel */, - TRAFFIC_ANNOTATION_FOR_TESTS)); + + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + GetSSLConfig() /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); // Verify requested socket is tagged properly. ClientSocketHandle handle; int rv = handle.Init( - kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + kGroupId, socket_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.is_initialized()); ASSERT_TRUE(handle.socket()); @@ -2216,9 +2161,9 @@ StreamSocket* socket = handle.socket(); handle.Reset(); rv = handle.Init( - kGroupId, params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + kGroupId, socket_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -2305,9 +2250,11 @@ base::span<MockRead>(), kWrites); { // Create 1 socket. - scoped_refptr<TransportSocketParams> transport_params( - base::MakeRefCounted<TransportSocketParams>( - kHostPortPair1, OnHostResolutionCallback())); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + nullptr /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); session_deps.socket_factory->AddSocketDataProvider(&provider_socket_1); ClientSocketHandle connection; TestCompletionCallback callback; @@ -2315,9 +2262,8 @@ ClientSocketPool::GroupId(kHostPortPair1, ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED), - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - transport_params), - MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + ClientSocketPool::SocketParams::CreateForHttpForTesting(), MEDIUM, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL, ProxyServer::Direct()), @@ -2349,9 +2295,11 @@ { // Request a new socket to trigger cleanup of idle timedout sockets. - scoped_refptr<TransportSocketParams> transport_params( - base::MakeRefCounted<TransportSocketParams>( - kHostPortPair2, OnHostResolutionCallback())); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + nullptr /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); SequencedSocketData provider_socket_2(MockConnect(ASYNC, OK), base::span<MockRead>(), base::span<MockWrite>()); @@ -2362,10 +2310,9 @@ ClientSocketPool::GroupId(kHostPortPair2, ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED), - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - transport_params), - MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), + socket_params, MEDIUM, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL, ProxyServer::Direct()), NetLogWithSource());
diff --git a/net/socket/transport_connect_job.h b/net/socket/transport_connect_job.h index b25ebc5..7d8b23f 100644 --- a/net/socket/transport_connect_job.h +++ b/net/socket/transport_connect_job.h
@@ -8,6 +8,7 @@ #include <memory> #include <string> +#include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" @@ -24,10 +25,6 @@ class NetLogWithSource; class SocketTag; -typedef base::RepeatingCallback<int(const AddressList&, - const NetLogWithSource& net_log)> - OnHostResolutionCallback; - class NET_EXPORT_PRIVATE TransportSocketParams : public base::RefCounted<TransportSocketParams> { public:
diff --git a/net/socket/websocket_transport_client_socket_pool_unittest.cc b/net/socket/websocket_transport_client_socket_pool_unittest.cc index b6210b4..ecc554a2 100644 --- a/net/socket/websocket_transport_client_socket_pool_unittest.cc +++ b/net/socket/websocket_transport_client_socket_pool_unittest.cc
@@ -66,10 +66,7 @@ : group_id_(HostPortPair("www.google.com", 80), ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED), - params_(ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), - OnHostResolutionCallback()))), + params_(ClientSocketPool::SocketParams::CreateForHttpForTesting()), host_resolver_(new MockHostResolver), client_socket_factory_(&net_log_), common_connect_job_params_( @@ -181,17 +178,17 @@ } TEST_F(WebSocketTransportClientSocketPoolTest, InitHostResolutionFailure) { - host_resolver_->rules()->AddSimulatedFailure("unresolvable.host.name"); + HostPortPair host_port_pair("unresolvable.host.name", 80); + host_resolver_->rules()->AddSimulatedFailure(host_port_pair.host()); TestCompletionCallback callback; ClientSocketHandle handle; - HostPortPair host_port_pair("unresolvable.host.name", 80); - scoped_refptr<ClientSocketPool::SocketParams> dest( - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - host_port_pair, OnHostResolutionCallback()))); EXPECT_EQ( ERR_IO_PENDING, - handle.Init(group_id_, dest, kDefaultPriority, SocketTag(), + handle.Init(ClientSocketPool::GroupId(host_port_pair, + ClientSocketPool::SocketType::kHttp, + PRIVACY_MODE_DISABLED), + ClientSocketPool::SocketParams::CreateForHttpForTesting(), + kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -416,14 +413,11 @@ handle->socket()->Disconnect(); handle->Reset(); - scoped_refptr<ClientSocketPool::SocketParams> dest( - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), OnHostResolutionCallback()))); int rv = handle->Init( - group_id, dest, LOWEST, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, nested_callback->callback(), - ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); + group_id, ClientSocketPool::SocketParams::CreateForHttpForTesting(), + LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + nested_callback->callback(), ClientSocketPool::ProxyAuthCallback(), pool, + NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); if (ERR_IO_PENDING != rv) nested_callback->callback().Run(rv); @@ -434,17 +428,13 @@ // ClientSocketHandle for the second socket, after disconnecting the first. TEST_F(WebSocketTransportClientSocketPoolTest, RequestTwice) { ClientSocketHandle handle; - scoped_refptr<ClientSocketPool::SocketParams> dest( - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), OnHostResolutionCallback()))); TestCompletionCallback second_result_callback; - int rv = handle.Init(group_id_, dest, LOWEST, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - base::BindOnce(&RequestSocketOnComplete, group_id_, - &handle, &pool_, &second_result_callback), - ClientSocketPool::ProxyAuthCallback(), &pool_, - NetLogWithSource()); + int rv = handle.Init( + group_id_, ClientSocketPool::SocketParams::CreateForHttpForTesting(), + LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + base::BindOnce(&RequestSocketOnComplete, group_id_, &handle, &pool_, + &second_result_callback), + ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource()); ASSERT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_THAT(second_result_callback.WaitForResult(), IsOk());
diff --git a/net/spdy/spdy_session_unittest.cc b/net/spdy/spdy_session_unittest.cc index 370eee0b..799fc421 100644 --- a/net/spdy/spdy_session_unittest.cc +++ b/net/spdy/spdy_session_unittest.cc
@@ -3532,8 +3532,6 @@ // post a task asynchronously to try and close the session. TestCompletionCallback callback2; HostPortPair host_port2("2.com", 80); - scoped_refptr<TransportSocketParams> params2( - new TransportSocketParams(host_port2, OnHostResolutionCallback())); auto connection2 = std::make_unique<ClientSocketHandle>(); EXPECT_EQ( ERR_IO_PENDING, @@ -3541,8 +3539,7 @@ ClientSocketPool::GroupId(host_port2, ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED), - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - params2), + ClientSocketPool::SocketParams::CreateForHttpForTesting(), DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource())); @@ -3617,8 +3614,6 @@ // post a task asynchronously to try and close the session. TestCompletionCallback callback3; HostPortPair host_port3("3.com", 80); - scoped_refptr<TransportSocketParams> params3( - new TransportSocketParams(host_port3, OnHostResolutionCallback())); auto connection3 = std::make_unique<ClientSocketHandle>(); EXPECT_EQ( ERR_IO_PENDING, @@ -3626,8 +3621,7 @@ ClientSocketPool::GroupId(host_port3, ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED), - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - params3), + ClientSocketPool::SocketParams::CreateForHttpForTesting(), DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource())); @@ -3700,8 +3694,6 @@ // post a task asynchronously to try and close the session. TestCompletionCallback callback2; HostPortPair host_port2("2.com", 80); - scoped_refptr<TransportSocketParams> params2( - new TransportSocketParams(host_port2, OnHostResolutionCallback())); auto connection2 = std::make_unique<ClientSocketHandle>(); EXPECT_EQ( ERR_IO_PENDING, @@ -3709,8 +3701,7 @@ ClientSocketPool::GroupId(host_port2, ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED), - ClientSocketPool::SocketParams::CreateFromTransportSocketParams( - params2), + ClientSocketPool::SocketParams::CreateForHttpForTesting(), DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()));
diff --git a/net/spdy/spdy_test_util_common.cc b/net/spdy/spdy_test_util_common.cc index 988d82b..078173b 100644 --- a/net/spdy/spdy_test_util_common.cc +++ b/net/spdy/spdy_test_util_common.cc
@@ -30,9 +30,7 @@ #include "net/socket/socket_tag.h" #include "net/socket/socks_connect_job.h" #include "net/socket/ssl_client_socket.h" -#include "net/socket/ssl_connect_job.h" #include "net/socket/transport_client_socket_pool.h" -#include "net/socket/transport_connect_job.h" #include "net/spdy/buffered_spdy_framer.h" #include "net/spdy/spdy_http_utils.h" #include "net/spdy/spdy_stream.h" @@ -490,23 +488,21 @@ key, enable_ip_based_pooling, /* is_websocket = */ false, NetLogWithSource())); - auto transport_params = base::MakeRefCounted<TransportSocketParams>( - key.host_port_pair(), OnHostResolutionCallback()); - auto connection = std::make_unique<ClientSocketHandle>(); TestCompletionCallback callback; - SSLConfig ssl_config; - auto ssl_params = base::MakeRefCounted<SSLSocketParams>( - transport_params, nullptr, nullptr, key.host_port_pair(), ssl_config, - key.privacy_mode()); + scoped_refptr<ClientSocketPool::SocketParams> socket_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(), + std::make_unique<SSLConfig>() /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); int rv = connection->Init( ClientSocketPool::GroupId(key.host_port_pair(), ClientSocketPool::SocketType::kSsl, key.privacy_mode()), - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(ssl_params), - MEDIUM, key.socket_tag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), + socket_params, MEDIUM, key.socket_tag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), http_session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL, ProxyServer::Direct()), net_log);
diff --git a/net/tools/cert_verify_tool/cert_verify_tool.cc b/net/tools/cert_verify_tool/cert_verify_tool.cc index 99fadb9..481446fe 100644 --- a/net/tools/cert_verify_tool/cert_verify_tool.cc +++ b/net/tools/cert_verify_tool/cert_verify_tool.cc
@@ -61,7 +61,8 @@ #if defined(USE_NSS_CERTS) net::SetURLRequestContextForNSSHttpIO(context->get()); #endif - net::SetGlobalCertNetFetcher(net::CreateCertNetFetcher(context->get())); + net::SetGlobalCertNetFetcher( + base::MakeRefCounted<net::CertNetFetcherImpl>(context->get())); initialization_complete_event->Signal(); }
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 788259f..70cd67b2 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -3153,6 +3153,8 @@ "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&" "LaxSameSiteCookie=1;SameSite=Lax"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); + req->set_site_for_cookies(test_server.GetURL(kHost, "/")); + req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/"))); req->Start(); d.RunUntilComplete(); EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); @@ -3276,6 +3278,121 @@ } } +TEST_F(URLRequestTest, SettingSameSiteCookies) { + HttpTestServer test_server; + ASSERT_TRUE(test_server.Start()); + + TestNetworkDelegate network_delegate; + default_context().set_network_delegate(&network_delegate); + + const std::string kHost = "example.test"; + const std::string kSubHost = "subdomain.example.test"; + const std::string kCrossHost = "cross-origin.test"; + + int expected_cookies = 0; + + { + TestDelegate d; + std::unique_ptr<URLRequest> req(default_context().CreateRequest( + test_server.GetURL(kHost, + "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&" + "LaxSameSiteCookie=1;SameSite=Lax"), + DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); + req->set_site_for_cookies(test_server.GetURL(kHost, "/")); + req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/"))); + + // 'SameSite' cookies are settable from strict same-site contexts + // (same-origin site_for_cookies, same-origin initiator), so this request + // should result in two cookies being created. + expected_cookies += 2; + + req->Start(); + d.RunUntilComplete(); + EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count()); + } + + { + TestDelegate d; + std::unique_ptr<URLRequest> req(default_context().CreateRequest( + test_server.GetURL(kHost, + "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&" + "LaxSameSiteCookie=1;SameSite=Lax"), + DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); + req->set_site_for_cookies(test_server.GetURL(kHost, "/")); + req->set_initiator( + url::Origin::Create(test_server.GetURL(kCrossHost, "/"))); + + // 'SameSite' cookies are settable from lax same-site contexts (same-origin + // site_for_cookies, cross-site initiator), so this request should result in + // two cookies being created. + expected_cookies += 2; + + req->Start(); + d.RunUntilComplete(); + EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count()); + } + + { + TestDelegate d; + std::unique_ptr<URLRequest> req(default_context().CreateRequest( + test_server.GetURL(kHost, + "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&" + "LaxSameSiteCookie=1;SameSite=Lax"), + DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); + req->set_site_for_cookies(test_server.GetURL(kSubHost, "/")); + req->set_initiator( + url::Origin::Create(test_server.GetURL(kCrossHost, "/"))); + + // 'SameSite' cookies are settable from lax same-site contexts (same-site + // site_for_cookies, cross-site initiator), so this request should result in + // two cookies being created. + expected_cookies += 2; + + req->Start(); + d.RunUntilComplete(); + EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count()); + } + + { + TestDelegate d; + std::unique_ptr<URLRequest> req(default_context().CreateRequest( + test_server.GetURL(kHost, + "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&" + "LaxSameSiteCookie=1;SameSite=Lax"), + DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); + req->set_site_for_cookies(test_server.GetURL(kSubHost, "/")); + + // 'SameSite' cookies are settable from strict same-site contexts (same-site + // site_for_cookies, no initiator), so this request should result in two + // cookies being created. + expected_cookies += 2; + + req->Start(); + d.RunUntilComplete(); + EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count()); + } + + { + TestDelegate d; + std::unique_ptr<URLRequest> req(default_context().CreateRequest( + test_server.GetURL(kHost, + "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&" + "LaxSameSiteCookie=1;SameSite=Lax"), + DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); + req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/")); + req->set_initiator( + url::Origin::Create(test_server.GetURL(kCrossHost, "/"))); + + // 'SameSite' cookies are not settable from cross-site contexts, so this + // should not result in any new cookies being created. + expected_cookies += 0; + + req->Start(); + d.RunUntilComplete(); + EXPECT_EQ(expected_cookies, network_delegate.set_cookie_count()); + } +} + // Tests that __Secure- cookies can't be set on non-secure origins. TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) { EmbeddedTestServer http_server; @@ -10787,7 +10904,8 @@ test_root_.reset(new ScopedTestRoot(root_cert.get())); #if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER) - SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_)); + SetGlobalCertNetFetcherForTesting( + base::MakeRefCounted<CertNetFetcherImpl>(&context_)); #endif #if defined(USE_NSS_CERTS)
diff --git a/net/websockets/websocket_basic_stream_adapters_test.cc b/net/websockets/websocket_basic_stream_adapters_test.cc index 07e34e59..456cb10e 100644 --- a/net/websockets/websocket_basic_stream_adapters_test.cc +++ b/net/websockets/websocket_basic_stream_adapters_test.cc
@@ -19,18 +19,14 @@ #include "net/base/test_completion_callback.h" #include "net/dns/mock_host_resolver.h" #include "net/http/http_network_session.h" -#include "net/http/http_proxy_connect_job.h" #include "net/log/net_log_with_source.h" #include "net/socket/client_socket_handle.h" #include "net/socket/client_socket_pool_manager_impl.h" #include "net/socket/connect_job.h" #include "net/socket/socket_tag.h" #include "net/socket/socket_test_util.h" -#include "net/socket/socks_connect_job.h" #include "net/socket/ssl_client_socket.h" -#include "net/socket/ssl_connect_job.h" #include "net/socket/transport_client_socket_pool.h" -#include "net/socket/transport_connect_job.h" #include "net/socket/websocket_endpoint_lock_manager.h" #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_key.h" @@ -93,29 +89,24 @@ net_log_.net_log(), &websocket_endpoint_lock_manager_), nullptr /* ssl_config_service */, - HttpNetworkSession::NORMAL_SOCKET_POOL)), - transport_params_(base::MakeRefCounted<TransportSocketParams>( - host_port_pair_, - OnHostResolutionCallback())), - ssl_params_( - base::MakeRefCounted<SSLSocketParams>(transport_params_, - nullptr, - nullptr, - host_port_pair_, - SSLConfig(), - PRIVACY_MODE_DISABLED)) {} + HttpNetworkSession::NORMAL_SOCKET_POOL)) {} ~WebSocketClientSocketHandleAdapterTest() override = default; bool InitClientSocketHandle(ClientSocketHandle* connection) { + scoped_refptr<ClientSocketPool::SocketParams> socks_params = + base::MakeRefCounted<ClientSocketPool::SocketParams>( + MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + std::make_unique<SSLConfig>() /* ssl_config_for_origin */, + nullptr /* ssl_config_for_proxy */, OnHostResolutionCallback()); TestCompletionCallback callback; int rv = connection->Init( ClientSocketPool::GroupId(host_port_pair_, ClientSocketPool::SocketType::kSsl, PrivacyMode::PRIVACY_MODE_DISABLED), - ClientSocketPool::SocketParams::CreateFromSSLSocketParams(ssl_params_), - MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), + socks_params, MEDIUM, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), socket_pool_manager_->GetSocketPool(ProxyServer::Direct()), net_log_); rv = callback.GetResult(rv); return rv == OK; @@ -126,8 +117,6 @@ MockClientSocketFactory socket_factory_; MockHostResolver host_resolver; std::unique_ptr<ClientSocketPoolManagerImpl> socket_pool_manager_; - scoped_refptr<TransportSocketParams> transport_params_; - scoped_refptr<SSLSocketParams> ssl_params_; WebSocketEndpointLockManager websocket_endpoint_lock_manager_; };
diff --git a/services/device/public/mojom/BUILD.gn b/services/device/public/mojom/BUILD.gn index 4a786db..25b916d 100644 --- a/services/device/public/mojom/BUILD.gn +++ b/services/device/public/mojom/BUILD.gn
@@ -24,7 +24,6 @@ "public_ip_address_geolocation_provider.mojom", "screen_orientation.mojom", "screen_orientation_lock_types.mojom", - "serial.mojom", "time_zone_monitor.mojom", "vibration_manager.mojom", "wake_lock.mojom", @@ -34,6 +33,7 @@ public_deps = [ ":constants", + ":serial", "//mojo/public/mojom/base", "//services/network/public/mojom", "//services/network/public/mojom:mutable_network_traffic_annotation_interface", @@ -100,3 +100,17 @@ ":*", ] } + +mojom("serial") { + sources = [ + "serial.mojom", + ] + + public_deps = [ + "//mojo/public/mojom/base", + ] + + export_class_attribute_blink = "BLINK_PLATFORM_EXPORT" + export_define_blink = "BLINK_PLATFORM_IMPLEMENTATION=1" + export_header_blink = "third_party/blink/public/platform/web_common.h" +}
diff --git a/services/device/serial/BUILD.gn b/services/device/serial/BUILD.gn index 79daf9e6..bf6eff78 100644 --- a/services/device/serial/BUILD.gn +++ b/services/device/serial/BUILD.gn
@@ -44,7 +44,7 @@ public_configs = [ ":platform_support" ] public_deps = [ - "//services/device/public/mojom", + "//services/device/public/mojom:serial", ] deps = [
diff --git a/services/identity/public/cpp/BUILD.gn b/services/identity/public/cpp/BUILD.gn index 206ad63..3c04bf4 100644 --- a/services/identity/public/cpp/BUILD.gn +++ b/services/identity/public/cpp/BUILD.gn
@@ -89,6 +89,10 @@ "//components/image_fetcher/core:test_support", "//components/signin/core/browser", ] + + if (is_ios) { + deps += [ "//components/signin/ios/browser" ] + } } source_set("tests") {
diff --git a/services/identity/public/cpp/DEPS b/services/identity/public/cpp/DEPS index 73f14c6..f5e3e33 100644 --- a/services/identity/public/cpp/DEPS +++ b/services/identity/public/cpp/DEPS
@@ -37,6 +37,10 @@ "accounts_mutator_unittest.cc": [ "+services/network/test/test_url_loader_factory.h", ], + "identity_test_environment.cc": [ + "+components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h", + "+components/signin/ios/browser/profile_oauth2_token_service_ios_provider.h", + ], "identity_manager_unittest.cc": [ "+google_apis/gaia/oauth2_token_service_delegate.h", "+services/network/test/test_cookie_manager.h",
diff --git a/services/identity/public/cpp/identity_manager.cc b/services/identity/public/cpp/identity_manager.cc index ba62e54..5f01575 100644 --- a/services/identity/public/cpp/identity_manager.cc +++ b/services/identity/public/cpp/identity_manager.cc
@@ -40,20 +40,20 @@ } // namespace IdentityManager::IdentityManager( + std::unique_ptr<AccountTrackerService> account_tracker_service, std::unique_ptr<ProfileOAuth2TokenService> token_service, std::unique_ptr<GaiaCookieManagerService> gaia_cookie_manager_service, std::unique_ptr<SigninManagerBase> signin_manager, std::unique_ptr<AccountFetcherService> account_fetcher_service, - AccountTrackerService* account_tracker_service, std::unique_ptr<PrimaryAccountMutator> primary_account_mutator, std::unique_ptr<AccountsMutator> accounts_mutator, std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator, std::unique_ptr<DiagnosticsProvider> diagnostics_provider) - : token_service_(std::move(token_service)), + : account_tracker_service_(std::move(account_tracker_service)), + token_service_(std::move(token_service)), gaia_cookie_manager_service_(std::move(gaia_cookie_manager_service)), signin_manager_(std::move(signin_manager)), account_fetcher_service_(std::move(account_fetcher_service)), - account_tracker_service_(account_tracker_service), primary_account_mutator_(std::move(primary_account_mutator)), accounts_mutator_(std::move(accounts_mutator)), accounts_cookie_mutator_(std::move(accounts_cookie_mutator)), @@ -296,6 +296,7 @@ ProfileOAuth2TokenService::RegisterProfilePrefs(registry); SigninManagerBase::RegisterProfilePrefs(registry); AccountFetcherService::RegisterPrefs(registry); + AccountTrackerService::RegisterPrefs(registry); } std::string IdentityManager::PickAccountIdForAccount( @@ -413,6 +414,7 @@ account_fetcher_service_->Shutdown(); gaia_cookie_manager_service_->Shutdown(); token_service_->Shutdown(); + account_tracker_service_->Shutdown(); } SigninManagerBase* IdentityManager::GetSigninManager() { @@ -424,7 +426,7 @@ } AccountTrackerService* IdentityManager::GetAccountTrackerService() { - return account_tracker_service_; + return account_tracker_service_.get(); } AccountFetcherService* IdentityManager::GetAccountFetcherService() {
diff --git a/services/identity/public/cpp/identity_manager.h b/services/identity/public/cpp/identity_manager.h index 2e6eb22..0d207e6c 100644 --- a/services/identity/public/cpp/identity_manager.h +++ b/services/identity/public/cpp/identity_manager.h
@@ -194,11 +194,11 @@ }; IdentityManager( + std::unique_ptr<AccountTrackerService> account_tracker_service, std::unique_ptr<ProfileOAuth2TokenService> token_service, std::unique_ptr<GaiaCookieManagerService> gaia_cookie_manager_service, std::unique_ptr<SigninManagerBase> signin_manager, std::unique_ptr<AccountFetcherService> account_fetcher_service, - AccountTrackerService* account_tracker_service, std::unique_ptr<PrimaryAccountMutator> primary_account_mutator, std::unique_ptr<AccountsMutator> accounts_mutator, std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator, @@ -651,11 +651,11 @@ // these classes in the IdentityManager implementation, as all such // synchronous access will become impossible when IdentityManager is // backed by the Identity Service. + std::unique_ptr<AccountTrackerService> account_tracker_service_; std::unique_ptr<ProfileOAuth2TokenService> token_service_; std::unique_ptr<GaiaCookieManagerService> gaia_cookie_manager_service_; std::unique_ptr<SigninManagerBase> signin_manager_; std::unique_ptr<AccountFetcherService> account_fetcher_service_; - AccountTrackerService* account_tracker_service_; // PrimaryAccountMutator instance. May be null if mutation of the primary // account state is not supported on the current platform.
diff --git a/services/identity/public/cpp/identity_manager_unittest.cc b/services/identity/public/cpp/identity_manager_unittest.cc index 3e96b65..bd8b333e 100644 --- a/services/identity/public/cpp/identity_manager_unittest.cc +++ b/services/identity/public/cpp/identity_manager_unittest.cc
@@ -211,11 +211,9 @@ class IdentityManagerTest : public testing::Test { protected: IdentityManagerTest() : signin_client_(&pref_service_) { - AccountTrackerService::RegisterPrefs(pref_service_.registry()); IdentityManager::RegisterProfilePrefs(pref_service_.registry()); IdentityManager::RegisterLocalStatePrefs(pref_service_.registry()); - account_tracker_.Initialize(&pref_service_, base::FilePath()); RecreateIdentityManager(signin::AccountConsistencyMethod::kDisabled, SigninManagerSetup::kWithAuthenticatedAccout); } @@ -223,7 +221,6 @@ ~IdentityManagerTest() override { identity_manager_->Shutdown(); signin_client_.Shutdown(); - account_tracker_.Shutdown(); } void SetUp() override { @@ -242,7 +239,9 @@ return identity_manager_diagnostics_observer_.get(); } - AccountTrackerService* account_tracker() { return &account_tracker_; } + AccountTrackerService* account_tracker() { + return identity_manager()->GetAccountTrackerService(); + } CustomFakeProfileOAuth2TokenService* token_service() { return static_cast<CustomFakeProfileOAuth2TokenService*>( @@ -292,19 +291,22 @@ }, test_url_loader_factory())); + auto account_tracker_service = std::make_unique<AccountTrackerService>(); + account_tracker_service->Initialize(&pref_service_, base::FilePath()); + auto account_fetcher_service = std::make_unique<AccountFetcherService>(); account_fetcher_service->Initialize( - &signin_client_, token_service.get(), &account_tracker_, + &signin_client_, token_service.get(), account_tracker_service.get(), std::make_unique<image_fetcher::FakeImageDecoder>()); #if defined(OS_CHROMEOS) DCHECK_EQ(account_consistency, signin::AccountConsistencyMethod::kDisabled) << "AccountConsistency is not used by SigninManagerBase"; auto signin_manager = std::make_unique<SigninManagerBase>( - &signin_client_, token_service.get(), &account_tracker_); + &signin_client_, token_service.get(), account_tracker_service.get()); #else auto signin_manager = std::make_unique<SigninManager>( - &signin_client_, token_service.get(), &account_tracker_, + &signin_client_, token_service.get(), account_tracker_service.get(), gaia_cookie_manager_service.get(), account_consistency); #endif @@ -327,10 +329,10 @@ token_service.get(), gaia_cookie_manager_service.get()); identity_manager_.reset(new IdentityManager( - std::move(token_service), std::move(gaia_cookie_manager_service), - std::move(signin_manager), std::move(account_fetcher_service), - &account_tracker_, nullptr, nullptr, std::move(accounts_cookie_mutator), - std::move(diagnostics_provider))); + std::move(account_tracker_service), std::move(token_service), + std::move(gaia_cookie_manager_service), std::move(signin_manager), + std::move(account_fetcher_service), nullptr, nullptr, + std::move(accounts_cookie_mutator), std::move(diagnostics_provider))); identity_manager_observer_.reset( new TestIdentityManagerObserver(identity_manager_.get())); identity_manager_diagnostics_observer_.reset( @@ -371,7 +373,6 @@ private: base::MessageLoop message_loop_; sync_preferences::TestingPrefServiceSyncable pref_service_; - AccountTrackerService account_tracker_; TestSigninClient signin_client_; network::TestURLLoaderFactory test_url_loader_factory_; std::unique_ptr<IdentityManager> identity_manager_;
diff --git a/services/identity/public/cpp/identity_test_environment.cc b/services/identity/public/cpp/identity_test_environment.cc index c62d623..e88a08e 100644 --- a/services/identity/public/cpp/identity_test_environment.cc +++ b/services/identity/public/cpp/identity_test_environment.cc
@@ -25,6 +25,11 @@ #include "services/identity/public/cpp/primary_account_mutator.h" #include "services/identity/public/cpp/test_identity_manager_observer.h" +#if defined(OS_IOS) +#include "components/signin/ios/browser/profile_oauth2_token_service_ios_delegate.h" +#include "components/signin/ios/browser/profile_oauth2_token_service_ios_provider.h" +#endif + #if !defined(OS_CHROMEOS) #include "services/identity/public/cpp/primary_account_mutator_impl.h" #endif @@ -139,21 +144,15 @@ sync_preferences::TestingPrefServiceSyncable* test_pref_service = dependencies_owner_->pref_service(); - AccountTrackerService::RegisterPrefs(test_pref_service->registry()); - - auto token_service = - std::make_unique<FakeProfileOAuth2TokenService>(test_pref_service); - - owned_account_tracker_service_ = std::make_unique<AccountTrackerService>(); - owned_account_tracker_service_->Initialize(test_pref_service, - base::FilePath()); - IdentityManager::RegisterProfilePrefs(test_pref_service->registry()); IdentityManager::RegisterLocalStatePrefs(test_pref_service->registry()); + owned_identity_manager_ = BuildIdentityManagerForTests( - test_signin_client, test_pref_service, std::move(token_service), - owned_account_tracker_service_.get(), account_consistency, - test_url_loader_factory); + test_signin_client, test_pref_service, base::FilePath(), +#if defined(OS_IOS) + std::unique_ptr<ProfileOAuth2TokenServiceIOSProvider>(), +#endif + account_consistency, test_url_loader_factory); Initialize(); } @@ -163,23 +162,45 @@ IdentityTestEnvironment::BuildIdentityManagerForTests( SigninClient* signin_client, PrefService* pref_service, - std::unique_ptr<FakeProfileOAuth2TokenService> token_service, - AccountTrackerService* account_tracker_service, + base::FilePath user_data_dir, +#if defined(OS_IOS) + std::unique_ptr<ProfileOAuth2TokenServiceIOSProvider> + token_service_ios_provider, +#endif signin::AccountConsistencyMethod account_consistency, network::TestURLLoaderFactory* test_url_loader_factory) { + auto account_tracker_service = std::make_unique<AccountTrackerService>(); + account_tracker_service->Initialize(pref_service, user_data_dir); + +#if defined(OS_IOS) + std::unique_ptr<ProfileOAuth2TokenService> token_service; + if (token_service_ios_provider) { + token_service = std::make_unique<FakeProfileOAuth2TokenService>( + pref_service, std::make_unique<ProfileOAuth2TokenServiceIOSDelegate>( + signin_client, std::move(token_service_ios_provider), + account_tracker_service.get())); + } else { + token_service = + std::make_unique<FakeProfileOAuth2TokenService>(pref_service); + } +#else + auto token_service = + std::make_unique<FakeProfileOAuth2TokenService>(pref_service); +#endif + auto account_fetcher_service = std::make_unique<AccountFetcherService>(); account_fetcher_service->Initialize( - signin_client, token_service.get(), account_tracker_service, + signin_client, token_service.get(), account_tracker_service.get(), std::make_unique<image_fetcher::FakeImageDecoder>()); #if defined(OS_CHROMEOS) std::unique_ptr<SigninManagerBase> signin_manager = std::make_unique<SigninManagerBase>(signin_client, token_service.get(), - account_tracker_service); + account_tracker_service.get()); #else std::unique_ptr<SigninManagerBase> signin_manager = std::make_unique<SigninManager>(signin_client, token_service.get(), - account_tracker_service, nullptr, + account_tracker_service.get(), nullptr, account_consistency); #endif signin_manager->Initialize(pref_service); @@ -204,13 +225,13 @@ #if !defined(OS_CHROMEOS) primary_account_mutator = std::make_unique<PrimaryAccountMutatorImpl>( - account_tracker_service, + account_tracker_service.get(), static_cast<SigninManager*>(signin_manager.get())); #endif #if !defined(OS_ANDROID) && !defined(OS_IOS) accounts_mutator = std::make_unique<AccountsMutatorImpl>( - token_service.get(), account_tracker_service, signin_manager.get(), + token_service.get(), account_tracker_service.get(), signin_manager.get(), pref_service); #endif @@ -221,7 +242,7 @@ gaia_cookie_manager_service.get()); return std::make_unique<IdentityManagerWrapper>( - account_tracker_service, std::move(token_service), + std::move(account_tracker_service), std::move(token_service), std::move(gaia_cookie_manager_service), std::move(signin_manager), std::move(account_fetcher_service), std::move(primary_account_mutator), std::move(accounts_mutator), std::move(accounts_cookie_mutator), @@ -233,10 +254,6 @@ // initialization. identity_manager()->RemoveDiagnosticsObserver(this); - if (owned_account_tracker_service_) { - owned_account_tracker_service_->Shutdown(); - } - // Call shutdown only if we own the IdentityManager. // It is the owner's responsibility to call Shutdown. if (owned_identity_manager_) {
diff --git a/services/identity/public/cpp/identity_test_environment.h b/services/identity/public/cpp/identity_test_environment.h index 4a3e05a..4667f605 100644 --- a/services/identity/public/cpp/identity_test_environment.h +++ b/services/identity/public/cpp/identity_test_environment.h
@@ -6,6 +6,7 @@ #define SERVICES_IDENTITY_PUBLIC_CPP_IDENTITY_TEST_ENVIRONMENT_H_ #include "base/optional.h" +#include "build/build_config.h" #include "components/signin/core/browser/account_consistency_method.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/diagnostics_provider_impl.h" @@ -21,6 +22,10 @@ class PrefService; class TestSigninClient; +#if defined(OS_IOS) +class ProfileOAuth2TokenServiceIOSProvider; +#endif + namespace sync_preferences { class TestingPrefServiceSyncable; } @@ -337,10 +342,6 @@ // IdentityTestEnvironment's constructor. std::unique_ptr<TestSigninClient> owned_signin_client_; - // This will be null if a AccountTrackerService was provided to - // IdentityTestEnvironment's constructor. - std::unique_ptr<AccountTrackerService> owned_account_tracker_service_; - // Depending on which constructor is used, exactly one of these will be // non-null. See the documentation on the constructor wherein IdentityManager // is passed in for required lifetime invariants in that case. @@ -353,11 +354,17 @@ std::vector<AccessTokenRequestState> requesters_; // Create an IdentityManager instance for tests. + // Note: |token_service_ios_provider| is an iOS-specific parameter; if + // non-null, an iOS delegate instance will be constructed for the token + // service as opposed to the default fake delegate. static std::unique_ptr<IdentityManagerWrapper> BuildIdentityManagerForTests( SigninClient* signin_client, PrefService* pref_service, - std::unique_ptr<FakeProfileOAuth2TokenService> token_service, - AccountTrackerService* account_tracker_service, + base::FilePath user_data_dir, +#if defined(OS_IOS) + std::unique_ptr<ProfileOAuth2TokenServiceIOSProvider> + token_service_ios_provider, +#endif signin::AccountConsistencyMethod account_consistency = signin::AccountConsistencyMethod::kDisabled, network::TestURLLoaderFactory* test_url_loader_factory = nullptr);
diff --git a/services/network/cookie_manager_unittest.cc b/services/network/cookie_manager_unittest.cc index 7e299f4..35e20c8 100644 --- a/services/network/cookie_manager_unittest.cc +++ b/services/network/cookie_manager_unittest.cc
@@ -122,6 +122,8 @@ net::CanonicalCookie::CookieInclusionStatus result_out = net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_UNKNOWN_ERROR; net::CookieOptions options; + options.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); if (modify_http_only) options.set_include_httponly(); cookie_service_->SetCanonicalCookie( @@ -143,6 +145,8 @@ bool modify_http_only) { base::RunLoop run_loop; net::CookieOptions options; + options.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); if (modify_http_only) options.set_include_httponly(); net::CanonicalCookie::CookieInclusionStatus result_out = @@ -228,8 +232,11 @@ net::ResultSavingCookieCallback<net::CanonicalCookie::CookieInclusionStatus> callback; net::CookieOptions options; + options.set_same_site_cookie_context( + net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); if (can_modify_httponly) options.set_include_httponly(); + cookie_monster_->SetCanonicalCookieAsync( std::make_unique<net::CanonicalCookie>(cookie), std::move(source_scheme), options,
diff --git a/services/network/network_context.cc b/services/network/network_context.cc index 99110cb..22028a01 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc
@@ -2077,8 +2077,8 @@ #endif #if defined(OS_ANDROID) || defined(OS_FUCHSIA) || \ (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX) - net::SetGlobalCertNetFetcher( - net::CreateCertNetFetcher(result.url_request_context.get())); + net::SetGlobalCertNetFetcher(base::MakeRefCounted<net::CertNetFetcherImpl>( + result.url_request_context.get())); #endif }
diff --git a/testing/scripts/test_traffic_annotation_auditor.py b/testing/scripts/test_traffic_annotation_auditor.py index f5b17c1..0dc8e17 100755 --- a/testing/scripts/test_traffic_annotation_auditor.py +++ b/testing/scripts/test_traffic_annotation_auditor.py
@@ -24,8 +24,10 @@ "last_update_column_name": "Last Update", } -def is_linux(): - return sys.platform.startswith('linux') + +def is_windows(): + return os.name == 'nt' + def main_run(args): annotations_file = tempfile.NamedTemporaryFile() @@ -43,8 +45,10 @@ ] rc = common.run_command(command_line) - # Update the Google Sheets on success, but only on the Linux trybot. - if rc == 0 and is_linux(): + # Update the Google Sheets on success, but only on the Windows trybot. + if rc == 0 and is_windows(): + print("Tests succeeded. Updating annotations sheet...") + config_file = tempfile.NamedTemporaryFile(delete=False) json.dump(SHEET_CONFIG, config_file, indent=4) config_filename = config_file.name
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 1392fa2f..29de0a1f 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -6093,6 +6093,10 @@ "experiments": [ { "name": "Enabled", + "params": { + "saturation_margin": "5", + "use_peaks_not_rms": "false" + }, "enable_features": [ "WebRtcHybridAgc" ]
diff --git a/third_party/blink/public/platform/web_runtime_features.h b/third_party/blink/public/platform/web_runtime_features.h index dd4a7aa..54c3e4b2 100644 --- a/third_party/blink/public/platform/web_runtime_features.h +++ b/third_party/blink/public/platform/web_runtime_features.h
@@ -197,7 +197,6 @@ BLINK_PLATFORM_EXPORT static void EnableWebVR(bool); BLINK_PLATFORM_EXPORT static void EnableWebXR(bool); BLINK_PLATFORM_EXPORT static void EnableWebXRHitTest(bool); - BLINK_PLATFORM_EXPORT static void EnableXSLT(bool); BLINK_PLATFORM_EXPORT static void ForceOverlayFullscreenVideo(bool); BLINK_PLATFORM_EXPORT static void EnableTimerThrottlingForBackgroundTabs( bool);
diff --git a/third_party/blink/renderer/core/aom/accessible_node.cc b/third_party/blink/renderer/core/aom/accessible_node.cc index ae03029d..f0e6361 100644 --- a/third_party/blink/renderer/core/aom/accessible_node.cc +++ b/third_party/blink/renderer/core/aom/accessible_node.cc
@@ -11,8 +11,8 @@ #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/page/page.h" -#include "third_party/blink/renderer/platform//weborigin/security_origin.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" +#include "third_party/blink/renderer/platform/weborigin/security_origin.h" namespace blink {
diff --git a/third_party/blink/renderer/core/css/css_inherited_value.h b/third_party/blink/renderer/core/css/css_inherited_value.h index e706038..466c275 100644 --- a/third_party/blink/renderer/core/css/css_inherited_value.h +++ b/third_party/blink/renderer/core/css/css_inherited_value.h
@@ -27,7 +27,7 @@ namespace blink { -class CSSInheritedValue : public CSSValue { +class CORE_EXPORT CSSInheritedValue : public CSSValue { public: static CSSInheritedValue* Create();
diff --git a/third_party/blink/renderer/core/css/css_unset_value.h b/third_party/blink/renderer/core/css/css_unset_value.h index 851e523..946bc54 100644 --- a/third_party/blink/renderer/core/css/css_unset_value.h +++ b/third_party/blink/renderer/core/css/css_unset_value.h
@@ -15,7 +15,7 @@ namespace cssvalue { -class CSSUnsetValue : public CSSValue { +class CORE_EXPORT CSSUnsetValue : public CSSValue { public: static CSSUnsetValue* Create();
diff --git a/third_party/blink/renderer/core/css/parser/css_property_parser.cc b/third_party/blink/renderer/core/css/parser/css_property_parser.cc index e62c334..1da570e 100644 --- a/third_party/blink/renderer/core/css/parser/css_property_parser.cc +++ b/third_party/blink/renderer/core/css/parser/css_property_parser.cc
@@ -27,6 +27,31 @@ class CSSIdentifierValue; +namespace { + +const CSSValue* MaybeConsumeCSSWideKeyword(CSSParserTokenRange& range) { + CSSParserTokenRange local_range = range; + + CSSValueID id = local_range.ConsumeIncludingWhitespace().Id(); + if (!local_range.AtEnd()) + return nullptr; + + const CSSValue* value = nullptr; + if (id == CSSValueID::kInitial) + value = CSSInitialValue::Create(); + if (id == CSSValueID::kInherit) + value = CSSInheritedValue::Create(); + if (id == CSSValueID::kUnset) + value = cssvalue::CSSUnsetValue::Create(); + + if (value) + range = local_range; + + return value; +} + +} // namespace + CSSPropertyParser::CSSPropertyParser( const CSSParserTokenRange& range, const CSSParserContext* context, @@ -74,6 +99,10 @@ const CSSParserContext* context) { DCHECK(context); CSSPropertyParser parser(range, context, nullptr); + + if (const CSSValue* value = MaybeConsumeCSSWideKeyword(parser.range_)) + return value; + const CSSValue* value = ParseLonghand(property, CSSPropertyID::kInvalid, *parser.context_, parser.range_); if (!value || !parser.range_.AtEnd()) @@ -215,18 +244,9 @@ bool CSSPropertyParser::ConsumeCSSWideKeyword(CSSPropertyID unresolved_property, bool important) { CSSParserTokenRange range_copy = range_; - CSSValueID id = range_copy.ConsumeIncludingWhitespace().Id(); - if (!range_copy.AtEnd()) - return false; - CSSValue* value = nullptr; - if (id == CSSValueID::kInitial) - value = CSSInitialValue::Create(); - else if (id == CSSValueID::kInherit) - value = CSSInheritedValue::Create(); - else if (id == CSSValueID::kUnset) - value = cssvalue::CSSUnsetValue::Create(); - else + const CSSValue* value = MaybeConsumeCSSWideKeyword(range_copy); + if (!value) return false; CSSPropertyID property = resolveCSSPropertyID(unresolved_property);
diff --git a/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc b/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc index 0082ae7d..8b32f60 100644 --- a/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc +++ b/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc
@@ -4,7 +4,10 @@ #include "third_party/blink/renderer/core/css/resolver/css_variable_resolver.h" #include "third_party/blink/renderer/core/css/css_custom_property_declaration.h" +#include "third_party/blink/renderer/core/css/css_inherited_value.h" +#include "third_party/blink/renderer/core/css/css_initial_value.h" #include "third_party/blink/renderer/core/css/css_syntax_string_parser.h" +#include "third_party/blink/renderer/core/css/css_unset_value.h" #include "third_party/blink/renderer/core/css/css_variable_reference_value.h" #include "third_party/blink/renderer/core/css/document_style_environment_variables.h" #include "third_party/blink/renderer/core/css/parser/css_parser_context.h" @@ -75,6 +78,33 @@ name, tokens, false, *CSSParserContext::Create(GetDocument())); } + const CSSVariableReferenceValue* CreateVariableReference( + const String& value) { + const auto tokens = CSSTokenizer(value).TokenizeToEOF(); + + const CSSParserContext* context = CSSParserContext::Create(GetDocument()); + const bool is_animation_tainted = false; + const bool needs_variable_resolution = true; + + return MakeGarbageCollected<CSSVariableReferenceValue>( + CSSVariableData::Create(tokens, is_animation_tainted, + needs_variable_resolution, context->BaseURL(), + context->Charset()), + *context); + } + + const CSSValue* ResolveVar(StyleResolverState& state, + CSSPropertyID property_id, + const String& value) { + const CSSVariableReferenceValue* var = CreateVariableReference(value); + + CSSVariableResolver resolver(state); + const bool disallow_animation_tainted = false; + + return resolver.ResolveVariableReferences(property_id, *var, + disallow_animation_tainted); + } + const CSSValue* CreatePxValue(double px) { return CSSPrimitiveValue::Create(px, CSSPrimitiveValue::UnitType::kPixels); } @@ -506,4 +536,50 @@ EXPECT_EQ(expected_unique_strings, impls.size()); } +TEST_F(CSSVariableResolverTest, CSSWideKeywords) { + using CSSUnsetValue = cssvalue::CSSUnsetValue; + + const ComputedStyle* initial = &ComputedStyle::InitialStyle(); + StyleResolverState state(GetDocument(), nullptr, initial, initial); + + scoped_refptr<ComputedStyle> style = ComputedStyle::Create(); + style->InheritFrom(*initial); + state.SetStyle(std::move(style)); + + const CSSValue* whitespace = CreateCustomProperty("--w", " "); + StyleBuilder::ApplyProperty(CSSPropertyName("--w"), state, *whitespace); + + // Test initial/inherit/unset for an inherited property: + EXPECT_EQ(CSSInitialValue::Create(), + ResolveVar(state, CSSPropertyID::kColor, "var(--w) initial")); + EXPECT_EQ(CSSInheritedValue::Create(), + ResolveVar(state, CSSPropertyID::kColor, "var(--w) inherit")); + EXPECT_EQ(CSSUnsetValue::Create(), + ResolveVar(state, CSSPropertyID::kColor, "var(--w) unset")); + + // Test initial/inherit/unset for a non-inherited property: + EXPECT_EQ(CSSInitialValue::Create(), + ResolveVar(state, CSSPropertyID::kWidth, "var(--w) initial")); + EXPECT_EQ(CSSInheritedValue::Create(), + ResolveVar(state, CSSPropertyID::kWidth, "var(--w) inherit")); + EXPECT_EQ(CSSUnsetValue::Create(), + ResolveVar(state, CSSPropertyID::kWidth, "var(--w) unset")); + + // Test initial/inherit/unset in fallbacks: + + EXPECT_EQ(CSSInitialValue::Create(), + ResolveVar(state, CSSPropertyID::kColor, "var(--u,initial)")); + EXPECT_EQ(CSSInheritedValue::Create(), + ResolveVar(state, CSSPropertyID::kColor, "var(--u,inherit)")); + EXPECT_EQ(CSSUnsetValue::Create(), + ResolveVar(state, CSSPropertyID::kColor, "var(--u,unset)")); + + EXPECT_EQ(CSSInitialValue::Create(), + ResolveVar(state, CSSPropertyID::kWidth, "var(--u,initial)")); + EXPECT_EQ(CSSInheritedValue::Create(), + ResolveVar(state, CSSPropertyID::kWidth, "var(--u,inherit)")); + EXPECT_EQ(CSSUnsetValue::Create(), + ResolveVar(state, CSSPropertyID::kWidth, "var(--u,unset)")); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/dom/cdata_section.h b/third_party/blink/renderer/core/dom/cdata_section.h index 2ed11b2..df4a7c7f 100644 --- a/third_party/blink/renderer/core/dom/cdata_section.h +++ b/third_party/blink/renderer/core/dom/cdata_section.h
@@ -24,6 +24,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_CDATA_SECTION_H_ #include "third_party/blink/renderer/core/dom/text.h" +#include "third_party/blink/renderer/platform/wtf/casting.h" namespace blink { @@ -41,7 +42,12 @@ Text* CloneWithData(Document&, const String&) const override; }; -DEFINE_NODE_TYPE_CASTS(CDATASection, getNodeType() == Node::kCdataSectionNode); +template <> +struct DowncastTraits<CDATASection> { + static bool AllowFrom(const Node& node) { + return node.getNodeType() == Node::kCdataSectionNode; + } +}; } // namespace blink
diff --git a/third_party/blink/renderer/core/dom/character_data.h b/third_party/blink/renderer/core/dom/character_data.h index eefaf4f..b3acf28 100644 --- a/third_party/blink/renderer/core/dom/character_data.h +++ b/third_party/blink/renderer/core/dom/character_data.h
@@ -27,6 +27,7 @@ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/platform/bindings/parkable_string.h" +#include "third_party/blink/renderer/platform/wtf/casting.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -108,7 +109,10 @@ delete; // This will catch anyone doing an unnecessary check. }; -DEFINE_NODE_TYPE_CASTS(CharacterData, IsCharacterDataNode()); +template <> +struct DowncastTraits<CharacterData> { + static bool AllowFrom(const Node& node) { return node.IsCharacterDataNode(); } +}; } // namespace blink
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 8a7abae..fae5d258 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -4112,9 +4112,13 @@ if (layout_parent) layout_parent->EnsureComputedStyle(); } - scoped_refptr<ComputedStyle> new_style = - HasCustomStyleCallbacks() ? CustomStyleForLayoutObject() - : OriginalStyleForLayoutObject(); + scoped_refptr<ComputedStyle> new_style = nullptr; + // TODO(crbug.com/953707): Avoid setting inline style during + // HTMLImageElement::CustomStyleForLayoutObject. + if (HasCustomStyleCallbacks() && !IsHTMLImageElement(*this)) + new_style = CustomStyleForLayoutObject(); + else + new_style = OriginalStyleForLayoutObject(); element_style = new_style.get(); element_style->SetIsEnsuredInDisplayNone(); SetComputedStyle(std::move(new_style));
diff --git a/third_party/blink/renderer/core/dom/node.cc b/third_party/blink/renderer/core/dom/node.cc index eb2eb1b..51a2afb 100644 --- a/third_party/blink/renderer/core/dom/node.cc +++ b/third_party/blink/renderer/core/dom/node.cc
@@ -1798,8 +1798,8 @@ // This covers ProcessingInstruction and Comment that should return their // value when .textContent is accessed on them, but should be ignored when // iterated over as a descendant of a ContainerNode. - if (IsCharacterDataNode()) - return ToCharacterData(this)->data(); + if (auto* character_data = DynamicTo<CharacterData>(this)) + return character_data->data(); // Attribute nodes have their attribute values as textContent. if (auto* attr = DynamicTo<Attr>(this))
diff --git a/third_party/blink/renderer/core/dom/processing_instruction.cc b/third_party/blink/renderer/core/dom/processing_instruction.cc index fce0804..9543626 100644 --- a/third_party/blink/renderer/core/dom/processing_instruction.cc +++ b/third_party/blink/renderer/core/dom/processing_instruction.cc
@@ -140,7 +140,7 @@ // We need to make a synthetic XSLStyleSheet that is embedded. // It needs to be able to kick off import/include loads that // can hang off some parent sheet. - if (is_xsl_ && RuntimeEnabledFeatures::XSLTEnabled()) { + if (is_xsl_) { KURL final_url(local_href_); sheet_ = XSLStyleSheet::CreateEmbedded(this, final_url); loading_ = false; @@ -150,9 +150,6 @@ ClearResource(); - if (is_xsl_ && !RuntimeEnabledFeatures::XSLTEnabled()) - return; - ResourceLoaderOptions options; options.initiator_info.name = fetch_initiator_type_names::kProcessinginstruction; @@ -160,7 +157,6 @@ options); loading_ = true; if (is_xsl_) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); params.MutableResourceRequest().SetFetchRequestMode( network::mojom::FetchRequestMode::kSameOrigin); XSLStyleSheetResource::Fetch(params, GetDocument().Fetcher(), this);
diff --git a/third_party/blink/renderer/core/dom/range.cc b/third_party/blink/renderer/core/dom/range.cc index 904e6a4..fe24dfc 100644 --- a/third_party/blink/renderer/core/dom/range.cc +++ b/third_party/blink/renderer/core/dom/range.cc
@@ -512,7 +512,7 @@ case Node::kCdataSectionNode: case Node::kCommentNode: case Node::kProcessingInstructionNode: - return ToCharacterData(node)->length(); + return To<CharacterData>(node)->length(); case Node::kElementNode: case Node::kDocumentNode: case Node::kDocumentFragmentNode: @@ -674,7 +674,7 @@ case Node::kCdataSectionNode: case Node::kCommentNode: case Node::kProcessingInstructionNode: - end_offset = std::min(end_offset, ToCharacterData(container)->length()); + end_offset = std::min(end_offset, To<CharacterData>(container)->length()); if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) { CharacterData* c = static_cast<CharacterData*>(container->cloneNode(true)); @@ -687,7 +687,7 @@ } } if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) - ToCharacterData(container)->deleteData( + To<CharacterData>(container)->deleteData( start_offset, end_offset - start_offset, exception_state); break; case Node::kElementNode: @@ -953,7 +953,7 @@ for (Node* n = FirstNode(); n != past_last; n = NodeTraversal::Next(*n)) { Node::NodeType type = n->getNodeType(); if (type == Node::kTextNode || type == Node::kCdataSectionNode) { - String data = ToCharacterData(n)->data(); + String data = To<CharacterData>(n)->data(); unsigned length = data.length(); unsigned start = (n == start_.Container()) ? std::min(start_.Offset(), length) : 0; @@ -1050,12 +1050,12 @@ case Node::kCdataSectionNode: case Node::kCommentNode: case Node::kTextNode: - if (offset > ToCharacterData(n)->length()) { + if (offset > To<CharacterData>(n)->length()) { exception_state.ThrowDOMException( DOMExceptionCode::kIndexSizeError, "The offset " + String::Number(offset) + " is larger than the node's length (" + - String::Number(ToCharacterData(n)->length()) + ")."); + String::Number(To<CharacterData>(n)->length()) + ")."); } else if (offset > static_cast<unsigned>(std::numeric_limits<int>::max())) { exception_state.ThrowDOMException(
diff --git a/third_party/blink/renderer/core/dom/range_boundary_point.h b/third_party/blink/renderer/core/dom/range_boundary_point.h index a4f4656f..9026294 100644 --- a/third_party/blink/renderer/core/dom/range_boundary_point.h +++ b/third_party/blink/renderer/core/dom/range_boundary_point.h
@@ -176,8 +176,8 @@ inline void RangeBoundaryPoint::SetToEndOfNode(Node& container) { container_node_ = &container; - if (container_node_->IsCharacterDataNode()) { - offset_in_container_ = ToCharacterData(container_node_)->length(); + if (auto* character_data = DynamicTo<CharacterData>(container_node_.Get())) { + offset_in_container_ = character_data->length(); child_before_boundary_ = nullptr; } else { child_before_boundary_ = container_node_->lastChild();
diff --git a/third_party/blink/renderer/core/editing/commands/apply_style_command.cc b/third_party/blink/renderer/core/editing/commands/apply_style_command.cc index 6d4ce45..86d5e25 100644 --- a/third_party/blink/renderer/core/editing/commands/apply_style_command.cc +++ b/third_party/blink/renderer/core/editing/commands/apply_style_command.cc
@@ -108,8 +108,8 @@ } static bool OffsetIsBeforeLastNodeOffset(int offset, Node* anchor_node) { - if (anchor_node->IsCharacterDataNode()) - return offset < static_cast<int>(ToCharacterData(anchor_node)->length()); + if (auto* character_data = DynamicTo<CharacterData>(anchor_node)) + return offset < static_cast<int>(character_data->length()); int current_offset = 0; for (Node* node = NodeTraversal::FirstChild(*anchor_node); node && current_offset < offset;
diff --git a/third_party/blink/renderer/core/editing/editing_strategy.cc b/third_party/blink/renderer/core/editing/editing_strategy.cc index 59967488..add81ff5 100644 --- a/third_party/blink/renderer/core/editing/editing_strategy.cc +++ b/third_party/blink/renderer/core/editing/editing_strategy.cc
@@ -45,8 +45,8 @@ DCHECK(node); if (!node) return 0; - if (node->IsCharacterDataNode()) - return static_cast<int>(ToCharacterData(node)->length()); + if (auto* character_data = DynamicTo<CharacterData>(node)) + return static_cast<int>(character_data->length()); if (Traversal::HasChildren(*node)) return Traversal::CountChildren(*node);
diff --git a/third_party/blink/renderer/core/editing/layout_selection.cc b/third_party/blink/renderer/core/editing/layout_selection.cc index 86a5cfd4..5cbe5c5 100644 --- a/third_party/blink/renderer/core/editing/layout_selection.cc +++ b/third_party/blink/renderer/core/editing/layout_selection.cc
@@ -51,7 +51,7 @@ DCHECK(layout_object); if (layout_object->IsInline()) return layout_object->ContainingNGBlockFlow(); - if (LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(layout_object)) + if (auto* block_flow = DynamicTo<LayoutBlockFlow>(layout_object)) return NGBlockNode::CanUseNewLayout(*block_flow); return false; }
diff --git a/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc b/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc index d613357b..09c7724c 100644 --- a/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc +++ b/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc
@@ -537,7 +537,7 @@ const unsigned start_offset = node == range_start_container ? range_start_offset : 0; - const unsigned max_character_offset = ToCharacterData(node).length(); + const unsigned max_character_offset = To<CharacterData>(node).length(); const unsigned end_offset = node == range_end_container ? range_end_offset : max_character_offset;
diff --git a/third_party/blink/renderer/core/editing/position.cc b/third_party/blink/renderer/core/editing/position.cc index 537897b..a40fdcd 100644 --- a/third_party/blink/renderer/core/editing/position.cc +++ b/third_party/blink/renderer/core/editing/position.cc
@@ -131,11 +131,9 @@ DCHECK_EQ(offset, 0); return; } - if (anchor_node_->IsCharacterDataNode()) { + if (auto* data = DynamicTo<CharacterData>(anchor_node_.Get())) { DCHECK_GE(offset, 0); - DCHECK_LE(static_cast<unsigned>(offset), - ToCharacterData(anchor_node_)->length()) - << anchor_node_; + DCHECK_LE(static_cast<unsigned>(offset), data->length()) << anchor_node_; return; } DCHECK_GE(offset, 0); @@ -201,8 +199,8 @@ template <typename Strategy> static int MinOffsetForNode(Node* anchor_node, int offset) { - if (anchor_node->IsCharacterDataNode()) - return std::min(offset, static_cast<int>(ToCharacterData(anchor_node)->length())); + if (auto* data = DynamicTo<CharacterData>(anchor_node)) + return std::min(offset, static_cast<int>(data->length())); int new_offset = 0; for (Node* node = Strategy::FirstChild(*anchor_node); @@ -543,9 +541,10 @@ // static template <typename Strategy> int PositionTemplate<Strategy>::LastOffsetInNode(const Node& node) { - return node.IsCharacterDataNode() - ? static_cast<int>(ToCharacterData(node).length()) - : static_cast<int>(Strategy::CountChildren(node)); + if (auto* data = DynamicTo<CharacterData>(node)) + return static_cast<int>(data->length()); + + return static_cast<int>(Strategy::CountChildren(node)); } // static
diff --git a/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc b/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc index 27f17080..8c23d05 100644 --- a/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc +++ b/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc
@@ -177,7 +177,7 @@ NOTREACHED(); break; case Node::kCdataSectionNode: - AppendCDATASection(result, ToCDATASection(node).data()); + AppendCDATASection(result, To<CDATASection>(node).data()); break; case Node::kAttributeNode: NOTREACHED();
diff --git a/third_party/blink/renderer/core/editing/testing/selection_sample.cc b/third_party/blink/renderer/core/editing/testing/selection_sample.cc index d560a4c..1c25120 100644 --- a/third_party/blink/renderer/core/editing/testing/selection_sample.cc +++ b/third_party/blink/renderer/core/editing/testing/selection_sample.cc
@@ -154,8 +154,8 @@ HandleElementNode(ToElement(node)); return; } - if (node->IsCharacterDataNode()) { - HandleCharacterData(ToCharacterData(node)); + if (auto* data = DynamicTo<CharacterData>(node)) { + HandleCharacterData(data); return; } NOTREACHED() << node; @@ -287,12 +287,12 @@ return; } if (node.IsTextNode()) { - HandleCharacterData(ToCharacterData(node)); + HandleCharacterData(To<CharacterData>(node)); return; } if (node.getNodeType() == Node::kCommentNode) { builder_.Append("<!--"); - HandleCharacterData(ToCharacterData(node)); + HandleCharacterData(To<CharacterData>(node)); builder_.Append("-->"); return; } @@ -300,7 +300,7 @@ builder_.Append("<?"); builder_.Append(ToProcessingInstruction(node).target()); builder_.Append(' '); - HandleCharacterData(ToCharacterData(node)); + HandleCharacterData(To<CharacterData>(node)); builder_.Append("?>"); return; }
diff --git a/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc b/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc index df956906..e27564fc7 100644 --- a/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc +++ b/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc
@@ -44,7 +44,7 @@ } // Display an error message. Do it only once in a while, else it will flood - // the browser process with the FrameHostMsg_DidAddMessageToConsole IPC. + // the browser process with the DidAddMessageToConsole Mojo call. if (!error_message_sent_) { error_message_sent_ = true; if (auto* local_frame = DynamicTo<LocalFrame>(frame_.Get())) {
diff --git a/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc b/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc index b67cfe7..acc32e5 100644 --- a/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc +++ b/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc
@@ -693,7 +693,11 @@ : kLow_SkFilterQuality; } -void HTMLCanvasElement::Paint(GraphicsContext& context, const LayoutRect& r) { +// In some instances we don't actually want to paint to the parent layer +// We still might want to set filter quality and MarkFirstContentfulPaint though +void HTMLCanvasElement::Paint(GraphicsContext& context, + const LayoutRect& r, + bool flatten_composited_layers) { if (context_creation_was_blocked_ || (context_ && context_->isContextLost())) { float device_scale_factor = @@ -727,8 +731,12 @@ if (HasResourceProvider() && !canvas_is_clear_) PaintTiming::From(GetDocument()).MarkFirstContentfulPaint(); - if (!PaintsIntoCanvasBuffer() && !GetDocument().Printing()) - return; + // If the canvas is gpu composited, it has another way of getting to screen + if (!PaintsIntoCanvasBuffer()) { + // For click-and-drag or printing we still want to draw + if (!(flatten_composited_layers || GetDocument().Printing())) + return; + } if (PlaceholderFrame()) { DCHECK(GetDocument().Printing()); @@ -739,6 +747,11 @@ return; } + PaintInternal(context, r); +} + +void HTMLCanvasElement::PaintInternal(GraphicsContext& context, + const LayoutRect& r) { context_->PaintRenderingResultsToCanvas(kFrontBuffer); if (HasResourceProvider()) { if (!context.ContextDisabled()) {
diff --git a/third_party/blink/renderer/core/html/canvas/html_canvas_element.h b/third_party/blink/renderer/core/html/canvas/html_canvas_element.h index eace8c95..cc82f762 100644 --- a/third_party/blink/renderer/core/html/canvas/html_canvas_element.h +++ b/third_party/blink/renderer/core/html/canvas/html_canvas_element.h
@@ -157,7 +157,9 @@ void DidDraw(const FloatRect&) override; void DidDraw() override; - void Paint(GraphicsContext&, const LayoutRect&); + void Paint(GraphicsContext&, + const LayoutRect&, + bool flatten_composited_layers); void DisableDeferral(DisableDeferralReason); @@ -321,6 +323,8 @@ private: void Dispose(); + void PaintInternal(GraphicsContext&, const LayoutRect&); + using ContextFactoryVector = Vector<std::unique_ptr<CanvasRenderingContextFactory>>; static ContextFactoryVector& RenderingContextFactories();
diff --git a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc index e4feda93..2e8214f 100644 --- a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc
@@ -2319,34 +2319,20 @@ Vector<Color>* colors, String* computed_font_size, String* computed_font_weight) { - LayoutRect content_bounds; - LayoutObject* element_layout = element->GetLayoutObject(); - if (!element_layout) + // TODO: only support the single text child node here. + // Follow up with a larger fix post-merge. + if (!element->firstChild() || !element->firstChild()->IsTextNode() || + element->firstChild()->nextSibling()) { return; - - for (const Node* child = element->firstChild(); child; - child = child->nextSibling()) { - if (!child->IsTextNode()) - continue; - content_bounds.Unite(LayoutRect(child->BoundingBox())); - } - if (content_bounds.Size().IsEmpty() && element_layout->IsBox()) { - // Return content box instead - may have indirect text children. - LayoutBox* layout_box = ToLayoutBox(element_layout); - content_bounds = layout_box->PhysicalContentBoxRect(); - content_bounds = LayoutRect( - element_layout->LocalToAbsoluteQuad(FloatRect(content_bounds)) - .BoundingBox()); } - if (content_bounds.Size().IsEmpty()) - return; - - LocalFrameView* view = element->GetDocument().View(); + Text* text_node = ToText(element->firstChild()); + LayoutRect content_bounds(text_node->BoundingBox()); + LocalFrameView* view = text_node->GetDocument().View(); if (!view) return; - Document& document = element->GetDocument(); + Document& document = text_node->GetDocument(); bool is_main_frame = document.IsInMainFrame(); bool found_opaque_color = false; if (is_main_frame) { @@ -2356,8 +2342,8 @@ found_opaque_color = !base_background_color.HasAlpha(); } - found_opaque_color = GetColorsFromRect(content_bounds, element->GetDocument(), - element, *colors); + found_opaque_color = GetColorsFromRect( + content_bounds, text_node->GetDocument(), element, *colors); if (!found_opaque_color && !is_main_frame) { for (HTMLFrameOwnerElement* owner_element = document.LocalOwner();
diff --git a/third_party/blink/renderer/core/layout/layout_block.cc b/third_party/blink/renderer/core/layout/layout_block.cc index 481a0be..d363f50 100644 --- a/third_party/blink/renderer/core/layout/layout_block.cc +++ b/third_party/blink/renderer/core/layout/layout_block.cc
@@ -1461,7 +1461,7 @@ if (ShouldApplySizeContainment()) { // For multicol containers we need the column gaps. So allow descending into // the flow thread, which will take care of that. - const auto* block_flow = ToLayoutBlockFlowOrNull(this); + const auto* block_flow = DynamicTo<LayoutBlockFlow>(this); if (!block_flow || !block_flow->MultiColumnFlowThread()) { max_logical_width = LayoutUnit(scrollbar_width); min_logical_width = LayoutUnit(scrollbar_width);
diff --git a/third_party/blink/renderer/core/layout/layout_block_flow.cc b/third_party/blink/renderer/core/layout/layout_block_flow.cc index 7646b170..468a994 100644 --- a/third_party/blink/renderer/core/layout/layout_block_flow.cc +++ b/third_party/blink/renderer/core/layout/layout_block_flow.cc
@@ -2847,7 +2847,7 @@ FloatingObjectSetIterator end = floating_object_set.end(); for (LayoutObject* next = NextSibling(); next; next = next->NextSibling()) { - LayoutBlockFlow* next_block = ToLayoutBlockFlowOrNull(next); + auto* next_block = DynamicTo<LayoutBlockFlow>(next); if (!next_block || (!float_to_remove && (next_block->IsFloatingOrOutOfFlowPositioned() || next_block->CreatesNewFormattingContext())))
diff --git a/third_party/blink/renderer/core/layout/layout_block_flow.h b/third_party/blink/renderer/core/layout/layout_block_flow.h index a0cafc96..efaa1a2 100644 --- a/third_party/blink/renderer/core/layout/layout_block_flow.h +++ b/third_party/blink/renderer/core/layout/layout_block_flow.h
@@ -1030,8 +1030,6 @@ // END METHODS DEFINED IN LayoutBlockFlowLine }; -DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutBlockFlow, IsLayoutBlockFlow()); - template <> struct DowncastTraits<LayoutBlockFlow> { static bool AllowFrom(const LayoutObject& object) {
diff --git a/third_party/blink/renderer/core/layout/layout_block_test.cc b/third_party/blink/renderer/core/layout/layout_block_test.cc index 6669dd6..33cac11 100644 --- a/third_party/blink/renderer/core/layout/layout_block_test.cc +++ b/third_party/blink/renderer/core/layout/layout_block_test.cc
@@ -113,8 +113,7 @@ )HTML"); Element* target_element = GetDocument().getElementById("target"); - LayoutBlockFlow* target = - ToLayoutBlockFlow(target_element->GetLayoutObject()); + auto* target = To<LayoutBlockFlow>(target_element->GetLayoutObject()); LayoutBox* contained = ToLayoutBox(GetLayoutObjectByElementId("contained")); EXPECT_TRUE(target->PositionedObjects()->Contains(contained));
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc index 1c01e10..3287bee 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -210,7 +210,7 @@ if (!CanUseNewLayout()) return RunOldLayout(constraint_space); - LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(box_); + auto* block_flow = DynamicTo<LayoutBlockFlow>(box_); if (RuntimeEnabledFeatures::TrackLayoutPassesPerBlockEnabled() && block_flow) block_flow->IncrementLayoutPassCount(); @@ -618,7 +618,7 @@ box_->SetMargin(ComputePhysicalMargins(constraint_space, Style())); } - LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(box_); + auto* block_flow = DynamicTo<LayoutBlockFlow>(box_); LayoutMultiColumnFlowThread* flow_thread = GetFlowThread(block_flow); if (UNLIKELY(flow_thread)) { PlaceChildrenInFlowThread(constraint_space, physical_fragment); @@ -813,7 +813,7 @@ } bool NGBlockNode::ChildrenInline() const { - if (const auto* block = ToLayoutBlockFlowOrNull(box_)) + if (const auto* block = DynamicTo<LayoutBlockFlow>(box_)) return AreNGBlockFlowChildrenInline(block); return false; }
diff --git a/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.cc b/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.cc index 47acd28..a2ff23a 100644 --- a/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.cc +++ b/third_party/blink/renderer/core/loader/resource/xsl_style_sheet_resource.cc
@@ -29,7 +29,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/text_resource_decoder_options.h" -#include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { @@ -62,7 +61,6 @@ XSLStyleSheetResource* XSLStyleSheetResource::Fetch(FetchParameters& params, ResourceFetcher* fetcher, ResourceClient* client) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); ApplyXSLRequestProperties(params); return ToXSLStyleSheetResource( fetcher->RequestResource(params, XSLStyleSheetResourceFactory(), client));
diff --git a/third_party/blink/renderer/core/paint/html_canvas_painter.cc b/third_party/blink/renderer/core/paint/html_canvas_painter.cc index 9e427c0..660d949 100644 --- a/third_party/blink/renderer/core/paint/html_canvas_painter.cc +++ b/third_party/blink/renderer/core/paint/html_canvas_painter.cc
@@ -58,7 +58,9 @@ DrawingRecorder recorder(context, layout_html_canvas_, paint_info.phase); ScopedInterpolationQuality interpolation_quality_scope( context, InterpolationQualityForCanvas(layout_html_canvas_.StyleRef())); - canvas->Paint(context, paint_rect); + canvas->Paint( + context, paint_rect, + paint_info.GetGlobalPaintFlags() == kGlobalPaintFlattenCompositingLayers); } } // namespace blink
diff --git a/third_party/blink/renderer/core/xml/document_xslt.cc b/third_party/blink/renderer/core/xml/document_xslt.cc index ab5aa46..ccb2cd6 100644 --- a/third_party/blink/renderer/core/xml/document_xslt.cc +++ b/third_party/blink/renderer/core/xml/document_xslt.cc
@@ -30,7 +30,6 @@ : processing_instruction_(pi) {} void Invoke(ExecutionContext* execution_context, Event* event) override { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); DCHECK_EQ(event->type(), "DOMContentLoaded"); Document& document = *To<Document>(execution_context); @@ -111,9 +110,6 @@ if (!pi->IsXSL()) return false; - if (!RuntimeEnabledFeatures::XSLTEnabled() || !document.GetFrame()) - return true; - auto* listener = MakeGarbageCollected<DOMContentLoadedListener>(pi); document.addEventListener(event_type_names::kDOMContentLoaded, listener, false); @@ -131,7 +127,6 @@ if (!pi->EventListenerForXSLT()) return true; - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); document.removeEventListener(event_type_names::kDOMContentLoaded, pi->EventListenerForXSLT(), false); pi->ClearEventListenerForXSLT(); @@ -142,8 +137,8 @@ if (!pi->IsXSL()) return false; - if (RuntimeEnabledFeatures::XSLTEnabled() && !document.Parsing() && - !pi->IsLoading() && !DocumentXSLT::HasTransformSourceDocument(document)) { + if (!document.Parsing() && !pi->IsLoading() && + !DocumentXSLT::HasTransformSourceDocument(document)) { if (FindXSLStyleSheet(document) == pi) ApplyXSLTransform(document, pi); }
diff --git a/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc b/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc index 5eebb52..cd1b48a 100644 --- a/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc +++ b/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc
@@ -72,7 +72,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" -#include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/shared_buffer.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/wtf/text/utf8.h" @@ -1166,9 +1165,6 @@ if (pi->IsCSS()) saw_css_ = true; - if (!RuntimeEnabledFeatures::XSLTEnabled()) - return; - saw_xsl_transform_ = !saw_first_element_ && pi->IsXSL(); if (saw_xsl_transform_ && !DocumentXSLT::HasTransformSourceDocument(*GetDocument())) {
diff --git a/third_party/blink/renderer/core/xml/xsl_style_sheet.h b/third_party/blink/renderer/core/xml/xsl_style_sheet.h index d59872e..f6c1ebb 100644 --- a/third_party/blink/renderer/core/xml/xsl_style_sheet.h +++ b/third_party/blink/renderer/core/xml/xsl_style_sheet.h
@@ -28,7 +28,6 @@ #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/core/css/style_sheet.h" #include "third_party/blink/renderer/core/dom/processing_instruction.h" -#include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { @@ -37,13 +36,11 @@ static XSLStyleSheet* Create(ProcessingInstruction* parent_node, const String& original_url, const KURL& final_url) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); return MakeGarbageCollected<XSLStyleSheet>(parent_node, original_url, final_url, false); } static XSLStyleSheet* CreateEmbedded(ProcessingInstruction* parent_node, const KURL& final_url) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); return MakeGarbageCollected<XSLStyleSheet>( parent_node, final_url.GetString(), final_url, true); } @@ -55,7 +52,6 @@ Node* stylesheet_root_node, const String& original_url, const KURL& final_url) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); return MakeGarbageCollected<XSLStyleSheet>(document, stylesheet_root_node, original_url, final_url, false); }
diff --git a/third_party/blink/renderer/core/xml/xslt_extensions.cc b/third_party/blink/renderer/core/xml/xslt_extensions.cc index 4c65879..cf972aa 100644 --- a/third_party/blink/renderer/core/xml/xslt_extensions.cc +++ b/third_party/blink/renderer/core/xml/xslt_extensions.cc
@@ -30,7 +30,6 @@ #include <libxslt/extensions.h> #include <libxslt/extra.h> #include <libxslt/xsltutils.h> -#include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" namespace blink { @@ -75,7 +74,6 @@ } void RegisterXSLTExtensions(xsltTransformContextPtr ctxt) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); xsltRegisterExtFunction(ctxt, (const xmlChar*)"node-set", (const xmlChar*)"http://exslt.org/common", ExsltNodeSetFunction);
diff --git a/third_party/blink/renderer/core/xml/xslt_processor.h b/third_party/blink/renderer/core/xml/xslt_processor.h index acfaf8c..1c8ad94 100644 --- a/third_party/blink/renderer/core/xml/xslt_processor.h +++ b/third_party/blink/renderer/core/xml/xslt_processor.h
@@ -26,7 +26,6 @@ #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/core/xml/xsl_style_sheet.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/text/string_hash.h" @@ -44,7 +43,6 @@ public: static XSLTProcessor* Create(Document& document) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); return MakeGarbageCollected<XSLTProcessor>(document); }
diff --git a/third_party/blink/renderer/core/xml/xslt_processor.idl b/third_party/blink/renderer/core/xml/xslt_processor.idl index ba796f26..3f88ab31 100644 --- a/third_party/blink/renderer/core/xml/xslt_processor.idl +++ b/third_party/blink/renderer/core/xml/xslt_processor.idl
@@ -33,7 +33,6 @@ [ Constructor, ConstructorCallWith=Document, - RuntimeEnabled=XSLT, MeasureAs=XSLTProcessor ] interface XSLTProcessor {
diff --git a/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js b/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js index 8d1095f8..f6e638e 100644 --- a/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js +++ b/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js
@@ -382,7 +382,7 @@ this._originGroups = new Map(); /** @type {!Map<!Security.SecurityPanelSidebarTree.OriginGroup, string>} */ - const originGroupTitles = new Map([ + this._originGroupTitles = new Map([ [Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin, ls`Main origin`], [Security.SecurityPanelSidebarTree.OriginGroup.NonSecure, ls`Non-secure origins`], [Security.SecurityPanelSidebarTree.OriginGroup.Secure, ls`Secure origins`], @@ -391,7 +391,7 @@ for (const key in Security.SecurityPanelSidebarTree.OriginGroup) { const group = Security.SecurityPanelSidebarTree.OriginGroup[key]; - const element = this._createOriginGroupElement(originGroupTitles.get(group)); + const element = this._createOriginGroupElement(this._originGroupTitles.get(group)); this._originGroups.set(group, element); this.appendChild(element); } @@ -461,6 +461,10 @@ let newParent; if (origin === this._mainOrigin) { newParent = this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin); + if (securityState === Protocol.Security.SecurityState.Secure) + newParent.title = ls`Main origin (secure)`; + else + newParent.title = ls`Main origin (non-secure)`; } else { switch (securityState) { case Protocol.Security.SecurityState.Secure: @@ -492,7 +496,9 @@ originGroup.removeChildren(); originGroup.hidden = true; } - this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin).hidden = false; + const mainOrigin = this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin); + mainOrigin.title = this._originGroupTitles.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin); + mainOrigin.hidden = false; } clearOrigins() {
diff --git a/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc b/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc index 19d2588..7223a88 100644 --- a/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc +++ b/third_party/blink/renderer/modules/accessibility/testing/accessibility_selection_test.cc
@@ -254,7 +254,7 @@ private: void HandleCharacterData(const AXObject& text_object) { - CharacterData* const node = ToCharacterData(text_object.GetNode()); + auto* const node = To<CharacterData>(text_object.GetNode()); Vector<int> base_offsets; Vector<int> extent_offsets; unsigned number_of_markers = 0;
diff --git a/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc b/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc index f822e39..31a7e7d 100644 --- a/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc +++ b/third_party/blink/renderer/modules/animationworklet/worklet_animation.cc
@@ -218,7 +218,7 @@ return nullptr; } - Document& document = keyframe_effects.at(0)->target()->GetDocument(); + Document& document = *To<Document>(ExecutionContext::From(script_state)); if (!document.GetWorkletAnimationController().IsAnimatorRegistered( animator_name)) { exception_state.ThrowDOMException(
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc b/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc index c5cbe6e..5c76192b 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc
@@ -4,6 +4,8 @@ #include "third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h" +#include <memory> + #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -96,6 +98,7 @@ if (current_state_.state() != webrtc::DtlsTransportState::kClosed) { DispatchEvent(*Event::Create(event_type_names::kStatechange)); } + ice_transport_->stop(); } // Implementation of DtlsTransportProxy::Delegate @@ -110,11 +113,6 @@ if (!closed_from_owner_) { DispatchEvent(*Event::Create(event_type_names::kStatechange)); } - if (current_state_.state() == webrtc::DtlsTransportState::kClosed) { - // Make sure the ICE transport is also closed. This must happen prior - // to garbage collection. - ice_transport_->stop(); - } } const AtomicString& RTCDtlsTransport::InterfaceName() const {
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc index e7db2c3..785627d1 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.cc
@@ -20,6 +20,7 @@ #include "third_party/blink/renderer/modules/peerconnection/rtc_ice_gather_options.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_ice_parameters.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_ice_server.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event_init.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h" @@ -128,7 +129,8 @@ RTCIceTransport* RTCIceTransport::Create( ExecutionContext* context, - rtc::scoped_refptr<webrtc::IceTransportInterface> ice_transport) { + rtc::scoped_refptr<webrtc::IceTransportInterface> ice_transport, + RTCPeerConnection* peer_connection) { LocalFrame* frame = To<Document>(context)->GetFrame(); scoped_refptr<base::SingleThreadTaskRunner> proxy_thread = frame->GetTaskRunner(TaskType::kNetworking); @@ -137,7 +139,8 @@ return MakeGarbageCollected<RTCIceTransport>( context, std::move(proxy_thread), std::move(host_thread), std::make_unique<DtlsIceTransportAdapterCrossThreadFactory>( - std::move(ice_transport))); + std::move(ice_transport)), + peer_connection); } RTCIceTransport* RTCIceTransport::Create( @@ -154,8 +157,9 @@ ExecutionContext* context, scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, scoped_refptr<base::SingleThreadTaskRunner> host_thread, - std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory) - : ContextLifecycleObserver(context) { + std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory, + RTCPeerConnection* peer_connection) + : ContextLifecycleObserver(context), peer_connection_(peer_connection) { DCHECK(context); DCHECK(proxy_thread); DCHECK(host_thread); @@ -171,6 +175,17 @@ GenerateLocalParameters(); } +RTCIceTransport::RTCIceTransport( + ExecutionContext* context, + scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, + scoped_refptr<base::SingleThreadTaskRunner> host_thread, + std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory) + : RTCIceTransport(context, + std::move(proxy_thread), + std::move(host_thread), + std::move(adapter_factory), + nullptr) {} + RTCIceTransport::~RTCIceTransport() { DCHECK(!proxy_); } @@ -420,9 +435,6 @@ } void RTCIceTransport::stop() { - if (IsClosed()) { - return; - } Close(CloseReason::kStopped); } @@ -486,6 +498,13 @@ selected_candidate_pair_ = nullptr; } DispatchEvent(*Event::Create(event_type_names::kStatechange)); + if (peer_connection_) { + peer_connection_->UpdateIceConnectionState(); + } + if (state_ == webrtc::IceTransportState::kClosed || + state_ == webrtc::IceTransportState::kFailed) { + stop(); + } } void RTCIceTransport::OnSelectedCandidatePairChanged( @@ -502,7 +521,9 @@ } void RTCIceTransport::Close(CloseReason reason) { - DCHECK_NE(state_, webrtc::IceTransportState::kClosed); + if (IsClosed()) { + return; + } if (HasConsumer()) { consumer_->OnIceTransportClosed(reason); } @@ -533,16 +554,13 @@ } void RTCIceTransport::ContextDestroyed(ExecutionContext*) { - if (IsClosed()) { - return; - } Close(CloseReason::kContextDestroyed); } bool RTCIceTransport::HasPendingActivity() const { // Only allow the RTCIceTransport to be garbage collected if the ICE // implementation is not active. - return static_cast<bool>(proxy_); + return !!proxy_; } void RTCIceTransport::Trace(blink::Visitor* visitor) { @@ -552,8 +570,13 @@ visitor->Trace(remote_parameters_); visitor->Trace(selected_candidate_pair_); visitor->Trace(consumer_); + visitor->Trace(peer_connection_); EventTargetWithInlineData::Trace(visitor); ContextLifecycleObserver::Trace(visitor); } +void RTCIceTransport::Dispose() { + Close(CloseReason::kDisposed); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h index 4b3fd86..687578da 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h
@@ -29,6 +29,7 @@ class RTCIceGatherOptions; class IceTransportAdapterCrossThreadFactory; class RTCQuicTransport; +class RTCPeerConnection; // Blink bindings for the RTCIceTransport JavaScript object. // @@ -46,6 +47,7 @@ public IceTransportProxy::Delegate { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(RTCIceTransport); + USING_PRE_FINALIZER(RTCIceTransport, Dispose); public: enum class CloseReason { @@ -53,19 +55,28 @@ kStopped, // The ExecutionContext is being destroyed. kContextDestroyed, + // The object is being garbage collected. + kDisposed, }; static RTCIceTransport* Create(ExecutionContext* context); static RTCIceTransport* Create( ExecutionContext* context, - rtc::scoped_refptr<webrtc::IceTransportInterface> ice_transport_channel); + rtc::scoped_refptr<webrtc::IceTransportInterface> ice_transport_channel, + RTCPeerConnection* peer_connection); static RTCIceTransport* Create( ExecutionContext* context, scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, scoped_refptr<base::SingleThreadTaskRunner> host_thread, std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory); - explicit RTCIceTransport( + RTCIceTransport( + ExecutionContext* context, + scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, + scoped_refptr<base::SingleThreadTaskRunner> host_thread, + std::unique_ptr<IceTransportAdapterCrossThreadFactory> adapter_factory, + RTCPeerConnection* peer_connection); + RTCIceTransport( ExecutionContext* context, scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, scoped_refptr<base::SingleThreadTaskRunner> host_thread, @@ -78,6 +89,8 @@ // Returns the role specified in start(). cricket::IceRole GetRole() const { return role_; } + webrtc::IceTransportState GetState() const { return state_; } + // Returns true if the RTCIceTransport is in a terminal state. bool IsClosed() const { return state_ == webrtc::IceTransportState::kClosed; } @@ -122,7 +135,7 @@ void ContextDestroyed(ExecutionContext*) override; // ActiveScriptWrappable overrides. - bool HasPendingActivity() const override; + bool HasPendingActivity() const final; // For garbage collection. void Trace(blink::Visitor* visitor) override; @@ -146,6 +159,7 @@ void Close(CloseReason reason); bool RaiseExceptionIfClosed(ExceptionState& exception_state) const; + void Dispose(); cricket::IceRole role_ = cricket::ICEROLE_UNKNOWN; webrtc::IceTransportState state_ = webrtc::IceTransportState::kNew; @@ -159,6 +173,7 @@ Member<RTCIceCandidatePair> selected_candidate_pair_; Member<RTCQuicTransport> consumer_; + const WeakMember<RTCPeerConnection> peer_connection_; // Handle to the WebRTC ICE transport. Created when this binding is // constructed and deleted once network traffic should be stopped.
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index 0b499ed4..dc6ecdc 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -1166,6 +1166,11 @@ user_media_controller->HasRequestedUserMedia(); } +void RTCPeerConnection::UpdateIceConnectionState() { + DCHECK_EQ(webrtc::SdpSemantics::kUnifiedPlan, sdp_semantics_); + ChangeIceConnectionState(ComputeIceConnectionState()); +} + void RTCPeerConnection::ReportSetSdpUsage( SetSdpOperationType operation_type, const RTCSessionDescriptionInit* session_description_init) const { @@ -2488,7 +2493,7 @@ return transport_locator->value; } RTCIceTransport* transport = - RTCIceTransport::Create(GetExecutionContext(), ice_transport); + RTCIceTransport::Create(GetExecutionContext(), ice_transport, this); ice_transports_by_native_transport_.insert(ice_transport.get(), transport); return transport; } @@ -2527,9 +2532,9 @@ void RTCPeerConnection::close() { if (signaling_state_ == - webrtc::PeerConnectionInterface::SignalingState::kClosed) + webrtc::PeerConnectionInterface::SignalingState::kClosed) { return; - + } CloseInternal(); } @@ -2623,7 +2628,10 @@ webrtc::PeerConnectionInterface::IceConnectionState new_state) { DCHECK(!closed_); DCHECK(GetExecutionContext()->IsContextThread()); - ChangeIceConnectionState(new_state); + // Unified plan relies on UpdateIceConnectionState instead. + if (sdp_semantics_ != webrtc::SdpSemantics::kUnifiedPlan) { + ChangeIceConnectionState(new_state); + } } void RTCPeerConnection::DidChangePeerConnectionState( @@ -2996,29 +3004,92 @@ void RTCPeerConnection::ChangeIceConnectionState( webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state) { - if (ice_connection_state_ != - webrtc::PeerConnectionInterface::kIceConnectionClosed) { - ScheduleDispatchEvent( - Event::Create(event_type_names::kIceconnectionstatechange), - WTF::Bind(&RTCPeerConnection::SetIceConnectionState, - WrapPersistent(this), ice_connection_state)); + if (ice_connection_state_ == + webrtc::PeerConnectionInterface::kIceConnectionClosed || + ice_connection_state_ == ice_connection_state) { + return; + } + ice_connection_state_ = ice_connection_state; + DispatchEvent(*Event::Create(event_type_names::kIceconnectionstatechange)); + if (ice_connection_state_ == + webrtc::PeerConnectionInterface::kIceConnectionConnected) { + RecordRapporMetrics(); } } -bool RTCPeerConnection::SetIceConnectionState( - webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state) { - if (ice_connection_state_ != - webrtc::PeerConnectionInterface::kIceConnectionClosed && - ice_connection_state_ != ice_connection_state) { - ice_connection_state_ = ice_connection_state; - if (ice_connection_state_ == - webrtc::PeerConnectionInterface::kIceConnectionConnected) - RecordRapporMetrics(); - return true; +webrtc::PeerConnectionInterface::IceConnectionState +RTCPeerConnection::ComputeIceConnectionState() { + if (closed_) + return webrtc::PeerConnectionInterface::kIceConnectionClosed; + if (HasAnyFailedIceTransport()) + return webrtc::PeerConnectionInterface::kIceConnectionFailed; + if (HasAnyDisconnectedIceTransport()) + return webrtc::PeerConnectionInterface::kIceConnectionDisconnected; + if (HasAllNewOrClosedIceTransports()) + return webrtc::PeerConnectionInterface::kIceConnectionNew; + if (HasAnyNewOrCheckingIceTransport()) + return webrtc::PeerConnectionInterface::kIceConnectionChecking; + if (HasAllCompletedOrClosedIceTransports()) + return webrtc::PeerConnectionInterface::kIceConnectionCompleted; + if (HasAllConnectedCompletedOrClosedIceTransports()) + return webrtc::PeerConnectionInterface::kIceConnectionConnected; + + return ice_connection_state_; +} + +bool RTCPeerConnection::HasAnyFailedIceTransport() const { + for (auto transport : ice_transports_by_native_transport_.Values()) { + if (transport->GetState() == webrtc::IceTransportState::kFailed) + return true; } return false; } +bool RTCPeerConnection::HasAnyDisconnectedIceTransport() const { + for (auto transport : ice_transports_by_native_transport_.Values()) { + if (transport->GetState() == webrtc::IceTransportState::kDisconnected) + return true; + } + return false; +} + +bool RTCPeerConnection::HasAllNewOrClosedIceTransports() const { + for (auto transport : ice_transports_by_native_transport_.Values()) { + if (transport->GetState() != webrtc::IceTransportState::kNew && + transport->GetState() != webrtc::IceTransportState::kClosed) + return false; + } + return true; +} + +bool RTCPeerConnection::HasAnyNewOrCheckingIceTransport() const { + for (auto transport : ice_transports_by_native_transport_.Values()) { + if (transport->GetState() == webrtc::IceTransportState::kNew || + transport->GetState() == webrtc::IceTransportState::kChecking) + return true; + } + return false; +} + +bool RTCPeerConnection::HasAllCompletedOrClosedIceTransports() const { + for (auto transport : ice_transports_by_native_transport_.Values()) { + if (transport->GetState() != webrtc::IceTransportState::kCompleted && + transport->GetState() != webrtc::IceTransportState::kClosed) + return false; + } + return true; +} + +bool RTCPeerConnection::HasAllConnectedCompletedOrClosedIceTransports() const { + for (auto transport : ice_transports_by_native_transport_.Values()) { + if (transport->GetState() != webrtc::IceTransportState::kConnected && + transport->GetState() != webrtc::IceTransportState::kCompleted && + transport->GetState() != webrtc::IceTransportState::kClosed) + return false; + } + return true; +} + void RTCPeerConnection::ChangePeerConnectionState( webrtc::PeerConnectionInterface::PeerConnectionState peer_connection_state) {
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h index 20a59070..6fb8d955 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h
@@ -338,8 +338,10 @@ // getUserMedia(). bool HasDocumentMedia() const; - // Look up, and potentially create, a DTLSTransport object. - RTCDtlsTransport* LookupDtlsTransportByMid(String mid); + // Called by RTCIceTransport::OnStateChange to update the ice connection + // state. + void UpdateIceConnectionState(); + void Trace(blink::Visitor*) override; private: @@ -460,8 +462,14 @@ void ChangeIceConnectionState( webrtc::PeerConnectionInterface::IceConnectionState); - bool SetIceConnectionState( - webrtc::PeerConnectionInterface::IceConnectionState); + webrtc::PeerConnectionInterface::IceConnectionState + ComputeIceConnectionState(); + bool HasAnyFailedIceTransport() const; + bool HasAnyDisconnectedIceTransport() const; + bool HasAllNewOrClosedIceTransports() const; + bool HasAnyNewOrCheckingIceTransport() const; + bool HasAllCompletedOrClosedIceTransports() const; + bool HasAllConnectedCompletedOrClosedIceTransports() const; void ChangePeerConnectionState( webrtc::PeerConnectionInterface::PeerConnectionState);
diff --git a/third_party/blink/renderer/modules/xr/xr.cc b/third_party/blink/renderer/modules/xr/xr.cc index 52dbc23..d5fbc0b 100644 --- a/third_party/blink/renderer/modules/xr/xr.cc +++ b/third_party/blink/renderer/modules/xr/xr.cc
@@ -15,6 +15,7 @@ #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/inspector/console_message.h" +#include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/modules/event_modules.h" #include "third_party/blink/renderer/modules/event_target_modules.h" #include "third_party/blink/renderer/modules/xr/xr_frame_provider.h" @@ -104,8 +105,11 @@ : ContextLifecycleObserver(frame.GetDocument()), FocusChangedObserver(frame.GetPage()), ukm_source_id_(ukm_source_id), - binding_(this) { + binding_(this), + navigation_start_( + frame.Loader().GetDocumentLoader()->GetTiming().NavigationStart()) { // See https://bit.ly/2S0zRAS for task types. + DCHECK(frame.IsAttached()); frame.GetInterfaceProvider().GetInterface(mojo::MakeRequest( &service_, frame.GetTaskRunner(TaskType::kMiscPlatformAPI))); service_.set_connection_error_handler(
diff --git a/third_party/blink/renderer/modules/xr/xr.h b/third_party/blink/renderer/modules/xr/xr.h index 9c04d8f..7b644b5e 100644 --- a/third_party/blink/renderer/modules/xr/xr.h +++ b/third_party/blink/renderer/modules/xr/xr.h
@@ -74,6 +74,8 @@ void AddEnvironmentProviderErrorHandler( EnvironmentProviderErrorCallback callback); + TimeTicks NavigationStart() const { return navigation_start_; } + private: class PendingSessionQuery final : public GarbageCollected<PendingSessionQuery> { @@ -147,6 +149,10 @@ device::mojom::blink::XREnvironmentIntegrationProviderAssociatedPtr environment_provider_; mojo::Binding<device::mojom::blink::VRServiceClient> binding_; + + // Time at which navigation started. Used as the base for relative timestamps, + // such as for Gamepad objects. + TimeTicks navigation_start_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/xr/xr_input_source.cc b/third_party/blink/renderer/modules/xr/xr_input_source.cc index da5a3f11..353fce01 100644 --- a/third_party/blink/renderer/modules/xr/xr_input_source.cc +++ b/third_party/blink/renderer/modules/xr/xr_input_source.cc
@@ -4,7 +4,8 @@ #include "third_party/blink/renderer/modules/xr/xr_input_source.h" -#include "third_party/blink/renderer/modules/gamepad/gamepad.h" +#include "base/time/time.h" +#include "third_party/blink/renderer/modules/xr/xr.h" #include "third_party/blink/renderer/modules/xr/xr_grip_space.h" #include "third_party/blink/renderer/modules/xr/xr_session.h" #include "third_party/blink/renderer/modules/xr/xr_space.h" @@ -16,7 +17,8 @@ : session_(session), source_id_(source_id), target_ray_space_(MakeGarbageCollected<XRTargetRaySpace>(session, this)), - grip_space_(MakeGarbageCollected<XRGripSpace>(session, this)) { + grip_space_(MakeGarbageCollected<XRGripSpace>(session, this)), + base_timestamp_(session->xr()->NavigationStart()) { SetTargetRayMode(kGaze); SetHandedness(kHandNone); } @@ -96,6 +98,23 @@ pointer_transform_matrix_ = std::move(pointer_transform_matrix); } +// TODO(https://crbug.com/955101): Should Gamepad objects be updated in-place, +// or should a new object be created on every call? +void XRInputSource::SetGamepad(const base::Optional<device::Gamepad> gamepad) { + if (gamepad) { + if (!gamepad_) { + // TODO(https://crbug.com/955104): Is the Gamepad object creation time the + // correct time floor? + gamepad_ = MakeGarbageCollected<Gamepad>(this, 0, base_timestamp_, + TimeTicks::Now()); + } + + gamepad_->UpdateFromDeviceState(*gamepad); + } else { + gamepad_ = nullptr; + } +} + void XRInputSource::Trace(blink::Visitor* visitor) { visitor->Trace(session_); visitor->Trace(target_ray_space_);
diff --git a/third_party/blink/renderer/modules/xr/xr_input_source.h b/third_party/blink/renderer/modules/xr/xr_input_source.h index ab59afa..4f096eb 100644 --- a/third_party/blink/renderer/modules/xr/xr_input_source.h +++ b/third_party/blink/renderer/modules/xr/xr_input_source.h
@@ -5,22 +5,27 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_INPUT_SOURCE_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_XR_XR_INPUT_SOURCE_H_ +#include "third_party/blink/renderer/modules/gamepad/gamepad.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/transforms/transformation_matrix.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" +namespace device { +class Gamepad; +} + namespace blink { -class Gamepad; class XRGripSpace; class XRSession; class XRSpace; class XRTargetRaySpace; -class XRInputSource : public ScriptWrappable { +class XRInputSource : public ScriptWrappable, public Gamepad::Client { DEFINE_WRAPPERTYPEINFO(); + USING_GARBAGE_COLLECTED_MIXIN(XRInputSource); public: enum Handedness { @@ -50,6 +55,16 @@ void SetEmulatedPosition(bool emulated_position); void SetBasePoseMatrix(std::unique_ptr<TransformationMatrix>); void SetPointerTransformMatrix(std::unique_ptr<TransformationMatrix>); + void SetGamepad(const base::Optional<device::Gamepad>); + + // Gamepad::Client + GamepadHapticActuator* GetVibrationActuatorForGamepad( + const Gamepad&) override { + // TODO(https://crbug.com/955097): XRInputSource implementation of + // Gamepad::Client must manage vibration actuator state in a similar way to + // NavigatorGamepad. + return nullptr; + } void Trace(blink::Visitor*) override; @@ -80,6 +95,9 @@ // This is the transform to apply to the base_pose_matrix_ to get the pointer // matrix. In most cases it should be static. std::unique_ptr<TransformationMatrix> pointer_transform_matrix_; + + // gamepad_ uses this to get relative timestamps. + TimeTicks base_timestamp_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/xr/xr_session.cc b/third_party/blink/renderer/modules/xr/xr_session.cc index aa4ed96..996336b 100644 --- a/third_party/blink/renderer/modules/xr/xr_session.cc +++ b/third_party/blink/renderer/modules/xr/xr_session.cc
@@ -873,6 +873,8 @@ if (!input_source || !state) return; + input_source->SetGamepad(state->gamepad); + // Update the input source's description if this state update // includes them. if (state->description) {
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string.cc b/third_party/blink/renderer/platform/bindings/parkable_string.cc index 7136c792..97fe705 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string.cc
@@ -493,12 +493,15 @@ base::StringPiece(reinterpret_cast<const char*>(data), size); } + // If the buffer size is incorrect, then we have a corrupted data issue, + // and in such case there is nothing else to do than crash. + CHECK_EQ(compression::GetUncompressedSize(compressed_string_piece), + uncompressed_string_piece.size()); // If decompression fails, this is either because: - // 1. The output buffer is too small - // 2. Compressed data is corrupted - // 3. Cannot allocate memory in zlib + // 1. Compressed data is corrupted + // 2. Cannot allocate memory in zlib // - // (1-2) are data corruption, and (3) is OOM. In all cases, we cannot + // (1) is data corruption, and (2) is OOM. In all cases, we cannot // recover the string we need, nothing else to do than to abort. // // Stability sheriffs: If you see this, this is likely an OOM.
diff --git a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc index a79ea53..846a200 100644 --- a/third_party/blink/renderer/platform/bindings/parkable_string_test.cc +++ b/third_party/blink/renderer/platform/bindings/parkable_string_test.cc
@@ -157,6 +157,36 @@ EXPECT_EQ(MakeLargeString(), parkable.ToString()); } +TEST_F(ParkableStringTest, DecompressUtf16String) { + UChar emoji_grinning_face[2] = {0xd83d, 0xde00}; + size_t size_in_chars = 2 * kSizeKb * 1000 / sizeof(UChar); + + std::vector<UChar> data(size_in_chars); + for (size_t i = 0; i < size_in_chars / 2; ++i) { + data[i * 2] = emoji_grinning_face[0]; + data[i * 2 + 1] = emoji_grinning_face[1]; + } + + String large_string = String(&data[0], size_in_chars); + String copy = large_string.IsolatedCopy(); + ParkableString parkable(large_string.ReleaseImpl()); + large_string = String(); + EXPECT_FALSE(parkable.Is8Bit()); + EXPECT_EQ(size_in_chars, parkable.length()); + EXPECT_EQ(sizeof(UChar) * size_in_chars, parkable.CharactersSizeInBytes()); + + EXPECT_TRUE(parkable.Impl()->Park(ParkableStringImpl::ParkingMode::kAlways)); + RunPostedTasks(); + EXPECT_TRUE(parkable.Impl()->is_parked()); + + // Decompression checks that the size is correct. + String unparked = parkable.ToString(); + EXPECT_FALSE(unparked.Is8Bit()); + EXPECT_EQ(size_in_chars, unparked.length()); + EXPECT_EQ(sizeof(UChar) * size_in_chars, unparked.CharactersSizeInBytes()); + EXPECT_EQ(copy, unparked); +} + TEST_F(ParkableStringTest, Simple) { ParkableString parkable_abc(String("abc").ReleaseImpl()); @@ -968,6 +998,12 @@ TEST_F(ParkableStringForegroundParkingTest, ReportTotalUnparkingTime) { base::HistogramTester histogram_tester; + // On some platforms, initialization takes time, though it happens when + // base::ThreadTicks is used. To prevent flakiness depending on test execution + // ordering, force initialization. + if (base::ThreadTicks::IsSupported()) + base::ThreadTicks::WaitUntilInitialized(); + // Need to make the string really large, otherwise unparking takes less than // 1ms, and the 0 bucket is populated. const size_t original_size = 5 * 1000 * 1000;
diff --git a/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/third_party/blink/renderer/platform/exported/web_runtime_features.cc index e7ad1eb..52f3aff 100644 --- a/third_party/blink/renderer/platform/exported/web_runtime_features.cc +++ b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -415,10 +415,6 @@ RuntimeEnabledFeatures::SetWebGLImageChromiumEnabled(enable); } -void WebRuntimeFeatures::EnableXSLT(bool enable) { - RuntimeEnabledFeatures::SetXSLTEnabled(enable); -} - void WebRuntimeFeatures::EnableOverlayScrollbars(bool enable) { RuntimeEnabledFeatures::SetOverlayScrollbarsEnabled(enable); }
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc index 0321a82f..ea5f234b 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
@@ -1768,12 +1768,12 @@ #endif GlyphBoundsAccumulator bounds(run_advance); - for (unsigned i = 0; i < num_glyphs; ++i) { - const HarfBuzzRunGlyphData& glyph_data = run.glyph_data_[i]; + for (unsigned j = 0; j < num_glyphs; ++j) { + const HarfBuzzRunGlyphData& glyph_data = run.glyph_data_[j]; #if defined(OS_MACOSX) FloatRect glyph_bounds = current_font_data.BoundsForGlyph(glyph_data.glyph); #else - FloatRect glyph_bounds(bounds_list[i]); + FloatRect glyph_bounds(bounds_list[j]); #endif bounds.Unite<is_horizontal_run>(glyph_data, glyph_bounds); bounds.origin += glyph_data.advance;
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc b/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc index 16fea1e..eaedff6 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result_view.cc
@@ -527,12 +527,12 @@ #endif GlyphBoundsAccumulator bounds(run_advance); - for (unsigned i = 0; i < num_glyphs; ++i) { - const HarfBuzzRunGlyphData& glyph_data = part.GlyphAt(i); + for (unsigned j = 0; j < num_glyphs; ++j) { + const HarfBuzzRunGlyphData& glyph_data = part.GlyphAt(j); #if defined(OS_MACOSX) FloatRect glyph_bounds = current_font_data.BoundsForGlyph(glyph_data.glyph); #else - FloatRect glyph_bounds(bounds_list[i]); + FloatRect glyph_bounds(bounds_list[j]); #endif bounds.Unite<is_horizontal_run>(glyph_data, glyph_bounds); bounds.origin += glyph_data.advance;
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc index 8860335..f4797a25 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
@@ -122,8 +122,6 @@ // Also parser-blocking scripts (set explicitly in loadPriority) return ResourceLoadPriority::kVeryHigh; case ResourceType::kXSLStyleSheet: - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); - FALLTHROUGH; case ResourceType::kRaw: case ResourceType::kImportResource: case ResourceType::kScript: @@ -269,8 +267,6 @@ (type == ResourceType::kImage && is_image_set == kImageIsImageSet)); switch (type) { case ResourceType::kXSLStyleSheet: - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); - FALLTHROUGH; case ResourceType::kCSSStyleSheet: return mojom::RequestContextType::STYLE; case ResourceType::kScript:
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 045cb2d..c7d253e 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1609,9 +1609,5 @@ name: "WorkerTaskQueue", status: "experimental" }, - { - name: "XSLT", - status: "stable", - }, ], }
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc index 9887dbd..d604573 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.cc
@@ -29,7 +29,7 @@ "RendererScheduler.TaskDurationPerTaskType2" #define COUNT_PER_FRAME_METRIC_NAME "RendererScheduler.TaskCountPerFrameType" #define COUNT_PER_FRAME_METRIC_NAME_WITH_SAFEPOINT \ - "RendererScheduler.TaskCountPerFrameType.HasSafepoint" + "RendererScheduler.TaskCountPerFrameType.HasSafePoint" #define DURATION_PER_TASK_USE_CASE_NAME \ "RendererScheduler.TaskDurationPerUseCase2"
diff --git a/third_party/blink/renderer/platform/text/character.h b/third_party/blink/renderer/platform/text/character.h index 38f632e..5818db4 100644 --- a/third_party/blink/renderer/platform/text/character.h +++ b/third_party/blink/renderer/platform/text/character.h
@@ -149,7 +149,9 @@ static bool IsEmojiTextDefault(UChar32); static bool IsEmojiEmojiDefault(UChar32); static bool IsEmojiModifierBase(UChar32); - static bool IsEmojiKeycapBase(UChar32); + static inline bool IsEmojiKeycapBase(UChar32 ch) { + return (ch >= '0' && ch <= '9') || ch == '#' || ch == '*'; + } static bool IsRegionalIndicator(UChar32); static bool IsModifier(UChar32 c) { return c >= 0x1F3FB && c <= 0x1F3FF; } // http://www.unicode.org/reports/tr51/proposed.html#flag-emoji-tag-sequences
diff --git a/third_party/blink/renderer/platform/text/character_emoji.cc b/third_party/blink/renderer/platform/text/character_emoji.cc index 0a05362..19c30f57 100644 --- a/third_party/blink/renderer/platform/text/character_emoji.cc +++ b/third_party/blink/renderer/platform/text/character_emoji.cc
@@ -257,10 +257,6 @@ } #endif // defined(USING_SYSTEM_ICU) && (U_ICU_VERSION_MAJOR_NUM <= 57) -bool Character::IsEmojiKeycapBase(UChar32 ch) { - return (ch >= '0' && ch <= '9') || ch == '#' || ch == '*'; -} - bool Character::IsRegionalIndicator(UChar32 ch) { return (ch >= 0x1F1E6 && ch <= 0x1F1FF); }
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 4112c25..79aca3d 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -538,6 +538,7 @@ # [css-contain] +crbug.com/947730 external/wpt/css/css-contain/contain-content-011.html [ Failure ] crbug.com/880802 external/wpt/css/css-contain/contain-layout-017.html [ Failure ] crbug.com/671132 external/wpt/css/css-contain/contain-layout-baseline-005.html [ Failure ] crbug.com/626703 external/wpt/css/css-contain/contain-layout-breaks-002.html [ Failure ] @@ -547,6 +548,7 @@ crbug.com/882367 external/wpt/css/css-contain/contain-paint-clip-015.html [ Failure ] crbug.com/882367 external/wpt/css/css-contain/contain-paint-clip-016.html [ Failure ] crbug.com/855261 external/wpt/css/css-contain/contain-size-grid-002.html [ Failure ] +crbug.com/947730 external/wpt/css/css-contain/contain-strict-011.html [ Failure ] crbug.com/869296 external/wpt/css/css-contain/contain-style-counters-004.html [ Failure ] crbug.com/882383 external/wpt/css/css-contain/counter-scoping-001.html [ Failure ] crbug.com/882383 external/wpt/css/css-contain/counter-scoping-002.html [ Failure ] @@ -3069,8 +3071,6 @@ crbug.com/626703 [ Retina ] external/wpt/html/semantics/embedded-content/media-elements/track/track-element/track-cue-negative-duration.html [ Timeout ] crbug.com/626703 external/wpt/html/semantics/embedded-content/media-elements/src_object_blob.html [ Timeout ] crbug.com/626703 external/wpt/css/css-lists/list-item-definition.html [ Failure ] -crbug.com/626703 external/wpt/css/css-contain/contain-content-011.html [ Failure ] -crbug.com/626703 external/wpt/css/css-contain/contain-strict-011.html [ Failure ] crbug.com/626703 external/wpt/html/semantics/forms/the-textarea-element/multiline-placeholder-cr.html [ Failure ] crbug.com/626703 [ Mac10.10 ] external/wpt/event-timing/event-timing-onloadthenobserve.html [ Timeout ] crbug.com/626703 [ Mac10.11 ] external/wpt/event-timing/event-timing-onloadthenobserve.html [ Timeout ] @@ -5731,8 +5731,6 @@ # WebRTC codec tests - software H.264 not present on webkit bot family crbug.com/840659 external/wpt/webrtc/protocol/video-codecs.https.html [ Pass Failure ] crbug.com/840659 virtual/webrtc-wpt-plan-b/external/wpt/webrtc/protocol/video-codecs.https.html [ Pass Failure ] -# WebRTC IceTransport flaky test -crbug.com/944036 external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https.html [ Pass Failure ] # Sheriff 2019-01-11 crbug.com/921038 virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/legacy-performance-memory-counters-enabled.html [ Skip ] @@ -6168,4 +6166,3 @@ crbug.com/954994 [ Mac ] virtual/gpu-rasterization/images/jpeg-yuv-image-decoding.html [ Pass Failure ] crbug.com/954319 [ Linux ] http/tests/devtools/sources/debugger-breakpoints/breakpoints-ui-in-multiple-workers.js [ Pass Timeout ] crbug.com/954998 [ Mac ] http/tests/devtools/tracing/timeline-js/timeline-js-line-level-profile-end-to-end.js [ Pass Timeout ] -crbug.com/955165 [ Mac ] fast/text/letter-spacing-negative-opacity.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/resources/iframe.html b/third_party/blink/web_tests/external/wpt/animation-worklet/resources/iframe.html new file mode 100644 index 0000000..e128fa5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/resources/iframe.html
@@ -0,0 +1,9 @@ +<!DOCTYPE html> +<style> +#iframe_box { + width: 100px; + height: 100px; + background-color: green; +} +</style> +<div id='iframe_box'></div>
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-creation.https.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-creation.https.html index 3e403fe..9ad60586d 100644 --- a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-creation.https.html +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-creation.https.html
@@ -61,6 +61,36 @@ promise_test(async t => { await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let iframe = document.createElement('iframe'); + iframe.src = 'resources/iframe.html'; + document.body.appendChild(iframe); + + await waitForAnimationFrameWithCondition(_ => { + return iframe.contentDocument.getElementById('iframe_box') != null; + }); + let iframe_document = iframe.contentDocument; + let effect = CreateKeyframeEffect(iframe_document.getElementById('iframe_box')); + + let animation_with_main_frame_timeline = + new WorkletAnimation('test-animator', effect, document.timeline); + assert_equals(animation_with_main_frame_timeline.timeline, document.timeline); + + let animation_with_iframe_timeline = + new WorkletAnimation('test-animator', effect, iframe_document.timeline); + assert_equals(animation_with_iframe_timeline.timeline, iframe_document.timeline); + + let animation_with_default_timeline = new WorkletAnimation('test-animator', effect); + // The spec says that the default timeline is taken from 'the Document that is + // associated with the window that is the current global object'. In this case + // that is the main document's timeline, not the iframe (despite the target + // being in the iframe). + assert_equals(animation_with_default_timeline.timeline, document.timeline); + + iframe.remove(); + }, 'WorkletAnimation creation should choose the correct timeline based on the current global object'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); let effect = CreateKeyframeEffect(document.querySelector('#element')); let options = { my_param: 'foo', my_other_param: true }; let workletAnimation = new WorkletAnimation(
diff --git a/third_party/blink/web_tests/external/wpt/cookies/resources/cookie-helper.sub.js b/third_party/blink/web_tests/external/wpt/cookies/resources/cookie-helper.sub.js index 2974da9..1cd924a 100644 --- a/third_party/blink/web_tests/external/wpt/cookies/resources/cookie-helper.sub.js +++ b/third_party/blink/web_tests/external/wpt/cookies/resources/cookie-helper.sub.js
@@ -20,10 +20,6 @@ // Set the global cookie name. window.HTTP_COOKIE = "cookie_via_http"; - - // If we're not on |HOST|, move ourselves there: - if (window.location.hostname != HOST) - window.location.hostname = HOST; })(); // A tiny helper which returns the result of fetching |url| with credentials. @@ -120,27 +116,44 @@ STRICT: "strict" }; +const wait_for_message = (type, origin) => { + return new Promise((resolve, reject) => { + window.addEventListener('message', e => { + if (e.origin != origin) { + reject("Message from unexpected origin in wait_for_message:" + e.origin); + return; + } + + if (e.data.type && e.data.type === type) + resolve(e); + }, { once: true }); + }); +}; + // Reset SameSite test cookies on |origin|. If |origin| matches `self.origin`, assert // (via `document.cookie`) that they were properly removed and reset. -function resetSameSiteCookies(origin, value) { - return credFetch(origin + "/cookies/resources/dropSameSite.py") - .then(_ => { - if (origin == self.origin) { - assert_dom_cookie("samesite_strict", value, false); - assert_dom_cookie("samesite_lax", value, false); - assert_dom_cookie("samesite_none", value, false); - } - }) - .then(_ => { - return credFetch(origin + "/cookies/resources/setSameSite.py?" + value) - .then(_ => { - if (origin == self.origin) { - assert_dom_cookie("samesite_strict", value, true); - assert_dom_cookie("samesite_lax", value, true); - assert_dom_cookie("samesite_none", value, true); - } - }) - }) +async function resetSameSiteCookies(origin, value) { + let w = window.open(origin + "/cookies/samesite/resources/puppet.html"); + try { + await wait_for_message("READY", origin); + w.postMessage({type: "drop", useOwnOrigin: true}, "*"); + await wait_for_message("drop-complete", origin); + if (origin == self.origin) { + assert_dom_cookie("samesite_strict", value, false); + assert_dom_cookie("samesite_lax", value, false); + assert_dom_cookie("samesite_none", value, false); + } + + w.postMessage({type: "set", value: value, useOwnOrigin: true}, "*"); + await wait_for_message("set-complete", origin); + if (origin == self.origin) { + assert_dom_cookie("samesite_strict", value, true); + assert_dom_cookie("samesite_lax", value, true); + assert_dom_cookie("samesite_none", value, true); + } + } finally { + w.close(); + } } // Given an |expectedStatus| and |expectedValue|, assert the |cookies| contains the
diff --git a/third_party/blink/web_tests/external/wpt/cookies/samesite/resources/puppet.html b/third_party/blink/web_tests/external/wpt/cookies/samesite/resources/puppet.html new file mode 100644 index 0000000..9f4f8e22 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/cookies/samesite/resources/puppet.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<script src="/cookies/resources/cookie-helper.sub.js"></script> +<script> + // Helper to either set or clear some cookies on its own origin, or + // (potentially) cross-site on ORIGIN. + window.onmessage = e => { + var originToUse = ORIGIN; + if (e.data.useOwnOrigin) + originToUse = self.origin; + + if (e.data.type === "set") { + credFetch(originToUse + "/cookies/resources/setSameSite.py?" + e.data.value) + .then(_ => { + e.source.postMessage({ + type: "set-complete", + value: e.data.value + }, "*"); + }); + } + + if (e.data.type === "drop") { + credFetch(originToUse + "/cookies/resources/dropSameSite.py") + .then(_ => { + e.source.postMessage({type: "drop-complete"}, "*"); + }); + } + }; + + window.opener.postMessage({ + type: "READY" + }, "*"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/cookies/samesite/setcookie-lax.html b/third_party/blink/web_tests/external/wpt/cookies/samesite/setcookie-lax.html new file mode 100644 index 0000000..2826f67 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/cookies/samesite/setcookie-lax.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<meta charset="utf-8"/> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/cookies/resources/cookie-helper.sub.js"></script> +<script> + promise_test(async function(t) { + let w = window.open(ORIGIN + "/cookies/samesite/resources/puppet.html"); + await wait_for_message("READY", ORIGIN); + let random = "" + Math.random(); + w.postMessage({type: "set", value: random}, "*"); + let e = await wait_for_message("set-complete", ORIGIN) + assert_dom_cookie("samesite_strict", e.data.value, true); + assert_dom_cookie("samesite_lax", e.data.value, true); + assert_dom_cookie("samesite_none", e.data.value, true); + w.close(); + }, "Same-site window should be able to set `SameSite=Lax` or `SameSite=Strict` cookies."); + + promise_test(async function(t) { + let w = window.open(CROSS_SITE_ORIGIN + "/cookies/samesite/resources/puppet.html"); + await wait_for_message("READY", CROSS_SITE_ORIGIN); + let random = "" + Math.random(); + w.postMessage({type: "set", value: random}, "*"); + let e = await wait_for_message("set-complete", CROSS_SITE_ORIGIN); + assert_dom_cookie("samesite_strict", e.data.value, false); + assert_dom_cookie("samesite_lax", e.data.value, false); + assert_dom_cookie("samesite_none", e.data.value, true); + w.close(); + }, "Cross-site window shouldn't be able to set `SameSite=Lax` or `SameSite=Strict` cookies."); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt deleted file mode 100644 index 7ea53f6..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS Initial iceConnectionState should be new -PASS Closing the connection should set iceConnectionState to closed -PASS connection with one data channel should eventually have connected or completed connection state -FAIL connection with one data channel should eventually have connected connection state assert_equals: Expect ICE transport to be in checking state when iceConnectionState is checking expected "checking" but got "connected" -PASS ICE can connect in a recvonly usecase -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https.html b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https.html index 768da23..1bb0793 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https.html +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https.html
@@ -160,13 +160,14 @@ assert_equals(iceTransport.state, 'connected', 'Expect ICE transport to be in connected state when' + ' iceConnectionState is connected'); - + t.done(); } else if(iceConnectionState === 'completed') { const iceTransport = pc1.sctp.transport.iceTransport; assert_equals(iceTransport.state, 'completed', 'Expect ICE transport to be in connected state when' + ' iceConnectionState is completed'); + t.done(); } });
diff --git a/third_party/blink/web_tests/http/tests/devtools/security/main-origin-assigned-despite-request-missing-expected.txt b/third_party/blink/web_tests/http/tests/devtools/security/main-origin-assigned-despite-request-missing-expected.txt index 02fafdec..a9cdbdd 100644 --- a/third_party/blink/web_tests/http/tests/devtools/security/main-origin-assigned-despite-request-missing-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/security/main-origin-assigned-despite-request-missing-expected.txt
@@ -2,7 +2,7 @@ Page origin: http://127.0.0.1:8000 Detected main origin: http://127.0.0.1:8000 -Group: Main origin +Group: Main origin (non-secure) <SPAN > <SPAN class=url-scheme-unknown > http
diff --git a/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors-expected.txt b/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors-expected.txt index 4725ea9..44b3467 100644 --- a/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors-expected.txt +++ b/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors-expected.txt
@@ -12,10 +12,6 @@ Opaque background color: should be red {"backgroundColors":["rgb(255, 0, 0)"],"computedFontSize":"16px","computedFontWeight":"400"} -Running test: testNoDirectText -No direct text: should be red -{"backgroundColors":["rgb(255, 0, 0)"],"computedFontSize":"16px","computedFontWeight":"400"} - Running test: testLayeredOpaqueBgColors Opaque background color in front of another opaque background color: should be blue {"backgroundColors":["rgb(0, 0, 255)"],"computedFontSize":"16px","computedFontWeight":"400"}
diff --git a/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors.js b/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors.js index 8d64a17..5cf9b454 100644 --- a/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors.js +++ b/third_party/blink/web_tests/inspector-protocol/css/css-get-background-colors.js
@@ -28,10 +28,6 @@ testRunner.log('Opaque background color: should be red'); await testGetBgColors('.opaqueBgColor p'); }, - async function testNoDirectText() { - testRunner.log('No direct text: should be red'); - await testGetBgColors('.noDirectText p'); - }, async function testLayeredOpaqueBgColors() { testRunner.log('Opaque background color in front of another opaque background color: should be blue'); await testGetBgColors('.layeredOpaqueBgColors p');
diff --git a/third_party/blink/web_tests/inspector-protocol/css/resources/css-get-background-colors.html b/third_party/blink/web_tests/inspector-protocol/css/resources/css-get-background-colors.html index 0c35833..c31feb3e 100644 --- a/third_party/blink/web_tests/inspector-protocol/css/resources/css-get-background-colors.html +++ b/third_party/blink/web_tests/inspector-protocol/css/resources/css-get-background-colors.html
@@ -48,22 +48,6 @@ </div> </div> -<!-- No direct text --> -<style> -.noDirectText > .background { - background-color: red; -} -</style> -<div class="testCase noDirectText"> - <div class="background layer"></div> - <div class="layer"> - <p> - <span> - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. - </span> - </p> - </div> -</div> <!-- Layered opaque background colors --> <style>
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/letter-spacing-negative-opacity-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/letter-spacing-negative-opacity-expected.png index 455ade5f..17c5569 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/letter-spacing-negative-opacity-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.10/fast/text/letter-spacing-negative-opacity-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/letter-spacing-negative-opacity-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/letter-spacing-negative-opacity-expected.png index 2f01fe19b..95d48f1 100644 --- a/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/letter-spacing-negative-opacity-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac10.12/fast/text/letter-spacing-negative-opacity-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/text/letter-spacing-negative-opacity-expected.png b/third_party/blink/web_tests/platform/mac/fast/text/letter-spacing-negative-opacity-expected.png index 5f213ca..1d02806d 100644 --- a/third_party/blink/web_tests/platform/mac/fast/text/letter-spacing-negative-opacity-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/text/letter-spacing-negative-opacity-expected.png Binary files differ
diff --git a/third_party/gvr-android-sdk/BUILD.gn b/third_party/gvr-android-sdk/BUILD.gn index e4684eb2..cccd50b 100644 --- a/third_party/gvr-android-sdk/BUILD.gn +++ b/third_party/gvr-android-sdk/BUILD.gn
@@ -4,6 +4,9 @@ import("//build/config/android/rules.gni") import("//build/config/c++/c++.gni") +import("//device/vr/buildflags/buildflags.gni") + +assert(enable_vr) android_aar_prebuilt("controller_test_api_java") { testonly = true
diff --git a/third_party/webxr_test_pages/webxr-samples/tests/permission-request.html b/third_party/webxr_test_pages/webxr-samples/tests/permission-request.html index bc21a35..0d22f8af 100644 --- a/third_party/webxr_test_pages/webxr-samples/tests/permission-request.html +++ b/third_party/webxr_test_pages/webxr-samples/tests/permission-request.html
@@ -203,6 +203,11 @@ icon: '../test-media/third-party/screen-share-button.png', callback: (success, fail) => { navigator.mediaDevices.getDisplayMedia() + .then(device => { + // Assign the device to a temp variable to keep it from + // getting garbage collected immediately. + window.getDisplayMediaRetVal = device; + }) .then(success, fail); } },
diff --git a/tools/OWNERS b/tools/OWNERS index 4f3ab75..9796621 100644 --- a/tools/OWNERS +++ b/tools/OWNERS
@@ -30,7 +30,7 @@ per-file gyp-explain.py=thakis@chromium.org -per-file gypv8shy.py=jochen@chromium.org +per-file gypv8sh.py=jochen@chromium.org per-file include_tracer.py=thakis@chromium.org
diff --git a/tools/gypv8sh.py b/tools/gypv8sh.py index e6d655f..152b5e9 100755 --- a/tools/gypv8sh.py +++ b/tools/gypv8sh.py
@@ -29,7 +29,7 @@ parser = optparse.OptionParser() parser.set_usage( "%prog v8_shell mock.js test_api.js js2webui.js " - "testtype inputfile inputrelfile cxxoutfile jsoutfile") + "testtype inputfile srcrootdir cxxoutfile jsoutfile") parser.add_option('-v', '--verbose', action='store_true') parser.add_option('-n', '--impotent', action='store_true', help="don't execute; just print (as if verbose)") @@ -43,9 +43,9 @@ if len(args) != 9: parser.error('all arguments are required.') (v8_shell, mock_js, test_api, js2webui, test_type, - inputfile, inputrelfile, cxxoutfile, jsoutfile) = args + inputfile, srcrootdir, cxxoutfile, jsoutfile) = args cmd = [v8_shell] - arguments = [js2webui, inputfile, inputrelfile, opts.deps_js, + arguments = [js2webui, inputfile, srcrootdir, opts.deps_js, cxxoutfile, test_type] cmd.extend(['-e', "arguments=" + json.dumps(arguments), mock_js, test_api, js2webui])
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 9c7dd62..ac0226e 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -19865,6 +19865,12 @@ </int> </enum> +<enum name="FaviconAvailabilityStatus"> + <int value="0" label="Favicon available locally"/> + <int value="1" label="Favicon available via sync"/> + <int value="2" label="Favicon not available"/> +</enum> + <enum name="FaviconDownloadStatus"> <int value="0" label="SUCCEEDED">Download succeeded.</int> <int value="1" label="FAILED">Download failed.</int> @@ -40062,6 +40068,12 @@ <int value="9" label="Unknown"/> </enum> +<enum name="NetworkCellularUsage"> + <int value="0" label="ConnectAndOnlyNetwork"/> + <int value="1" label="ConnectWithOtherNetwork"/> + <int value="2" label="NotConnected"/> +</enum> + <enum name="NetworkCellularUsageRequestStatus"> <summary> Status code that we received in response to a cellular usage API request.
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 847b018..533110a 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -72754,6 +72754,14 @@ </summary> </histogram> +<histogram name="Network.Cellular.Usage.Count" enum="NetworkCellularUsage"> + <owner>azeemarshad@chromium.org</owner> + <summary> + Tracks the number of times a cellular network is connected as the only + network, or with other network or not connected at all. + </summary> +</histogram> + <histogram name="Network.Cellular.UsageRequestStatus" enum="NetworkCellularUsageRequestStatus" expires_after="2016-04-29"> <obsolete> @@ -123610,6 +123618,17 @@ </summary> </histogram> +<histogram base="true" name="Sync.FaviconAvailability" + enum="FaviconAvailabilityStatus" expires_after="2020-04-10"> + <owner>victorvianna@google.com</owner> + <owner>jkrcal@chromium.org</owner> + <summary> + Records the availability status (local, sync or non-available) for each + favicon in a certain interface. Recorded when responding to the request done + to chrome://favicon URL. + </summary> +</histogram> + <histogram name="Sync.FaviconCacheLookupSucceeded" enum="BooleanSuccess" expires_after="M77"> <owner>zea@chromium.org</owner> @@ -155328,6 +155347,16 @@ <affected-histogram name="Sync.ConfigureTime_Subsequent"/> </histogram_suffixes> +<histogram_suffixes name="SyncFaviconRequestOrigin" separator="."> + <suffix name="HISTORY" label="Request made by chrome://history."/> + <suffix name="RECENTLY_CLOSED_TABS" + label="Request made by the recently closed tabs menu."/> + <suffix name="SYNCED_TABS" + label="Request made by chrome://history/syncedTabs."/> + <suffix name="UNKNOWN" label="Request made by an unknown source."/> + <affected-histogram name="Sync.FaviconAvailability"/> +</histogram_suffixes> + <histogram_suffixes name="SyncKeyDerivationMethod" separator="."> <suffix name="Pbkdf2" label="PBKDF2_HMAC_SHA1_1003"/> <suffix name="Scrypt8192" label="SCRYPT_8192_8_11"/>
diff --git a/ui/chromeos/ime/candidate_view_unittest.cc b/ui/chromeos/ime/candidate_view_unittest.cc index 6a972fb..39cacf38 100644 --- a/ui/chromeos/ime/candidate_view_unittest.cc +++ b/ui/chromeos/ime/candidate_view_unittest.cc
@@ -72,8 +72,8 @@ } protected: - CandidateView* GetCandidateAt(int index) { - return static_cast<CandidateView*>(container_->child_at(index)); + CandidateView* GetCandidateAt(size_t index) { + return static_cast<CandidateView*>(container_->children()[index]); } size_t GetHighlightedCount() const {
diff --git a/ui/chromeos/search_box/search_box_view_base.h b/ui/chromeos/search_box/search_box_view_base.h index d3a8d44..881f9284 100644 --- a/ui/chromeos/search_box/search_box_view_base.h +++ b/ui/chromeos/search_box/search_box_view_base.h
@@ -7,6 +7,7 @@ #include <vector> +#include "base/bind.h" #include "base/macros.h" #include "base/strings/string16.h" #include "ui/chromeos/search_box/search_box_constants.h" @@ -85,7 +86,6 @@ // Overridden from views::View: gfx::Size CalculatePreferredSize() const override; - void OnEnabledChanged() override; const char* GetClassName() const override; void OnGestureEvent(ui::GestureEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; @@ -172,28 +172,30 @@ views::Background* GetSearchBoxBackground(); private: - virtual void ModelChanged() = 0; + virtual void ModelChanged() {} // Shows/hides the virtual keyboard if the search box is active. - virtual void UpdateKeyboardVisibility() = 0; + virtual void UpdateKeyboardVisibility() {} // Updates model text and selection model with current Textfield info. - virtual void UpdateModel(bool initiated_by_user) = 0; + virtual void UpdateModel(bool initiated_by_user) {} // Updates the search icon. - virtual void UpdateSearchIcon() = 0; + virtual void UpdateSearchIcon() {} // Update search box border based on whether the search box is activated. - virtual void UpdateSearchBoxBorder() = 0; + virtual void UpdateSearchBoxBorder() {} // Setup button's image, accessible name, and tooltip text etc. - virtual void SetupAssistantButton() = 0; - virtual void SetupCloseButton() = 0; - virtual void SetupBackButton() = 0; + virtual void SetupAssistantButton() {} + virtual void SetupCloseButton() {} + virtual void SetupBackButton() {} // Records in histograms the activation of the searchbox. virtual void RecordSearchBoxActivationHistogram(ui::EventType event_type) {} + void OnEnabledChanged(); + SearchBoxViewDelegate* delegate_; // Not owned. // Owned by views hierarchy. @@ -219,6 +221,11 @@ // The current search box color. SkColor search_box_color_ = kDefaultSearchboxColor; + views::PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&SearchBoxViewBase::OnEnabledChanged, + base::Unretained(this))); + DISALLOW_COPY_AND_ASSIGN(SearchBoxViewBase); };
diff --git a/ui/file_manager/file_manager/foreground/js/main_scripts.js b/ui/file_manager/file_manager/foreground/js/main_scripts.js index 80fcd29..5e695431 100644 --- a/ui/file_manager/file_manager/foreground/js/main_scripts.js +++ b/ui/file_manager/file_manager/foreground/js/main_scripts.js
@@ -41,7 +41,6 @@ // <include src="../../../../webui/resources/js/event_tracker.js"> // <include src="../../../../webui/resources/js/cr/ui.js"> // <include src="../../../../webui/resources/js/cr/event_target.js"> -// <include src="../../../../webui/resources/js/cr/ui/touch_handler.js"> // <include src="../../../../webui/resources/js/cr/ui/array_data_model.js"> // <include src="../../../../webui/resources/js/cr/ui/dialogs.js"> // <include src="../../../../webui/resources/js/cr/ui/list_item.js">
diff --git a/ui/file_manager/gallery/js/gallery_scripts.js b/ui/file_manager/gallery/js/gallery_scripts.js index 074aac15..8cbb3fd 100644 --- a/ui/file_manager/gallery/js/gallery_scripts.js +++ b/ui/file_manager/gallery/js/gallery_scripts.js
@@ -24,7 +24,6 @@ // <include src="../../../webui/resources/js/cr/ui.js"> // <include src="../../../webui/resources/js/cr/event_target.js"> -// <include src="../../../webui/resources/js/cr/ui/touch_handler.js"> // <include src="../../../webui/resources/js/cr/ui/array_data_model.js"> // <include src="../../../webui/resources/js/cr/ui/dialogs.js"> // <include src="../../../webui/resources/js/cr/ui/list_item.js">
diff --git a/ui/gfx/image/image_skia.cc b/ui/gfx/image/image_skia.cc index 245a7408..7c43d4f 100644 --- a/ui/gfx/image/image_skia.cc +++ b/ui/gfx/image/image_skia.cc
@@ -339,22 +339,22 @@ return ImageSkia(ImageSkiaRep(bitmap, 0.0f)); } -std::unique_ptr<ImageSkia> ImageSkia::DeepCopy() const { - ImageSkia* copy = new ImageSkia; +ImageSkia ImageSkia::DeepCopy() const { + ImageSkia copy; if (isNull()) - return base::WrapUnique(copy); + return copy; CHECK(CanRead()); std::vector<gfx::ImageSkiaRep>& reps = storage_->image_reps(); for (auto iter = reps.begin(); iter != reps.end(); ++iter) { - copy->AddRepresentation(*iter); + copy.AddRepresentation(*iter); } // The copy has its own storage. Detach the copy from the current // sequence so that other sequences can use this. - if (!copy->isNull()) - copy->storage_->DetachFromSequence(); - return base::WrapUnique(copy); + if (!copy.isNull()) + copy.storage_->DetachFromSequence(); + return copy; } bool ImageSkia::BackedBySameObjectAs(const gfx::ImageSkia& other) const {
diff --git a/ui/gfx/image/image_skia.h b/ui/gfx/image/image_skia.h index b268ce68..94e36e8b 100644 --- a/ui/gfx/image/image_skia.h +++ b/ui/gfx/image/image_skia.h
@@ -87,7 +87,7 @@ // If you want to create a deep copy with ImageSkiaReps for supported // scale factors, you need to explicitly call // |EnsureRepsForSupportedScales()| first. - std::unique_ptr<ImageSkia> DeepCopy() const; + ImageSkia DeepCopy() const; // Returns true if this object is backed by the same ImageSkiaStorage as // |other|. Will also return true if both images are isNull().
diff --git a/ui/gfx/image/image_skia_unittest.cc b/ui/gfx/image/image_skia_unittest.cc index 507fda7b..c2139962 100644 --- a/ui/gfx/image/image_skia_unittest.cc +++ b/ui/gfx/image/image_skia_unittest.cc
@@ -388,27 +388,27 @@ EXPECT_TRUE(image.CanModify()); image.DetachStorageFromSequence(); - std::unique_ptr<ImageSkia> deep_copy(image.DeepCopy()); - EXPECT_FALSE(deep_copy->IsThreadSafe()); - test::TestOnThread deepcopy_on_thread(deep_copy.get()); + ImageSkia deep_copy(image.DeepCopy()); + EXPECT_FALSE(deep_copy.IsThreadSafe()); + test::TestOnThread deepcopy_on_thread(&deep_copy); deepcopy_on_thread.StartAndJoin(); EXPECT_TRUE(deepcopy_on_thread.can_read()); EXPECT_TRUE(deepcopy_on_thread.can_modify()); - EXPECT_FALSE(deep_copy->CanRead()); - EXPECT_FALSE(deep_copy->CanModify()); + EXPECT_FALSE(deep_copy.CanRead()); + EXPECT_FALSE(deep_copy.CanModify()); - std::unique_ptr<ImageSkia> deep_copy2(image.DeepCopy()); - EXPECT_EQ(1U, deep_copy2->image_reps().size()); + ImageSkia deep_copy2(image.DeepCopy()); + EXPECT_EQ(1U, deep_copy2.image_reps().size()); // Access it from current thread so that it can't be // accessed from another thread. - deep_copy2->image_reps(); - EXPECT_FALSE(deep_copy2->IsThreadSafe()); - test::TestOnThread deepcopy2_on_thread(deep_copy2.get()); + deep_copy2.image_reps(); + EXPECT_FALSE(deep_copy2.IsThreadSafe()); + test::TestOnThread deepcopy2_on_thread(&deep_copy2); deepcopy2_on_thread.StartAndJoin(); EXPECT_FALSE(deepcopy2_on_thread.can_read()); EXPECT_FALSE(deepcopy2_on_thread.can_modify()); - EXPECT_TRUE(deep_copy2->CanRead()); - EXPECT_TRUE(deep_copy2->CanModify()); + EXPECT_TRUE(deep_copy2.CanRead()); + EXPECT_TRUE(deep_copy2.CanModify()); image.DetachStorageFromSequence(); image.SetReadOnly();
diff --git a/ui/message_center/views/message_popup_collection_unittest.cc b/ui/message_center/views/message_popup_collection_unittest.cc index 9902177..d6d5a3e 100644 --- a/ui/message_center/views/message_popup_collection_unittest.cc +++ b/ui/message_center/views/message_popup_collection_unittest.cc
@@ -141,11 +141,11 @@ void AutoCollapse() override { if (expandable_) - child_at(0)->SetPreferredSize(gfx::Size(kNotificationWidth, 42)); + children().front()->SetPreferredSize(gfx::Size(kNotificationWidth, 42)); } void SetPreferredHeight(int height) { - child_at(0)->SetPreferredSize(gfx::Size(kNotificationWidth, height)); + children().front()->SetPreferredSize(gfx::Size(kNotificationWidth, height)); } void SetHovered(bool is_hovered) {
diff --git a/ui/message_center/views/notification_header_view.cc b/ui/message_center/views/notification_header_view.cc index 58a9a8b8..a2c4ee4 100644 --- a/ui/message_center/views/notification_header_view.cc +++ b/ui/message_center/views/notification_header_view.cc
@@ -67,6 +67,9 @@ // "Roboto-Regular, 12sp" is specified in the mock. constexpr int kHeaderTextFontSize = 12; +// Minimum spacing before the control buttons. +constexpr int kControlButtonSpacing = 16; + // ExpandButtton forwards all mouse and key events to NotificationHeaderView, // but takes tab focus for accessibility purpose. class ExpandButton : public views::ImageView { @@ -156,7 +159,7 @@ const views::FlexSpecification kSpacerFlex = views::FlexSpecification::ForSizeRule( - views::MinimumFlexSizeRule::kScaleToZero, + views::MinimumFlexSizeRule::kScaleToMinimum, views::MaximumFlexSizeRule::kUnbounded) .WithOrder(2); @@ -229,7 +232,8 @@ // Spacer between left-aligned views and right-aligned views views::View* spacer = new views::View; - spacer->SetPreferredSize(gfx::Size(1, kInnerHeaderHeight)); + spacer->SetPreferredSize( + gfx::Size(kControlButtonSpacing, kInnerHeaderHeight)); AddChildView(spacer); layout->SetFlexForView(spacer, kSpacerFlex); @@ -237,6 +241,8 @@ SetPreferredSize(gfx::Size(kNotificationWidth, kHeaderHeight)); } +NotificationHeaderView::~NotificationHeaderView() = default; + void NotificationHeaderView::SetAppIcon(const gfx::ImageSkia& img) { app_icon_view_->SetImage(img); using_default_app_icon_ = false; @@ -305,7 +311,7 @@ &relative_time, &next_update); timestamp_view_->SetText(relative_time); - has_timestamp_ = true; + timestamp_ = timestamp; UpdateSummaryTextVisibility(); // Unretained is safe as the timer cancels the task on destruction. @@ -315,9 +321,14 @@ base::Unretained(this), timestamp)); } -void NotificationHeaderView::ClearTimestamp() { - has_timestamp_ = false; - timestamp_update_timer_.Stop(); +void NotificationHeaderView::SetTimestampVisible(bool visible) { + timestamp_visible_ = visible; + + if (visible && timestamp_) + SetTimestamp(timestamp_.value()); + else + timestamp_update_timer_.Stop(); + UpdateSummaryTextVisibility(); } @@ -391,11 +402,15 @@ } void NotificationHeaderView::UpdateSummaryTextVisibility() { - const bool visible = !summary_text_view_->text().empty(); - summary_text_divider_->SetVisible(visible); - summary_text_view_->SetVisible(visible); - timestamp_divider_->SetVisible(!has_progress_ && has_timestamp_); - timestamp_view_->SetVisible(!has_progress_ && has_timestamp_); + const bool summary_visible = !summary_text_view_->text().empty(); + summary_text_divider_->SetVisible(summary_visible); + summary_text_view_->SetVisible(summary_visible); + + const bool timestamp_visible = + !has_progress_ && timestamp_visible_ && timestamp_; + timestamp_divider_->SetVisible(timestamp_visible); + timestamp_view_->SetVisible(timestamp_visible); + Layout(); }
diff --git a/ui/message_center/views/notification_header_view.h b/ui/message_center/views/notification_header_view.h index 8278caa..e67234d3 100644 --- a/ui/message_center/views/notification_header_view.h +++ b/ui/message_center/views/notification_header_view.h
@@ -6,6 +6,7 @@ #define UI_MESSAGE_CENTER_VIEWS_NOTIFICATION_HEADER_VIEW_H_ #include "base/macros.h" +#include "base/optional.h" #include "base/timer/timer.h" #include "ui/gfx/text_constants.h" #include "ui/message_center/message_center_export.h" @@ -22,6 +23,7 @@ class MESSAGE_CENTER_EXPORT NotificationHeaderView : public views::Button { public: explicit NotificationHeaderView(views::ButtonListener* listener); + ~NotificationHeaderView() override; void SetAppIcon(const gfx::ImageSkia& img); void SetAppName(const base::string16& name); void SetAppNameElideBehavior(gfx::ElideBehavior elide_behavior); @@ -33,6 +35,7 @@ void SetOverflowIndicator(int count); void SetTimestamp(base::Time timestamp); + void SetTimestampVisible(bool visible); void SetExpandButtonEnabled(bool enabled); void SetExpanded(bool expanded); void SetSettingsButtonEnabled(bool enabled); @@ -49,7 +52,6 @@ void ClearAppIcon(); void ClearProgress(); - void ClearTimestamp(); bool IsExpandButtonEnabled(); void SetSubpixelRenderingEnabled(bool enabled); @@ -81,6 +83,7 @@ // Timer that updates the timestamp over time. base::OneShotTimer timestamp_update_timer_; + base::Optional<base::Time> timestamp_; views::Label* app_name_view_ = nullptr; views::Label* summary_text_divider_ = nullptr; @@ -92,7 +95,7 @@ bool settings_button_enabled_ = false; bool has_progress_ = false; - bool has_timestamp_ = false; + bool timestamp_visible_ = true; bool is_expanded_ = false; bool using_default_app_icon_ = false;
diff --git a/ui/message_center/views/notification_view_md.cc b/ui/message_center/views/notification_view_md.cc index 6f09667..022ed60 100644 --- a/ui/message_center/views/notification_view_md.cc +++ b/ui/message_center/views/notification_view_md.cc
@@ -1015,7 +1015,7 @@ AddChildViewAt(image_container_view_, GetIndexOf(content_row_) + 1); } - static_cast<LargeImageView*>(image_container_view_->child_at(0)) + static_cast<LargeImageView*>(image_container_view_->children().front()) ->SetImage(notification.image().AsImageSkia()); } @@ -1148,6 +1148,10 @@ } bool NotificationViewMD::IsExpandable() { + // Inline settings can not be expanded. + if (GetMode() == Mode::SETTING) + return false; + // Expandable if the message exceeds one line. if (message_view_ && message_view_->visible() && message_view_->GetLinesForWidthAndLimit(message_view_->width(), -1) > 1) { @@ -1230,6 +1234,7 @@ settings_row_->SetVisible(inline_settings_visible); content_row_->SetVisible(!inline_settings_visible); + header_row_->SetTimestampVisible(!inline_settings_visible); // Always check "Don't block" when inline settings is shown. // If it's already blocked, users should not see inline settings.
diff --git a/ui/views/accessibility/ax_aura_obj_cache.cc b/ui/views/accessibility/ax_aura_obj_cache.cc index f8e1ae7..9a9131b 100644 --- a/ui/views/accessibility/ax_aura_obj_cache.cc +++ b/ui/views/accessibility/ax_aura_obj_cache.cc
@@ -176,7 +176,7 @@ auto* non_client = focused_widget->non_client_view(); auto* client = non_client ? non_client->client_view() : nullptr; return (client && !client->children().empty()) - ? client->child_at(0) + ? client->children().front() : focused_widget->GetRootView(); }
diff --git a/ui/views/bubble/bubble_frame_view.cc b/ui/views/bubble/bubble_frame_view.cc index 1298d31..b1234206 100644 --- a/ui/views/bubble/bubble_frame_view.cc +++ b/ui/views/bubble/bubble_frame_view.cc
@@ -395,7 +395,7 @@ if (!details.is_add && details.parent == footnote_container_ && footnote_container_->children().size() == 1 && - details.child == footnote_container_->child_at(0)) { + details.child == footnote_container_->children().front()) { // Setting the footnote_container_ to be hidden and null it. This will // remove update the bubble to have no placeholder for the footnote and // enable the destructor to delete the footnote_container_ later.
diff --git a/ui/views/controls/button/button.cc b/ui/views/controls/button/button.cc index 3bf33fe0..ebcf85c 100644 --- a/ui/views/controls/button/button.cc +++ b/ui/views/controls/button/button.cc
@@ -4,8 +4,6 @@ #include "ui/views/controls/button/button.h" -#include <utility> - #include "base/strings/utf_string_conversions.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/class_property.h" @@ -218,20 +216,6 @@ //////////////////////////////////////////////////////////////////////////////// // Button, View overrides: -void Button::OnEnabledChanged() { - if (enabled() ? (state_ != STATE_DISABLED) : (state_ == STATE_DISABLED)) - return; - - if (enabled()) { - bool should_enter_hover_state = ShouldEnterHoveredState(); - SetState(should_enter_hover_state ? STATE_HOVERED : STATE_NORMAL); - GetInkDrop()->SetHovered(should_enter_hover_state); - } else { - SetState(STATE_DISABLED); - GetInkDrop()->SetHovered(false); - } -} - const char* Button::GetClassName() const { return kViewClassName; } @@ -602,6 +586,20 @@ return check_mouse_position && IsMouseHovered(); } +void Button::OnEnabledChanged() { + if (GetEnabled() ? (state_ != STATE_DISABLED) : (state_ == STATE_DISABLED)) + return; + + if (GetEnabled()) { + bool should_enter_hover_state = ShouldEnterHoveredState(); + SetState(should_enter_hover_state ? STATE_HOVERED : STATE_NORMAL); + GetInkDrop()->SetHovered(should_enter_hover_state); + } else { + SetState(STATE_DISABLED); + GetInkDrop()->SetHovered(false); + } +} + void Button::WidgetActivationChanged(Widget* widget, bool active) { StateChanged(state()); }
diff --git a/ui/views/controls/button/button.h b/ui/views/controls/button/button.h index d564d87..efff837 100644 --- a/ui/views/controls/button/button.h +++ b/ui/views/controls/button/button.h
@@ -7,6 +7,7 @@ #include <memory> +#include "base/bind.h" #include "base/macros.h" #include "build/build_config.h" #include "ui/events/event_constants.h" @@ -168,7 +169,6 @@ void SetHighlighted(bool bubble_visible); // Overridden from View: - void OnEnabledChanged() override; const char* GetClassName() const override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; @@ -328,6 +328,8 @@ DISALLOW_COPY_AND_ASSIGN(WidgetObserverButtonBridge); }; + void OnEnabledChanged(); + void WidgetActivationChanged(Widget* widget, bool active); // The text shown in a tooltip. @@ -383,6 +385,10 @@ // ButtonController. std::unique_ptr<ButtonController> button_controller_; + PropertyChangedSubscription enabled_changed_subscription_{ + AddEnabledChangedCallback(base::BindRepeating(&Button::OnEnabledChanged, + base::Unretained(this)))}; + DISALLOW_COPY_AND_ASSIGN(Button); };
diff --git a/ui/views/controls/button/label_button_label.cc b/ui/views/controls/button/label_button_label.cc index 6d13e04f..07e6213 100644 --- a/ui/views/controls/button/label_button_label.cc +++ b/ui/views/controls/button/label_button_label.cc
@@ -25,16 +25,15 @@ Label::SetEnabledColor(color); } -void LabelButtonLabel::OnEnabledChanged() { - SetColorForEnableState(); - Label::OnEnabledChanged(); -} - void LabelButtonLabel::OnNativeThemeChanged(const ui::NativeTheme* theme) { SetColorForEnableState(); Label::OnNativeThemeChanged(theme); } +void LabelButtonLabel::OnEnabledChanged() { + SetColorForEnableState(); +} + void LabelButtonLabel::SetColorForEnableState() { if (enabled() ? enabled_color_set_ : disabled_color_set_) { Label::SetEnabledColor(enabled() ? requested_enabled_color_
diff --git a/ui/views/controls/button/label_button_label.h b/ui/views/controls/button/label_button_label.h index 1657726..94865fa 100644 --- a/ui/views/controls/button/label_button_label.h +++ b/ui/views/controls/button/label_button_label.h
@@ -5,6 +5,7 @@ #ifndef UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_LABEL_H_ #define UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_LABEL_H_ +#include "base/bind.h" #include "base/macros.h" #include "base/strings/string16.h" #include "third_party/skia/include/core/SkColor.h" @@ -29,16 +30,20 @@ protected: // Label: - void OnEnabledChanged() override; void OnNativeThemeChanged(const ui::NativeTheme* theme) override; private: + void OnEnabledChanged(); void SetColorForEnableState(); SkColor requested_disabled_color_ = SK_ColorRED; SkColor requested_enabled_color_ = SK_ColorRED; bool disabled_color_set_ = false; bool enabled_color_set_ = false; + PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&LabelButtonLabel::OnEnabledChanged, + base::Unretained(this))); DISALLOW_COPY_AND_ASSIGN(LabelButtonLabel); };
diff --git a/ui/views/controls/menu/menu_controller.cc b/ui/views/controls/menu/menu_controller.cc index ba2451e..d7bd4cc 100644 --- a/ui/views/controls/menu/menu_controller.cc +++ b/ui/views/controls/menu/menu_controller.cc
@@ -712,7 +712,8 @@ // |menu| is null means this event is from an empty menu or a separator. // If it is from an empty menu, use parent context menu instead of that. if (!menu && part.submenu->children().size() == 1 && - part.submenu->child_at(0)->id() == MenuItemView::kEmptyMenuItemViewID) { + part.submenu->children().front()->id() == + MenuItemView::kEmptyMenuItemViewID) { menu = part.parent; }
diff --git a/ui/views/controls/menu/menu_controller_unittest.cc b/ui/views/controls/menu/menu_controller_unittest.cc index 3b8f477..1c3c2ddf 100644 --- a/ui/views/controls/menu/menu_controller_unittest.cc +++ b/ui/views/controls/menu/menu_controller_unittest.cc
@@ -1051,13 +1051,13 @@ TEST_F(MenuControllerTest, SelectChildButtonView) { AddButtonMenuItems(); - View* buttons_view = menu_item()->GetSubmenu()->child_at(4); + View* buttons_view = menu_item()->GetSubmenu()->children()[4]; ASSERT_NE(nullptr, buttons_view); - Button* button1 = Button::AsButton(buttons_view->child_at(0)); + Button* button1 = Button::AsButton(buttons_view->children()[0]); ASSERT_NE(nullptr, button1); - Button* button2 = Button::AsButton(buttons_view->child_at(1)); + Button* button2 = Button::AsButton(buttons_view->children()[1]); ASSERT_NE(nullptr, button2); - Button* button3 = Button::AsButton(buttons_view->child_at(2)); + Button* button3 = Button::AsButton(buttons_view->children()[2]); ASSERT_NE(nullptr, button2); // Handle searching for 'f'; should find "Four". @@ -1126,13 +1126,13 @@ SelectByChar('f'); EXPECT_EQ(4, pending_state_item()->GetCommand()); - View* buttons_view = menu_item()->GetSubmenu()->child_at(4); + View* buttons_view = menu_item()->GetSubmenu()->children()[4]; ASSERT_NE(nullptr, buttons_view); - Button* button1 = Button::AsButton(buttons_view->child_at(0)); + Button* button1 = Button::AsButton(buttons_view->children()[0]); ASSERT_NE(nullptr, button1); - Button* button2 = Button::AsButton(buttons_view->child_at(1)); + Button* button2 = Button::AsButton(buttons_view->children()[1]); ASSERT_NE(nullptr, button2); - Button* button3 = Button::AsButton(buttons_view->child_at(2)); + Button* button3 = Button::AsButton(buttons_view->children()[2]); ASSERT_NE(nullptr, button2); EXPECT_FALSE(button1->IsHotTracked()); EXPECT_FALSE(button2->IsHotTracked()); @@ -1168,13 +1168,13 @@ SelectByChar('f'); EXPECT_EQ(4, pending_state_item()->GetCommand()); - View* buttons_view = menu_item()->GetSubmenu()->child_at(4); + View* buttons_view = menu_item()->GetSubmenu()->children()[4]; ASSERT_NE(nullptr, buttons_view); - Button* button1 = Button::AsButton(buttons_view->child_at(0)); + Button* button1 = Button::AsButton(buttons_view->children()[0]); ASSERT_NE(nullptr, button1); - Button* button2 = Button::AsButton(buttons_view->child_at(1)); + Button* button2 = Button::AsButton(buttons_view->children()[1]); ASSERT_NE(nullptr, button2); - Button* button3 = Button::AsButton(buttons_view->child_at(2)); + Button* button3 = Button::AsButton(buttons_view->children()[2]); ASSERT_NE(nullptr, button2); EXPECT_FALSE(button1->IsHotTracked()); EXPECT_FALSE(button2->IsHotTracked()); @@ -2161,9 +2161,9 @@ MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2); MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3); MenuItemView* const item5 = menu_item()->GetSubmenu()->GetMenuItemAt(4); - Button* const button1 = Button::AsButton(item5->child_at(0)); - Button* const button2 = Button::AsButton(item5->child_at(1)); - Button* const button3 = Button::AsButton(item5->child_at(2)); + Button* const button1 = Button::AsButton(item5->children()[0]); + Button* const button2 = Button::AsButton(item5->children()[1]); + Button* const button3 = Button::AsButton(item5->children()[2]); OpenMenu(menu_item()); ui::AXNodeData data; @@ -2203,11 +2203,11 @@ MenuItemView* const item3 = menu_item()->GetSubmenu()->GetMenuItemAt(2); MenuItemView* const item4 = menu_item()->GetSubmenu()->GetMenuItemAt(3); MenuItemView* const item5 = menu_item()->GetSubmenu()->GetMenuItemAt(4); - Button* const button1 = Button::AsButton(item5->child_at(0)); + Button* const button1 = Button::AsButton(item5->children()[0]); button1->SetEnabled(false); - Button* const button2 = Button::AsButton(item5->child_at(1)); + Button* const button2 = Button::AsButton(item5->children()[1]); button2->SetVisible(false); - Button* const button3 = Button::AsButton(item5->child_at(2)); + Button* const button3 = Button::AsButton(item5->children()[2]); OpenMenu(menu_item()); ui::AXNodeData data;
diff --git a/ui/views/controls/menu/menu_item_view.cc b/ui/views/controls/menu/menu_item_view.cc index fb25485f4..ad87692c 100644 --- a/ui/views/controls/menu/menu_item_view.cc +++ b/ui/views/controls/menu/menu_item_view.cc
@@ -179,7 +179,7 @@ if (IsContainer()) { // The first child is taking over, just use its accessible name instead of // |title_|. - View* child = child_at(0); + View* child = children().front(); ui::AXNodeData node_data; child->GetAccessibleNodeData(&node_data); item_text = @@ -514,7 +514,7 @@ return GetPreferredSize().height(); const gfx::Insets margins = GetContainerMargins(); - int height = child_at(0)->GetHeightForWidth(width - margins.width()); + int height = children().front()->GetHeightForWidth(width - margins.width()); if (!icon_view_ && GetRootMenuItem()->has_icons()) height = std::max(height, MenuConfig::instance().check_height); @@ -642,7 +642,7 @@ // bounds, less the margins. gfx::Rect bounds = GetContentsBounds(); bounds.Inset(GetContainerMargins()); - child_at(0)->SetBoundsRect(bounds); + children().front()->SetBoundsRect(bounds); } else { // Child views are laid out right aligned and given the full height. To // right align start with the last view and progress to the first. @@ -1180,7 +1180,7 @@ return gfx::Size(); if (IsContainer()) - return child_at(0)->GetPreferredSize(); + return children().front()->GetPreferredSize(); const auto add_width = [this](int width, const View* child) { if (child == icon_view_ || child == radio_check_image_view_ || @@ -1357,7 +1357,7 @@ // Use the child's preferred margins but take the standard top and bottom // margins as minimums. const gfx::Insets* margins_prop = - child_at(0)->GetProperty(views::kMarginsKey); + children().front()->GetProperty(views::kMarginsKey); gfx::Insets margins = margins_prop ? *margins_prop : gfx::Insets(); margins.set_top(std::max(margins.top(), GetTopMargin())); margins.set_bottom(std::max(margins.bottom(), GetBottomMargin()));
diff --git a/ui/views/controls/menu/menu_item_view_unittest.cc b/ui/views/controls/menu/menu_item_view_unittest.cc index 038ef1f0..8dd8f34 100644 --- a/ui/views/controls/menu/menu_item_view_unittest.cc +++ b/ui/views/controls/menu/menu_item_view_unittest.cc
@@ -116,7 +116,7 @@ // Because all of the submenu's children are hidden, an empty menu item should // have been added. ASSERT_EQ(3u, submenu->children().size()); - MenuItemView* empty_item = static_cast<MenuItemView*>(submenu->child_at(0)); + auto* empty_item = static_cast<MenuItemView*>(submenu->children().front()); ASSERT_TRUE(empty_item); ASSERT_EQ(MenuItemView::kEmptyMenuItemViewID, empty_item->id()); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_APP_MENU_EMPTY_SUBMENU), @@ -150,7 +150,7 @@ // Because all of the submenu's children are hidden, an empty menu item should // have been added. ASSERT_EQ(3u, submenu->children().size()); - MenuItemView* empty_item = static_cast<MenuItemView*>(submenu->child_at(0)); + auto* empty_item = static_cast<MenuItemView*>(submenu->children().front()); ASSERT_TRUE(empty_item); // Not allowed to add an duplicated empty menu item // if it already has an empty menu item.
diff --git a/ui/views/controls/menu/menu_scroll_view_container.cc b/ui/views/controls/menu/menu_scroll_view_container.cc index f3ff29e3..50e9b3ad 100644 --- a/ui/views/controls/menu/menu_scroll_view_container.cc +++ b/ui/views/controls/menu/menu_scroll_view_container.cc
@@ -161,9 +161,7 @@ } // Returns the contents, which is the SubmenuView. - View* GetContents() { - return child_at(0); - } + View* GetContents() { return children().front(); } private: DISALLOW_COPY_AND_ASSIGN(MenuScrollView);
diff --git a/ui/views/controls/scroll_view.cc b/ui/views/controls/scroll_view.cc index e32e5a7f..5d5e1b56 100644 --- a/ui/views/controls/scroll_view.cc +++ b/ui/views/controls/scroll_view.cc
@@ -120,7 +120,7 @@ if (children().empty() || !parent()) return; - View* contents = child_at(0); + View* contents = children().front(); gfx::Rect scroll_rect(rect); if (scroll_view_->ScrollsWithLayers()) {
diff --git a/ui/views/controls/styled_label_unittest.cc b/ui/views/controls/styled_label_unittest.cc index 8abd7d4..310bf9f 100644 --- a/ui/views/controls/styled_label_unittest.cc +++ b/ui/views/controls/styled_label_unittest.cc
@@ -45,9 +45,9 @@ protected: StyledLabel* styled() { return styled_.get(); } - Label* LabelAt(int index, + Label* LabelAt(size_t index, std::string expected_classname = Label::kViewClassName) { - View* const child = styled_->child_at(index); + View* const child = styled_->children()[index]; EXPECT_EQ(expected_classname, child->GetClassName()); return static_cast<Label*>(child); } @@ -159,9 +159,9 @@ styled()->GetInsets().height() + 2 * label_preferred_size.height()); styled()->Layout(); ASSERT_EQ(2u, styled()->children().size()); - EXPECT_EQ(3, styled()->child_at(0)->x()); - EXPECT_EQ(3, styled()->child_at(0)->y()); - EXPECT_EQ(styled()->height() - 3, styled()->child_at(1)->bounds().bottom()); + EXPECT_EQ(3, styled()->children()[0]->x()); + EXPECT_EQ(3, styled()->children()[0]->y()); + EXPECT_EQ(styled()->height() - 3, styled()->children()[1]->bounds().bottom()); } TEST_F(StyledLabelTest, AllowEmptyLines) { @@ -175,7 +175,7 @@ EXPECT_EQ(3 * default_height, styled()->GetHeightForWidth(1000)); ASSERT_EQ(2u, styled()->children().size()); EXPECT_EQ(styled()->GetHeightForWidth(1000), - styled()->child_at(1)->bounds().bottom()); + styled()->children()[1]->bounds().bottom()); } TEST_F(StyledLabelTest, WrapLongWords) { @@ -249,9 +249,9 @@ ASSERT_EQ(2u, styled()->children().size()); // No additional insets should be added. - EXPECT_EQ(0, styled()->child_at(0)->x()); + EXPECT_EQ(0, styled()->children()[0]->x()); // The Link shouldn't be offset. - EXPECT_EQ(0, styled()->child_at(1)->x()); + EXPECT_EQ(0, styled()->children()[1]->x()); } TEST_F(StyledLabelTest, StyledRangeWithDisabledLineWrapping) { @@ -274,8 +274,8 @@ styled()->SetBounds(0, 0, label_preferred_size.width(), pref_height); styled()->Layout(); ASSERT_EQ(2u, styled()->children().size()); - EXPECT_EQ(0, styled()->child_at(0)->x()); - EXPECT_EQ(0, styled()->child_at(1)->x()); + EXPECT_EQ(0, styled()->children()[0]->x()); + EXPECT_EQ(0, styled()->children()[1]->x()); } TEST_F(StyledLabelTest, StyledRangeCustomFontUnderlined) { @@ -442,19 +442,19 @@ ASSERT_EQ(5u, styled()->children().size()); // The labels shouldn't be offset to cater for focus rings. - EXPECT_EQ(0, styled()->child_at(0)->x()); - EXPECT_EQ(0, styled()->child_at(2)->x()); + EXPECT_EQ(0, styled()->children()[0]->x()); + EXPECT_EQ(0, styled()->children()[2]->x()); - EXPECT_EQ(styled()->child_at(0)->bounds().right(), - styled()->child_at(1)->x()); - EXPECT_EQ(styled()->child_at(2)->bounds().right(), - styled()->child_at(3)->x()); - EXPECT_EQ(0, styled()->child_at(4)->x()); + EXPECT_EQ(styled()->children()[0]->bounds().right(), + styled()->children()[1]->x()); + EXPECT_EQ(styled()->children()[2]->bounds().right(), + styled()->children()[3]->x()); + EXPECT_EQ(0, styled()->children()[4]->x()); base::string16 tooltip = - styled()->child_at(1)->GetTooltipText(gfx::Point(1, 1)); + styled()->children()[1]->GetTooltipText(gfx::Point(1, 1)); EXPECT_EQ(ASCIIToUTF16("tooltip"), tooltip); - tooltip = styled()->child_at(2)->GetTooltipText(gfx::Point(1, 1)); + tooltip = styled()->children()[2]->GetTooltipText(gfx::Point(1, 1)); EXPECT_EQ(ASCIIToUTF16("tooltip"), tooltip); } @@ -542,7 +542,7 @@ // height should be the same as precalculated int real_height = styled()->GetHeightForWidth(styled()->width()); View* first_child_after_layout = - styled()->children().empty() ? nullptr : styled()->child_at(0); + styled()->children().empty() ? nullptr : styled()->children().front(); EXPECT_LT(0u, styled()->children().size()); EXPECT_LT(0, real_height); EXPECT_EQ(real_height, precalculated_height); @@ -550,7 +550,7 @@ // another call to Layout should not kill and recreate all controls styled()->Layout(); View* first_child_after_second_layout = - styled()->children().empty() ? nullptr : styled()->child_at(0); + styled()->children().empty() ? nullptr : styled()->children().front(); EXPECT_EQ(first_child_after_layout, first_child_after_second_layout); // if text is changed: @@ -560,7 +560,7 @@ int updated_height = styled()->GetHeightForWidth(styled()->width()); EXPECT_NE(updated_height, real_height); View* first_child_after_text_update = - styled()->children().empty() ? nullptr : styled()->child_at(0); + styled()->children().empty() ? nullptr : styled()->children().front(); EXPECT_NE(first_child_after_text_update, first_child_after_layout); } @@ -649,24 +649,25 @@ InitStyledLabel(text); styled()->SetBounds(0, 0, 1000, 1000); styled()->Layout(); - ASSERT_EQ(1u, styled()->children().size()); + const auto& children = styled()->children(); + ASSERT_EQ(1u, children.size()); // Test the default alignment puts the text on the leading side (left). - EXPECT_EQ(0, styled()->child_at(0)->bounds().x()); + EXPECT_EQ(0, children.front()->bounds().x()); styled()->SetHorizontalAlignment(gfx::ALIGN_RIGHT); styled()->Layout(); - EXPECT_EQ(1000, styled()->child_at(0)->bounds().right()); + EXPECT_EQ(1000, children.front()->bounds().right()); styled()->SetHorizontalAlignment(gfx::ALIGN_LEFT); styled()->Layout(); - EXPECT_EQ(0, styled()->child_at(0)->bounds().x()); + EXPECT_EQ(0, children.front()->bounds().x()); styled()->SetHorizontalAlignment(gfx::ALIGN_CENTER); styled()->Layout(); Label label(ASCIIToUTF16(text)); EXPECT_EQ((1000 - label.GetPreferredSize().width()) / 2, - styled()->child_at(0)->bounds().x()); + children.front()->bounds().x()); } TEST_F(StyledLabelTest, AlignmentInRTL) { @@ -681,27 +682,28 @@ InitStyledLabel(text); styled()->SetBounds(0, 0, 1000, 1000); styled()->Layout(); - ASSERT_EQ(1u, styled()->children().size()); + const auto& children = styled()->children(); + ASSERT_EQ(1u, children.size()); // Test the default alignment puts the text on the leading side (right). // Note that x-coordinates in RTL place the origin (0) on the right. - EXPECT_EQ(0, styled()->child_at(0)->bounds().x()); + EXPECT_EQ(0, children.front()->bounds().x()); // Setting |ALIGN_LEFT| should be flipped to |ALIGN_RIGHT|. styled()->SetHorizontalAlignment(gfx::ALIGN_LEFT); styled()->Layout(); - EXPECT_EQ(1000, styled()->child_at(0)->bounds().right()); + EXPECT_EQ(1000, children.front()->bounds().right()); // Setting |ALIGN_RIGHT| should be flipped to |ALIGN_LEFT|. styled()->SetHorizontalAlignment(gfx::ALIGN_RIGHT); styled()->Layout(); - EXPECT_EQ(0, styled()->child_at(0)->bounds().x()); + EXPECT_EQ(0, children.front()->bounds().x()); styled()->SetHorizontalAlignment(gfx::ALIGN_CENTER); styled()->Layout(); Label label(ASCIIToUTF16(text)); EXPECT_EQ((1000 - label.GetPreferredSize().width()) / 2, - styled()->child_at(0)->bounds().x()); + children.front()->bounds().x()); } TEST_F(StyledLabelTest, ViewsCenteredWithLinkAndCustomView) { @@ -730,8 +732,8 @@ int height = styled()->GetPreferredSize().height(); ASSERT_EQ(3u, styled()->children().size()); - const auto is_centered = [this, height](int index) { - const auto* child = styled()->child_at(index); + const auto is_centered = [this, height](size_t index) { + const auto* child = styled()->children()[index]; return child->bounds().y() == ((height - child->bounds().height()) / 2); }; EXPECT_TRUE(is_centered(0));
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane.cc b/ui/views/controls/tabbed_pane/tabbed_pane.cc index 29f4fd59..95f1c701 100644 --- a/ui/views/controls/tabbed_pane/tabbed_pane.cc +++ b/ui/views/controls/tabbed_pane/tabbed_pane.cc
@@ -601,7 +601,7 @@ // underneath or on the right of the selected tab will be overdrawn later. gfx::Rect rect; if (is_horizontal) { - max_cross_axis = child_at(0)->y() + child_at(0)->height(); + max_cross_axis = children().front()->bounds().bottom(); rect = gfx::Rect(0, max_cross_axis - kUnselectedBorderThickness, width(), kUnselectedBorderThickness); } else {
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane_accessibility_mac_unittest.mm b/ui/views/controls/tabbed_pane/tabbed_pane_accessibility_mac_unittest.mm index b35d0d6..bdd0064 100644 --- a/ui/views/controls/tabbed_pane/tabbed_pane_accessibility_mac_unittest.mm +++ b/ui/views/controls/tabbed_pane/tabbed_pane_accessibility_mac_unittest.mm
@@ -66,8 +66,8 @@ WidgetTest::TearDown(); } - Tab* GetTabAt(int index) { - return static_cast<Tab*>(tabbed_pane_->tab_strip_->child_at(index)); + Tab* GetTabAt(size_t index) { + return static_cast<Tab*>(tabbed_pane_->tab_strip_->children()[index]); } id<NSAccessibility> A11yElementAtPoint(const gfx::Point& point) { @@ -77,7 +77,7 @@ accessibilityHitTest:ns_point]); } - gfx::Point TabCenterPoint(int index) { + gfx::Point TabCenterPoint(size_t index) { return GetTabAt(index)->GetBoundsInScreen().CenterPoint(); } @@ -117,7 +117,7 @@ // Compare the value attribute against native Cocoa and check it matches up // with whether tabs are actually selected. - for (int i : {0, 1}) { + for (size_t i : {0, 1}) { NSNumber* cocoa_value = GetLegacyA11yAttributeValue( cocoa_tabs[i], NSAccessibilityValueAttribute); // Verify that only the second tab is selected.
diff --git a/ui/views/controls/textfield/textfield.cc b/ui/views/controls/textfield/textfield.cc index a12db5c39..dddefc53 100644 --- a/ui/views/controls/textfield/textfield.cc +++ b/ui/views/controls/textfield/textfield.cc
@@ -11,7 +11,6 @@ #include <vector> #endif -#include "base/bind.h" #include "base/command_line.h" #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.h" @@ -1079,13 +1078,6 @@ touch_selection_controller_->SelectionChanged(); } -void Textfield::OnEnabledChanged() { - View::OnEnabledChanged(); - if (GetInputMethod()) - GetInputMethod()->OnTextInputTypeChanged(this); - SchedulePaint(); -} - void Textfield::OnPaint(gfx::Canvas* canvas) { OnPaintBackground(canvas); PaintTextAndCursor(canvas); @@ -2355,4 +2347,9 @@ cursor_view_.SetVisible(!cursor_view_.visible()); } +void Textfield::OnEnabledChanged() { + if (GetInputMethod()) + GetInputMethod()->OnTextInputTypeChanged(this); +} + } // namespace views
diff --git a/ui/views/controls/textfield/textfield.h b/ui/views/controls/textfield/textfield.h index a3a3572..d620fb1e 100644 --- a/ui/views/controls/textfield/textfield.h +++ b/ui/views/controls/textfield/textfield.h
@@ -15,6 +15,7 @@ #include <vector> #endif +#include "base/bind.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -285,7 +286,6 @@ void OnBoundsChanged(const gfx::Rect& previous_bounds) override; bool GetNeedsNotificationWhenVisibleBoundsChange() const override; void OnVisibleBoundsChanged() override; - void OnEnabledChanged() override; void OnPaint(gfx::Canvas* canvas) override; void OnFocus() override; void OnBlur() override; @@ -522,6 +522,8 @@ // Returns the color to use for the FocusRing, if one is present. SkColor GetFocusRingColor() const; + void OnEnabledChanged(); + // The text model. std::unique_ptr<TextfieldModel> model_; @@ -657,6 +659,12 @@ // Extra insets, useful to make room for a button for example. gfx::Insets extra_insets_ = gfx::Insets(); + // Holds the subscription object for the enabled changed callback. + PropertyChangedSubscription enabled_changed_subscription_ = + AddEnabledChangedCallback( + base::BindRepeating(&Textfield::OnEnabledChanged, + base::Unretained(this))); + // Used to bind callback functions to this object. base::WeakPtrFactory<Textfield> weak_ptr_factory_;
diff --git a/ui/views/debug_utils.cc b/ui/views/debug_utils.cc index 859bef0..089fb79 100644 --- a/ui/views/debug_utils.cc +++ b/ui/views/debug_utils.cc
@@ -48,7 +48,7 @@ *out << '\n'; if (!view->children().empty()) - PrintFocusHierarchyImp(view->child_at(0), indent + 2, out); + PrintFocusHierarchyImp(view->children().front(), indent + 2, out); const View* next_focusable = view->GetNextFocusableView(); if (next_focusable)
diff --git a/ui/views/examples/layout_example_base.cc b/ui/views/examples/layout_example_base.cc index 9ff66d26..b098285 100644 --- a/ui/views/examples/layout_example_base.cc +++ b/ui/views/examples/layout_example_base.cc
@@ -48,8 +48,8 @@ void FullPanel::Layout() { DCHECK_EQ(2u, children().size()); - View* left_panel = child_at(0); - View* right_panel = child_at(1); + View* left_panel = children()[0]; + View* right_panel = children()[1]; gfx::Rect bounds = GetContentsBounds(); left_panel->SetBounds(bounds.x(), bounds.y(), (bounds.width() * 75) / 100, bounds.height());
diff --git a/ui/views/examples/scroll_view_example.cc b/ui/views/examples/scroll_view_example.cc index f254ca6..fa12476 100644 --- a/ui/views/examples/scroll_view_example.cc +++ b/ui/views/examples/scroll_view_example.cc
@@ -37,8 +37,8 @@ to_color_ = to; } - void PlaceChildY(int index, int y) { - View* view = child_at(index); + void PlaceChildY(size_t index, int y) { + View* view = children()[index]; gfx::Size size = view->GetPreferredSize(); view->SetBounds(0, y, size.width(), size.height()); }
diff --git a/ui/views/focus/focus_search.cc b/ui/views/focus/focus_search.cc index 026f0abe..e8f563b3 100644 --- a/ui/views/focus/focus_search.cc +++ b/ui/views/focus/focus_search.cc
@@ -194,8 +194,9 @@ if (can_go_down) { if (!starting_view->children().empty()) { View* v = FindNextFocusableViewImpl( - starting_view->child_at(0), StartingViewPolicy::kCheckStartingView, - false, true, can_go_into_anchored_dialog, skip_group_id, seen_views, + starting_view->children().front(), + StartingViewPolicy::kCheckStartingView, false, true, + can_go_into_anchored_dialog, skip_group_id, seen_views, focus_traversable, focus_traversable_view); if (v || *focus_traversable) return v;
diff --git a/ui/views/layout/flex_layout_unittest.cc b/ui/views/layout/flex_layout_unittest.cc index 009a270a..f2a9fc9 100644 --- a/ui/views/layout/flex_layout_unittest.cc +++ b/ui/views/layout/flex_layout_unittest.cc
@@ -1848,8 +1848,8 @@ class NestedFlexLayoutTest : public FlexLayoutTest { public: - void AddChildren(int num_children) { - for (int i = 0; i < num_children; ++i) { + void AddChildren(size_t num_children) { + for (size_t i = 0; i < num_children; ++i) { auto v = std::make_unique<View>(); FlexLayout* layout = v->SetLayoutManager(std::make_unique<FlexLayout>()); children_.push_back(v.get()); @@ -1859,20 +1859,20 @@ } View* AddGrandchild( - int child_index, + size_t child_index, const gfx::Size& preferred, const base::Optional<gfx::Size>& minimum = base::nullopt) { return AddChild(children_[child_index - 1], preferred, minimum); } - View* child(int child_index) const { return children_[child_index - 1]; } + View* child(size_t child_index) const { return children_[child_index - 1]; } - FlexLayout* layout(int child_index) const { + FlexLayout* layout(size_t child_index) const { return layouts_[child_index - 1]; } - View* grandchild(int child_index, int grandchild_index) const { - return children_[child_index - 1]->child_at(grandchild_index - 1); + View* grandchild(size_t child_index, size_t grandchild_index) const { + return children_[child_index - 1]->children()[grandchild_index - 1]; } private:
diff --git a/ui/views/layout/grid_layout_unittest.cc b/ui/views/layout/grid_layout_unittest.cc index e7869cc33..0f361466 100644 --- a/ui/views/layout/grid_layout_unittest.cc +++ b/ui/views/layout/grid_layout_unittest.cc
@@ -586,12 +586,12 @@ layout()->Layout(&host()); + auto i = host().children().cbegin(); for (size_t row = 0; row < kRowCount; ++row) { - for (size_t column = 0; column < kColumnCount; ++column) { - View* view = host().child_at(row * kColumnCount + column); + for (size_t column = 0; column < kColumnCount; ++column, ++i) { ExpectViewBoundsEquals( 2 + kTitleWidth * column + (kTitleWidth - kPrefWidth) / 2, - 2 + kPrefHeight * row, kPrefWidth, kPrefHeight, view); + 2 + kPrefHeight * row, kPrefWidth, kPrefHeight, *i); } }
diff --git a/ui/views/touchui/touch_selection_menu_runner_views.cc b/ui/views/touchui/touch_selection_menu_runner_views.cc index a853f47..9fd1616 100644 --- a/ui/views/touchui/touch_selection_menu_runner_views.cc +++ b/ui/views/touchui/touch_selection_menu_runner_views.cc
@@ -29,7 +29,7 @@ LabelButton* TouchSelectionMenuRunnerViews::TestApi::GetFirstButton() const { TouchSelectionMenuViews* menu = menu_runner_->menu_; - return menu ? static_cast<LabelButton*>(menu->child_at(0)) : nullptr; + return menu ? static_cast<LabelButton*>(menu->children().front()) : nullptr; } Widget* TouchSelectionMenuRunnerViews::TestApi::GetWidget() const {
diff --git a/ui/views/view.cc b/ui/views/view.cc index a70aea1..41be0d2 100644 --- a/ui/views/view.cc +++ b/ui/views/view.cc
@@ -461,10 +461,6 @@ enabled_ = is_enabled; AdvanceFocusIfNecessary(); OnPropertyChanged(&enabled_, kPropertyEffectsPaint); - - // TODO(kylixrd): Remove this once all overridden instances are refactored - // to use property change callback. - OnEnabledChanged(); } PropertyChangedSubscription View::AddEnabledChangedCallback( @@ -472,9 +468,6 @@ return AddPropertyChangedCallback(&enabled_, std::move(callback)); } -void View::OnEnabledChanged() { -} - View::Views View::GetChildrenInZOrder() { return children_; }
diff --git a/ui/views/view.h b/ui/views/view.h index f875502..faa1c0a 100644 --- a/ui/views/view.h +++ b/ui/views/view.h
@@ -1383,10 +1383,6 @@ // its ancestors. This is used for clipping NativeViewHost. virtual void OnVisibleBoundsChanged(); - // Override to be notified when the enabled state of this View has - // changed. The default implementation calls SchedulePaint() on this View. - virtual void OnEnabledChanged(); - bool needs_layout() const { return needs_layout_; } // Tree operations -----------------------------------------------------------
diff --git a/ui/views/view_unittest.cc b/ui/views/view_unittest.cc index 0332627..ebfd11ca 100644 --- a/ui/views/view_unittest.cc +++ b/ui/views/view_unittest.cc
@@ -71,7 +71,7 @@ // Convenience functions for walking a View tree. const views::View* FirstView(const views::View* view) { const views::View* v; - for (v = view; !v->children().empty(); v = v->child_at(0)) { + for (v = view; !v->children().empty(); v = v->children().front()) { } return v; } @@ -180,13 +180,13 @@ size_t count = view->children().size(); if (count > 1) { - const int max = int{count - 1}; - int a = base::RandInt(0, max); - int b = base::RandInt(0, max); + const uint64_t max = count - 1; + size_t a = size_t{base::RandGenerator(max)}; + size_t b = size_t{base::RandGenerator(max)}; if (a != b) { - views::View* view_a = view->child_at(a); - views::View* view_b = view->child_at(b); + views::View* view_a = view->children()[a]; + views::View* view_b = view->children()[b]; view->ReorderChildView(view_a, b); view->ReorderChildView(view_b, a); } @@ -4918,34 +4918,34 @@ }; TEST_F(ViewTest, ChildViewZOrderChanged) { - const int kChildrenCount = 4; + const size_t kNumChildren = 4; auto view = std::make_unique<OrderableView>(); view->SetPaintToLayer(); - for (int i = 0; i < kChildrenCount; ++i) + for (size_t i = 0; i < kNumChildren; ++i) AddViewWithChildLayer(view.get()); View::Views children = view->GetChildrenInZOrder(); const std::vector<ui::Layer*>& layers = view->layer()->children(); - EXPECT_EQ(kChildrenCount, static_cast<int>(layers.size())); - EXPECT_EQ(kChildrenCount, static_cast<int>(children.size())); - for (int i = 0; i < kChildrenCount; ++i) { - EXPECT_EQ(view->child_at(i), children[i]); - EXPECT_EQ(view->child_at(i)->layer(), layers[i]); + ASSERT_EQ(kNumChildren, children.size()); + ASSERT_EQ(kNumChildren, layers.size()); + for (size_t i = 0; i < kNumChildren; ++i) { + EXPECT_EQ(view->children()[i], children[i]); + EXPECT_EQ(view->children()[i]->layer(), layers[i]); } // Raise one of the children in z-order and add another child to reorder. - view->child_at(2)->set_id(OrderableView::VIEW_ID_RAISED); + view->children()[2]->set_id(OrderableView::VIEW_ID_RAISED); AddViewWithChildLayer(view.get()); // 2nd child should be now on top, i.e. the last element in the array returned // by GetChildrenInZOrder(). Its layer should also be above the others. // The rest of the children and layers order should be unchanged. - const int expected_order[] = {0, 1, 3, 4, 2}; + const size_t expected_order[] = {0, 1, 3, 4, 2}; children = view->GetChildrenInZOrder(); - EXPECT_EQ(kChildrenCount + 1, static_cast<int>(children.size())); - EXPECT_EQ(kChildrenCount + 1, static_cast<int>(layers.size())); - for (size_t i = 0; i < kChildrenCount + 1; ++i) { - EXPECT_EQ(view->child_at(expected_order[i]), children[i]); - EXPECT_EQ(view->child_at(expected_order[i])->layer(), layers[i]); + EXPECT_EQ(kNumChildren + 1, children.size()); + EXPECT_EQ(kNumChildren + 1, layers.size()); + for (size_t i = 0; i < kNumChildren + 1; ++i) { + EXPECT_EQ(view->children()[expected_order[i]], children[i]); + EXPECT_EQ(view->children()[expected_order[i]]->layer(), layers[i]); } }
diff --git a/ui/views/widget/root_view.cc b/ui/views/widget/root_view.cc index ca3f654..5b7654d 100644 --- a/ui/views/widget/root_view.cc +++ b/ui/views/widget/root_view.cc
@@ -197,7 +197,7 @@ } View* RootView::GetContentsView() { - return children().empty() ? nullptr : child_at(0); + return children().empty() ? nullptr : children().front(); } void RootView::NotifyNativeViewHierarchyChanged() {