diff --git a/.gn b/.gn index e29a1249..a534ebe 100644 --- a/.gn +++ b/.gn
@@ -354,7 +354,6 @@ "//third_party/pdfium:*", # 1 error "//third_party/private-join-and-compute/src:*", # 1 error "//third_party/wayland:*", # 3 errors - "//third_party/weston:*", # 1 error # //v8/*, https://crbug.com/v8/7330 "//v8/src/inspector:*", # 20 errors
diff --git a/DEPS b/DEPS index f620cd0..e7d767d 100644 --- a/DEPS +++ b/DEPS
@@ -195,7 +195,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'c1eb58de32c016eb60e7a46046321ffe351e8222', + 'skia_revision': '09357ccfa85a3a14c3a73adb2c70266bb7ea4057', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -211,7 +211,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': 'c5d08140dbebcdb01cd8debc7fcc2647599d0bb3', + 'swiftshader_revision': 'f272427bda39a1abf3aa6e1a1bdd9b628b5ea5b1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -266,7 +266,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '62ab4833a6a13ab1c863fa8a2682afea87447c77', + 'devtools_frontend_revision': '84d986f9a16ac7224e31dc2e7971ed94d60822ef', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -875,7 +875,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'a7bd9cbfeffaacb664d700322dcf236029605282', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '8fbd57f0d966a8a8785e13952df48f2859c351b1', 'condition': 'checkout_linux', }, @@ -1231,7 +1231,7 @@ Var('chromium_git') + '/external/github.com/cisco/openh264' + '@' + 'a5473711f3e20c6bd1c33d81b6c7b9a0618aa18f', 'src/third_party/openscreen/src': - Var('chromium_git') + '/openscreen' + '@' + 'b0b5891ddfacb9033d24b18e7495f5f0b664c863', + Var('chromium_git') + '/openscreen' + '@' + '921d95386ccd785317948682de4dd51c311e161a', 'src/third_party/openxr/src': { 'url': Var('chromium_git') + '/external/github.com/KhronosGroup/OpenXR-SDK' + '@' + '9e97b73e7dd2bfc07745489d728f6a36665c648f', @@ -1548,7 +1548,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@86079a48c1576f04239c4de46a1efcdd86d858d0', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@b4a89393df3ca518edeb1ad70ff954347ff802d0', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/aw_browser_context.cc b/android_webview/browser/aw_browser_context.cc index dbf71c0a..3c303ad 100644 --- a/android_webview/browser/aw_browser_context.cc +++ b/android_webview/browser/aw_browser_context.cc
@@ -276,7 +276,7 @@ base::MakeRefCounted<JsonPrefStore>(GetPrefStorePath()), persistent_prefs, mojo::Remote<::prefs::mojom::TrackedPreferenceValidationDelegate>())); - policy::URLBlacklistManager::RegisterProfilePrefs(pref_registry.get()); + policy::URLBlocklistManager::RegisterProfilePrefs(pref_registry.get()); AwBrowserPolicyConnector* browser_policy_connector = AwBrowserProcess::GetInstance()->browser_policy_connector(); pref_service_factory.set_managed_prefs(
diff --git a/android_webview/browser/aw_browser_policy_connector.cc b/android_webview/browser/aw_browser_policy_connector.cc index 3501719..29588e4f 100644 --- a/android_webview/browser/aw_browser_policy_connector.cc +++ b/android_webview/browser/aw_browser_policy_connector.cc
@@ -49,9 +49,9 @@ policy::key::kURLAllowlist, policy::policy_prefs::kUrlWhitelist, base::Value::Type::LIST))); handlers->AddHandler(std::make_unique<policy::SimpleDeprecatingPolicyHandler>( - std::make_unique<policy::URLBlacklistPolicyHandler>( + std::make_unique<policy::URLBlocklistPolicyHandler>( policy::key::kURLBlacklist), - std::make_unique<policy::URLBlacklistPolicyHandler>( + std::make_unique<policy::URLBlocklistPolicyHandler>( policy::key::kURLBlocklist))); // HTTP Negotiate authentication
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index 511761a..1a759996 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -628,7 +628,7 @@ throttles.push_back( navigation_interception::InterceptNavigationDelegate::CreateThrottleFor( navigation_handle, navigation_interception::SynchronyMode::kSync)); - throttles.push_back(std::make_unique<PolicyBlacklistNavigationThrottle>( + throttles.push_back(std::make_unique<PolicyBlocklistNavigationThrottle>( navigation_handle, AwBrowserContext::FromWebContents( navigation_handle->GetWebContents()))); throttles.push_back(
diff --git a/android_webview/browser/safe_browsing/README.md b/android_webview/browser/safe_browsing/README.md index 2e3036e3..94516e7 100644 --- a/android_webview/browser/safe_browsing/README.md +++ b/android_webview/browser/safe_browsing/README.md
@@ -29,7 +29,7 @@ The WebView we ship to users is based on downstream (private) build targets. If you need to test the GMS-based implementation which we use to block real malware, you need to build one of the downstream targets. See [Google-internal -instructions](http://go/clank-webview/building-webview/android_webview-tests). +instructions](http://go/clank-webview/build_instructions.md). ## Opt-in/consent/requirements
diff --git a/android_webview/docs/build-instructions.md b/android_webview/docs/build-instructions.md index 3244eb3..5348f1e0 100644 --- a/android_webview/docs/build-instructions.md +++ b/android_webview/docs/build-instructions.md
@@ -221,5 +221,5 @@ _TODO(ntfschr): document cases here which could arise generally, but wouldn't for the quick start._ -[1]: http://go/clank-webview/building-webview/android_webview-tests +[1]: http://go/clank-webview/build_instructions.md [2]: https://groups.google.com/a/chromium.org/forum/#!forum/android-webview-dev
diff --git a/android_webview/docs/device-setup.md b/android_webview/docs/device-setup.md index 8405259..7d596f6d 100644 --- a/android_webview/docs/device-setup.md +++ b/android_webview/docs/device-setup.md
@@ -45,7 +45,7 @@ ### Flash a prebuilt image Googlers can consult internal instructions -[here](http://go/clank-webview/building-webview/device-setup). +[here](http://go/clank-webview/device_setup.md). External contributors can flash a prebuilt userdebug image (based off aosp-master) onto a Pixel device with [Android Flash
diff --git a/android_webview/tools/webview_log_verbosifier/README.md b/android_webview/tools/webview_log_verbosifier/README.md index c618ad6..e6e05439 100644 --- a/android_webview/tools/webview_log_verbosifier/README.md +++ b/android_webview/tools/webview_log_verbosifier/README.md
@@ -22,8 +22,8 @@ We no longer support building the log verbosifier from source. Googlers can get a [prebuilt copy of the log -verbosifier](http://go/clank-webview/zzarchive/webview-manual-testing). External -contributors can request a precompiled copy by [emailing the WebView +verbosifier](http://go/clank-webview-legacy/zzarchive/webview-manual-testing). +External contributors can request a precompiled copy by [emailing the WebView team](https://groups.google.com/a/chromium.org/forum/#!forum/android-webview-dev). ## Searching logcat
diff --git a/ash/system/audio/mic_gain_slider_controller.cc b/ash/system/audio/mic_gain_slider_controller.cc index e1cbeee5..c323f7c 100644 --- a/ash/system/audio/mic_gain_slider_controller.cc +++ b/ash/system/audio/mic_gain_slider_controller.cc
@@ -59,6 +59,12 @@ if (reason != views::SliderChangeReason::kByUser) return; + // Unmute if muted. + if (CrasAudioHandler::Get()->IsInputMuted()) { + CrasAudioHandler::Get()->SetMuteForDevice( + CrasAudioHandler::Get()->GetPrimaryActiveInputNode(), false); + } + CrasAudioHandler::Get()->SetInputGainPercent(value * 100); }
diff --git a/ash/system/power/power_button_controller.cc b/ash/system/power/power_button_controller.cc index 83c068ff..43f332a8 100644 --- a/ash/system/power/power_button_controller.cc +++ b/ash/system/power/power_button_controller.cc
@@ -298,8 +298,11 @@ } void PowerButtonController::DismissMenu() { - if (IsMenuOpened()) + if (IsMenuOpened()) { + static_cast<PowerButtonMenuScreenView*>(menu_widget_->GetContentsView()) + ->ResetOpacity(); menu_widget_->Hide(); + } show_menu_animation_done_ = false; active_window_paint_as_active_lock_.reset(); @@ -437,12 +440,17 @@ active_toplevel_widget ? active_toplevel_widget->LockPaintAsActive() : nullptr; - if (!menu_widget_) + if (!menu_widget_) { menu_widget_ = CreateMenuWidget(); - menu_widget_->SetContentsView(std::make_unique<PowerButtonMenuScreenView>( - power_button_position_, power_button_offset_percentage_, - base::BindRepeating(&PowerButtonController::SetShowMenuAnimationDone, - base::Unretained(this)))); + menu_widget_->SetContentsView(std::make_unique<PowerButtonMenuScreenView>( + power_button_position_, power_button_offset_percentage_, + base::BindRepeating(&PowerButtonController::SetShowMenuAnimationDone, + base::Unretained(this)))); + } + auto* contents_view = + static_cast<PowerButtonMenuScreenView*>(menu_widget_->GetContentsView()); + contents_view->OnWidgetShown(power_button_position_, + power_button_offset_percentage_); menu_widget_->Show(); // Hide cursor, but let it reappear if the mouse moves. @@ -450,8 +458,7 @@ if (shell->cursor_manager()) shell->cursor_manager()->HideCursor(); - static_cast<PowerButtonMenuScreenView*>(menu_widget_->GetContentsView()) - ->ScheduleShowHideAnimation(true); + contents_view->ScheduleShowHideAnimation(true); } void PowerButtonController::ProcessCommandLine() {
diff --git a/ash/system/power/power_button_menu_item_view.cc b/ash/system/power/power_button_menu_item_view.cc index 46f8c6d1..fb39b81 100644 --- a/ash/system/power/power_button_menu_item_view.cc +++ b/ash/system/power/power_button_menu_item_view.cc
@@ -42,8 +42,6 @@ title_(new views::Label) { SetFocusBehavior(FocusBehavior::ALWAYS); SetFocusPainter(nullptr); - SetPaintToLayer(); - layer()->SetFillsBoundsOpaquely(false); const AshColorProvider* color_provider = AshColorProvider::Get(); icon_view_->SetImage(gfx::CreateVectorIcon(
diff --git a/ash/system/power/power_button_menu_screen_view.cc b/ash/system/power/power_button_menu_screen_view.cc index 1d4fd0f2..85732790 100644 --- a/ash/system/power/power_button_menu_screen_view.cc +++ b/ash/system/power/power_button_menu_screen_view.cc
@@ -67,6 +67,7 @@ layer()->SetColor(AshColorProvider::Get()->DeprecatedGetShieldLayerColor( AshColorProvider::ShieldLayerType::kShield60, kPowerButtonMenuFullscreenShieldColor)); + layer()->SetOpacity(0.f); } ~PowerButtonMenuBackgroundView() override = default; @@ -84,8 +85,8 @@ } void ScheduleShowHideAnimation(bool show) { + SetVisible(true); layer()->GetAnimator()->AbortAllAnimations(); - layer()->SetOpacity(show ? 0.f : layer()->opacity()); ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator()); animation.AddObserver(this); @@ -93,7 +94,8 @@ : gfx::Tween::FAST_OUT_LINEAR_IN); animation.SetTransitionDuration( PowerButtonMenuView::kMenuAnimationDuration); - + animation.SetPreemptionStrategy( + ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); layer()->SetOpacity(show ? kPowerButtonMenuOpacity : 0.f); } @@ -123,9 +125,6 @@ display::Screen::GetScreen()->AddObserver(this); - if (power_button_position_ != PowerButtonPosition::NONE) - InitializeMenuBoundsOrigins(); - AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); } @@ -138,6 +137,25 @@ power_button_menu_view_->ScheduleShowHideAnimation(show); } +void PowerButtonMenuScreenView::ResetOpacity() { + for (ui::Layer* layer : {power_button_screen_background_shield_->layer(), + power_button_menu_view_->layer()}) { + DCHECK(layer); + layer->SetOpacity(0.f); + } +} + +void PowerButtonMenuScreenView::OnWidgetShown( + PowerButtonController::PowerButtonPosition position, + double offset_percentage) { + power_button_position_ = position; + power_button_offset_percentage_ = offset_percentage; + if (power_button_position_ != PowerButtonPosition::NONE) + UpdateMenuBoundsOrigins(); + power_button_menu_view_->RecreateItems(); + Layout(); +} + const char* PowerButtonMenuScreenView::GetClassName() const { return "PowerButtonMenuScreenView"; } @@ -197,7 +215,7 @@ power_button_menu_view_->SetBoundsRect(GetMenuBounds()); } -void PowerButtonMenuScreenView::InitializeMenuBoundsOrigins() { +void PowerButtonMenuScreenView::UpdateMenuBoundsOrigins() { // Power button position offset in pixels from the top when the button is at // the left/right of the screen after rotation. int left_power_button_y = 0, right_power_button_y = 0; @@ -270,6 +288,7 @@ return; } + menu_bounds_origins_.clear(); const gfx::Size menu_size = power_button_menu_view_->GetPreferredSize(); // Power button position offset from the left when the button is at the left // is always zero.
diff --git a/ash/system/power/power_button_menu_screen_view.h b/ash/system/power/power_button_menu_screen_view.h index 0c2fe78..5aa0b8c0 100644 --- a/ash/system/power/power_button_menu_screen_view.h +++ b/ash/system/power/power_button_menu_screen_view.h
@@ -38,6 +38,15 @@ // Schedules an animation to show or hide the view. void ScheduleShowHideAnimation(bool show); + // Resets the shield and menu's opacity to 0. Used when dismissing the menu + // without animation to prepare for the next fade in animation. + void ResetOpacity(); + + // Called when the associated widget is shown. Updates power button related + // info and calculates |menu_bounds_origins_| if needed. Recreates menu items. + void OnWidgetShown(PowerButtonController::PowerButtonPosition position, + double offset_percentage); + // views::View: const char* GetClassName() const override; @@ -60,8 +69,8 @@ // Lays out the view without animation transform. void LayoutWithoutTransform(); - // Initializes |menu_bounds_origins_| according to power button position info. - void InitializeMenuBoundsOrigins(); + // Updates |menu_bounds_origins_| according to power button position info. + void UpdateMenuBoundsOrigins(); // Gets the bounds of power button menu. gfx::Rect GetMenuBounds();
diff --git a/ash/system/power/power_button_menu_view.cc b/ash/system/power/power_button_menu_view.cc index 4e9ccc1..9317e68 100644 --- a/ash/system/power/power_button_menu_view.cc +++ b/ash/system/power/power_button_menu_view.cc
@@ -4,6 +4,8 @@ #include "ash/system/power/power_button_menu_view.h" +#include <memory> + #include "ash/display/screen_orientation_controller.h" #include "ash/public/cpp/ash_features.h" #include "ash/public/cpp/new_window_delegate.h" @@ -19,8 +21,10 @@ #include "ash/wm/lock_state_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/canvas.h" +#include "ui/gfx/vector_icon_types.h" #include "ui/views/accessibility/view_accessibility.h" namespace ash { @@ -57,11 +61,11 @@ SetFocusBehavior(FocusBehavior::ALWAYS); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); + layer()->SetOpacity(0.f); GetViewAccessibility().OverrideRole(ax::mojom::Role::kMenu); GetViewAccessibility().OverrideName( l10n_util::GetStringUTF16(IDS_ASH_POWER_BUTTON_MENU_ACCESSIBLE)); - - CreateItems(); + RecreateItems(); } PowerButtonMenuView::~PowerButtonMenuView() = default; @@ -71,19 +75,17 @@ } void PowerButtonMenuView::ScheduleShowHideAnimation(bool show) { - // Cancel any previous animation. - layer()->GetAnimator()->AbortAllAnimations(); - // Set initial state. SetVisible(true); - layer()->SetOpacity(show ? 0.f : layer()->opacity()); + layer()->GetAnimator()->AbortAllAnimations(); ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator()); animation.AddObserver(this); animation.SetTweenType(show ? gfx::Tween::EASE_IN : gfx::Tween::FAST_OUT_LINEAR_IN); animation.SetTransitionDuration(kMenuAnimationDuration); - + animation.SetPreemptionStrategy( + ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); layer()->SetOpacity(show ? 1.0f : 0.f); // Animation of the menu view bounds change. @@ -145,43 +147,59 @@ return transform_displacement; } -const char* PowerButtonMenuView::GetClassName() const { - return "PowerButtonMenuView"; -} +void PowerButtonMenuView::RecreateItems() { + // Helper to add or remove a menu item from |this|. Stores weak pointer to + // |out_item_ptr|. + auto add_remove_item = [this]( + bool create, const gfx::VectorIcon& icon, + const base::string16& string, + PowerButtonMenuItemView** out_item_ptr) -> void { + // If an item needs to be created and exists, or needs to be destroyed but + // does not exist, there is nothing to be done. + if (create && *out_item_ptr) + return; + if (!create && !*out_item_ptr) + return; -void PowerButtonMenuView::CreateItems() { - power_off_item_ = new PowerButtonMenuItemView( - this, kSystemPowerButtonMenuPowerOffIcon, - l10n_util::GetStringUTF16(IDS_ASH_POWER_BUTTON_MENU_POWER_OFF_BUTTON)); - AddChildView(power_off_item_); + if (create) { + *out_item_ptr = AddChildView( + std::make_unique<PowerButtonMenuItemView>(this, icon, string)); + } else { + std::unique_ptr<PowerButtonMenuItemView> to_delete = + RemoveChildViewT(*out_item_ptr); + *out_item_ptr = nullptr; + } + }; const SessionControllerImpl* const session_controller = Shell::Get()->session_controller(); const LoginStatus login_status = session_controller->login_status(); - if (login_status != LoginStatus::NOT_LOGGED_IN) { - sign_out_item_ = new PowerButtonMenuItemView( - this, kSystemPowerButtonMenuSignOutIcon, - user::GetLocalizedSignOutStringForStatus(login_status, false)); - AddChildView(sign_out_item_); - } + const bool create_sign_out = login_status != LoginStatus::NOT_LOGGED_IN; + const bool create_lock_screen = login_status != LoginStatus::LOCKED && + session_controller->CanLockScreen(); + const bool create_feedback = login_status != LoginStatus::NOT_LOGGED_IN && + login_status != LoginStatus::LOCKED && + login_status != LoginStatus::KIOSK_APP; - if (login_status != LoginStatus::LOCKED && - session_controller->CanLockScreen()) { - lock_screen_item_ = new PowerButtonMenuItemView( - this, kSystemPowerButtonMenuLockScreenIcon, - l10n_util::GetStringUTF16( - IDS_ASH_POWER_BUTTON_MENU_LOCK_SCREEN_BUTTON)); - AddChildView(lock_screen_item_); - } + add_remove_item( + true, kSystemPowerButtonMenuPowerOffIcon, + l10n_util::GetStringUTF16(IDS_ASH_POWER_BUTTON_MENU_POWER_OFF_BUTTON), + &power_off_item_); + add_remove_item(create_sign_out, kSystemPowerButtonMenuSignOutIcon, + user::GetLocalizedSignOutStringForStatus(login_status, false), + &sign_out_item_); + add_remove_item( + create_lock_screen, kSystemPowerButtonMenuPowerOffIcon, + l10n_util::GetStringUTF16(IDS_ASH_POWER_BUTTON_MENU_LOCK_SCREEN_BUTTON), + &lock_screen_item_); + add_remove_item( + create_feedback, kSystemPowerButtonMenuPowerOffIcon, + l10n_util::GetStringUTF16(IDS_ASH_POWER_BUTTON_MENU_FEEDBACK_BUTTON), + &feedback_item_); +} - if (login_status != LoginStatus::NOT_LOGGED_IN && - login_status != LoginStatus::LOCKED && - login_status != LoginStatus::KIOSK_APP) { - feedback_item_ = new PowerButtonMenuItemView( - this, kSystemPowerButtonMenuFeedbackIcon, - l10n_util::GetStringUTF16(IDS_ASH_POWER_BUTTON_MENU_FEEDBACK_BUTTON)); - AddChildView(feedback_item_); - } +const char* PowerButtonMenuView::GetClassName() const { + return "PowerButtonMenuView"; } void PowerButtonMenuView::Layout() {
diff --git a/ash/system/power/power_button_menu_view.h b/ash/system/power/power_button_menu_view.h index 49268ba3..b2a1d81 100644 --- a/ash/system/power/power_button_menu_view.h +++ b/ash/system/power/power_button_menu_view.h
@@ -64,13 +64,14 @@ // Gets the transform displacement, which contains direction and distance. TransformDisplacement GetTransformDisplacement() const; + // Called whenever the associated widget is shown and when |this| is + // constructed. Adds/removes menu items as needed. + void RecreateItems(); + // views::View: const char* GetClassName() const override; private: - // Creates the items that in the menu. - void CreateItems(); - // views::View: void Layout() override; void OnPaint(gfx::Canvas* canvas) override;
diff --git a/base/allocator/partition_allocator/page_allocator_constants.h b/base/allocator/partition_allocator/page_allocator_constants.h index ca45567..9038da5 100644 --- a/base/allocator/partition_allocator/page_allocator_constants.h +++ b/base/allocator/partition_allocator/page_allocator_constants.h
@@ -47,6 +47,15 @@ static constexpr size_t kPageMetadataShift = 5; // 32 bytes per partition page. static constexpr size_t kPageMetadataSize = 1 << kPageMetadataShift; +// See DecommitSystemPages(), this is not guaranteed to be synchronous on all +// platforms. +static constexpr bool kDecommittedPagesAreAlwaysZeroed = +#if defined(OS_MACOSX) + false; +#else + true; +#endif + } // namespace base #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PAGE_ALLOCATOR_CONSTANTS_H_
diff --git a/base/allocator/partition_allocator/page_allocator_unittest.cc b/base/allocator/partition_allocator/page_allocator_unittest.cc index ff91b66..4f0488a5 100644 --- a/base/allocator/partition_allocator/page_allocator_unittest.cc +++ b/base/allocator/partition_allocator/page_allocator_unittest.cc
@@ -251,9 +251,10 @@ } #endif // defined(OS_ANDROID) -#if !defined(OS_MACOSX) - TEST(PageAllocatorTest, DecommitErasesMemory) { + if (!kDecommittedPagesAreAlwaysZeroed) + return; + size_t size = kPageAllocationGranularity; void* buffer = AllocPages(nullptr, size, kPageAllocationGranularity, PageReadWrite, PageTag::kChromium, true); @@ -274,8 +275,6 @@ FreePages(buffer, size); } -#endif // defined(OS_MACOSX) - TEST(PageAllocatorTest, MappedPagesAccounting) { size_t size = kPageAllocationGranularity; size_t mapped_size_before = GetTotalMappedSize();
diff --git a/base/allocator/partition_allocator/partition_alloc.h b/base/allocator/partition_allocator/partition_alloc.h index 8c85ad2..a3a286c6 100644 --- a/base/allocator/partition_allocator/partition_alloc.h +++ b/base/allocator/partition_allocator/partition_alloc.h
@@ -863,7 +863,7 @@ // Handle cases such as size = 16, alignment = 64. // Wastes memory when a large alignment is requested with a small size, but // this is hard to avoid, and should not be too common. - if (size < alignment) { + if (UNLIKELY(size < alignment)) { ptr = Alloc(alignment, ""); } else { // PartitionAlloc only guarantees alignment for power-of-two sized @@ -875,7 +875,10 @@ ptr = Alloc(size_rounded_up, ""); } - PA_CHECK(reinterpret_cast<uintptr_t>(ptr) % alignment == 0ull); + // |alignment| is a power of two, but the compiler doesn't necessarily know + // that. A regular % operation is very slow, make sure to use the equivalent, + // faster form. + PA_CHECK(!(reinterpret_cast<uintptr_t>(ptr) & (alignment - 1))); return ptr; }
diff --git a/base/allocator/partition_allocator/partition_bucket.cc b/base/allocator/partition_allocator/partition_bucket.cc index e8c58a318..993af9f 100644 --- a/base/allocator/partition_allocator/partition_bucket.cc +++ b/base/allocator/partition_allocator/partition_bucket.cc
@@ -567,6 +567,7 @@ PartitionExcessiveAllocationSize(size); } new_page = PartitionDirectMap(root, flags, size); + // New pages from PageAllocator are always zeroed. *is_already_zeroed = true; } else if (LIKELY(SetNewActivePage())) { // First, did we find an active page in the active pages list? @@ -598,9 +599,7 @@ void* addr = PartitionPage<thread_safe>::ToPointer(new_page); root->RecommitSystemPages(addr, new_page->bucket->get_bytes_per_span()); new_page->Reset(); - // TODO(https://crbug.com/890752): Optimizing here might cause pages to - // not be zeroed. - // *is_already_zeroed = true; + *is_already_zeroed = kDecommittedPagesAreAlwaysZeroed; } PA_DCHECK(new_page); } else { @@ -611,9 +610,8 @@ new_page = PartitionPage<thread_safe>::FromPointerNoAlignmentCheck(raw_pages); InitializeSlotSpan(new_page); - // TODO(https://crbug.com/890752): Optimizing here causes pages to not be - // zeroed on at least macOS. - // *is_already_zeroed = true; + // New pages from PageAllocator are always zeroed. + *is_already_zeroed = true; } }
diff --git a/base/i18n/file_util_icu_unittest.cc b/base/i18n/file_util_icu_unittest.cc index 72e65f2..e1517df 100644 --- a/base/i18n/file_util_icu_unittest.cc +++ b/base/i18n/file_util_icu_unittest.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include "base/files/file_util.h" +#include "base/logging.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h"
diff --git a/base/i18n/rtl_unittest.cc b/base/i18n/rtl_unittest.cc index 8722310..6846bac 100644 --- a/base/i18n/rtl_unittest.cc +++ b/base/i18n/rtl_unittest.cc
@@ -9,6 +9,7 @@ #include <algorithm> #include "base/files/file_path.h" +#include "base/logging.h" #include "base/macros.h" #include "base/strings/string_util.h" #include "base/strings/sys_string_conversions.h"
diff --git a/base/strings/string_util_win.h b/base/strings/string_util_win.h index cd4bb2f..0756608d 100644 --- a/base/strings/string_util_win.h +++ b/base/strings/string_util_win.h
@@ -147,7 +147,7 @@ BASE_EXPORT bool TrimString(WStringPiece input, WStringPiece trim_chars, - std::string* output); + std::wstring* output); BASE_EXPORT WStringPiece TrimString(WStringPiece input, WStringPiece trim_chars,
diff --git a/base/task/thread_pool/job_task_source.cc b/base/task/thread_pool/job_task_source.cc index 1e6b04c8..9fd1d3f 100644 --- a/base/task/thread_pool/job_task_source.cc +++ b/base/task/thread_pool/job_task_source.cc
@@ -18,6 +18,7 @@ #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "base/time/time_override.h" +#include "base/trace_event/base_tracing.h" namespace base { namespace internal { @@ -34,48 +35,6 @@ } // namespace -// Memory ordering on |state_| operations -// -// The write operation on |state_| in WillRunTask() uses -// std::memory_order_release, matched by std::memory_order_acquire on read -// operations (in DidProcessTask()) to establish a -// Release-Acquire ordering. When a call to WillRunTask() is caused by an -// increase of max concurrency followed by an associated -// NotifyConcurrencyIncrease(), the priority queue lock guarantees an -// happens-after relation with NotifyConcurrencyIncrease(). This ensures that an -// increase of max concurrency that happened-before NotifyConcurrencyIncrease() -// is visible to a read operation that happens-after WillRunTask(). -// -// In DidProcessTask(), this is necessary to -// ensure that the task source is always re-enqueued when it needs to. When the -// task source needs to be queued, either because the current task yielded or -// because of NotifyConcurrencyIncrease(), one of the following is true: -// A) DidProcessTask() happens-after WillRunTask(): -// T1: Current task returns (because it is done) or yields. -// T2: Increases the value returned by GetMaxConcurrency() -// NotifyConcurrencyIncrease() enqueues the task source -// T3: WillRunTask(), in response to the concurrency increase - Release -// Does not keep the TaskSource in PriorityQueue because it is at max -// concurrency -// T1: DidProcessTask() - Acquire - Because of memory barrier, sees the same -// (or newer) max concurrency as T2 -// Re-enqueues the TaskSource because no longer at max concurrency -// Without the memory barrier, T1 may see an outdated max concurrency that -// is lower than the actual max concurrency and won't re-enqueue the -// task source, because it thinks it's already saturated. -// The task source often needs to be re-enqueued if its task -// completed because it yielded and |max_concurrency| wasn't decreased. -// B) DidProcessTask() happens-before WillRunTask(): -// T1: Current task returns (because it is done) or yields -// T2: Increases the value returned by GetMaxConcurrency() -// NotifyConcurrencyIncrease() enqueues the task source -// T1: DidProcessTask() - Acquire (ineffective) -// Since the task source is already in the queue, it doesn't matter -// whether T1 re-enqueues the task source or not. -// Note that stale values the other way around can cause incorrectly -// re-enqueuing this task_source, which is not an issue because the queues -// support empty task sources. - JobTaskSource::State::State() = default; JobTaskSource::State::~State() = default; @@ -83,46 +42,19 @@ return {value_.fetch_or(kCanceledMask, std::memory_order_relaxed)}; } -JobTaskSource::State::Value -JobTaskSource::State::TryIncrementWorkerCountFromWorkerRelease( - size_t max_concurrency) { - uint32_t value_before_add = value_.load(std::memory_order_relaxed); - - // std::memory_order_release on success to establish Release-Acquire ordering - // with DecrementWorkerCountAcquire() (see Memory Ordering comment at top of - // the file). - while (!(value_before_add & kCanceledMask) && - (value_before_add >> kWorkerCountBitOffset) < max_concurrency && - !value_.compare_exchange_weak( - value_before_add, value_before_add + kWorkerCountIncrement, - std::memory_order_release, std::memory_order_relaxed)) { - } - return {value_before_add}; -} - -JobTaskSource::State::Value -JobTaskSource::State::DecrementWorkerCountFromWorkerAcquire() { - const size_t value_before_sub = - value_.fetch_sub(kWorkerCountIncrement, std::memory_order_acquire); - DCHECK((value_before_sub >> kWorkerCountBitOffset) > 0); - return {value_before_sub}; -} - -JobTaskSource::State::Value -JobTaskSource::State::IncrementWorkerCountFromJoiningThread() { - size_t value_before_add = - value_.fetch_add(kWorkerCountIncrement, std::memory_order_relaxed); - return {value_before_add}; -} - -JobTaskSource::State::Value -JobTaskSource::State::DecrementWorkerCountFromJoiningThread() { +JobTaskSource::State::Value JobTaskSource::State::DecrementWorkerCount() { const size_t value_before_sub = value_.fetch_sub(kWorkerCountIncrement, std::memory_order_relaxed); DCHECK((value_before_sub >> kWorkerCountBitOffset) > 0); return {value_before_sub}; } +JobTaskSource::State::Value JobTaskSource::State::IncrementWorkerCount() { + size_t value_before_add = + value_.fetch_add(kWorkerCountIncrement, std::memory_order_relaxed); + return {value_before_add}; +} + JobTaskSource::State::Value JobTaskSource::State::Load() const { return {value_.load(std::memory_order_relaxed)}; } @@ -167,6 +99,12 @@ queue_time_(TimeTicks::Now()), delegate_(delegate) { DCHECK(delegate_); +#if DCHECK_IS_ON() + version_condition_for_dcheck_ = worker_lock_.CreateConditionVariable(); + // Prevent wait from triggering a ScopedBlockingCall as this would add + // complexity outside this DCHECK-only code. + version_condition_for_dcheck_->declare_only_used_while_idle(); +#endif // DCHECK_IS_ON() } JobTaskSource::~JobTaskSource() { @@ -179,15 +117,14 @@ } bool JobTaskSource::WillJoin() { - { - CheckedAutoLock auto_lock(lock_); - DCHECK(!worker_released_condition_); // This may only be called once. - worker_released_condition_ = lock_.CreateConditionVariable(); - } - // std::memory_order_relaxed on |worker_count_| is sufficient because call to - // GetMaxConcurrency() is used for a best effort early exit. Stale values will - // only cause WaitForParticipationOpportunity() to be called. - const auto state_before_add = state_.IncrementWorkerCountFromJoiningThread(); + TRACE_EVENT0("base", "Job.WaitForParticipationOpportunity"); + CheckedAutoLock auto_lock(worker_lock_); + DCHECK(!worker_released_condition_); // This may only be called once. + worker_released_condition_ = worker_lock_.CreateConditionVariable(); + // Prevent wait from triggering a ScopedBlockingCall as this would cause + // |ThreadGroup::lock_| to be acquired, causing lock inversion. + worker_released_condition_->declare_only_used_while_idle(); + const auto state_before_add = state_.IncrementWorkerCount(); if (!state_before_add.is_canceled() && state_before_add.worker_count() < GetMaxConcurrency()) { @@ -200,33 +137,34 @@ JobDelegate job_delegate{this, nullptr}; worker_task_.Run(&job_delegate); - // std::memory_order_relaxed on |worker_count_| is sufficient because the call - // to GetMaxConcurrency() is used for a best effort early exit. Stale values - // will only cause WaitForParticipationOpportunity() to be called. - const auto state = state_.Load(); + // It is safe to read |state_| without a lock since this variable is atomic + // and the call to GetMaxConcurrency() is used for a best effort early exit. + // Stale values will only cause WaitForParticipationOpportunity() to be + // called. + const auto state = TS_UNCHECKED_READ(state_).Load(); if (!state.is_canceled() && state.worker_count() <= GetMaxConcurrency()) return true; + TRACE_EVENT0("base", "Job.WaitForParticipationOpportunity"); + CheckedAutoLock auto_lock(worker_lock_); return WaitForParticipationOpportunity(); } void JobTaskSource::Cancel(TaskSource::Transaction* transaction) { + CheckedAutoLock auto_lock(worker_lock_); // Sets the kCanceledMask bit on |state_| so that further calls to // WillRunTask() never succeed. std::memory_order_relaxed is sufficient // because this task source never needs to be re-enqueued after Cancel(). state_.Cancel(); #if DCHECK_IS_ON() - { - AutoLock auto_lock(version_lock_); ++increase_version_; - version_condition_.Broadcast(); - } + version_condition_for_dcheck_->Broadcast(); #endif // DCHECK_IS_ON() } +// EXCLUSIVE_LOCK_REQUIRED(worker_lock_) bool JobTaskSource::WaitForParticipationOpportunity() { - CheckedAutoLock auto_lock(lock_); DCHECK(!join_flag_.IsWaiting()); // std::memory_order_relaxed is sufficient because no other state is @@ -259,16 +197,19 @@ // Only the joining thread remains. DCHECK_EQ(state.worker_count(), 1U); DCHECK(state.is_canceled() || max_concurrency == 0U); - state_.DecrementWorkerCountFromJoiningThread(); + state_.DecrementWorkerCount(); return false; } TaskSource::RunStatus JobTaskSource::WillRunTask() { + CheckedAutoLock auto_lock(worker_lock_); + const size_t max_concurrency = GetMaxConcurrency(); - // std::memory_order_release on success to establish Release-Acquire ordering - // with read operations (see Memory Ordering comment at top of the file). - const auto state_before_add = - state_.TryIncrementWorkerCountFromWorkerRelease(max_concurrency); + auto state_before_add = state_.Load(); + if (!state_before_add.is_canceled() && + state_before_add.worker_count() < max_concurrency) { + state_before_add = state_.IncrementWorkerCount(); + } // Don't allow this worker to run the task if either: // A) |state_| was canceled. @@ -289,9 +230,9 @@ } size_t JobTaskSource::GetRemainingConcurrency() const { - // std::memory_order_relaxed is sufficient because no other state is - // synchronized with GetRemainingConcurrency(). - const auto state = state_.Load(); + // It is safe to read |state_| without a lock since this variable is atomic, + // and no other state is synchronized with GetRemainingConcurrency(). + const auto state = TS_UNCHECKED_READ(state_).Load(); const size_t max_concurrency = GetMaxConcurrency(); // Avoid underflows. if (state.is_canceled() || state.worker_count() > max_concurrency) @@ -302,9 +243,9 @@ void JobTaskSource::NotifyConcurrencyIncrease() { #if DCHECK_IS_ON() { - AutoLock auto_lock(version_lock_); + CheckedAutoLock auto_lock(worker_lock_); ++increase_version_; - version_condition_.Broadcast(); + version_condition_for_dcheck_->Broadcast(); } #endif // DCHECK_IS_ON() @@ -316,7 +257,7 @@ { // Lock is taken to access |join_flag_| below and signal // |worker_released_condition_|. - CheckedAutoLock auto_lock(lock_); + CheckedAutoLock auto_lock(worker_lock_); if (join_flag_.ShouldWorkerSignal()) worker_released_condition_->Signal(); } @@ -358,22 +299,22 @@ } bool JobTaskSource::ShouldYield() { - // It is safe to read |join_flag_| without a lock since this - // variable is atomic, keeping in mind that threads may not immediately see + // It is safe to read |join_flag_| and |state_| without a lock since these + // variables are atomic, keeping in mind that threads may not immediately see // the new value when it is updated. return TS_UNCHECKED_READ(join_flag_).ShouldWorkerYield() || - state_.Load().is_canceled(); + TS_UNCHECKED_READ(state_).Load().is_canceled(); } #if DCHECK_IS_ON() size_t JobTaskSource::GetConcurrencyIncreaseVersion() const { - AutoLock auto_lock(version_lock_); + CheckedAutoLock auto_lock(worker_lock_); return increase_version_; } bool JobTaskSource::WaitForConcurrencyIncreaseUpdate(size_t recorded_version) { - AutoLock auto_lock(version_lock_); + CheckedAutoLock auto_lock(worker_lock_); constexpr TimeDelta timeout = TimeDelta::FromSeconds(1); const base::TimeTicks start_time = subtle::TimeTicksNowIgnoringOverride(); do { @@ -384,7 +325,7 @@ // Waiting is acceptable because it is in DCHECK-only code. ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_base_sync_primitives; - version_condition_.TimedWait(timeout); + version_condition_for_dcheck_->TimedWait(timeout); } while (subtle::TimeTicksNowIgnoringOverride() - start_time < timeout); return false; } @@ -394,21 +335,16 @@ Task JobTaskSource::TakeTask(TaskSource::Transaction* transaction) { // JobTaskSource members are not lock-protected so no need to acquire a lock // if |transaction| is nullptr. - DCHECK_GT(state_.Load().worker_count(), 0U); + DCHECK_GT(TS_UNCHECKED_READ(state_).Load().worker_count(), 0U); DCHECK(primary_task_); return Task(from_here_, primary_task_, TimeDelta()); } -bool JobTaskSource::DidProcessTask(TaskSource::Transaction* transaction) { +bool JobTaskSource::DidProcessTask(TaskSource::Transaction* /*transaction*/) { // Lock is needed to access |join_flag_| below and signal - // |worker_released_condition_|. If |transaction|, then |lock_| is already - // taken. - CheckedAutoLockMaybe auto_lock(transaction ? nullptr : &lock_); - AnnotateAcquiredLockAlias annotate(lock_, lock_); - - // std::memory_order_acquire to establish Release-Acquire ordering with - // WillRunTask() (see Memory Ordering comment at top of the file). - const auto state_before_sub = state_.DecrementWorkerCountFromWorkerAcquire(); + // |worker_released_condition_|. + CheckedAutoLock auto_lock(worker_lock_); + const auto state_before_sub = state_.DecrementWorkerCount(); if (join_flag_.ShouldWorkerSignal()) worker_released_condition_->Signal();
diff --git a/base/task/thread_pool/job_task_source.h b/base/task/thread_pool/job_task_source.h index 7b8c13e4..43b6a7ed 100644 --- a/base/task/thread_pool/job_task_source.h +++ b/base/task/thread_pool/job_task_source.h
@@ -15,7 +15,7 @@ #include "base/macros.h" #include "base/optional.h" #include "base/synchronization/condition_variable.h" -#include "base/synchronization/lock.h" +#include "base/task/common/checked_lock.h" #include "base/task/post_job.h" #include "base/task/task_traits.h" #include "base/task/thread_pool/sequence_sort_key.h" @@ -91,7 +91,9 @@ private: // Atomic internal state to track the number of workers running a task from - // this JobTaskSource and whether this JobTaskSource is canceled. + // this JobTaskSource and whether this JobTaskSource is canceled. All + // operations are performed with std::memory_order_relaxed as State is only + // ever modified under a lock or read atomically (optimistic read). class State { public: static constexpr size_t kCanceledMask = 1; @@ -109,28 +111,17 @@ State(); ~State(); - // Sets as canceled using std::memory_order_relaxed. Returns the state + // Sets as canceled. Returns the state // before the operation. Value Cancel(); - // Increments the worker count by 1 if smaller than |max_concurrency| and if - // |!is_canceled()|, using std::memory_order_release, and returns the state - // before the operation. Equivalent to Load() otherwise. - Value TryIncrementWorkerCountFromWorkerRelease(size_t max_concurrency); + // Increments the worker count by 1. Returns the state before the operation. + Value IncrementWorkerCount(); - // Decrements the worker count by 1 using std::memory_order_acquire. Returns - // the state before the operation. - Value DecrementWorkerCountFromWorkerAcquire(); + // Decrements the worker count by 1. Returns the state before the operation. + Value DecrementWorkerCount(); - // Increments the worker count by 1 using std::memory_order_relaxed. Returns - // the state before the operation. - Value IncrementWorkerCountFromJoiningThread(); - - // Decrements the worker count by 1 using std::memory_order_relaxed. Returns - // the state before the operation. - Value DecrementWorkerCountFromJoiningThread(); - - // Loads and returns the state, using std::memory_order_relaxed. + // Loads and returns the state. Value Load() const; private: @@ -186,7 +177,7 @@ // DidProcessTask()). Returns true if the joining thread should run a task, or // false if joining was completed and all other workers returned because // either there's no work remaining or Job was cancelled. - bool WaitForParticipationOpportunity(); + bool WaitForParticipationOpportunity() EXCLUSIVE_LOCKS_REQUIRED(worker_lock_); // TaskSource: RunStatus WillRunTask() override; @@ -195,15 +186,20 @@ bool DidProcessTask(TaskSource::Transaction* transaction) override; SequenceSortKey GetSortKey() const override; - // Current atomic state. - State state_; - std::atomic<uint32_t> assigned_task_ids_{0}; + // Synchronizes access to workers state. + mutable CheckedLock worker_lock_{UniversalSuccessor()}; + + // Current atomic state (atomic despite the lock to allow optimistic reads + // without the lock). + State state_ GUARDED_BY(worker_lock_); // Normally, |join_flag_| is protected by |lock_|, except in ShouldYield() // hence the use of atomics. - JoinFlag join_flag_ GUARDED_BY(lock_); + JoinFlag join_flag_ GUARDED_BY(worker_lock_); // Signaled when |join_flag_| is kWaiting* and a worker returns. std::unique_ptr<ConditionVariable> worker_released_condition_ - GUARDED_BY(lock_); + GUARDED_BY(worker_lock_); + + std::atomic<uint32_t> assigned_task_ids_{0}; const Location from_here_; RepeatingCallback<size_t()> max_concurrency_callback_; @@ -217,12 +213,10 @@ PooledTaskRunnerDelegate* delegate_; #if DCHECK_IS_ON() - // Synchronizes accesses to |increase_version_|. - mutable Lock version_lock_; - // Signaled whenever increase_version_ is updated. - ConditionVariable version_condition_{&version_lock_}; + // Signaled whenever |increase_version_| is updated. + std::unique_ptr<ConditionVariable> version_condition_for_dcheck_; // Incremented every time max concurrency is increased. - size_t increase_version_ GUARDED_BY(version_lock_) = 0; + size_t increase_version_ GUARDED_BY(worker_lock_) = 0; #endif // DCHECK_IS_ON() DISALLOW_COPY_AND_ASSIGN(JobTaskSource);
diff --git a/base/util/ranges/algorithm.h b/base/util/ranges/algorithm.h index 2c95a02..2669487 100644 --- a/base/util/ranges/algorithm.h +++ b/base/util/ranges/algorithm.h
@@ -792,7 +792,7 @@ // the first and second range, this is currently not supported due to // dispatching to std::is_permutation, which demands that `pred` is an // equivalence relation. -// TODO(https://crbug.com/1071094): Consider supporing different projections in +// TODO(https://crbug.com/1071094): Consider supporting different projections in // the future. // // Reference: @@ -2453,27 +2453,335 @@ // [sort] sort // Reference: https://wg21.link/sort -// TODO(crbug.com/1071094): Implement. +// Effects: Sorts the elements in the range `[first, last)` with respect to +// `comp` and `proj`. +// +// Returns: `last`. +// +// Complexity: Let `N` be `last - first`. `O(N log N)` comparisons and +// projections. +// +// Reference: https://wg21.link/sort#:~:text=ranges::sort(I +template <typename RandomAccessIterator, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::iterator_category_t<RandomAccessIterator>, + typename = indirect_result_t<Comp&, + projected<RandomAccessIterator, Proj>, + projected<RandomAccessIterator, Proj>>> +constexpr auto sort(RandomAccessIterator first, + RandomAccessIterator last, + Comp comp = {}, + Proj proj = {}) { + std::sort(first, last, internal::ProjectedBinaryPredicate(comp, proj, proj)); + return last; +} + +// Effects: Sorts the elements in `range` with respect to `comp` and `proj`. +// +// Returns: `end(range)`. +// +// Complexity: Let `N` be `size(range)`. `O(N log N)` comparisons and +// projections. +// +// Reference: https://wg21.link/sort#:~:text=ranges::sort(R +template <typename Range, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::range_category_t<Range>, + typename = indirect_result_t<Comp&, + projected<iterator_t<Range>, Proj>, + projected<iterator_t<Range>, Proj>>> +constexpr auto sort(Range&& range, Comp comp = {}, Proj proj = {}) { + return ranges::sort(ranges::begin(range), ranges::end(range), std::move(comp), + std::move(proj)); +} // [stable.sort] stable_sort // Reference: https://wg21.link/stable.sort -// TODO(crbug.com/1071094): Implement. +// Effects: Sorts the elements in the range `[first, last)` with respect to +// `comp` and `proj`. +// +// Returns: `last`. +// +// Complexity: Let `N` be `last - first`. If enough extra memory is available, +// `N log (N)` comparisons. Otherwise, at most `N log^2 (N)` comparisons. In +// either case, twice as many projections as the number of comparisons. +// +// Remarks: Stable. +// +// Reference: https://wg21.link/stable.sort#:~:text=ranges::stable_sort(I +template <typename RandomAccessIterator, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::iterator_category_t<RandomAccessIterator>, + typename = indirect_result_t<Comp&, + projected<RandomAccessIterator, Proj>, + projected<RandomAccessIterator, Proj>>> +constexpr auto stable_sort(RandomAccessIterator first, + RandomAccessIterator last, + Comp comp = {}, + Proj proj = {}) { + std::stable_sort(first, last, + internal::ProjectedBinaryPredicate(comp, proj, proj)); + return last; +} + +// Effects: Sorts the elements in `range` with respect to `comp` and `proj`. +// +// Returns: `end(rang)`. +// +// Complexity: Let `N` be `size(range)`. If enough extra memory is available, +// `N log (N)` comparisons. Otherwise, at most `N log^2 (N)` comparisons. In +// either case, twice as many projections as the number of comparisons. +// +// Remarks: Stable. +// +// Reference: https://wg21.link/stable.sort#:~:text=ranges::stable_sort(R +template <typename Range, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::range_category_t<Range>, + typename = indirect_result_t<Comp&, + projected<iterator_t<Range>, Proj>, + projected<iterator_t<Range>, Proj>>> +constexpr auto stable_sort(Range&& range, Comp comp = {}, Proj proj = {}) { + return ranges::stable_sort(ranges::begin(range), ranges::end(range), + std::move(comp), std::move(proj)); +} // [partial.sort] partial_sort // Reference: https://wg21.link/partial.sort -// TODO(crbug.com/1071094): Implement. +// Preconditions: `[first, middle)` and `[middle, last)` are valid ranges. +// +// Effects: Places the first `middle - first` elements from the range +// `[first, last)` as sorted with respect to `comp` and `proj` into the range +// `[first, middle)`. The rest of the elements in the range `[middle, last)` are +// placed in an unspecified order. +// +// Returns: `last`. +// +// Complexity: Approximately `(last - first) * log(middle - first)` comparisons, +// and twice as many projections. +// +// Reference: https://wg21.link/partial.sort#:~:text=ranges::partial_sort(I +template <typename RandomAccessIterator, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::iterator_category_t<RandomAccessIterator>, + typename = indirect_result_t<Comp&, + projected<RandomAccessIterator, Proj>, + projected<RandomAccessIterator, Proj>>> +constexpr auto partial_sort(RandomAccessIterator first, + RandomAccessIterator middle, + RandomAccessIterator last, + Comp comp = {}, + Proj proj = {}) { + std::partial_sort(first, middle, last, + internal::ProjectedBinaryPredicate(comp, proj, proj)); + return last; +} + +// Preconditions: `[begin(range), middle)` and `[middle, end(range))` are valid +// ranges. +// +// Effects: Places the first `middle - begin(range)` elements from `range` as +// sorted with respect to `comp` and `proj` into the range +// `[begin(range), middle)`. The rest of the elements in the range +// `[middle, end(range))` are placed in an unspecified order. +// +// Returns: `end(range)`. +// +// Complexity: Approximately `size(range) * log(middle - begin(range))` +// comparisons, and twice as many projections. +// +// Reference: https://wg21.link/partial.sort#:~:text=ranges::partial_sort(R +template <typename Range, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::range_category_t<Range>, + typename = indirect_result_t<Comp&, + projected<iterator_t<Range>, Proj>, + projected<iterator_t<Range>, Proj>>> +constexpr auto partial_sort(Range&& range, + iterator_t<Range> middle, + Comp comp = {}, + Proj proj = {}) { + return ranges::partial_sort(ranges::begin(range), middle, ranges::end(range), + std::move(comp), std::move(proj)); +} // [partial.sort.copy] partial_sort_copy // Reference: https://wg21.link/partial.sort.copy -// TODO(crbug.com/1071094): Implement. +// Let `N` be `min(last - first, result_last - result_first)`. +// +// Preconditions: For iterators `a1` and `b1` in `[first, last)`, and iterators +// `x2` and `y2` in `[result_first, result_last)`, after evaluating the +// assignment `*y2 = *b1`, let `E` be the value of `bool(invoke(comp, +// invoke(proj1, *a1), invoke(proj2, *y2)))`. Then, after evaluating the +// assignment `*x2 = *a1`, `E` is equal to `bool(invoke(comp, invoke(proj2, +// *x2), invoke(proj2, *y2)))`. +// +// Effects: Places the first `N` elements as sorted with respect to `comp` and +// `proj2` into the range `[result_first, result_first + N)`. +// +// Returns: `result_first + N`. +// +// Complexity: Approximately `(last - first) * log N` comparisons, and twice as +// many projections. +// +// Reference: +// https://wg21.link/partial.sort.copy#:~:text=ranges::partial_sort_copy(I1 +// +// Note: Currently different projections are not supported due to some +// incompatible validation logic within libc++. +// TODO(https://crbug.com/1071094): Consider supporting different projections in +// the future. +template <typename InputIterator, + typename RandomAccessIterator, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::iterator_category_t<InputIterator>, + typename = internal::iterator_category_t<RandomAccessIterator>, + typename = indirect_result_t<Comp&, + projected<InputIterator, Proj>, + projected<RandomAccessIterator, Proj>>> +constexpr auto partial_sort_copy(InputIterator first, + InputIterator last, + RandomAccessIterator result_first, + RandomAccessIterator result_last, + Comp comp = {}, + Proj proj = {}) { + return std::partial_sort_copy( + first, last, result_first, result_last, + internal::ProjectedBinaryPredicate(comp, proj, proj)); +} + +// Let `N` be `min(size(range), size(result_range))`. +// +// Preconditions: For iterators `a1` and `b1` in `range`, and iterators +// `x2` and `y2` in `result_range`, after evaluating the assignment +// `*y2 = *b1`, let `E` be the value of +// `bool(invoke(comp, invoke(proj1, *a1), invoke(proj2, *y2)))`. Then, after +// evaluating the assignment `*x2 = *a1`, `E` is equal to +// `bool(invoke(comp, invoke(proj2, *x2), invoke(proj2, *y2)))`. +// +// Effects: Places the first `N` elements as sorted with respect to `comp` and +// `proj2` into the range `[begin(result_range), begin(result_range) + N)`. +// +// Returns: `begin(result_range) + N`. +// +// Complexity: Approximately `size(range) * log N` comparisons, and twice as +// many projections. +// +// Reference: +// https://wg21.link/partial.sort.copy#:~:text=ranges::partial_sort_copy(R1 +// +// Note: Currently different projections are not supported due to some +// incompatible validation logic within libc++. +// TODO(https://crbug.com/1071094): Consider supporting different projections in +// the future. +template <typename Range1, + typename Range2, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::range_category_t<Range1>, + typename = internal::range_category_t<Range2>, + typename = indirect_result_t<Comp&, + projected<iterator_t<Range1>, Proj>, + projected<iterator_t<Range2>, Proj>>> +constexpr auto partial_sort_copy(Range1&& range, + Range2&& result_range, + Comp comp = {}, + Proj proj = {}) { + return ranges::partial_sort_copy( + ranges::begin(range), ranges::end(range), ranges::begin(result_range), + ranges::end(result_range), std::move(comp), std::move(proj)); +} // [is.sorted] is_sorted // Reference: https://wg21.link/is.sorted -// TODO(crbug.com/1071094): Implement. +// Returns: Whether the range `[first, last)` is sorted with respect to `comp` +// and `proj`. +// +// Complexity: Linear. + +// Reference: https://wg21.link/is.sorted#:~:text=ranges::is_sorted(I +template <typename ForwardIterator, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::iterator_category_t<ForwardIterator>, + typename = indirect_result_t<Comp&, + projected<ForwardIterator, Proj>, + projected<ForwardIterator, Proj>>> +constexpr auto is_sorted(ForwardIterator first, + ForwardIterator last, + Comp comp = {}, + Proj proj = {}) { + return std::is_sorted(first, last, + internal::ProjectedBinaryPredicate(comp, proj, proj)); +} + +// Returns: Whether the range `[first, last)` is sorted with respect to `comp` +// and `proj`. +// +// Complexity: Linear. + +// Reference: https://wg21.link/is.sorted#:~:text=ranges::is_sorted(R +template <typename Range, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::range_category_t<Range>, + typename = indirect_result_t<Comp&, + projected<iterator_t<Range>, Proj>, + projected<iterator_t<Range>, Proj>>> +constexpr auto is_sorted(Range&& range, Comp comp = {}, Proj proj = {}) { + return ranges::is_sorted(ranges::begin(range), ranges::end(range), + std::move(comp), std::move(proj)); +} + +// Returns: The last iterator `i` in `[first, last]` for which the range +// `[first, i)` is sorted with respect to `comp` and `proj`. +// +// Complexity: Linear. + +// Reference: https://wg21.link/is.sorted#:~:text=ranges::is_sorted_until(I +template <typename ForwardIterator, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::iterator_category_t<ForwardIterator>, + typename = indirect_result_t<Comp&, + projected<ForwardIterator, Proj>, + projected<ForwardIterator, Proj>>> +constexpr auto is_sorted_until(ForwardIterator first, + ForwardIterator last, + Comp comp = {}, + Proj proj = {}) { + return std::is_sorted_until( + first, last, internal::ProjectedBinaryPredicate(comp, proj, proj)); +} + +// Returns: The last iterator `i` in `[begin(range), end(range)]` for which the +// range `[begin(range), i)` is sorted with respect to `comp` and `proj`. +// +// Complexity: Linear. + +// Reference: https://wg21.link/is.sorted#:~:text=ranges::is_sorted_until(R +template <typename Range, + typename Comp = ranges::less, + typename Proj = identity, + typename = internal::range_category_t<Range>, + typename = indirect_result_t<Comp&, + projected<iterator_t<Range>, Proj>, + projected<iterator_t<Range>, Proj>>> +constexpr auto is_sorted_until(Range&& range, Comp comp = {}, Proj proj = {}) { + return ranges::is_sorted_until(ranges::begin(range), ranges::end(range), + std::move(comp), std::move(proj)); +} // [alg.nth.element] Nth element // Reference: https://wg21.link/alg.nth.element
diff --git a/base/util/ranges/algorithm_unittest.cc b/base/util/ranges/algorithm_unittest.cc index e018502..785550e 100644 --- a/base/util/ranges/algorithm_unittest.cc +++ b/base/util/ranges/algorithm_unittest.cc
@@ -736,6 +736,120 @@ EXPECT_THAT(input, ::testing::UnorderedElementsAre(0, 1, 2, 3, 4)); } +TEST(RangesTest, Sort) { + int input[] = {3, 1, 2, 0, 4}; + EXPECT_EQ(input + 4, ranges::sort(input, input + 4)); + EXPECT_THAT(input, ElementsAre(0, 1, 2, 3, 4)); + + EXPECT_EQ(input + 5, ranges::sort(input, input + 5, ranges::greater())); + EXPECT_THAT(input, ElementsAre(4, 3, 2, 1, 0)); + + Int ints[] = {6, 7, 9, 8, 5}; + EXPECT_EQ(ints + 5, ranges::sort(ints, {}, &Int::value)); + EXPECT_THAT(ints, ElementsAre(5, 6, 7, 8, 9)); + + EXPECT_EQ(ints + 5, ranges::sort(ints, ranges::greater(), &Int::value)); + EXPECT_THAT(ints, ElementsAre(9, 8, 7, 6, 5)); +} + +TEST(RangesTest, StableSort) { + // Integer divide each element by 2 to check stability of elements that + // compare equal. + auto idiv2 = [](int i) { return i / 2; }; + + int input[] = {3, 1, 2, 0, 4}; + EXPECT_EQ(input + 4, ranges::stable_sort(input, input + 4, {}, idiv2)); + EXPECT_THAT(input, ElementsAre(1, 0, 3, 2, 4)); + + EXPECT_EQ(input + 5, + ranges::stable_sort(input, input + 5, ranges::greater())); + EXPECT_THAT(input, ElementsAre(4, 3, 2, 1, 0)); + + auto Idiv2 = [](Int i) { return i.value / 2; }; + Int ints[] = {6, 7, 9, 8, 5}; + EXPECT_EQ(ints + 5, ranges::stable_sort(ints, {}, Idiv2)); + EXPECT_THAT(ints, ElementsAre(5, 6, 7, 9, 8)); + + EXPECT_EQ(ints + 5, ranges::stable_sort(ints, ranges::greater(), Idiv2)); + EXPECT_THAT(ints, ElementsAre(9, 8, 6, 7, 5)); +} + +TEST(RangesTest, PartialSort) { + int input[] = {3, 1, 2, 0, 4}; + EXPECT_EQ(input + 4, ranges::partial_sort(input, input + 2, input + 4)); + EXPECT_EQ(input[0], 0); + EXPECT_EQ(input[1], 1); + + EXPECT_EQ(input + 5, ranges::partial_sort(input, input + 3, input + 5, + ranges::greater())); + EXPECT_EQ(input[0], 4); + EXPECT_EQ(input[1], 3); + EXPECT_EQ(input[2], 2); + + Int ints[] = {6, 7, 9, 8, 5}; + EXPECT_EQ(ints + 5, ranges::partial_sort(ints, ints + 4, {}, &Int::value)); + EXPECT_EQ(ints[0], 5); + EXPECT_EQ(ints[1], 6); + EXPECT_EQ(ints[2], 7); + EXPECT_EQ(ints[3], 8); + + EXPECT_EQ(ints + 5, ranges::partial_sort(ints, ints + 3, ranges::greater(), + &Int::value)); + EXPECT_EQ(ints[0], 9); + EXPECT_EQ(ints[1], 8); + EXPECT_EQ(ints[2], 7); +} + +TEST(RangesTest, PartialSortCopy) { + int input[] = {3, 1, 2, 0, 4}; + int output[] = {0, 0, 0, 0, 0}; + EXPECT_EQ(output + 2, + ranges::partial_sort_copy(input, input + 2, output, output + 4)); + EXPECT_THAT(input, ElementsAre(3, 1, 2, 0, 4)); + EXPECT_THAT(output, ElementsAre(1, 3, 0, 0, 0)); + + EXPECT_EQ(output + 5, + ranges::partial_sort_copy(input, input + 3, output + 3, output + 5, + ranges::greater())); + EXPECT_THAT(input, ElementsAre(3, 1, 2, 0, 4)); + EXPECT_THAT(output, ElementsAre(1, 3, 0, 3, 2)); + + Int ints[] = {3, 1, 2, 0, 4}; + Int outs[] = {0, 0, 0}; + EXPECT_EQ(outs + 3, ranges::partial_sort_copy(ints, outs, {}, &Int::value)); + EXPECT_THAT(ints, ElementsAre(3, 1, 2, 0, 4)); + EXPECT_THAT(outs, ElementsAre(0, 1, 2)); + + EXPECT_EQ(outs + 3, ranges::partial_sort_copy(ints, outs, ranges::greater(), + &Int::value)); + EXPECT_THAT(ints, ElementsAre(3, 1, 2, 0, 4)); + EXPECT_THAT(outs, ElementsAre(4, 3, 2)); +} + +TEST(RangesTest, IsSorted) { + int input[] = {3, 1, 2, 0, 4}; + EXPECT_TRUE(ranges::is_sorted(input + 1, input + 3)); + EXPECT_FALSE(ranges::is_sorted(input + 1, input + 4)); + EXPECT_TRUE(ranges::is_sorted(input, input + 2, ranges::greater())); + + Int ints[] = {0, 1, 2, 3, 4}; + EXPECT_TRUE(ranges::is_sorted(ints, {}, &Int::value)); + EXPECT_FALSE(ranges::is_sorted(ints, ranges::greater(), &Int::value)); +} + +TEST(RangesTest, IsSortedUntil) { + int input[] = {3, 1, 2, 0, 4}; + EXPECT_EQ(input + 3, ranges::is_sorted_until(input + 1, input + 3)); + EXPECT_EQ(input + 3, ranges::is_sorted_until(input + 1, input + 4)); + EXPECT_EQ(input + 2, + ranges::is_sorted_until(input, input + 2, ranges::greater())); + + Int ints[] = {0, 1, 2, 3, 4}; + EXPECT_EQ(ints + 5, ranges::is_sorted_until(ints, {}, &Int::value)); + EXPECT_EQ(ints + 1, + ranges::is_sorted_until(ints, ranges::greater(), &Int::value)); +} + TEST(RangesTest, LowerBound) { int array[] = {0, 0, 1, 1, 2, 2};
diff --git a/build/android/docs/class_verification_failures.md b/build/android/docs/class_verification_failures.md index 36ee97e..be99495 100644 --- a/build/android/docs/class_verification_failures.md +++ b/build/android/docs/class_verification_failures.md
@@ -187,7 +187,7 @@ ``` Googlers can also download mappings for [official -builds](http://go/clank-webview/official-builds). +builds](http://go/webview-official-builds). ### Understanding the reason for the failure
diff --git a/build/android/gyp/compile_resources.py b/build/android/gyp/compile_resources.py index e57510a..c96306f 100755 --- a/build/android/gyp/compile_resources.py +++ b/build/android/gyp/compile_resources.py
@@ -1100,6 +1100,12 @@ custom_root_package_name = options.r_java_root_package_name grandparent_custom_package_name = None + # Always generate an R.java file for the package listed in + # AndroidManifest.xml because this is where Android framework looks to find + # onResourcesLoaded() for shared library apks. While not actually necessary + # for application apks, it also doesn't hurt. + apk_package_name = manifest_package_name + if options.package_name and not options.arsc_package_name: # Feature modules have their own custom root package name and should # inherit from the appropriate base module package. This behaviour should @@ -1108,15 +1114,14 @@ # apk under test. custom_root_package_name = options.package_name grandparent_custom_package_name = options.r_java_root_package_name - - if options.shared_resources or options.app_as_shared_lib: - package_for_library = manifest_package_name - else: - package_for_library = None + # Feature modules have the same manifest package as the base module but + # they should not create an R.java for said manifest package because it + # will be created in the base module. + apk_package_name = None logging.debug('Creating R.srcjar') resource_utils.CreateRJavaFiles( - build.srcjar_dir, package_for_library, build.r_txt_path, + build.srcjar_dir, apk_package_name, build.r_txt_path, options.extra_res_packages, rjava_build_options, options.srcjar_out, custom_root_package_name, grandparent_custom_package_name, options.extra_main_r_text_files)
diff --git a/build/android/gyp/create_r_java.py b/build/android/gyp/create_r_java.py index 6ef7a98..6c55a06 100755 --- a/build/android/gyp/create_r_java.py +++ b/build/android/gyp/create_r_java.py
@@ -22,6 +22,7 @@ rjava_build_options = resource_utils.RJavaBuildOptions() rjava_build_options.ExportAllResources() rjava_build_options.ExportAllStyleables() + rjava_build_options.GenerateOnResourcesLoaded(fake=True) resource_utils.CreateRJavaFiles(build.srcjar_dir, package_name, rtxt_out,
diff --git a/build/android/gyp/prepare_resources.py b/build/android/gyp/prepare_resources.py index 3e17f26..454dfff 100755 --- a/build/android/gyp/prepare_resources.py +++ b/build/android/gyp/prepare_resources.py
@@ -191,7 +191,7 @@ rjava_build_options.ExportAllResources() rjava_build_options.ExportAllStyleables() if options.shared_resources: - rjava_build_options.GenerateOnResourcesLoaded() + rjava_build_options.GenerateOnResourcesLoaded(fake=True) # Not passing in custom_root_package_name or parent to keep # file names unique.
diff --git a/build/android/gyp/util/resource_utils.py b/build/android/gyp/util/resource_utils.py index 4fdad8a29..7b83981 100644 --- a/build/android/gyp/util/resource_utils.py +++ b/build/android/gyp/util/resource_utils.py
@@ -402,6 +402,7 @@ self.has_on_resources_loaded = False self.export_const_styleable = False self.final_package_id = None + self.fake_on_resources_loaded = False def ExportNoResources(self): """Make all resource IDs final, and don't generate a method.""" @@ -435,15 +436,20 @@ """ self.export_const_styleable = True - def GenerateOnResourcesLoaded(self): + def GenerateOnResourcesLoaded(self, fake=False): """Generate an onResourcesLoaded() method. This Java method will be called at runtime by the framework when the corresponding library (which includes the R.java source file) will be loaded at runtime. This corresponds to the --shared-resources or --app-as-shared-lib flags of 'aapt package'. + + if |fake|, then the method will be empty bodied to compile faster. This + useful for dummy R.java files that will eventually be replaced by real + ones. """ self.has_on_resources_loaded = True + self.fake_on_resources_loaded = fake def SetFinalPackageId(self, package_id): """Sets a package ID to be used for resources marked final.""" @@ -669,8 +675,7 @@ extends_string = 'extends {{ parent_path }}.R.{{ resource_type }} ' dep_path = GetCustomPackagePath(grandparent_custom_package_name) - template = Template( - """/* AUTO-GENERATED FILE. DO NOT MODIFY. */ + template = Template("""/* AUTO-GENERATED FILE. DO NOT MODIFY. */ package {{ package }}; @@ -690,6 +695,10 @@ } {% endfor %} {% if has_on_resources_loaded %} + {% if fake_on_resources_loaded %} + public static void onResourcesLoaded(int packageId) { + } + {% else %} private static boolean sResourcesDidLoad; public static void onResourcesLoaded(int packageId) { if (sResourcesDidLoad) { @@ -718,15 +727,17 @@ {% endfor %} } {% endfor %} + {% endif %} {% endif %} } """, - trim_blocks=True, - lstrip_blocks=True) + trim_blocks=True, + lstrip_blocks=True) return template.render( package=package, resource_types=sorted(_ALL_RESOURCE_TYPES), has_on_resources_loaded=rjava_build_options.has_on_resources_loaded, + fake_on_resources_loaded=rjava_build_options.fake_on_resources_loaded, final_resources=final_resources_by_type, non_final_resources=non_final_resources_by_type, startIndex=_GetNonSystemIndex,
diff --git a/build/android/gyp/write_build_config.py b/build/android/gyp/write_build_config.py index fd7baa9..6d3c86b 100755 --- a/build/android/gyp/write_build_config.py +++ b/build/android/gyp/write_build_config.py
@@ -1211,10 +1211,7 @@ if options.type == 'android_apk' and options.tested_apk_config: tested_apk_deps = Deps([options.tested_apk_config]) tested_apk_config = tested_apk_deps.Direct()[0] - tested_apk_resources_deps = tested_apk_deps.All('android_resources') gradle['apk_under_test'] = tested_apk_config['name'] - all_resources_deps = [ - d for d in all_resources_deps if not d in tested_apk_resources_deps] if options.type == 'android_app_bundle_module': deps_info['is_base_module'] = bool(options.is_base_module) @@ -1402,7 +1399,6 @@ c['package_name'] for c in all_library_deps if 'package_name' in c ]) - # For feature modules, remove any resources that already exist in the base # module. if base_module_build_config: @@ -1415,14 +1411,21 @@ base_module_build_config['deps_info']['extra_package_names'] ] - config['deps_info']['dependency_zips'] = dependency_zips - config['deps_info']['extra_package_names'] = extra_package_names if options.type == 'android_apk' and options.tested_apk_config: config['deps_info']['arsc_package_name'] = ( tested_apk_config['package_name']) + # We should not shadow the actual R.java files of the apk_under_test by + # creating new R.java files with the same package names in the tested apk. + extra_package_names = [ + package for package in extra_package_names + if package not in tested_apk_config['extra_package_names'] + ] if options.res_size_info: config['deps_info']['res_size_info'] = options.res_size_info + config['deps_info']['dependency_zips'] = dependency_zips + config['deps_info']['extra_package_names'] = extra_package_names + if options.type == 'group': if options.extra_classpath_jars: # These are .jars to add to javac classpath but not to runtime classpath.
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 312778f3..813a550e 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -597,7 +597,11 @@ template("generate_r_java") { action_with_pydeps(target_name) { - forward_variables_from(invoker, [ "deps" ]) + forward_variables_from(invoker, + [ + "deps", + "testonly", + ]) if (!defined(deps)) { deps = [] }
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index 8e1562a6..1ce62ce 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -978,9 +978,6 @@ # No package means resources override their deps. if (defined(custom_package) || defined(android_manifest)) { r_text = _r_text_out_path - } else { - assert(defined(invoker.deps), - "Must specify deps when custom_package is omitted.") } if (defined(_srcjar_path)) { srcjar = _srcjar_path
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 0418dca..558994d 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn
@@ -86,8 +86,9 @@ # We currently only have default profiles for Chromium in-tree, so we disable # this by default for all downstream projects, since these profiles are likely # nonsensical for said projects. - clang_use_default_sample_profile = build_with_chromium && is_official_build && - (is_android || is_desktop_linux) + clang_use_default_sample_profile = + chrome_pgo_phase == 0 && build_with_chromium && is_official_build && + (is_android || is_desktop_linux) # This configuration is used to select a default profile in Chrome OS based on # the microarchitectures we are using. This is only used if @@ -2195,6 +2196,7 @@ } } if (_clang_sample_profile != "") { + assert(chrome_pgo_phase == 0, "AFDO can't be used in PGO builds") rebased_clang_sample_profile = rebase_path(_clang_sample_profile, root_build_dir) cflags += [ "-fprofile-sample-use=${rebased_clang_sample_profile}" ]
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 7feab25..b8c71f4 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -0.20200721.1.1 +0.20200721.2.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 7feab25..b8c71f4 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -0.20200721.1.1 +0.20200721.2.1
diff --git a/build/vs_toolchain.py b/build/vs_toolchain.py index fee52de..6bc24a92 100755 --- a/build/vs_toolchain.py +++ b/build/vs_toolchain.py
@@ -307,17 +307,16 @@ if not suffix.startswith('.'): # ucrtbased.dll is located at {win_sdk_dir}/bin/{a.b.c.d}/{target_cpu}/ # ucrt/. - sdk_redist_root = os.path.join(win_sdk_dir, 'bin') - sdk_bin_sub_dirs = os.listdir(sdk_redist_root) + sdk_bin_root = os.path.join(win_sdk_dir, 'bin') + sdk_bin_sub_dirs = glob.glob(os.path.join(sdk_bin_root, '10.*')) # Select the most recent SDK if there are multiple versions installed. _SortByHighestVersionNumberFirst(sdk_bin_sub_dirs) for directory in sdk_bin_sub_dirs: - sdk_redist_root_version = os.path.join(sdk_redist_root, directory) + sdk_redist_root_version = os.path.join(sdk_bin_root, directory) if not os.path.isdir(sdk_redist_root_version): continue - if re.match(r'10\.\d+\.\d+\.\d+', directory): - source_dir = os.path.join(sdk_redist_root_version, target_cpu, 'ucrt') - break + source_dir = os.path.join(sdk_redist_root_version, target_cpu, 'ucrt') + break _CopyRuntimeImpl(os.path.join(target_dir, 'ucrtbase' + suffix), os.path.join(source_dir, 'ucrtbase' + suffix))
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index 63248da..6fa8fc40 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -513,7 +513,6 @@ "java/src/org/chromium/chrome/browser/directactions/MenuDirectActionHandler.java", "java/src/org/chromium/chrome/browser/directactions/SimpleDirectActionHandler.java", "java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutController.java", - "java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTabHelper.java", "java/src/org/chromium/chrome/browser/document/ChromeIntentUtil.java", "java/src/org/chromium/chrome/browser/document/ChromeLauncherActivity.java", "java/src/org/chromium/chrome/browser/document/DocumentWebContentsDelegate.java",
diff --git a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java index 7fac896..0df8986e 100644 --- a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java +++ b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceTest.java
@@ -250,6 +250,11 @@ TabUiTestHelper.createTabs(cta, true, 1); TabUiTestHelper.verifyTabModelTabCount(cta, 1, 1); + if (isInstantReturn()) { + // TODO(crbug.com/1076274): fix toolbar to avoid wrongly focusing on the toolbar + // omnibox. + return; + } TabUiTestHelper.enterTabSwitcher(cta); if (!isInstantReturn()) { // TODO(crbug.com/1076274): fix toolbar to make incognito switch part of the view. @@ -305,7 +310,11 @@ TabUiTestHelper.createTabs(cta, true, 1); TabUiTestHelper.verifyTabModelTabCount(cta, 1, 1); - + if (isInstantReturn()) { + // TODO(crbug.com/1076274): fix toolbar to avoid wrongly focusing on the toolbar + // omnibox. + return; + } TabUiTestHelper.enterTabSwitcher(cta); if (!isInstantReturn()) { // TODO(crbug.com/1076274): fix toolbar to make incognito switch part of the view. @@ -397,16 +406,15 @@ fail("Failed to tap 'more tabs' " + e.toString()); } onViewWaiting(withId(R.id.secondary_tasks_surface_view)); + if (isInstantReturn()) { + // TODO(crbug.com/1076274): fix toolbar to avoid wrongly focusing on the toolbar + // omnibox. + return; + } pressBack(); onViewWaiting(withId(R.id.primary_tasks_surface_view)); - if (isInstantReturn()) { - // TODO(crbug.com/1092642): Fix androidx.test.espresso.PerformException issue when - // performing a single click on position: 0. See code below. - return; - } - OverviewModeBehaviorWatcher hideWatcher = TabUiTestHelper.createOverviewHideWatcher(mActivityTestRule.getActivity()); onView(allOf(withParent(withId( @@ -465,16 +473,15 @@ fail("Failed to tap 'more tabs' " + e.toString()); } onViewWaiting(withId(R.id.secondary_tasks_surface_view)); + if (isInstantReturn()) { + // TODO(crbug.com/1076274): fix toolbar to avoid wrongly focusing on the toolbar + // omnibox. + return; + } pressBack(); onViewWaiting(withId(R.id.primary_tasks_surface_view)); - if (isInstantReturn()) { - // TODO(crbug.com/1092642): Fix androidx.test.espresso.PerformException issue when - // performing a single click on position: 0. See code below. - return; - } - OverviewModeBehaviorWatcher hideWatcher = TabUiTestHelper.createOverviewHideWatcher(mActivityTestRule.getActivity()); onView(allOf(withParent(withId( @@ -538,6 +545,11 @@ } onViewWaiting(withId(R.id.secondary_tasks_surface_view)); + if (isInstantReturn()) { + // TODO(crbug.com/1076274): fix toolbar to avoid wrongly focusing on the toolbar + // omnibox. + return; + } pressBack(); onViewWaiting(withId(R.id.primary_tasks_surface_view)); @@ -623,15 +635,13 @@ // Single surface is shown as homepage. Exit in order to get into tab switcher later. pressBack(); } - - TabUiTestHelper.enterTabSwitcher(mActivityTestRule.getActivity()); - onViewWaiting(allOf(withId(R.id.secondary_tasks_surface_view), isDisplayed())); - if (isInstantReturn()) { - // TODO(crbug.com/1092642): Fix androidx.test.espresso.PerformException issue when - // performing a single click on position: 0. See code below. + // TODO(crbug.com/1076274): fix toolbar to avoid wrongly focusing on the toolbar + // omnibox. return; } + TabUiTestHelper.enterTabSwitcher(mActivityTestRule.getActivity()); + onViewWaiting(allOf(withId(R.id.secondary_tasks_surface_view), isDisplayed())); OverviewModeBehaviorWatcher hideWatcher = TabUiTestHelper.createOverviewHideWatcher(mActivityTestRule.getActivity());
diff --git a/chrome/android/features/tab_ui/java/DEPS b/chrome/android/features/tab_ui/DEPS similarity index 100% rename from chrome/android/features/tab_ui/java/DEPS rename to chrome/android/features/tab_ui/DEPS
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSuggestionMessageCardTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSuggestionMessageCardTest.java index 4872b5b..a1da2e03 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSuggestionMessageCardTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSuggestionMessageCardTest.java
@@ -192,6 +192,7 @@ @Test @MediumTest + @DisabledTest(message = "crbug.com/1085452") // clang-format off @CommandLineFlags.Add({BASE_PARAMS + "/baseline_group_tab_suggestions/true" + "/baseline_close_tab_suggestions/true/min_time_between_prefetches/0"})
diff --git a/chrome/android/features/tab_ui/junit/DEPS b/chrome/android/features/tab_ui/junit/DEPS deleted file mode 100644 index 8154ebc..0000000 --- a/chrome/android/features/tab_ui/junit/DEPS +++ /dev/null
@@ -1,8 +0,0 @@ -include_rules = [ - "+chrome/browser/android/lifecycle", - "+chrome/browser/profiles/android/java", - "+chrome/browser/tab/java", - "+content/public/android/java/src/org/chromium/content_public/browser", - "+components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement", - "+components/search_engines/android/java/src/org/chromium/components/search_engines", -]
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutController.java b/chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutController.java index 6334e63..fe0f63c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutController.java
@@ -14,21 +14,29 @@ import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; +import org.chromium.base.UserData; +import org.chromium.base.UserDataHost; import org.chromium.blink.mojom.ViewportFit; +import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.tab.EmptyTabObserver; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.TabObserver; +import org.chromium.chrome.browser.tab.TabSelectionType; import org.chromium.components.browser_ui.widget.InsetObserverView; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.ui.base.WindowAndroid; /** - * Controls the display safe area for a {@link WebContents} and the cutout mode for an {@link - * Activity} window. - * - * The WebContents is updated with the safe area continuously, as long as {@link - * Delegate#getAttachedActivity()} returns a non-null value. The cutout mode is set on the - * Activity's window only in P+, and only when the associated WebContents is fullscreen. + * Controls the display cutout state for the tab. */ -public class DisplayCutoutController implements InsetObserverView.WindowInsetObserver { +public class DisplayCutoutController implements InsetObserverView.WindowInsetObserver, UserData { + private static final Class<DisplayCutoutController> USER_DATA_KEY = + DisplayCutoutController.class; + + /** The tab that this controller belongs to. */ + private Tab mTab; + /** {@link Window} of the current {@link Activity}. */ private Window mWindow; @@ -41,47 +49,73 @@ */ private @Nullable InsetObserverView mInsetObserverView; - /** An interface for providing embedder-specific behavior to the controller. */ - interface Delegate { - /** Returns the activity this controller is associated with, if there is one. */ - @Nullable - Activity getAttachedActivity(); + /** Listens to various Tab events. */ + private final TabObserver mTabObserver = new EmptyTabObserver() { + @Override + public void onShown(Tab tab, @TabSelectionType int type) { + assert tab == mTab; - /** - * Returns the {@link WebContents} this controller should update the safe area for, if - * there is one. - */ - @Nullable - WebContents getWebContents(); + // Force a layout update if we are now being shown. + maybeUpdateLayout(); + } - /** Returns the view this controller uses for safe area updates, if there is one. */ - @Nullable - InsetObserverView getInsetObserverView(); + @Override + public void onInteractabilityChanged(Tab tab, boolean interactable) { + // Force a layout update if the tab is now in the foreground. + maybeUpdateLayout(); + } - /** Returns whether the user can interact with the associated WebContents/UI element. */ - boolean isInteractable(); - } - private final Delegate mDelegate; + @Override + public void onActivityAttachmentChanged(Tab tab, @Nullable WindowAndroid window) { + assert tab == mTab; - public DisplayCutoutController(Delegate delegate) { - mDelegate = delegate; - maybeAddInsetObserver(); + if (window != null) { + maybeAddInsetObserver(tab.getWindowAndroid().getActivity().get()); + } else { + maybeRemoveInsetObserver(); + } + } + }; + + public static DisplayCutoutController from(Tab tab) { + UserDataHost host = tab.getUserDataHost(); + DisplayCutoutController controller = host.getUserData(USER_DATA_KEY); + return controller == null + ? host.setUserData(USER_DATA_KEY, new DisplayCutoutController(tab)) + : controller; } - /** Add an observer to {@link InsetObserverView} if we have not already added one. */ - void maybeAddInsetObserver() { - Activity activity = mDelegate.getAttachedActivity(); + /** + * Constructs a new DisplayCutoutController for a specific tab. + * @param tab The tab that this controller belongs to. + */ + @VisibleForTesting + DisplayCutoutController(Tab tab) { + mTab = tab; + + tab.addObserver(mTabObserver); + maybeAddInsetObserver(tab.getWindowAndroid().getActivity().get()); + } + + /** + * Add an observer to {@link InsetObserverView} if we have not already added + * one. + */ + private void maybeAddInsetObserver(Activity activity) { if (mInsetObserverView != null || activity == null) return; - mInsetObserverView = mDelegate.getInsetObserverView(); + mInsetObserverView = ((ChromeActivity) activity).getInsetObserverView(); if (mInsetObserverView == null) return; mInsetObserverView.addObserver(this); mWindow = activity.getWindow(); } - /** Remove the observer added to {@link InsetObserverView} if we have added one. */ - void maybeRemoveInsetObserver() { + /** + * Remove the observer added to {@link InsetObserverView} if we have added + * one. + */ + private void maybeRemoveInsetObserver() { if (mInsetObserverView == null) return; mInsetObserverView.removeObserver(this); @@ -89,7 +123,9 @@ mWindow = null; } + @Override public void destroy() { + mTab.removeObserver(mTabObserver); maybeRemoveInsetObserver(); } @@ -98,10 +134,6 @@ * @param value The new viewport fit value. */ public void setViewportFit(@WebContentsObserver.ViewportFitType int value) { - if (value != ViewportFit.AUTO) { - assert mDelegate.getWebContents().isFullscreenForCurrentTab(); - } - if (value == mViewportFit) return; mViewportFit = value; @@ -111,7 +143,7 @@ /** Implements {@link WindowInsetsObserver}. */ @Override public void onSafeAreaChanged(Rect area) { - WebContents webContents = mDelegate.getWebContents(); + WebContents webContents = mTab.getWebContents(); if (webContents == null) return; float dipScale = getDipScale(); @@ -131,13 +163,18 @@ * @param dipScale The devices dip scale as an integer. * @return The CSS pixel value adjusted for scale. */ - private static int adjustInsetForScale(int inset, float dipScale) { + private int adjustInsetForScale(int inset, float dipScale) { return (int) Math.ceil(inset / dipScale); } @VisibleForTesting + static void initForTesting(UserDataHost host, DisplayCutoutController controller) { + host.setUserData(USER_DATA_KEY, controller); + } + + @VisibleForTesting protected float getDipScale() { - return mDelegate.getWebContents().getTopLevelNativeWindow().getDisplay().getDipScale(); + return mTab.getWindowAndroid().getDisplay().getDipScale(); } /** @@ -149,7 +186,7 @@ @TargetApi(Build.VERSION_CODES.P) protected int getDisplayCutoutMode() { // If we are not interactable then force the default mode. - if (!mDelegate.isInteractable()) { + if (!mTab.isUserInteractable()) { return LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT; } @@ -186,12 +223,4 @@ attributes.layoutInDisplayCutoutMode = getDisplayCutoutMode(); setWindowAttributes(attributes); } - - void onActivityAttachmentChanged(@Nullable WindowAndroid window) { - if (window == null) { - maybeRemoveInsetObserver(); - } else { - maybeAddInsetObserver(); - } - } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTabHelper.java deleted file mode 100644 index ca3eb370..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTabHelper.java +++ /dev/null
@@ -1,127 +0,0 @@ -// Copyright 2020 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.display_cutout; - -import android.app.Activity; - -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; - -import org.chromium.base.UserData; -import org.chromium.base.UserDataHost; -import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.tab.EmptyTabObserver; -import org.chromium.chrome.browser.tab.Tab; -import org.chromium.chrome.browser.tab.TabObserver; -import org.chromium.chrome.browser.tab.TabSelectionType; -import org.chromium.components.browser_ui.widget.InsetObserverView; -import org.chromium.content_public.browser.WebContents; -import org.chromium.content_public.browser.WebContentsObserver; -import org.chromium.ui.base.WindowAndroid; - -/** - * Wraps a {@link DisplayCutoutController} for a Chrome {@link Tab}. - * - * This will only be created once the tab sets a non-default viewport fit. - */ -public class DisplayCutoutTabHelper implements UserData { - private static final Class<DisplayCutoutTabHelper> USER_DATA_KEY = DisplayCutoutTabHelper.class; - - /** The tab that this object belongs to. */ - private Tab mTab; - - @VisibleForTesting - DisplayCutoutController mCutoutController; - - /** Listens to various Tab events. */ - private final TabObserver mTabObserver = new EmptyTabObserver() { - @Override - public void onShown(Tab tab, @TabSelectionType int type) { - assert tab == mTab; - - // Force a layout update if we are now being shown. - mCutoutController.maybeUpdateLayout(); - } - - @Override - public void onInteractabilityChanged(Tab tab, boolean interactable) { - // Force a layout update if the tab is now in the foreground. - mCutoutController.maybeUpdateLayout(); - } - - @Override - public void onActivityAttachmentChanged(Tab tab, @Nullable WindowAndroid window) { - assert tab == mTab; - - mCutoutController.onActivityAttachmentChanged(window); - } - }; - - public static DisplayCutoutTabHelper from(Tab tab) { - UserDataHost host = tab.getUserDataHost(); - DisplayCutoutTabHelper tabHelper = host.getUserData(USER_DATA_KEY); - return tabHelper == null ? host.setUserData(USER_DATA_KEY, new DisplayCutoutTabHelper(tab)) - : tabHelper; - } - - @VisibleForTesting - static class ChromeDisplayCutoutDelegate implements DisplayCutoutController.Delegate { - private Tab mTab; - - ChromeDisplayCutoutDelegate(Tab tab) { - mTab = tab; - } - - @Override - public Activity getAttachedActivity() { - return mTab.getWindowAndroid().getActivity().get(); - } - @Override - public WebContents getWebContents() { - return mTab.getWebContents(); - } - @Override - public InsetObserverView getInsetObserverView() { - Activity activity = getAttachedActivity(); - return activity == null ? null : ((ChromeActivity) activity).getInsetObserverView(); - } - @Override - public boolean isInteractable() { - return mTab.isUserInteractable(); - } - } - - /** - * Constructs a new DisplayCutoutTabHelper for a specific tab. - * @param tab The tab that this object belongs to. - */ - @VisibleForTesting - DisplayCutoutTabHelper(Tab tab) { - mTab = tab; - tab.addObserver(mTabObserver); - mCutoutController = new DisplayCutoutController(new ChromeDisplayCutoutDelegate(mTab)); - } - - /** - * Set the viewport fit value for the tab. - * @param value The new viewport fit value. - */ - public void setViewportFit(@WebContentsObserver.ViewportFitType int value) { - mCutoutController.setViewportFit(value); - } - - @Override - public void destroy() { - mTab.removeObserver(mTabObserver); - mCutoutController.destroy(); - } - - @VisibleForTesting - static void initForTesting(Tab tab, DisplayCutoutController controller) { - DisplayCutoutTabHelper tabHelper = new DisplayCutoutTabHelper(tab); - tabHelper.mCutoutController = controller; - tab.getUserDataHost().setUserData(USER_DATA_KEY, tabHelper); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentAppComparator.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentAppComparator.java index c7ca36d..74c8c3c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentAppComparator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentAppComparator.java
@@ -6,31 +6,20 @@ import org.chromium.components.autofill.Completable; import org.chromium.components.payments.PaymentApp; +import org.chromium.components.payments.PaymentRequestParams; import java.util.Comparator; /** A comparator that is used to rank the payment apps to be listed in the payment sheet. */ /* package */ class PaymentAppComparator implements Comparator<PaymentApp> { - private final ParamsProvider mParamsProvider; - - /** The provider of the parameters needed by this class. */ - /* package */ interface ParamsProvider { - /** @return The requestShipping set by the merchant. */ - boolean requestShipping(); - /** @return The requestPayerName set by the merchant. */ - boolean requestPayerName(); - /** @return The requestPayerEmail set by the merchant. */ - boolean requestPayerEmail(); - /** @return The requestPayerPhone set by the merchant. */ - boolean requestPayerPhone(); - } + private final PaymentRequestParams mParams; /** * Create an instance of PaymentAppComparator. - * @param paramsProvider The provider of the params needed by this class. + * @param params The parameters of PaymentRequest specified by the merchant. */ - /* package */ PaymentAppComparator(ParamsProvider paramsProvider) { - mParamsProvider = paramsProvider; + /* package */ PaymentAppComparator(PaymentRequestParams params) { + mParams = params; } /** @@ -89,7 +78,7 @@ if (completeness != 0) return completeness; // Payment apps which handle shipping address before others. - if (mParamsProvider.requestShipping()) { + if (mParams.requestShipping()) { int canHandleShipping = (b.handlesShippingAddress() ? 1 : 0) - (a.handlesShippingAddress() ? 1 : 0); if (canHandleShipping != 0) return canHandleShipping; @@ -98,15 +87,15 @@ // Payment apps which handle more contact information fields come first. int aSupportedContactDelegationsNum = 0; int bSupportedContactDelegationsNum = 0; - if (mParamsProvider.requestPayerName()) { + if (mParams.requestPayerName()) { if (a.handlesPayerName()) aSupportedContactDelegationsNum++; if (b.handlesPayerName()) bSupportedContactDelegationsNum++; } - if (mParamsProvider.requestPayerEmail()) { + if (mParams.requestPayerEmail()) { if (a.handlesPayerEmail()) aSupportedContactDelegationsNum++; if (b.handlesPayerEmail()) bSupportedContactDelegationsNum++; } - if (mParamsProvider.requestPayerPhone()) { + if (mParams.requestPayerPhone()) { if (a.handlesPayerPhone()) aSupportedContactDelegationsNum++; if (b.handlesPayerPhone()) bSupportedContactDelegationsNum++; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java index 6a8c685..f756a53 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java
@@ -22,7 +22,6 @@ import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.autofill.PersonalDataManager; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; -import org.chromium.chrome.browser.autofill.PersonalDataManager.CreditCard; import org.chromium.chrome.browser.autofill.PersonalDataManager.NormalizedAddressRequestDelegate; import org.chromium.chrome.browser.compositor.layouts.EmptyOverviewModeObserver; import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior; @@ -76,6 +75,7 @@ import org.chromium.components.payments.PaymentDetailsUpdateServiceHelper; import org.chromium.components.payments.PaymentFeatureList; import org.chromium.components.payments.PaymentHandlerHost; +import org.chromium.components.payments.PaymentRequestParams; import org.chromium.components.payments.PaymentRequestSpec; import org.chromium.components.payments.PaymentRequestUpdateEventListener; import org.chromium.components.payments.PaymentValidator; @@ -133,9 +133,8 @@ PaymentRequestUpdateEventListener, PaymentApp.AbortCallback, PaymentApp.InstrumentDetailsCallback, PaymentResponseHelper.PaymentResponseRequesterDelegate, FocusChangedObserver, - NormalizedAddressRequestDelegate, SettingsAutofillAndPaymentsObserver.Observer, - PaymentDetailsConverter.MethodChecker, PaymentHandlerUiObserver, - PaymentAppComparator.ParamsProvider { + NormalizedAddressRequestDelegate, PaymentDetailsConverter.MethodChecker, + PaymentHandlerUiObserver, PaymentRequestParams, PaymentUIsManager.Delegate { /** * A delegate to ask questions about the system, that allows tests to inject behaviour without * having to modify the entire system. This partially mirrors a similar C++ @@ -505,8 +504,8 @@ mSkipUiForNonUrlPaymentMethodIdentifiers = mDelegate.skipUiForBasicCard(); if (sObserverForTest != null) sObserverForTest.onPaymentRequestCreated(this); - mPaymentUIsManager = new PaymentUIsManager(addressEditor, cardEditor); - mPaymentAppComparator = new PaymentAppComparator(/*paramsProvider=*/this); + mPaymentUIsManager = new PaymentUIsManager(/*delegate=*/this, addressEditor, cardEditor); + mPaymentAppComparator = new PaymentAppComparator(/*params=*/this); } // Implement ComponentPaymentRequestDelegate: @@ -527,6 +526,7 @@ boolean googlePayBridgeEligible) { assert getClient() != null; mMethodData = new HashMap<>(); + mComponentPaymentRequestImpl.registerPaymentRequestLifecycleObserver(mPaymentUIsManager); if (!OriginSecurityChecker.isOriginSecure(mWebContents.getLastCommittedUrl())) { mJourneyLogger.setAborted(AbortReason.INVALID_DATA_FROM_RENDERER); @@ -609,15 +609,12 @@ } mId = details.id; - // Checks whether the merchant supports autofill cards before show is called. - boolean merchantSupportsAutofillCards = - AutofillPaymentAppFactory.merchantSupportsBasicCard(mMethodData); - // If in strict mode, don't give user an option to add an autofill card during the checkout - // to avoid the "unhappy" basic-card flow. - mPaymentUIsManager.setCanUserAddCreditCard(merchantSupportsAutofillCards - && !PaymentFeatureList.isEnabledOrExperimentalFeaturesEnabled( - PaymentFeatureList.STRICT_HAS_ENROLLED_AUTOFILL_INSTRUMENT)); - mPaymentUIsManager.setMerchantSupportsAutofillCards(merchantSupportsAutofillCards); + // The first time initializations and validation of all of the parameters of {@link + // PaymentRequestParams} should be done before {@link + // PaymentRequestLifeCycleObserver#onPaymentRequestParamsInitiated}. + mComponentPaymentRequestImpl.getPaymentRequestLifecycleObserver() + .onPaymentRequestParamsInitiated( + /*params=*/this); if (mRequestShipping || mRequestPayerName || mRequestPayerPhone || mRequestPayerEmail) { mAutofillProfiles = Collections.unmodifiableList( @@ -660,7 +657,7 @@ // Log the various types of payment methods that were requested by the merchant. boolean requestedMethodGoogle = false; // Not to record requestedMethodBasicCard because JourneyLogger ignore the case where the - // specified networks are unsupported. mPaymentUIsManager.isMerchantSupportsAutofillCards() + // specified networks are unsupported. mPaymentUIsManager.merchantSupportsAutofillCards() // better captures this group of interest than requestedMethodBasicCard. boolean requestedMethodOther = false; mURLPaymentMethodIdentifiersSupported = false; @@ -673,7 +670,7 @@ break; case MethodStrings.BASIC_CARD: // Not to record requestedMethodBasicCard because - // mPaymentUIsManager.isMerchantSupportsAutofillCards() is used instead. + // mPaymentUIsManager.merchantSupportsAutofillCards() is used instead. break; default: // "Other" includes https url, http url(when certifate check is bypassed) and @@ -1245,25 +1242,31 @@ return true; } - // Implement PaymentAppComparator.ParamsProvider: + // Implement PaymentRequestParams: + @Override + public Map<String, PaymentMethodData> getMethodDataMap() { + return getMethodData(); + } + + // Implement PaymentRequestParams: @Override public boolean requestShipping() { return mRequestShipping; } - // Implement PaymentAppComparator.ParamsProvider: + // Implement PaymentRequestParams: @Override public boolean requestPayerName() { return mRequestPayerName; } - // Implement PaymentAppComparator.ParamsProvider: + // Implement PaymentRequestParams: @Override public boolean requestPayerEmail() { return mRequestPayerEmail; } - // Implement PaymentAppComparator.ParamsProvider: + // Implement PaymentRequestParams: @Override public boolean requestPayerPhone() { return mRequestPayerPhone; @@ -1534,8 +1537,9 @@ return true; } - /** Updates the modifiers for payment apps and order summary. */ - private void updateAppModifiedTotals() { + // Implement PaymentUIsManager.Delegate: + @Override + public void updateAppModifiedTotals() { if (!PaymentFeatureList.isEnabled(PaymentFeatureList.WEB_PAYMENTS_MODIFIERS)) return; if (mModifiers == null) return; if (mPaymentUIsManager.getPaymentMethodsSection() == null) return; @@ -1721,7 +1725,8 @@ // origin completely. mPaymentUIsManager.getPaymentMethodsSection() .setDisplaySelectedItemSummaryInSingleLineInNormalMode( - getSelectedPaymentAppType() != PaymentAppType.SERVICE_WORKER_APP); + mPaymentUIsManager.getSelectedPaymentAppType() + != PaymentAppType.SERVICE_WORKER_APP); mPaymentInformationCallback.onResult(new PaymentInformation(mUiShoppingCart, mPaymentUIsManager.getShippingAddressesSection(), mUiShippingOptions, mPaymentUIsManager.getContactSection(), @@ -2067,19 +2072,11 @@ return; } - assert getSelectedPaymentAppType() == PaymentAppType.AUTOFILL; + assert mPaymentUIsManager.getSelectedPaymentAppType() == PaymentAppType.AUTOFILL; mPaymentUIsManager.getPaymentRequestUI().showProcessingMessage(); } - private @PaymentAppType int getSelectedPaymentAppType() { - return mPaymentUIsManager.getPaymentMethodsSection() != null - && mPaymentUIsManager.getPaymentMethodsSection().getSelectedItem() != null - ? ((PaymentApp) mPaymentUIsManager.getPaymentMethodsSection().getSelectedItem()) - .getPaymentAppType() - : PaymentAppType.UNDEFINED; - } - @Override public boolean onPayClicked(EditableOption selectedShippingAddress, EditableOption selectedShippingOption, EditableOption selectedPaymentMethod) { @@ -2353,83 +2350,6 @@ settingsLauncher.launchSettingsActivity(context); } - @Override - public void onAddressUpdated(AutofillAddress address) { - if (getClient() == null) return; - - address.setShippingAddressLabelWithCountry(); - mPaymentUIsManager.getCardEditor().updateBillingAddressIfComplete(address); - - if (mPaymentUIsManager.getShippingAddressesSection() != null) { - mPaymentUIsManager.getShippingAddressesSection().addAndSelectOrUpdateItem(address); - mPaymentUIsManager.getPaymentRequestUI().updateSection( - PaymentRequestUI.DataType.SHIPPING_ADDRESSES, - mPaymentUIsManager.getShippingAddressesSection()); - } - - if (mPaymentUIsManager.getContactSection() != null) { - mPaymentUIsManager.getContactSection().addOrUpdateWithAutofillAddress(address); - mPaymentUIsManager.getPaymentRequestUI().updateSection( - PaymentRequestUI.DataType.CONTACT_DETAILS, - mPaymentUIsManager.getContactSection()); - } - } - - @Override - public void onAddressDeleted(String guid) { - if (getClient() == null) return; - - // TODO: Delete the address from mPaymentUIsManager.getShippingAddressesSection() and - // mPaymentUIsManager.getContactSection(). Note that we only displayed SUGGESTIONS_LIMIT - // addresses, so we may want to add back previously ignored addresses. - } - - @Override - public void onCreditCardUpdated(CreditCard card) { - if (getClient() == null || !mPaymentUIsManager.merchantSupportsAutofillCards() - || mPaymentUIsManager.getPaymentMethodsSection() == null - || mPaymentUIsManager.getAutofillPaymentAppCreator() == null) { - return; - } - - PaymentApp updatedAutofillCard = - mPaymentUIsManager.getAutofillPaymentAppCreator().createPaymentAppForCard(card); - - // Can be null when the card added through settings does not match the requested card - // network or is invalid, because autofill settings do not perform the same level of - // validation as Basic Card implementation in Chrome. - if (updatedAutofillCard == null) return; - - mPaymentUIsManager.getPaymentMethodsSection().addAndSelectOrUpdateItem(updatedAutofillCard); - - updateAppModifiedTotals(); - - if (mPaymentUIsManager.getPaymentRequestUI() != null) { - mPaymentUIsManager.getPaymentRequestUI().updateSection( - PaymentRequestUI.DataType.PAYMENT_METHODS, - mPaymentUIsManager.getPaymentMethodsSection()); - } - } - - @Override - public void onCreditCardDeleted(String guid) { - if (getClient() == null) return; - if (!mPaymentUIsManager.merchantSupportsAutofillCards() - || mPaymentUIsManager.getPaymentMethodsSection() == null) { - return; - } - - mPaymentUIsManager.getPaymentMethodsSection().removeAndUnselectItem(guid); - - updateAppModifiedTotals(); - - if (mPaymentUIsManager.getPaymentRequestUI() != null) { - mPaymentUIsManager.getPaymentRequestUI().updateSection( - PaymentRequestUI.DataType.PAYMENT_METHODS, - mPaymentUIsManager.getPaymentMethodsSection()); - } - } - // Implement ComponentPaymentRequestDelegate: /** Called by the merchant website to check if the user has complete payment apps. */ @Override @@ -2759,7 +2679,11 @@ int missingFields = 0; if (mPendingApps.isEmpty()) { - if (mPaymentUIsManager.merchantSupportsAutofillCards()) { + // TODO(crbug.com/1107039): This value could be null when this method is entered from + // PaymentRequest#init. We should turn it into boolean after correcting this bug. + Boolean merchantSupportsAutofillCards = + mPaymentUIsManager.merchantSupportsAutofillCards(); + if (merchantSupportsAutofillCards != null && merchantSupportsAutofillCards) { // Record all fields if basic-card is supported but no card exists. missingFields = AutofillPaymentInstrument.CompletionStatus.CREDIT_CARD_EXPIRED | AutofillPaymentInstrument.CompletionStatus.CREDIT_CARD_NO_CARDHOLDER @@ -2778,7 +2702,7 @@ updateAppModifiedTotals(); - SettingsAutofillAndPaymentsObserver.getInstance().registerObserver(this); + SettingsAutofillAndPaymentsObserver.getInstance().registerObserver(mPaymentUIsManager); if (mIsCurrentPaymentRequestShowing) { // Send AppListReady signal when all apps are created and request.show() is called. @@ -3065,7 +2989,7 @@ mOverviewModeBehavior = null; } - SettingsAutofillAndPaymentsObserver.getInstance().unregisterObserver(this); + SettingsAutofillAndPaymentsObserver.getInstance().unregisterObserver(mPaymentUIsManager); // Destroy native objects. for (CurrencyFormatter formatter : mCurrencyFormatterMap.values()) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentUIsManager.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentUIsManager.java index 72535575..dee6c57c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentUIsManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ui/PaymentUIsManager.java
@@ -4,29 +4,48 @@ package org.chromium.chrome.browser.payments.ui; +import androidx.annotation.Nullable; + +import org.chromium.chrome.browser.autofill.PersonalDataManager.CreditCard; import org.chromium.chrome.browser.payments.AddressEditor; +import org.chromium.chrome.browser.payments.AutofillAddress; import org.chromium.chrome.browser.payments.AutofillPaymentAppCreator; +import org.chromium.chrome.browser.payments.AutofillPaymentAppFactory; import org.chromium.chrome.browser.payments.CardEditor; import org.chromium.chrome.browser.payments.PaymentRequestImpl; +import org.chromium.chrome.browser.payments.SettingsAutofillAndPaymentsObserver; +import org.chromium.components.payments.PaymentApp; +import org.chromium.components.payments.PaymentAppType; +import org.chromium.components.payments.PaymentFeatureList; +import org.chromium.components.payments.PaymentRequestLifecycleObserver; +import org.chromium.components.payments.PaymentRequestParams; /** * This class manages all of the UIs related to payment. The UI logic of {@link PaymentRequestImpl} * should be moved into this class. */ -public class PaymentUIsManager { - private PaymentRequestUI mPaymentRequestUI; - private PaymentUisShowStateReconciler mPaymentUisShowStateReconciler; - +public class PaymentUIsManager + implements SettingsAutofillAndPaymentsObserver.Observer, PaymentRequestLifecycleObserver { + private final Delegate mDelegate; private final AddressEditor mAddressEditor; private final CardEditor mCardEditor; + private final PaymentUisShowStateReconciler mPaymentUisShowStateReconciler; - private boolean mMerchantSupportsAutofillCards; + private PaymentRequestUI mPaymentRequestUI; + + private Boolean mMerchantSupportsAutofillCards; private SectionInformation mPaymentMethodsSection; private SectionInformation mShippingAddressesSection; private ContactDetailsSection mContactSection; private AutofillPaymentAppCreator mAutofillPaymentAppCreator; - private boolean mCanUserAddCreditCard; + private Boolean mCanUserAddCreditCard; + + /** The delegate of this class. */ + public interface Delegate { + /** Updates the modifiers for payment apps and order summary. */ + void updateAppModifiedTotals(); + } /** * This class is to coordinate the show state of a bottom sheet UI (either expandable payment @@ -84,10 +103,16 @@ /** * Create PaymentUIsManager. + * @param delegate The delegate of this class. * @param addressEditor The AddressEditor of the PaymentRequest UI. * @param cardEditor The CardEditor of the PaymentRequest UI. */ - public PaymentUIsManager(AddressEditor addressEditor, CardEditor cardEditor) { + // TODO(crbug.com/1107102): AddressEditor and CardEditor should be initialized in this + // constructor instead of the caller of the constructor, once CardEditor's "ForTest" symbols + // have been removed from the production code. + public PaymentUIsManager( + Delegate delegate, AddressEditor addressEditor, CardEditor cardEditor) { + mDelegate = delegate; mAddressEditor = addressEditor; mCardEditor = cardEditor; mPaymentUisShowStateReconciler = new PaymentUisShowStateReconciler(); @@ -122,15 +147,13 @@ } /** @return Whether the merchant supports autofill cards. */ - public boolean merchantSupportsAutofillCards() { + @Nullable + public Boolean merchantSupportsAutofillCards() { + // TODO(crbug.com/1107039): this value should be asserted not null to avoid being used + // before defined, after this bug is fixed. return mMerchantSupportsAutofillCards; } - /** Set whether the merchant supports autofill cards. */ - public void setMerchantSupportsAutofillCards(boolean merchantSupportsAutofillCards) { - mMerchantSupportsAutofillCards = merchantSupportsAutofillCards; - } - /** @return Get the PaymentMethodsSection of the PaymentRequest UI. */ public SectionInformation getPaymentMethodsSection() { return mPaymentMethodsSection; @@ -173,11 +196,97 @@ /** @return Whether user can add credit card. */ public boolean canUserAddCreditCard() { + assert mCanUserAddCreditCard != null; return mCanUserAddCreditCard; } - /** Set whether user can add credit card. */ - public void setCanUserAddCreditCard(boolean canUserAddCreditCard) { - mCanUserAddCreditCard = canUserAddCreditCard; + // Implement SettingsAutofillAndPaymentsObserver.Observer: + @Override + public void onAddressUpdated(AutofillAddress address) { + address.setShippingAddressLabelWithCountry(); + mCardEditor.updateBillingAddressIfComplete(address); + + if (mShippingAddressesSection != null) { + mShippingAddressesSection.addAndSelectOrUpdateItem(address); + mPaymentRequestUI.updateSection( + PaymentRequestUI.DataType.SHIPPING_ADDRESSES, mShippingAddressesSection); + } + + if (mContactSection != null) { + mContactSection.addOrUpdateWithAutofillAddress(address); + mPaymentRequestUI.updateSection( + PaymentRequestUI.DataType.CONTACT_DETAILS, mContactSection); + } + } + + // Implement SettingsAutofillAndPaymentsObserver.Observer: + @Override + public void onAddressDeleted(String guid) { + // TODO: Delete the address from getShippingAddressesSection() and + // getContactSection(). Note that we only displayed + // SUGGESTIONS_LIMIT addresses, so we may want to add back previously ignored addresses. + } + + // Implement SettingsAutofillAndPaymentsObserver.Observer: + @Override + public void onCreditCardUpdated(CreditCard card) { + assert mMerchantSupportsAutofillCards != null; + if (!mMerchantSupportsAutofillCards || mPaymentMethodsSection == null + || mAutofillPaymentAppCreator == null) { + return; + } + + PaymentApp updatedAutofillCard = mAutofillPaymentAppCreator.createPaymentAppForCard(card); + + // Can be null when the card added through settings does not match the requested card + // network or is invalid, because autofill settings do not perform the same level of + // validation as Basic Card implementation in Chrome. + if (updatedAutofillCard == null) return; + + mPaymentMethodsSection.addAndSelectOrUpdateItem(updatedAutofillCard); + + mDelegate.updateAppModifiedTotals(); + + if (mPaymentRequestUI != null) { + mPaymentRequestUI.updateSection( + PaymentRequestUI.DataType.PAYMENT_METHODS, mPaymentMethodsSection); + } + } + + // Implement SettingsAutofillAndPaymentsObserver.Observer: + @Override + public void onCreditCardDeleted(String guid) { + assert mMerchantSupportsAutofillCards != null; + if (!mMerchantSupportsAutofillCards || mPaymentMethodsSection == null) return; + + mPaymentMethodsSection.removeAndUnselectItem(guid); + + mDelegate.updateAppModifiedTotals(); + + if (mPaymentRequestUI != null) { + mPaymentRequestUI.updateSection( + PaymentRequestUI.DataType.PAYMENT_METHODS, mPaymentMethodsSection); + } + } + + // Implement PaymentRequestLifecycleObserver: + @Override + public void onPaymentRequestParamsInitiated(PaymentRequestParams params) { + // Checks whether the merchant supports autofill cards before show is called. + mMerchantSupportsAutofillCards = + AutofillPaymentAppFactory.merchantSupportsBasicCard(params.getMethodDataMap()); + + // If in strict mode, don't give user an option to add an autofill card during the checkout + // to avoid the "unhappy" basic-card flow. + mCanUserAddCreditCard = mMerchantSupportsAutofillCards + && !PaymentFeatureList.isEnabledOrExperimentalFeaturesEnabled( + PaymentFeatureList.STRICT_HAS_ENROLLED_AUTOFILL_INSTRUMENT); + } + + /** @return The selected payment app type. */ + public @PaymentAppType int getSelectedPaymentAppType() { + return mPaymentMethodsSection != null && mPaymentMethodsSection.getSelectedItem() != null + ? ((PaymentApp) mPaymentMethodsSection.getSelectedItem()).getPaymentAppType() + : PaymentAppType.UNDEFINED; } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java index c50509d..507e51e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java
@@ -26,14 +26,15 @@ model.get(AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA) != null; view.collapseAccountList(isSelectedAccountNonNull); } - } else if (propertyKey == AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA - && !model.get(AccountPickerBottomSheetProperties.IS_ACCOUNT_LIST_EXPANDED)) { - // Selected account data (which can be null) is only updated - // when the account list is collapsed. - DisplayableProfileData profileData = - model.get(AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA); - view.collapseAccountList(profileData != null); - view.updateCollapsedAccountList(profileData); + } else if (propertyKey == AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA) { + if (!model.get(AccountPickerBottomSheetProperties.IS_ACCOUNT_LIST_EXPANDED)) { + // Selected account data (which can be null) is only updated + // when the account list is collapsed. + DisplayableProfileData profileData = + model.get(AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA); + view.collapseAccountList(profileData != null); + view.updateCollapsedAccountList(profileData); + } } else if (propertyKey == AccountPickerBottomSheetProperties.ON_CONTINUE_AS_CLICKED) { view.getContinueAsButton().setOnClickListener(v -> { model.get(AccountPickerBottomSheetProperties.ON_CONTINUE_AS_CLICKED).run();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS index 766b6a96..6720286d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS
@@ -76,8 +76,5 @@ ], 'TabViewManagerImpl\.java': [ "+chrome/browser/browser_controls/android/java/src/org/chromium/chrome/browser/browser_controls/BrowserControlsMarginSupplier.java", - ], - 'TabWebContentsObserver\.java': [ - "+chrome/android/java/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTabHelper.java", ] }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java index 8ba6590..b319303f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsObserver.java
@@ -20,7 +20,7 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.SwipeRefreshHandler; -import org.chromium.chrome.browser.display_cutout.DisplayCutoutTabHelper; +import org.chromium.chrome.browser.display_cutout.DisplayCutoutController; import org.chromium.chrome.browser.media.MediaCaptureNotificationService; import org.chromium.chrome.browser.policy.PolicyAuditor; import org.chromium.chrome.browser.policy.PolicyAuditor.AuditEvent; @@ -347,7 +347,7 @@ @Override public void viewportFitChanged(@WebContentsObserver.ViewportFitType int value) { - DisplayCutoutTabHelper.from(mTab).setViewportFit(value); + DisplayCutoutController.from(mTab).setViewportFit(value); } @Override
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTestRule.java b/chrome/android/javatests/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTestRule.java index 8b1b782..96369ce9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTestRule.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutTestRule.java
@@ -59,8 +59,8 @@ private boolean mDeviceHasCutout = true; private float mDipScale = 1; - TestDisplayCutoutController(DisplayCutoutController.Delegate delegate) { - super(delegate); + TestDisplayCutoutController(Tab tab) { + super(tab); } @Override @@ -159,11 +159,10 @@ protected void setUp() { mTab = getActivity().getActivityTab(); - mTestController = new TestDisplayCutoutController( - new DisplayCutoutTabHelper.ChromeDisplayCutoutDelegate(mTab)); - + mTestController = new TestDisplayCutoutController(mTab); TestThreadUtils.runOnUiThreadBlocking( - () -> DisplayCutoutTabHelper.initForTesting(mTab, mTestController)); + () -> DisplayCutoutController.initForTesting( + mTab.getUserDataHost(), mTestController)); mListener = new FullscreenToggleObserver(); getActivity().getFullscreenManager().addObserver(mListener);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java index 5eb2b2a..bdcfd17 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java
@@ -166,7 +166,7 @@ @Test @MediumTest - public void testAccountDisappearedInCollapsedSheet() { + public void testAccountDisappearedOnCollapsedSheet() { buildAndShowCollapsedBottomSheet(); mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA1.getAccountName()); mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA2.getAccountName()); @@ -176,7 +176,7 @@ @Test @MediumTest - public void testAccountDisappearedInExpandedSheet() { + public void testAccountDisappearedOnExpandedSheet() { buildAndShowExpandedBottomSheet(); mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA1.getAccountName()); mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA2.getAccountName()); @@ -186,7 +186,7 @@ @Test @MediumTest - public void testAccountReappearedInCollapsedSheet() { + public void testAccountReappearedOnCollapsedSheet() { mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA1.getAccountName()); mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA2.getAccountName()); buildAndShowCollapsedBottomSheet(); @@ -199,7 +199,7 @@ @Test @MediumTest - public void testOtherAccountsChangeInCollapsedSheet() { + public void testOtherAccountsChangeOnCollapsedSheet() { buildAndShowCollapsedBottomSheet(); checkCollapsedAccountList(PROFILE_DATA1); mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA2.getAccountName()); @@ -209,7 +209,7 @@ @Test @MediumTest - public void testSelectedAccountChangeInCollapsedSheet() { + public void testSelectedAccountChangeOnCollapsedSheet() { buildAndShowCollapsedBottomSheet(); mAccountManagerTestRule.removeAccountAndWaitForSeeding(PROFILE_DATA1.getAccountName()); InstrumentationRegistry.getInstrumentation().waitForIdleSync(); @@ -218,7 +218,7 @@ @Test @MediumTest - public void testProfileDataUpdateInExpandedSheet() { + public void testProfileDataUpdateOnExpandedSheet() { buildAndShowExpandedBottomSheet(); String newFullName = "New Full Name1"; String newGivenName = "New Given Name1";
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java index 6accbf56..d12451b7 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java
@@ -31,7 +31,6 @@ import org.chromium.chrome.browser.tab.TabObserver; import org.chromium.chrome.browser.tab.TabSelectionType; import org.chromium.components.browser_ui.widget.InsetObserverView; -import org.chromium.content_public.browser.WebContents; import org.chromium.testing.local.LocalRobolectricTestRunner; import org.chromium.ui.base.WindowAndroid; @@ -47,9 +46,6 @@ private TabImpl mTab; @Mock - private WebContents mWebContents; - - @Mock private WindowAndroid mWindowAndroid; @Mock @@ -64,8 +60,7 @@ @Mock private InsetObserverView mInsetObserver; - private DisplayCutoutTabHelper mDisplayCutoutTabHelper; - private DisplayCutoutController mController; + private DisplayCutoutController mDisplayCutoutController; private WeakReference<Activity> mActivityRef; @@ -80,32 +75,28 @@ when(mChromeActivity.getWindow()).thenReturn(mWindow); when(mWindow.getAttributes()).thenReturn(new LayoutParams()); when(mTab.getWindowAndroid()).thenReturn(mWindowAndroid); - when(mTab.getWebContents()).thenReturn(mWebContents); - when(mWebContents.isFullscreenForCurrentTab()).thenReturn(true); when(mWindowAndroid.getActivity()).thenReturn(mActivityRef); when(mChromeActivity.getInsetObserverView()).thenReturn(mInsetObserver); - mDisplayCutoutTabHelper = spy(new DisplayCutoutTabHelper(mTab)); - mController = spy(mDisplayCutoutTabHelper.mCutoutController); - mDisplayCutoutTabHelper.mCutoutController = mController; + mDisplayCutoutController = spy(new DisplayCutoutController(mTab)); } @Test @SmallTest public void testViewportFitUpdate() { - verify(mController, never()).maybeUpdateLayout(); + verify(mDisplayCutoutController, never()).maybeUpdateLayout(); - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.COVER); - verify(mController).maybeUpdateLayout(); + mDisplayCutoutController.setViewportFit(ViewportFit.COVER); + verify(mDisplayCutoutController).maybeUpdateLayout(); } @Test @SmallTest public void testViewportFitUpdateNotChanged() { - verify(mController, never()).maybeUpdateLayout(); + verify(mDisplayCutoutController, never()).maybeUpdateLayout(); - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.AUTO); - verify(mController, never()).maybeUpdateLayout(); + mDisplayCutoutController.setViewportFit(ViewportFit.AUTO); + verify(mDisplayCutoutController, never()).maybeUpdateLayout(); } @Test @@ -113,9 +104,9 @@ public void testCutoutModeWhenAutoAndInteractable() { when(mTab.isUserInteractable()).thenReturn(true); - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.AUTO); + mDisplayCutoutController.setViewportFit(ViewportFit.AUTO); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @@ -123,9 +114,9 @@ public void testCutoutModeWhenCoverAndInteractable() { when(mTab.isUserInteractable()).thenReturn(true); - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.COVER); + mDisplayCutoutController.setViewportFit(ViewportFit.COVER); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @@ -133,9 +124,9 @@ public void testCutoutModeWhenCoverForcedAndInteractable() { when(mTab.isUserInteractable()).thenReturn(true); - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.COVER_FORCED_BY_USER_AGENT); + mDisplayCutoutController.setViewportFit(ViewportFit.COVER_FORCED_BY_USER_AGENT); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @@ -143,41 +134,41 @@ public void testCutoutModeWhenContainAndInteractable() { when(mTab.isUserInteractable()).thenReturn(true); - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.CONTAIN); + mDisplayCutoutController.setViewportFit(ViewportFit.CONTAIN); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @SmallTest public void testCutoutModeWhenAutoAndNotInteractable() { - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.AUTO); + mDisplayCutoutController.setViewportFit(ViewportFit.AUTO); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @SmallTest public void testCutoutModeWhenCoverAndNotInteractable() { - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.COVER); + mDisplayCutoutController.setViewportFit(ViewportFit.COVER); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @SmallTest public void testCutoutModeWhenCoverForcedAndNotInteractable() { - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.COVER_FORCED_BY_USER_AGENT); + mDisplayCutoutController.setViewportFit(ViewportFit.COVER_FORCED_BY_USER_AGENT); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @SmallTest public void testCutoutModeWhenContainAndNotInteractable() { - mDisplayCutoutTabHelper.setViewportFit(ViewportFit.CONTAIN); + mDisplayCutoutController.setViewportFit(ViewportFit.CONTAIN); Assert.assertEquals(LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT, - mController.getDisplayCutoutMode()); + mDisplayCutoutController.getDisplayCutoutMode()); } @Test @@ -185,7 +176,7 @@ public void testLayoutOnInteractability_True() { // In this test we are checking for a side effect of maybeUpdateLayout. // This is because the tab observer holds a reference to the original - // mDisplayCutoutTabHelper and not the spied one. + // mDisplayCutoutController and not the spied one. verify(mTab).addObserver(mTabObserverCaptor.capture()); reset(mTab); @@ -198,7 +189,7 @@ public void testLayoutOnInteractability_False() { // In this test we are checking for a side effect of maybeUpdateLayout. // This is because the tab observer holds a reference to the original - // mDisplayCutoutTabHelper and not the spied one. + // mDisplayCutoutController and not the spied one. verify(mTab).addObserver(mTabObserverCaptor.capture()); reset(mTab); @@ -223,7 +214,7 @@ public void testLayoutOnShown() { // In this test we are checking for a side effect of maybeUpdateLayout. // This is because the tab observer holds a reference to the original - // mDisplayCutoutTabHelper and not the spied one. + // mDisplayCutoutController and not the spied one. verify(mTab).addObserver(mTabObserverCaptor.capture()); reset(mTab);
diff --git a/chrome/android/webapk/shell_apk/BUILD.gn b/chrome/android/webapk/shell_apk/BUILD.gn index 9d7201f..bcbbe63 100644 --- a/chrome/android/webapk/shell_apk/BUILD.gn +++ b/chrome/android/webapk/shell_apk/BUILD.gn
@@ -307,7 +307,7 @@ config_file = "manifest/bound_manifest_config.json" manifest_to_upload_dep = ":generate_new_style_manifest_for_upload" apk_name = "NewSplashWebApk" - apk_package_name = "org.chromium.webapk.new.splash" + apk_package_name = "org.chromium.webapk.new_splash" } # Used by javatests
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 1a430439..76f4d79 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -3298,6 +3298,8 @@ "nearby_sharing/fast_initiation_manager.h", "nearby_sharing/file_attachment.cc", "nearby_sharing/file_attachment.h", + "nearby_sharing/incoming_share_target_info.cc", + "nearby_sharing/incoming_share_target_info.h", "nearby_sharing/instantmessaging/constants.h", "nearby_sharing/instantmessaging/receive_messages_express.cc", "nearby_sharing/instantmessaging/receive_messages_express.h",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 1fcbc991..d6791b4 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -5887,6 +5887,11 @@ {"enable-media-feeds", flag_descriptions::kEnableMediaFeedsName, flag_descriptions::kEnableMediaFeedsDescription, kOsDesktop, FEATURE_VALUE_TYPE(media::kMediaFeeds)}, + + {"enable-media-feeds-background-fetch", + flag_descriptions::kEnableMediaFeedsBackgroundFetchName, + flag_descriptions::kEnableMediaFeedsBackgroundFetchDescription, kOsDesktop, + FEATURE_VALUE_TYPE(media::kMediaFeedsBackgroundFetching)}, #endif // !defined(OS_ANDROID) {"autofill-enable-card-nickname-management",
diff --git a/chrome/browser/android/feed/v2/feed_stream_surface.cc b/chrome/browser/android/feed/v2/feed_stream_surface.cc index b16903d..e52b3ead 100644 --- a/chrome/browser/android/feed/v2/feed_stream_surface.cc +++ b/chrome/browser/android/feed/v2/feed_stream_surface.cc
@@ -19,7 +19,7 @@ #include "components/feed/core/proto/v2/ui.pb.h" #include "components/feed/core/v2/public/feed_service.h" #include "components/feed/core/v2/public/feed_stream_api.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" using base::android::JavaParamRef; using base::android::JavaRef; @@ -36,12 +36,12 @@ static base::android::ScopedJavaLocalRef<jintArray> JNI_FeedStreamSurface_GetExperimentIds(JNIEnv* env) { - auto* variations_http_header_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); - DCHECK(variations_http_header_provider != nullptr); + auto* variations_ids_provider = + variations::VariationsIdsProvider::GetInstance(); + DCHECK(variations_ids_provider != nullptr); return base::android::ToJavaIntArray( - env, variations_http_header_provider + env, variations_ids_provider ->GetVariationsVectorForWebPropertiesKeys()); }
diff --git a/chrome/browser/browser_about_handler.cc b/chrome/browser/browser_about_handler.cc index b859217..af22820 100644 --- a/chrome/browser/browser_about_handler.cc +++ b/chrome/browser/browser_about_handler.cc
@@ -49,11 +49,10 @@ std::string host(url->host()); std::string path; -#if !defined(OS_CHROMEOS) - // Handle chrome://settings. + // Do not handle chrome://settings rewrites, they are handled in the + // HandleWebUI handler. if (host == chrome::kChromeUISettingsHost) - return true; // Prevent further rewriting - this is a valid URL. -#endif // !defined(OS_CHROMEOS) + return false; // Do not handle chrome://help. if (host == chrome::kChromeUIHelpHost)
diff --git a/chrome/browser/chrome_browser_application_mac.mm b/chrome/browser/chrome_browser_application_mac.mm index 156035f..739554ca 100644 --- a/chrome/browser/chrome_browser_application_mac.mm +++ b/chrome/browser/chrome_browser_application_mac.mm
@@ -21,7 +21,6 @@ #include "content/public/browser/native_event_processor_mac.h" #include "content/public/browser/native_event_processor_observer_mac.h" #include "ui/base/cocoa/accessibility_focus_overrider.h" -#include "ui/events/base_event_utils.h" namespace chrome_browser_application_mac { @@ -95,16 +94,6 @@ default: break; } - - // TODO(bokan): Added temporarily to debug https://crbug.com/1039833. - base::TimeTicks event_timestamp = - ui::EventTimeStampFromSeconds([event timestamp]); - base::TimeTicks now = ui::EventTimeForNow(); - base::TimeDelta diff = now - event_timestamp; - desc += base::StringPrintf(" Now: %lld Diff: %lld", - (now - base::TimeTicks()).InSeconds(), - diff.InSeconds()); - return desc; }
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index c416e95d..bcab22a 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -146,7 +146,7 @@ #include "components/variations/synthetic_trials_active_group_id_provider.h" #include "components/variations/variations_associated_data.h" #include "components/variations/variations_crash_keys.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "components/variations/variations_switches.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_context.h" @@ -516,7 +516,7 @@ TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetrics"); metrics::MetricsService* metrics = browser_process_->metrics_service(); metrics->synthetic_trial_registry()->AddSyntheticTrialObserver( - variations::VariationsHttpHeaderProvider::GetInstance()); + variations::VariationsIdsProvider::GetInstance()); metrics->synthetic_trial_registry()->AddSyntheticTrialObserver( variations::SyntheticTrialsActiveGroupIdProvider::GetInstance()); // Now that field trials have been created, initializes metrics recording.
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 9819d8d..4b9b911d 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -259,7 +259,7 @@ #include "components/ukm/app_source_url_recorder.h" #include "components/url_formatter/url_fixer.h" #include "components/variations/variations_associated_data.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "components/variations/variations_switches.h" #include "components/version_info/version_info.h" #include "components/viz/common/features.h" @@ -994,14 +994,14 @@ return; bool is_whitelisted = false; - PolicyBlacklistService* service = - PolicyBlacklistFactory::GetForBrowserContext( + PolicyBlocklistService* service = + PolicyBlocklistFactory::GetForBrowserContext( web_contents->GetBrowserContext()); if (ShouldHonorPolicies() && service) { - const policy::URLBlacklist::URLBlacklistState url_state = - service->GetURLBlacklistState(url); + const policy::URLBlocklist::URLBlocklistState url_state = + service->GetURLBlocklistState(url); is_whitelisted = - url_state == policy::URLBlacklist::URLBlacklistState::URL_IN_WHITELIST; + url_state == policy::URLBlocklist::URLBlocklistState::URL_IN_ALLOWLIST; } // If the URL is in whitelist, we launch it without asking the user and @@ -4027,7 +4027,7 @@ MaybeAddThrottle(TabUnderNavigationThrottle::MaybeCreate(handle), &throttles); - throttles.push_back(std::make_unique<PolicyBlacklistNavigationThrottle>( + throttles.push_back(std::make_unique<PolicyBlocklistNavigationThrottle>( handle, handle->GetWebContents()->GetBrowserContext())); // Before setting up SSL error detection, configure SSLErrorHandler to invoke @@ -5042,6 +5042,12 @@ return true; // Return true to update the displayed URL. } + // Replace deprecated cookie settings URL with the current version. + if (*url == GURL(chrome::kChromeUICookieSettingsDeprecatedURL)) { + *url = GURL(chrome::kChromeUICookieSettingsURL); + return true; + } + #if defined(OS_WIN) // TODO(crbug.com/1003960): Remove when issue is resolved. if (url->SchemeIs(content::kChromeUIScheme) && @@ -5510,12 +5516,12 @@ bool ChromeContentBrowserClient::ShouldBlockRendererDebugURL( const GURL& url, content::BrowserContext* context) { - PolicyBlacklistService* service = - PolicyBlacklistFactory::GetForBrowserContext(context); + PolicyBlocklistService* service = + PolicyBlocklistFactory::GetForBrowserContext(context); - using URLBlacklistState = policy::URLBlacklist::URLBlacklistState; - URLBlacklistState blacklist_state = service->GetURLBlacklistState(url); - return blacklist_state == URLBlacklistState::URL_IN_BLACKLIST; + using URLBlocklistState = policy::URLBlocklist::URLBlocklistState; + URLBlocklistState blocklist_state = service->GetURLBlocklistState(url); + return blocklist_state == URLBlocklistState::URL_IN_BLOCKLIST; } ui::AXMode ChromeContentBrowserClient::GetAXModeForBrowserContext(
diff --git a/chrome/browser/chrome_content_browser_client_unittest.cc b/chrome/browser/chrome_content_browser_client_unittest.cc index 42c4094..70e7910 100644 --- a/chrome/browser/chrome_content_browser_client_unittest.cc +++ b/chrome/browser/chrome_content_browser_client_unittest.cc
@@ -596,6 +596,11 @@ GURL should_redirect = chrome_help; test_content_browser_client.HandleWebUI(&should_redirect, nullptr); EXPECT_NE(chrome_help, should_redirect); + + // Confirm that the deprecated cookies settings URL is rewritten. + GURL cookies_url = GURL(chrome::kChromeUICookieSettingsDeprecatedURL); + test_content_browser_client.HandleWebUI(&cookies_url, nullptr); + EXPECT_EQ(GURL(chrome::kChromeUICookieSettingsURL), cookies_url); } TEST(ChromeContentBrowserClientTest, HandleWebUIReverse) {
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.cc index 21631e8..e8a80156 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.cc
@@ -184,7 +184,7 @@ void PluginVmDriveImageDownloadService::CancelDownload() { DCHECK(cancel_callback_); - cancel_callback_.Run(); + std::move(cancel_callback_).Run(); } void PluginVmDriveImageDownloadService::ResetState() {
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.h b/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.h index 6fee88b6..c4341abf 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.h +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_drive_image_download_service.h
@@ -79,7 +79,7 @@ int64_t total_bytes_downloaded_ = 0; base::FilePath download_directory_{kPluginVmDriveDownloadDirectory}; base::FilePath download_file_path_; - google_apis::CancelCallback cancel_callback_; + google_apis::CancelCallbackOnce cancel_callback_; base::WeakPtrFactory<PluginVmDriveImageDownloadService> weak_ptr_factory_{ this};
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_installer_unittest.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_installer_unittest.cc index 1da12a8..85cacbd5 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_installer_unittest.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_installer_unittest.cc
@@ -123,7 +123,7 @@ bool cancel_callback_called() const { return cancel_callback_called_; } // DriveServiceInterface override. - google_apis::CancelCallback DownloadFile( + google_apis::CancelCallbackOnce DownloadFile( const base::FilePath& /*cache_path*/, const std::string& /*resource_id*/, const DownloadActionCallback& download_action_callback, @@ -135,8 +135,8 @@ // It is safe to use base::Unretained as this object will not get deleted // before the end of the test. - return base::BindRepeating(&SimpleFakeDriveService::CancelCallback, - base::Unretained(this)); + return base::BindOnce(&SimpleFakeDriveService::CancelCallback, + base::Unretained(this)); } private:
diff --git a/chrome/browser/chromeos/policy/device_cloud_external_data_policy_observer_browsertest.cc b/chrome/browser/chromeos/policy/device_cloud_external_data_policy_observer_browsertest.cc index 944d828..8ef0142 100644 --- a/chrome/browser/chromeos/policy/device_cloud_external_data_policy_observer_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_external_data_policy_observer_browsertest.cc
@@ -34,7 +34,7 @@ "policy/printers_configuration_updated.json"; // The name of an External Data Policy in Device Policy. -const char* const kPolicyName = key::kDeviceNativePrinters; +const char* const kPolicyName = key::kDevicePrinters; class MockDeviceCloudExternalDataPolicyObserverDelegate : public DeviceCloudExternalDataPolicyObserver::Delegate {
diff --git a/chrome/browser/chromeos/policy/device_policy_cloud_external_data_manager_browsertest.cc b/chrome/browser/chromeos/policy/device_policy_cloud_external_data_manager_browsertest.cc index d2d87c03..63c9346 100644 --- a/chrome/browser/chromeos/policy/device_policy_cloud_external_data_manager_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_policy_cloud_external_data_manager_browsertest.cc
@@ -52,7 +52,7 @@ const char kExternalDataPathOverSizeLimit[] = "policy/printers_configuration_over_size_limit.json"; // The name of an External Data Policy in Device Policy. -const char* const kPolicyName = policy::key::kDeviceNativePrinters; +const char* const kPolicyName = policy::key::kDevicePrinters; const int64_t kTestCacheMaxSize = 64;
diff --git a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc index 4e3e5ed..60db63c 100644 --- a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc +++ b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc
@@ -1194,11 +1194,19 @@ } } - if (policy.has_native_device_printers()) { + // Use DevicePrinters policy if present, fallback to DeviceNativePrinters. + if (policy.has_device_printers()) { + const em::DevicePrintersProto& container(policy.device_printers()); + if (container.has_external_policy()) { + SetExternalDataDevicePolicy(key::kDevicePrinters, + container.external_policy(), + external_data_manager, policies); + } + } else if (policy.has_native_device_printers()) { const em::DeviceNativePrintersProto& container( policy.native_device_printers()); if (container.has_external_policy()) { - SetExternalDataDevicePolicy(key::kDeviceNativePrinters, + SetExternalDataDevicePolicy(key::kDevicePrinters, container.external_policy(), external_data_manager, policies); } @@ -1430,40 +1438,78 @@ base::Value(container.name()), nullptr); } - if (policy.has_native_device_printers_access_mode()) { + // Use DevicePrintersAccessMode if present, fallback to + // DeviceNativePrintersAccessMode. + if (policy.has_device_printers_access_mode()) { + const em::DevicePrintersAccessModeProto& container( + policy.device_printers_access_mode()); + if (container.has_access_mode()) { + std::unique_ptr<base::Value> value( + DecodeIntegerValue(container.access_mode())); + if (value) { + policies->Set(key::kDevicePrintersAccessMode, POLICY_LEVEL_MANDATORY, + POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, + std::move(*value), nullptr); + } + } + } else if (policy.has_native_device_printers_access_mode()) { const em::DeviceNativePrintersAccessModeProto& container( policy.native_device_printers_access_mode()); if (container.has_access_mode()) { std::unique_ptr<base::Value> value( DecodeIntegerValue(container.access_mode())); if (value) { - policies->Set(key::kDeviceNativePrintersAccessMode, - POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, - POLICY_SOURCE_CLOUD, std::move(*value), nullptr); + policies->Set(key::kDevicePrintersAccessMode, POLICY_LEVEL_MANDATORY, + POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, + std::move(*value), nullptr); } } } - if (policy.has_native_device_printers_blacklist()) { + // Use DevicePrintersBlocklist if present, fallback to + // DeviceNativePrintersBlacklist. + if (policy.has_device_printers_blocklist()) { + const em::DevicePrintersBlocklistProto& container( + policy.device_printers_blocklist()); + base::Value blocklist(base::Value::Type::LIST); + for (const auto& entry : container.blocklist()) + blocklist.Append(entry); + + policies->Set(key::kDevicePrintersBlocklist, POLICY_LEVEL_MANDATORY, + POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, + std::move(blocklist), nullptr); + } else if (policy.has_native_device_printers_blacklist()) { const em::DeviceNativePrintersBlacklistProto& container( policy.native_device_printers_blacklist()); base::Value blacklist(base::Value::Type::LIST); for (const auto& entry : container.blacklist()) blacklist.Append(entry); - policies->Set(key::kDeviceNativePrintersBlacklist, POLICY_LEVEL_MANDATORY, + policies->Set(key::kDevicePrintersBlocklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, std::move(blacklist), nullptr); } - if (policy.has_native_device_printers_whitelist()) { + // Use DevicePrintersAllowlist if present, fallback to + // DeviceNativePrintersWhitelist. + if (policy.has_device_printers_allowlist()) { + const em::DevicePrintersAllowlistProto& container( + policy.device_printers_allowlist()); + base::Value allowlist(base::Value::Type::LIST); + for (const auto& entry : container.allowlist()) + allowlist.Append(entry); + + policies->Set(key::kDevicePrintersAllowlist, POLICY_LEVEL_MANDATORY, + POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, + std::move(allowlist), nullptr); + } else if (policy.has_native_device_printers_whitelist()) { const em::DeviceNativePrintersWhitelistProto& container( policy.native_device_printers_whitelist()); base::Value whitelist(base::Value::Type::LIST); for (const auto& entry : container.whitelist()) whitelist.Append(entry); - policies->Set(key::kDeviceNativePrintersWhitelist, POLICY_LEVEL_MANDATORY, + policies->Set(key::kDevicePrintersAllowlist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, std::move(whitelist), nullptr); }
diff --git a/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler.cc b/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler.cc index 5134703..c3e74d5f 100644 --- a/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler.cc +++ b/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler.cc
@@ -20,7 +20,7 @@ device_native_printers_observer_( std::make_unique<DeviceCloudExternalDataPolicyObserver>( policy_service, - key::kDeviceNativePrinters, + key::kDevicePrinters, this)) {} DeviceNativePrintersExternalDataHandler::
diff --git a/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler_unittest.cc b/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler_unittest.cc index 64c8ebc..fd83ee2 100644 --- a/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler_unittest.cc +++ b/chrome/browser/chromeos/policy/external_data_handlers/device_native_printers_external_data_handler_unittest.cc
@@ -93,9 +93,9 @@ EXPECT_TRUE(external_printers_->GetPrinters().empty()); device_native_printers_external_data_handler_->OnDeviceExternalDataSet( - key::kDeviceNativePrinters); + key::kDevicePrinters); device_native_printers_external_data_handler_->OnDeviceExternalDataFetched( - key::kDeviceNativePrinters, + key::kDevicePrinters, std::make_unique<std::string>(kDeviceNativePrintersContentsJson), base::FilePath()); task_environment_.RunUntilIdle(); @@ -112,13 +112,13 @@ EXPECT_TRUE(external_printers_->GetPrinters().empty()); device_native_printers_external_data_handler_->OnDeviceExternalDataSet( - key::kDeviceNativePrinters); + key::kDevicePrinters); device_native_printers_external_data_handler_->OnDeviceExternalDataFetched( - key::kDeviceNativePrinters, + key::kDevicePrinters, std::make_unique<std::string>(kDeviceNativePrintersContentsJson), base::FilePath()); device_native_printers_external_data_handler_->OnDeviceExternalDataCleared( - key::kDeviceNativePrinters); + key::kDevicePrinters); task_environment_.RunUntilIdle(); // Check that policy was cleared.
diff --git a/chrome/browser/chromeos/printing/enterprise_printers_provider.cc b/chrome/browser/chromeos/printing/enterprise_printers_provider.cc index 76587eb..5fa2718 100644 --- a/chrome/browser/chromeos/printing/enterprise_printers_provider.cc +++ b/chrome/browser/chromeos/printing/enterprise_printers_provider.cc
@@ -186,7 +186,8 @@ device_printers_is_complete_ = device_printers_->IsComplete() && (device_printers_->IsDataPolicySet() || - !PolicyWithDataIsSet(policy::key::kDeviceNativePrinters)); + (!PolicyWithDataIsSet(policy::key::kDeviceNativePrinters) && + !PolicyWithDataIsSet(policy::key::kDevicePrinters))); } void RecalculateCurrentPrintersList() {
diff --git a/chrome/browser/data_saver/lite_video_browsertest.cc b/chrome/browser/data_saver/lite_video_browsertest.cc index 61be129ef..9e5eabf 100644 --- a/chrome/browser/data_saver/lite_video_browsertest.cc +++ b/chrome/browser/data_saver/lite_video_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/lite_video/lite_video_switches.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -82,6 +83,8 @@ switches::autoplay::kNoUserGestureRequiredPolicy); if (enable_lite_mode_) command_line->AppendSwitch("enable-spdy-proxy-auth"); + command_line->AppendSwitch( + lite_video::switches::kLiteVideoForceOverrideDecision); } void SetUp() override {
diff --git a/chrome/browser/download/download_prefs.cc b/chrome/browser/download/download_prefs.cc index 6c30afb..8b7013b 100644 --- a/chrome/browser/download/download_prefs.cc +++ b/chrome/browser/download/download_prefs.cc
@@ -608,8 +608,8 @@ } void DownloadPrefs::UpdateAllowedURLsForOpenByPolicy() { - std::unique_ptr<policy::URLBlacklist> allowed_urls = - std::make_unique<policy::URLBlacklist>(); + std::unique_ptr<policy::URLBlocklist> allowed_urls = + std::make_unique<policy::URLBlocklist>(); PrefService* prefs = profile_->GetPrefs(); const auto* list = prefs->GetList(prefs::kDownloadAllowedURLsForOpenByPolicy);
diff --git a/chrome/browser/download/download_prefs.h b/chrome/browser/download/download_prefs.h index 4484ddc..02e581e3 100644 --- a/chrome/browser/download/download_prefs.h +++ b/chrome/browser/download/download_prefs.h
@@ -28,7 +28,7 @@ } namespace policy { -class URLBlacklist; +class URLBlocklist; } namespace user_prefs { @@ -170,7 +170,7 @@ AutoOpenSet auto_open_by_user_; AutoOpenSet auto_open_by_policy_; - std::unique_ptr<policy::URLBlacklist> auto_open_allowed_by_urls_; + std::unique_ptr<policy::URLBlocklist> auto_open_allowed_by_urls_; #if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_MACOSX) bool should_open_pdf_in_system_reader_;
diff --git a/chrome/browser/download/download_request_limiter.cc b/chrome/browser/download/download_request_limiter.cc index c0b4d24..d76244e 100644 --- a/chrome/browser/download/download_request_limiter.cc +++ b/chrome/browser/download/download_request_limiter.cc
@@ -205,9 +205,9 @@ } void DownloadRequestLimiter::TabDownloadState::DidGetUserInteraction( - const blink::WebInputEvent::Type type) { + const blink::WebInputEvent& event) { if (is_showing_prompt() || - type == blink::WebInputEvent::Type::kGestureScrollBegin) { + event.GetType() == blink::WebInputEvent::Type::kGestureScrollBegin) { // Don't change state if a prompt is showing or if the user has scrolled. return; }
diff --git a/chrome/browser/download/download_request_limiter.h b/chrome/browser/download/download_request_limiter.h index a2411951..ffcb95c 100644 --- a/chrome/browser/download/download_request_limiter.h +++ b/chrome/browser/download/download_request_limiter.h
@@ -127,7 +127,7 @@ content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override; + void DidGetUserInteraction(const blink::WebInputEvent& event) override; void WebContentsDestroyed() override; // Asks the user if they really want to allow the download.
diff --git a/chrome/browser/download/download_request_limiter_unittest.cc b/chrome/browser/download/download_request_limiter_unittest.cc index 86b9700e..38567ba 100644 --- a/chrome/browser/download/download_request_limiter_unittest.cc +++ b/chrome/browser/download/download_request_limiter_unittest.cc
@@ -26,6 +26,10 @@ #include "content/public/test/navigation_simulator.h" #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/input/web_gesture_event.h" +#include "third_party/blink/public/common/input/web_keyboard_event.h" +#include "third_party/blink/public/common/input/web_mouse_event.h" +#include "third_party/blink/public/common/input/web_touch_event.h" #if defined(OS_ANDROID) #include "chrome/browser/flags/android/chrome_feature_list.h" @@ -90,8 +94,27 @@ blink::WebInputEvent::Type type) { DownloadRequestLimiter::TabDownloadState* state = download_request_limiter_->GetDownloadState(web_contents, false); - if (state) - state->DidGetUserInteraction(type); + if (!state) + return; + std::unique_ptr<blink::WebInputEvent> event; + switch (type) { + case blink::WebInputEvent::Type::kRawKeyDown: + event = std::make_unique<blink::WebKeyboardEvent>(); + break; + case blink::WebInputEvent::Type::kGestureScrollBegin: + event = std::make_unique<blink::WebGestureEvent>(); + break; + case blink::WebInputEvent::Type::kMouseDown: + event = std::make_unique<blink::WebMouseEvent>(); + break; + case blink::WebInputEvent::Type::kTouchStart: + event = std::make_unique<blink::WebTouchEvent>(); + break; + default: + NOTREACHED(); + } + event->SetType(type); + state->DidGetUserInteraction(*event); } void ExpectAndResetCounts(
diff --git a/chrome/browser/engagement/site_engagement_helper.cc b/chrome/browser/engagement/site_engagement_helper.cc index 50f7152..655294c 100644 --- a/chrome/browser/engagement/site_engagement_helper.cc +++ b/chrome/browser/engagement/site_engagement_helper.cc
@@ -108,12 +108,14 @@ // Once the timer finishes running, the callbacks detecting user input will be // registered again. void SiteEngagementService::Helper::InputTracker::DidGetUserInteraction( - const blink::WebInputEvent::Type type) { + const blink::WebInputEvent& event) { // Only respond to raw key down to avoid multiple triggering on a single input // (e.g. keypress is a key down then key up). if (!is_tracking_) return; + const blink::WebInputEvent::Type type = event.GetType(); + // This switch has a default NOTREACHED case because it will not test all // of the values of the WebInputEvent::Type enum (hence it won't require the // compiler verifying that all cases are covered).
diff --git a/chrome/browser/engagement/site_engagement_helper.h b/chrome/browser/engagement/site_engagement_helper.h index 0d7c26b..5d9fa8b4 100644 --- a/chrome/browser/engagement/site_engagement_helper.h +++ b/chrome/browser/engagement/site_engagement_helper.h
@@ -108,7 +108,7 @@ bool is_tracking_; // content::WebContentsObserver overrides. - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override; + void DidGetUserInteraction(const blink::WebInputEvent& event) override; DISALLOW_COPY_AND_ASSIGN(InputTracker); };
diff --git a/chrome/browser/engagement/site_engagement_helper_unittest.cc b/chrome/browser/engagement/site_engagement_helper_unittest.cc index 4a92445..a2501fd 100644 --- a/chrome/browser/engagement/site_engagement_helper_unittest.cc +++ b/chrome/browser/engagement/site_engagement_helper_unittest.cc
@@ -20,6 +20,10 @@ #include "content/public/test/navigation_simulator.h" #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/input/web_gesture_event.h" +#include "third_party/blink/public/common/input/web_keyboard_event.h" +#include "third_party/blink/public/common/input/web_mouse_event.h" +#include "third_party/blink/public/common/input/web_touch_event.h" using content::NavigationSimulator; @@ -47,14 +51,32 @@ // Simulate a user interaction event and handle it. void HandleUserInput(SiteEngagementService::Helper* helper, blink::WebInputEvent::Type type) { - helper->input_tracker_.DidGetUserInteraction(type); + std::unique_ptr<blink::WebInputEvent> event; + switch (type) { + case blink::WebInputEvent::Type::kRawKeyDown: + event = std::make_unique<blink::WebKeyboardEvent>(); + break; + case blink::WebInputEvent::Type::kGestureScrollBegin: + event = std::make_unique<blink::WebGestureEvent>(); + break; + case blink::WebInputEvent::Type::kMouseDown: + event = std::make_unique<blink::WebMouseEvent>(); + break; + case blink::WebInputEvent::Type::kTouchStart: + event = std::make_unique<blink::WebTouchEvent>(); + break; + default: + NOTREACHED(); + } + event->SetType(type); + helper->input_tracker_.DidGetUserInteraction(*event); } // Simulate a user interaction event and handle it. Reactivates tracking // immediately. void HandleUserInputAndRestartTracking(SiteEngagementService::Helper* helper, blink::WebInputEvent::Type type) { - helper->input_tracker_.DidGetUserInteraction(type); + HandleUserInput(helper, type); helper->input_tracker_.TrackingStarted(); }
diff --git a/chrome/browser/extensions/unpacked_installer.cc b/chrome/browser/extensions/unpacked_installer.cc index 930f420..9024d95 100644 --- a/chrome/browser/extensions/unpacked_installer.cc +++ b/chrome/browser/extensions/unpacked_installer.cc
@@ -63,7 +63,7 @@ const std::vector<base::FilePath> reserved_filepaths = file_util::GetReservedMetadataFilePaths(extension_path); for (const auto& file : reserved_filepaths) - base::DeleteFile(file, true /*recursive*/); + base::DeletePathRecursively(file); const base::FilePath& metadata_dir = extension_path.Append(kMetadataFolder); if (base::IsDirectoryEmpty(metadata_dir))
diff --git a/chrome/browser/extensions/updater/local_extension_cache.cc b/chrome/browser/extensions/updater/local_extension_cache.cc index dc7a413..18c8031 100644 --- a/chrome/browser/extensions/updater/local_extension_cache.cc +++ b/chrome/browser/extensions/updater/local_extension_cache.cc
@@ -349,8 +349,7 @@ // Case #1 or #4, remove all instances from cache. while ((it != cache.end()) && (it->first == id)) { if (delete_files) { - base::DeleteFile(base::FilePath(it->second.file_path), - true /* recursive */); + base::DeletePathRecursively(base::FilePath(it->second.file_path)); VLOG(1) << "Remove older version " << it->second.version << " for extension id " << id; }
diff --git a/chrome/browser/external_protocol/external_protocol_observer.cc b/chrome/browser/external_protocol/external_protocol_observer.cc index 4160ae9c..31365941 100644 --- a/chrome/browser/external_protocol/external_protocol_observer.cc +++ b/chrome/browser/external_protocol/external_protocol_observer.cc
@@ -16,9 +16,9 @@ } void ExternalProtocolObserver::DidGetUserInteraction( - const blink::WebInputEvent::Type type) { + const blink::WebInputEvent& event) { // Ignore scroll events for allowing external protocol launch. - if (type != blink::WebInputEvent::Type::kGestureScrollBegin) + if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin) ExternalProtocolHandler::PermitLaunchUrl(); }
diff --git a/chrome/browser/external_protocol/external_protocol_observer.h b/chrome/browser/external_protocol/external_protocol_observer.h index 945a5aa..a703b76e 100644 --- a/chrome/browser/external_protocol/external_protocol_observer.h +++ b/chrome/browser/external_protocol/external_protocol_observer.h
@@ -18,7 +18,7 @@ ~ExternalProtocolObserver() override; // content::WebContentsObserver overrides. - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override; + void DidGetUserInteraction(const blink::WebInputEvent& event) override; private: explicit ExternalProtocolObserver(content::WebContents* web_contents);
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 7dbee3cb..d3e0e43 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1709,6 +1709,11 @@ "expiry_milestone": 90 }, { + "name": "enable-media-feeds-background-fetch", + "owners": [ "beccahughes", "media-dev" ], + "expiry_milestone": 90 + }, + { "name": "enable-media-foundation-video-capture", "owners": [ "armax", "guidou" ], "expiry_milestone": 90 @@ -2786,6 +2791,11 @@ "expiry_milestone": 85 }, { + "name": "ios-synthetic-crash-reports", + "owners": [ "eugenebut", "olivierrobin" ], + "expiry_milestone": 95 + }, + { "name": "isolate-origins", "owners": [ "site-isolation-dev", "alexmos", "creis", "lukasza" ], // This is useful for isolating additional origins beyond the normal site
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 2950b2f..2618d5c 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -4206,6 +4206,12 @@ "Enables the Media Feeds feature which allows us to fetch feeds of media " "items from websites that support the feature. "; +const char kEnableMediaFeedsBackgroundFetchName[] = + "Enables Media Feeds Background Fetch"; +const char kEnableMediaFeedsBackgroundFetchDescription[] = + "Enables the Media Feeds background fetch feature which allows feeds to be " + "fetched in the background. Requires #enable-media-feeds to be enabled. "; + const char kRemoteCopyReceiverName[] = "Enables the remote copy feature to receive messages"; const char kRemoteCopyReceiverDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 8114a9a..50f4833 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2458,6 +2458,9 @@ extern const char kEnableMediaFeedsName[]; extern const char kEnableMediaFeedsDescription[]; +extern const char kEnableMediaFeedsBackgroundFetchName[]; +extern const char kEnableMediaFeedsBackgroundFetchDescription[]; + extern const char kRemoteCopyReceiverName[]; extern const char kRemoteCopyReceiverDescription[];
diff --git a/chrome/browser/history/history_browsertest.cc b/chrome/browser/history/history_browsertest.cc index 8b7b9fa6..6912b5c 100644 --- a/chrome/browser/history/history_browsertest.cc +++ b/chrome/browser/history/history_browsertest.cc
@@ -787,3 +787,28 @@ browser()->tab_strip_model()->GetWebContentsAt(1); ASSERT_NE(history_url, second_tab->GetVisibleURL()); } + +// Verifies history.replaceState() to the same url without a user gesture does +// not log a visit. +IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, ReplaceStateSamePageIsNotRecorded) { + // Use the default embedded_test_server() for this test because replaceState + // requires a real, non-file URL. + ASSERT_TRUE(embedded_test_server()->Start()); + GURL url(embedded_test_server()->GetURL("foo.com", "/title3.html")); + ui_test_utils::NavigateToURL(browser(), url); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + // Do a replaceState() to create a new navigation entry. + ASSERT_TRUE(content::ExecuteScript(web_contents, + "history.replaceState({foo: 'bar'},'')")); + content::WaitForLoadStop(web_contents); + + // Because there was no user gesture and the url did not change, there should + // be a single url with a single visit. + std::vector<GURL> urls(GetHistoryContents()); + ASSERT_EQ(1u, urls.size()); + EXPECT_EQ(url, urls[0]); + history::QueryURLResult url_result = QueryURL(url); + EXPECT_EQ(1u, url_result.visits.size()); +}
diff --git a/chrome/browser/lite_video/lite_video_decider.cc b/chrome/browser/lite_video/lite_video_decider.cc index f7d5910..e5a5e42d 100644 --- a/chrome/browser/lite_video/lite_video_decider.cc +++ b/chrome/browser/lite_video/lite_video_decider.cc
@@ -73,7 +73,7 @@ // The default downlink bandwidth estimate used for throttling media requests. // Only used when forcing LiteVideos to be allowed. -constexpr double kLiteVideoDefaultDownlinkBandwidthKbps = 250.0; +constexpr double kLiteVideoDefaultDownlinkBandwidthKbps = 400.0; } // namespace @@ -129,8 +129,9 @@ if (switches::ShouldOverrideLiteVideoDecision()) { // Return a default configured hint. return LiteVideoHint(kLiteVideoDefaultDownlinkBandwidthKbps, - features::LiteVideoTargetDownlinkRTTLatencyMs(), - features::LiteVideoKilobytesToBufferBeforeThrottle()); + features::LiteVideoTargetDownlinkRTTLatency(), + features::LiteVideoKilobytesToBufferBeforeThrottle(), + features::LiteVideoMaxThrottlingDelay()); } if (!CanApplyOnCurrentNetworkConditions(is_cellular_network_,
diff --git a/chrome/browser/lite_video/lite_video_decider_unittest.cc b/chrome/browser/lite_video/lite_video_decider_unittest.cc index a6bf024..e4f2b574a 100644 --- a/chrome/browser/lite_video/lite_video_decider_unittest.cc +++ b/chrome/browser/lite_video/lite_video_decider_unittest.cc
@@ -213,8 +213,9 @@ navigation_handle.set_page_transition(ui::PAGE_TRANSITION_TYPED); lite_video::LiteVideoHint seeded_hint( /*target_downlink_bandwidth_kbps=*/123, - /*target_downlink_rtt_latency_ms=*/2500, - /*kilobytes_to_buffer_before_throttle=*/500); + /*target_downlink_rtt_latency=*/base::TimeDelta::FromMilliseconds(2500), + /*kilobytes_to_buffer_before_throttle=*/500, + /*max_throttling_delay=*/base::TimeDelta::FromMilliseconds(5000)); SeedLiteVideoHintCache(url, seeded_hint); lite_video::LiteVideoBlocklistReason blocklist_reason; @@ -226,10 +227,11 @@ EXPECT_EQ(blocklist_reason, lite_video::LiteVideoBlocklistReason::kAllowed); EXPECT_EQ(seeded_hint.target_downlink_bandwidth_kbps(), hint->target_downlink_bandwidth_kbps()); - EXPECT_EQ(seeded_hint.target_downlink_rtt_latency_ms(), - hint->target_downlink_rtt_latency_ms()); + EXPECT_EQ(seeded_hint.target_downlink_rtt_latency(), + hint->target_downlink_rtt_latency()); EXPECT_EQ(seeded_hint.kilobytes_to_buffer_before_throttle(), hint->kilobytes_to_buffer_before_throttle()); + EXPECT_EQ(seeded_hint.max_throttling_delay(), hint->max_throttling_delay()); histogram_tester.ExpectUniqueSample( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kAllowed, 1); @@ -249,8 +251,9 @@ navigation_handle.set_page_transition(ui::PAGE_TRANSITION_TYPED); lite_video::LiteVideoHint seeded_hint( /*target_downlink_bandwidth_kbps=*/123, - /*target_downlink_rtt_latency_ms=*/2500, - /*kilobytes_to_buffer_before_throttle=*/500); + /*target_downlink_rtt_latency=*/base::TimeDelta::FromMilliseconds(2500), + /*kilobytes_to_buffer_before_throttle=*/500, + /*max_throttling_delay=*/base::TimeDelta::FromMilliseconds(5000)); SeedLiteVideoHintCache(url, seeded_hint); lite_video::LiteVideoBlocklistReason blocklist_reason; @@ -277,8 +280,9 @@ navigation_handle.set_page_transition(ui::PAGE_TRANSITION_TYPED); lite_video::LiteVideoHint seeded_hint( /*target_downlink_bandwidth_kbps=*/123, - /*target_downlink_rtt_latency_ms=*/2500, - /*kilobytes_to_buffer_before_throttle=*/500); + /*target_downlink_rtt_latency=*/base::TimeDelta::FromMilliseconds(2500), + /*kilobytes_to_buffer_before_throttle=*/500, + /*max_throttling_delay=*/base::TimeDelta::FromMilliseconds(5000)); SeedLiteVideoHintCache(url, seeded_hint); lite_video::LiteVideoBlocklistReason blocklist_reason; @@ -289,10 +293,11 @@ EXPECT_EQ(blocklist_reason, lite_video::LiteVideoBlocklistReason::kAllowed); EXPECT_EQ(seeded_hint.target_downlink_bandwidth_kbps(), hint->target_downlink_bandwidth_kbps()); - EXPECT_EQ(seeded_hint.target_downlink_rtt_latency_ms(), - hint->target_downlink_rtt_latency_ms()); + EXPECT_EQ(seeded_hint.target_downlink_rtt_latency(), + hint->target_downlink_rtt_latency()); EXPECT_EQ(seeded_hint.kilobytes_to_buffer_before_throttle(), hint->kilobytes_to_buffer_before_throttle()); + EXPECT_EQ(seeded_hint.max_throttling_delay(), hint->max_throttling_delay()); histogram_tester.ExpectUniqueSample( "LiteVideo.CanApplyLiteVideo.UserBlocklist.SubFrame", lite_video::LiteVideoBlocklistReason::kAllowed, 1); @@ -313,8 +318,9 @@ lite_video::LiteVideoHint seeded_hint( /*target_downlink_bandwidth_kbps=*/123, - /*target_downlink_rtt_latency_ms=*/2500, - /*kilobytes_to_buffer_before_throttle=*/500); + /*target_downlink_rtt_latency=*/base::TimeDelta::FromMilliseconds(2500), + /*kilobytes_to_buffer_before_throttle=*/500, + /*max_throttling_delay=*/base::TimeDelta::FromMilliseconds(5000)); SeedLiteVideoHintCache(url, seeded_hint); lite_video::LiteVideoBlocklistReason blocklist_reason; @@ -344,8 +350,9 @@ lite_video::LiteVideoHint seeded_hint( /*target_downlink_bandwidth_kbps=*/123, - /*target_downlink_rtt_latency_ms=*/2500, - /*kilobytes_to_buffer_before_throttle=*/500); + /*target_downlink_rtt_latency=*/base::TimeDelta::FromMilliseconds(2500), + /*kilobytes_to_buffer_before_throttle=*/500, + /*max_throttling_delay=*/base::TimeDelta::FromMilliseconds(5000)); SeedLiteVideoHintCache(url, seeded_hint); lite_video::LiteVideoBlocklistReason blocklist_reason;
diff --git a/chrome/browser/lite_video/lite_video_features.cc b/chrome/browser/lite_video/lite_video_features.cc index e73e91b2e..5491473 100644 --- a/chrome/browser/lite_video/lite_video_features.cc +++ b/chrome/browser/lite_video/lite_video_features.cc
@@ -46,13 +46,19 @@ return lite_video_origin_hints; } -int LiteVideoTargetDownlinkRTTLatencyMs() { - return GetFieldTrialParamByFeatureAsInt( - ::features::kLiteVideo, "target_downlink_rtt_latency_ms", 2500); +base::TimeDelta LiteVideoTargetDownlinkRTTLatency() { + return base::TimeDelta::FromMilliseconds(GetFieldTrialParamByFeatureAsInt( + ::features::kLiteVideo, "target_downlink_rtt_latency_ms", 500)); } + int LiteVideoKilobytesToBufferBeforeThrottle() { return GetFieldTrialParamByFeatureAsInt( - ::features::kLiteVideo, "kilobyte_to_buffer_before_throttle", 500); + ::features::kLiteVideo, "kilobyte_to_buffer_before_throttle", 10); +} + +base::TimeDelta LiteVideoMaxThrottlingDelay() { + return base::TimeDelta::FromMilliseconds(GetFieldTrialParamByFeatureAsInt( + ::features::kLiteVideo, "max_throttling_delay_ms", 5000)); } size_t MaxUserBlocklistHosts() {
diff --git a/chrome/browser/lite_video/lite_video_features.h b/chrome/browser/lite_video/lite_video_features.h index b83c572..68957929 100644 --- a/chrome/browser/lite_video/lite_video_features.h +++ b/chrome/browser/lite_video/lite_video_features.h
@@ -31,12 +31,15 @@ // The target for of the round-trip time for media requests used when // throttling media requests. -int LiteVideoTargetDownlinkRTTLatencyMs(); +base::TimeDelta LiteVideoTargetDownlinkRTTLatency(); // The number of kilobytes to be buffered before starting to throttle media // requests. int LiteVideoKilobytesToBufferBeforeThrottle(); +// The maximum delay a throttle can introduce for a media request. +base::TimeDelta LiteVideoMaxThrottlingDelay(); + // The maximum number of hosts maintained for each blocklist for the LiteVideo // optimization. size_t MaxUserBlocklistHosts();
diff --git a/chrome/browser/lite_video/lite_video_hint.cc b/chrome/browser/lite_video/lite_video_hint.cc index 1e059f3..7dd8bec 100644 --- a/chrome/browser/lite_video/lite_video_hint.cc +++ b/chrome/browser/lite_video/lite_video_hint.cc
@@ -7,11 +7,12 @@ namespace lite_video { LiteVideoHint::LiteVideoHint(int target_downlink_bandwidth_kbps, - int target_downlink_rtt_latency_ms, - int kilobytes_to_buffer_before_throttle) + base::TimeDelta target_downlink_rtt_latency, + int kilobytes_to_buffer_before_throttle, + base::TimeDelta max_throttling_delay) : target_downlink_bandwidth_kbps_(target_downlink_bandwidth_kbps), - target_downlink_rtt_latency_ms_(target_downlink_rtt_latency_ms), - kilobytes_to_buffer_before_throttle_( - kilobytes_to_buffer_before_throttle) {} + target_downlink_rtt_latency_(target_downlink_rtt_latency), + kilobytes_to_buffer_before_throttle_(kilobytes_to_buffer_before_throttle), + max_throttling_delay_(max_throttling_delay) {} } // namespace lite_video
diff --git a/chrome/browser/lite_video/lite_video_hint.h b/chrome/browser/lite_video/lite_video_hint.h index c0aee1d..583e7fd 100644 --- a/chrome/browser/lite_video/lite_video_hint.h +++ b/chrome/browser/lite_video/lite_video_hint.h
@@ -7,31 +7,37 @@ #include <stdint.h> +#include "base/time/time.h" + namespace lite_video { class LiteVideoHint { public: LiteVideoHint(int target_downlink_bandwidth_kbps, - int target_downlink_rtt_latency_ms, - int kilobytes_to_buffer_before_throttle); + base::TimeDelta target_downlink_rtt_latency, + int kilobytes_to_buffer_before_throttle, + base::TimeDelta max_throttling_delay); ~LiteVideoHint() = default; int target_downlink_bandwidth_kbps() const { return target_downlink_bandwidth_kbps_; } - int target_downlink_rtt_latency_ms() const { - return target_downlink_rtt_latency_ms_; + base::TimeDelta target_downlink_rtt_latency() const { + return target_downlink_rtt_latency_; } int kilobytes_to_buffer_before_throttle() const { return kilobytes_to_buffer_before_throttle_; } + base::TimeDelta max_throttling_delay() const { return max_throttling_delay_; } + private: const int target_downlink_bandwidth_kbps_; - const int target_downlink_rtt_latency_ms_; + const base::TimeDelta target_downlink_rtt_latency_; const int kilobytes_to_buffer_before_throttle_; + const base::TimeDelta max_throttling_delay_; }; } // namespace lite_video
diff --git a/chrome/browser/lite_video/lite_video_hint_cache.cc b/chrome/browser/lite_video/lite_video_hint_cache.cc index 4d583fe7..1115cd09 100644 --- a/chrome/browser/lite_video/lite_video_hint_cache.cc +++ b/chrome/browser/lite_video/lite_video_hint_cache.cc
@@ -27,8 +27,9 @@ return base::nullopt; return LiteVideoHint(*target_downlink_bandwidth_kbps, - features::LiteVideoTargetDownlinkRTTLatencyMs(), - features::LiteVideoKilobytesToBufferBeforeThrottle()); + features::LiteVideoTargetDownlinkRTTLatency(), + features::LiteVideoKilobytesToBufferBeforeThrottle(), + features::LiteVideoMaxThrottlingDelay()); } } // namespace lite_video
diff --git a/chrome/browser/lite_video/lite_video_hint_cache_unittest.cc b/chrome/browser/lite_video/lite_video_hint_cache_unittest.cc index ed6c1d9..1878628 100644 --- a/chrome/browser/lite_video/lite_video_hint_cache_unittest.cc +++ b/chrome/browser/lite_video/lite_video_hint_cache_unittest.cc
@@ -50,8 +50,8 @@ EXPECT_EQ(123, hint->target_downlink_bandwidth_kbps()); EXPECT_EQ(lite_video::features::LiteVideoKilobytesToBufferBeforeThrottle(), hint->kilobytes_to_buffer_before_throttle()); - EXPECT_EQ(lite_video::features::LiteVideoTargetDownlinkRTTLatencyMs(), - hint->target_downlink_rtt_latency_ms()); + EXPECT_EQ(lite_video::features::LiteVideoTargetDownlinkRTTLatency(), + hint->target_downlink_rtt_latency()); histogram_tester.ExpectUniqueSample("LiteVideo.OriginHints.ParseResult", true, 1); }
diff --git a/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc b/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc index e678973..68c1060d 100644 --- a/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc +++ b/chrome/browser/lite_video/lite_video_keyed_service_browsertest.cc
@@ -223,6 +223,7 @@ 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", false, 1); + histogram_tester()->ExpectTotalCount("LiteVideo.HintAgent.HasHint", 0); histogram_tester()->ExpectUniqueSample( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kAllowed, 1); @@ -256,10 +257,12 @@ ui_test_utils::NavigateToURL(browser(), navigation_url); EXPECT_GT(RetryForHistogramUntilCountReached( - *histogram_tester(), "LiteVideo.Navigation.HasHint", 1), + *histogram_tester(), "LiteVideo.HintAgent.HasHint", 1), 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", true, 1); + histogram_tester()->ExpectUniqueSample("LiteVideo.HintAgent.HasHint", true, + 1); histogram_tester()->ExpectUniqueSample( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kAllowed, 1); @@ -295,6 +298,7 @@ 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", false, 1); + histogram_tester()->ExpectTotalCount("LiteVideo.HintAgent.HasHint", 0); histogram_tester()->ExpectUniqueSample( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kNavigationReload, 1); @@ -312,6 +316,7 @@ 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", false, 2); + histogram_tester()->ExpectTotalCount("LiteVideo.HintAgent.HasHint", 0); histogram_tester()->ExpectBucketCount( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kNavigationBlocklisted, 1); @@ -359,6 +364,7 @@ 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", false, 1); + histogram_tester()->ExpectTotalCount("LiteVideo.HintAgent.HasHint", 0); histogram_tester()->ExpectUniqueSample( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kNavigationForwardBack, 1); @@ -376,6 +382,7 @@ 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", false, 2); + histogram_tester()->ExpectTotalCount("LiteVideo.HintAgent.HasHint", 0); histogram_tester()->ExpectBucketCount( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kNavigationBlocklisted, 1); @@ -420,10 +427,12 @@ ui_test_utils::NavigateToURL(¶ms); EXPECT_GT(RetryForHistogramUntilCountReached( - *histogram_tester(), "LiteVideo.Navigation.HasHint", 1), + *histogram_tester(), "LiteVideo.HintAgent.HasHint", 1), 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", true, 1); + histogram_tester()->ExpectUniqueSample("LiteVideo.HintAgent.HasHint", true, + 1); histogram_tester()->ExpectUniqueSample( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kAllowed, 1); @@ -434,10 +443,11 @@ ui_test_utils::NavigateToURL(¶ms); EXPECT_GT(RetryForHistogramUntilCountReached( - *histogram_tester(), "LiteVideo.Navigation.HasHint", 2), + *histogram_tester(), "LiteVideo.HintAgent.HasHint", 2), 0); histogram_tester()->ExpectBucketCount("LiteVideo.Navigation.HasHint", true, 2); + histogram_tester()->ExpectBucketCount("LiteVideo.HintAgent.HasHint", true, 2); histogram_tester()->ExpectBucketCount( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", lite_video::LiteVideoBlocklistReason::kAllowed, 2); @@ -568,6 +578,7 @@ histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", false, 1); + histogram_tester()->ExpectTotalCount("LiteVideo.HintAgent.HasHint", 0); histogram_tester()->ExpectTotalCount( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", 0); histogram_tester()->ExpectTotalCount( @@ -595,6 +606,7 @@ 0); histogram_tester()->ExpectUniqueSample("LiteVideo.Navigation.HasHint", false, 1); + histogram_tester()->ExpectTotalCount("LiteVideo.HintAgent.HasHint", 0); histogram_tester()->ExpectTotalCount( "LiteVideo.CanApplyLiteVideo.UserBlocklist.MainFrame", 0); histogram_tester()->ExpectTotalCount(
diff --git a/chrome/browser/lite_video/lite_video_observer.cc b/chrome/browser/lite_video/lite_video_observer.cc index af29099..0a43b34 100644 --- a/chrome/browser/lite_video/lite_video_observer.cc +++ b/chrome/browser/lite_video/lite_video_observer.cc
@@ -109,9 +109,30 @@ LOCAL_HISTOGRAM_BOOLEAN("LiteVideo.Navigation.HasHint", hint ? true : false); - // TODO(crbug/1082553): Add logic to pass the hint via the - // ResourceLoadingAgent to the LiteVideoAgent for use when throttling media - // requests. Only pass a hint if the decision is kAllowed. + if (!hint) + return; + + content::RenderFrameHost* render_frame_host = + navigation_handle->GetRenderFrameHost(); + if (!render_frame_host || !render_frame_host->GetProcess()) + return; + + mojo::AssociatedRemote<blink::mojom::PreviewsResourceLoadingHintsReceiver> + loading_hints_agent; + + auto hint_ptr = blink::mojom::LiteVideoHint::New(); + hint_ptr->target_downlink_bandwidth_kbps = + hint->target_downlink_bandwidth_kbps(); + hint_ptr->kilobytes_to_buffer_before_throttle = + hint->kilobytes_to_buffer_before_throttle(); + hint_ptr->target_downlink_rtt_latency = hint->target_downlink_rtt_latency(); + hint_ptr->max_throttling_delay = hint->max_throttling_delay(); + + if (render_frame_host->GetRemoteAssociatedInterfaces()) { + render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface( + &loading_hints_agent); + loading_hints_agent->SetLiteVideoHint(std::move(hint_ptr)); + } } lite_video::LiteVideoDecision LiteVideoObserver::MakeLiteVideoDecision(
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc index aea1a9e..7a6592545 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.cc
@@ -117,7 +117,9 @@ feed_id, kMediaFeedsItemsMaxCount, // Require Safe Search checking if the integration is enabled. base::FeatureList::IsEnabled(media::kMediaFeedsSafeSearch)), - std::move(callback)); + base::BindOnce(&KaleidoscopeDataProviderImpl::OnGotMediaFeedContents, + weak_ptr_factory.GetWeakPtr(), std::move(callback), + feed_id)); } void KaleidoscopeDataProviderImpl::GetContinueWatchingMediaFeedItems( @@ -128,7 +130,9 @@ kMediaFeedsItemsMaxCount, // Require Safe Search checking if the integration is enabled. base::FeatureList::IsEnabled(media::kMediaFeedsSafeSearch)), - std::move(callback)); + base::BindOnce( + &KaleidoscopeDataProviderImpl::OnGotContinueWatchingMediaFeedItems, + weak_ptr_factory.GetWeakPtr(), std::move(callback))); } media_history::MediaHistoryKeyedService* @@ -151,3 +155,31 @@ pending_callbacks_.clear(); } + +void KaleidoscopeDataProviderImpl::OnGotMediaFeedContents( + GetMediaFeedContentsCallback callback, + const int64_t feed_id, + std::vector<media_feeds::mojom::MediaFeedItemPtr> items) { + std::set<int64_t> ids; + for (auto& item : items) + ids.insert(item->id); + + // Mark the returned feed and feed items as having been displayed. + GetMediaHistoryService()->UpdateMediaFeedDisplayTime(feed_id); + GetMediaHistoryService()->IncrementMediaFeedItemsShownCount(ids); + + std::move(callback).Run(std::move(items)); +} + +void KaleidoscopeDataProviderImpl::OnGotContinueWatchingMediaFeedItems( + GetContinueWatchingMediaFeedItemsCallback callback, + std::vector<media_feeds::mojom::MediaFeedItemPtr> items) { + std::set<int64_t> ids; + for (auto& item : items) + ids.insert(item->id); + + // Mark the returned feed items as having been displayed. + GetMediaHistoryService()->IncrementMediaFeedItemsShownCount(ids); + + std::move(callback).Run(std::move(items)); +}
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.h b/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.h index 0445428..584aa271 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.h +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_data_provider_impl.h
@@ -7,6 +7,7 @@ #include <memory> +#include "base/memory/weak_ptr.h" #include "chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom.h" #include "google_apis/gaia/google_service_auth_error.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -52,6 +53,14 @@ void OnAccessTokenAvailable(GoogleServiceAuthError error, signin::AccessTokenInfo access_token_info); + void OnGotMediaFeedContents( + GetMediaFeedContentsCallback callback, + const int64_t feed_id, + std::vector<media_feeds::mojom::MediaFeedItemPtr> items); + void OnGotContinueWatchingMediaFeedItems( + GetContinueWatchingMediaFeedItemsCallback callback, + std::vector<media_feeds::mojom::MediaFeedItemPtr> items); + // Helper for fetching OAuth2 access tokens. This is non-null iff an access // token request is currently in progress. std::unique_ptr<signin::PrimaryAccountAccessTokenFetcher> token_fetcher_; @@ -67,6 +76,8 @@ Profile* const profile_; mojo::Receiver<media::mojom::KaleidoscopeDataProvider> receiver_; + + base::WeakPtrFactory<KaleidoscopeDataProviderImpl> weak_ptr_factory{this}; }; #endif // CHROME_BROWSER_MEDIA_KALEIDOSCOPE_KALEIDOSCOPE_DATA_PROVIDER_IMPL_H_
diff --git a/chrome/browser/metrics/tab_stats_tracker.cc b/chrome/browser/metrics/tab_stats_tracker.cc index f10e358..af20b0f 100644 --- a/chrome/browser/metrics/tab_stats_tracker.cc +++ b/chrome/browser/metrics/tab_stats_tracker.cc
@@ -252,7 +252,7 @@ } } - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override { + void DidGetUserInteraction(const blink::WebInputEvent& event) override { tab_stats_tracker_->tab_stats_data_store()->OnTabInteraction( web_contents()); }
diff --git a/chrome/browser/metrics/tab_stats_tracker_unittest.cc b/chrome/browser/metrics/tab_stats_tracker_unittest.cc index 1e94aa9..c8da6598 100644 --- a/chrome/browser/metrics/tab_stats_tracker_unittest.cc +++ b/chrome/browser/metrics/tab_stats_tracker_unittest.cc
@@ -373,7 +373,7 @@ // Simulate an interaction on a tab, we should now see 3 tabs being marked as // used. content::WebContentsTester::For(web_contentses[2].get()) - ->TestDidReceiveInputEvent(blink::WebInputEvent::Type::kMouseDown); + ->TestDidReceiveMouseDownEvent(); tab_stats_tracker_->OnInterval(kValidLongInterval, interval_map); histogram_tester_.ExpectBucketCount( TestUmaStatsReportingDelegate::GetIntervalHistogramName( @@ -401,7 +401,7 @@ // We need to re-interact with the WebContents as each call to |OnInterval| // reset the interval and clear the interaction bit. content::WebContentsTester::For(web_contentses.back().get()) - ->TestDidReceiveInputEvent(blink::WebInputEvent::Type::kMouseDown); + ->TestDidReceiveMouseDownEvent(); web_contentses.pop_back(); tab_stats_tracker_->OnInterval(kValidLongInterval, interval_map); histogram_tester_.ExpectBucketCount(
diff --git a/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.cc b/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.cc index e6bacb3..43677bac 100644 --- a/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.cc +++ b/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.cc
@@ -183,6 +183,10 @@ NearbyShareDecryptedPublicCertificate::NearbyShareDecryptedPublicCertificate( NearbyShareDecryptedPublicCertificate&&) = default; +NearbyShareDecryptedPublicCertificate& +NearbyShareDecryptedPublicCertificate::operator=( + NearbyShareDecryptedPublicCertificate&&) = default; + NearbyShareDecryptedPublicCertificate:: ~NearbyShareDecryptedPublicCertificate() = default;
diff --git a/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h b/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h index b8bb8ca..490b62a7 100644 --- a/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h +++ b/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h
@@ -33,6 +33,8 @@ NearbyShareDecryptedPublicCertificate( NearbyShareDecryptedPublicCertificate&&); + NearbyShareDecryptedPublicCertificate& operator=( + NearbyShareDecryptedPublicCertificate&&); virtual ~NearbyShareDecryptedPublicCertificate();
diff --git a/chrome/browser/nearby_sharing/incoming_share_target_info.cc b/chrome/browser/nearby_sharing/incoming_share_target_info.cc new file mode 100644 index 0000000..aa4253d0 --- /dev/null +++ b/chrome/browser/nearby_sharing/incoming_share_target_info.cc
@@ -0,0 +1,27 @@ +// Copyright 2020 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/nearby_sharing/incoming_share_target_info.h" + +#include "chrome/browser/nearby_sharing/nearby_connection.h" + +IncomingShareTargetInfo::IncomingShareTargetInfo() = default; +IncomingShareTargetInfo::~IncomingShareTargetInfo() = default; + +IncomingShareTargetInfo::IncomingShareTargetInfo(IncomingShareTargetInfo&&) = + default; +IncomingShareTargetInfo& IncomingShareTargetInfo::operator=( + IncomingShareTargetInfo&&) = default; + +std::ostream& operator<<(std::ostream& out, + const IncomingShareTargetInfo& share_target) { + out << "IncomingShareTargetInfo<endpoint_id: " + << (share_target.endpoint_id().has_value() + ? share_target.endpoint_id().value() + : "") + << ", has_certificate: " << (share_target.certificate().has_value()) + << ", has_connection: " << (share_target.nearby_connection() != nullptr) + << ">"; + return out; +}
diff --git a/chrome/browser/nearby_sharing/incoming_share_target_info.h b/chrome/browser/nearby_sharing/incoming_share_target_info.h new file mode 100644 index 0000000..87fec12 --- /dev/null +++ b/chrome/browser/nearby_sharing/incoming_share_target_info.h
@@ -0,0 +1,64 @@ +// Copyright 2020 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_NEARBY_SHARING_INCOMING_SHARE_TARGET_INFO_H_ +#define CHROME_BROWSER_NEARBY_SHARING_INCOMING_SHARE_TARGET_INFO_H_ + +#include <memory> +#include <string> + +#include "base/optional.h" +#include "chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h" + +class NearbyConnection; + +class IncomingShareTargetInfo { + public: + IncomingShareTargetInfo(); + ~IncomingShareTargetInfo(); + + IncomingShareTargetInfo(const IncomingShareTargetInfo&) = delete; + IncomingShareTargetInfo& operator=(const IncomingShareTargetInfo&) = delete; + + IncomingShareTargetInfo(IncomingShareTargetInfo&&); + IncomingShareTargetInfo& operator=(IncomingShareTargetInfo&&); + + void set_endpoint_id(std::string endpoint_id) { + endpoint_id_ = std::move(endpoint_id); + } + + const base::Optional<std::string>& endpoint_id() const { + return endpoint_id_; + } + + void set_certificate(NearbyShareDecryptedPublicCertificate certificate) { + certificate_ = std::move(certificate); + } + + const base::Optional<NearbyShareDecryptedPublicCertificate>& certificate() + const { + return certificate_; + } + + void set_nearby_connection(std::unique_ptr<NearbyConnection> connection) { + connection_ = std::move(connection); + } + + NearbyConnection* nearby_connection() const { return connection_.get(); } + + void set_token(std::string token) { token_ = std::move(token); } + + const base::Optional<std::string>& token() const { return token_; } + + private: + friend std::ostream& operator<<(std::ostream& out, + const IncomingShareTargetInfo& share_target); + + base::Optional<std::string> endpoint_id_; + base::Optional<NearbyShareDecryptedPublicCertificate> certificate_; + std::unique_ptr<NearbyConnection> connection_; + base::Optional<std::string> token_; +}; + +#endif // CHROME_BROWSER_NEARBY_SHARING_INCOMING_SHARE_TARGET_INFO_H_
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc index dae2abc8..af2bca8 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc
@@ -646,3 +646,23 @@ advertising_power_level_ = PowerLevel::kUnknown; NS_LOG(VERBOSE) << __func__ << ": Advertising has stopped"; } + +void NearbySharingServiceImpl::OnIncomingTransferUpdate( + const ShareTarget& share_target, + TransferMetadata metadata) { + // TODO(himanshujaju) - Implement. +} + +IncomingShareTargetInfo& NearbySharingServiceImpl::GetIncomingShareTargetInfo( + const ShareTarget& share_target) { + auto ret = incoming_share_target_info_map_.insert( + {share_target.id(), IncomingShareTargetInfo()}); + DCHECK(ret.first != incoming_share_target_info_map_.end()); + + return ret.first->second; +} + +NearbyConnection* NearbySharingServiceImpl::GetIncomingConnection( + const ShareTarget& share_target) { + return GetIncomingShareTargetInfo(share_target).nearby_connection(); +}
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h index 1b18f47..b395076 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_NEARBY_SHARING_NEARBY_SHARING_SERVICE_IMPL_H_ #define CHROME_BROWSER_NEARBY_SHARING_NEARBY_SHARING_SERVICE_IMPL_H_ +#include <map> #include <memory> #include <string> #include <utility> @@ -14,6 +15,7 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "base/sequence_checker.h" +#include "chrome/browser/nearby_sharing/incoming_share_target_info.h" #include "chrome/browser/nearby_sharing/nearby_connections_manager.h" #include "chrome/browser/nearby_sharing/nearby_constants.h" #include "chrome/browser/nearby_sharing/nearby_notification_manager.h" @@ -102,6 +104,12 @@ void InvalidateReceiveSurfaceState(); void InvalidateAdvertisingState(); void StopAdvertising(); + void OnIncomingTransferUpdate(const ShareTarget& share_target, + TransferMetadata metadata); + + IncomingShareTargetInfo& GetIncomingShareTargetInfo( + const ShareTarget& share_target); + NearbyConnection* GetIncomingConnection(const ShareTarget& share_target); PrefService* prefs_; Profile* profile_; @@ -142,6 +150,11 @@ // True if we're currently sending or receiving a file. bool is_transferring_files_ = false; + // A map of ShareTarget id to IncomingShareTargetInfo. This lets us know which + // Nearby Connections endpoint and public certificate are related to the + // incoming share target. + std::map<int, IncomingShareTargetInfo> incoming_share_target_info_map_; + SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<NearbySharingServiceImpl> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/net/variations_http_headers_browsertest.cc b/chrome/browser/net/variations_http_headers_browsertest.cc index 8cad5008..51943f5 100644 --- a/chrome/browser/net/variations_http_headers_browsertest.cc +++ b/chrome/browser/net/variations_http_headers_browsertest.cc
@@ -34,7 +34,7 @@ #include "components/optimization_guide/proto/hints.pb.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/variations/net/variations_http_headers.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/test/browser_test.h" @@ -65,7 +65,7 @@ void PostEarlyInitialization() override { // Set up some fake variations. auto* variations_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); + variations::VariationsIdsProvider::GetInstance(); variations_provider->ForceVariationIds({"12", "456", "t789"}, ""); } @@ -380,10 +380,10 @@ scoped_refptr<base::FieldTrial> trial_1(CreateTrialAndAssociateId( "t1", default_name, variations::GOOGLE_WEB_PROPERTIES_SIGNED_IN, 123)); - auto* variations_http_header_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); - EXPECT_NE(variations_http_header_provider->GetClientDataHeader(true), - variations_http_header_provider->GetClientDataHeader(false)); + auto* variations_ids_provider = + variations::VariationsIdsProvider::GetInstance(); + EXPECT_NE(variations_ids_provider->GetClientDataHeader(true), + variations_ids_provider->GetClientDataHeader(false)); } } // namespace @@ -438,7 +438,7 @@ base::Optional<std::string> header = GetReceivedHeader(GetGoogleUrl(), "X-Client-Data"); ASSERT_TRUE(header); - EXPECT_EQ(*header, variations::VariationsHttpHeaderProvider::GetInstance() + EXPECT_EQ(*header, variations::VariationsIdsProvider::GetInstance() ->GetClientDataHeader(true)); } @@ -453,7 +453,7 @@ base::Optional<std::string> header = GetReceivedHeader(GetGoogleUrl(), "X-Client-Data"); ASSERT_TRUE(header); - EXPECT_EQ(*header, variations::VariationsHttpHeaderProvider::GetInstance() + EXPECT_EQ(*header, variations::VariationsIdsProvider::GetInstance() ->GetClientDataHeader(false)); }
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index eb654cfec..c84039d4 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -1455,8 +1455,8 @@ handlers->AddHandler(std::make_unique<BrowsingHistoryPolicyHandler>()); handlers->AddHandler(std::make_unique<SimpleDeprecatingPolicyHandler>( - std::make_unique<URLBlacklistPolicyHandler>(key::kURLBlacklist), - std::make_unique<URLBlacklistPolicyHandler>(key::kURLBlocklist))); + std::make_unique<URLBlocklistPolicyHandler>(key::kURLBlacklist), + std::make_unique<URLBlocklistPolicyHandler>(key::kURLBlocklist))); handlers->AddHandler(std::make_unique<SimpleDeprecatingPolicyHandler>( std::make_unique<SimplePolicyHandler>(key::kURLWhitelist, policy_prefs::kUrlWhitelist,
diff --git a/chrome/browser/policy/profile_policy_connector.cc b/chrome/browser/policy/profile_policy_connector.cc index db816163..1db33c3 100644 --- a/chrome/browser/policy/profile_policy_connector.cc +++ b/chrome/browser/policy/profile_policy_connector.cc
@@ -21,11 +21,13 @@ #include "components/policy/core/common/cloud/cloud_policy_manager.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/configuration_policy_provider.h" +#include "components/policy/core/common/legacy_chrome_policy_migrator.h" #include "components/policy/core/common/policy_bundle.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_service_impl.h" #include "components/policy/core/common/schema_registry_tracking_policy_provider.h" +#include "components/policy/policy_constants.h" #if defined(OS_CHROMEOS) #include "chrome/browser/browser_process_platform_part.h" @@ -220,6 +222,9 @@ #endif #if defined(OS_CHROMEOS) + migrators.push_back(std::make_unique<LegacyChromePolicyMigrator>( + policy::key::kDeviceNativePrinters, policy::key::kDevicePrinters)); + ConfigurationPolicyProvider* user_policy_delegate_candidate = configuration_policy_provider ? configuration_policy_provider : special_user_policy_provider_.get();
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 326e702..4480b63a 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -909,7 +909,7 @@ PermissionBubbleMediaAccessHandler::RegisterProfilePrefs(registry); PlatformNotificationServiceImpl::RegisterProfilePrefs(registry); policy::DeveloperToolsPolicyHandler::RegisterProfilePrefs(registry); - policy::URLBlacklistManager::RegisterProfilePrefs(registry); + policy::URLBlocklistManager::RegisterProfilePrefs(registry); PrefProxyConfigTrackerImpl::RegisterProfilePrefs(registry); PrefsTabHelper::RegisterProfilePrefs(registry, locale); PreviewsHTTPSNotificationInfoBarDecider::RegisterProfilePrefs(registry);
diff --git a/chrome/browser/profiles/profile.cc b/chrome/browser/profiles/profile.cc index f1a0dda4..c8f93c04 100644 --- a/chrome/browser/profiles/profile.cc +++ b/chrome/browser/profiles/profile.cc
@@ -30,7 +30,7 @@ #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_service.h" #include "components/variations/variations_client.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/storage_partition.h" @@ -93,7 +93,7 @@ } std::string GetVariationsHeader() const override { - return variations::VariationsHttpHeaderProvider::GetInstance() + return variations::VariationsIdsProvider::GetInstance() ->GetClientDataHeader(IsSignedIn()); }
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index b190c5b7..752426f 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -2533,10 +2533,10 @@ if (!local_state->GetBoolean(prefs::kAllowFileSelectionDialogs)) return false; - PolicyBlacklistService* service = - PolicyBlacklistFactory::GetForBrowserContext(browser_context_); - if (service->GetURLBlacklistState(params_.link_url) == - policy::URLBlacklist::URLBlacklistState::URL_IN_BLACKLIST) { + PolicyBlocklistService* service = + PolicyBlocklistFactory::GetForBrowserContext(browser_context_); + if (service->GetURLBlocklistState(params_.link_url) == + policy::URLBlocklist::URLBlocklistState::URL_IN_BLOCKLIST) { return false; }
diff --git a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc index 680266de..8e717c5 100644 --- a/chrome/browser/resource_coordinator/tab_manager_browsertest.cc +++ b/chrome/browser/resource_coordinator/tab_manager_browsertest.cc
@@ -951,8 +951,9 @@ } // namespace -// Do not run in debug builds to avoid timeouts due to multiple navigations. -#if !defined(NDEBUG) +// Do not run in debug or ASAN builds to avoid timeouts due to multiple +// navigations. https://crbug.com/1106485 +#if !defined(NDEBUG) || defined(ADDRESS_SANITIZER) #define MAYBE_DiscardTabsWithMinimizedWindow \ DISABLED_DiscardTabsWithMinimizedWindow #else @@ -988,13 +989,13 @@ IsTabDiscarded(browser()->tab_strip_model()->GetWebContentsAt(1))); } -// Do not run in debug builds to avoid timeouts due to multiple navigations. -#if !defined(NDEBUG) +// Do not run in debug or ASAN builds to avoid timeouts due to multiple +// navigations. https://crbug.com/1106485 +#if !defined(NDEBUG) || defined(ADDRESS_SANITIZER) #define MAYBE_DiscardTabsWithOccludedWindow \ DISABLED_DiscardTabsWithOccludedWindow #else -// TODO(https://crbug.com/1106485): The test is flaky on release builds. -#define MAYBE_DiscardTabsWithOccludedWindow DISABLED_DiscardTabsWithOccludedWindow +#define MAYBE_DiscardTabsWithOccludedWindow DiscardTabsWithOccludedWindow #endif IN_PROC_BROWSER_TEST_F(TabManagerTest, MAYBE_DiscardTabsWithOccludedWindow) { // Occluded browser.
diff --git a/chrome/browser/resources/settings/chromeos/device_page/display.js b/chrome/browser/resources/settings/chromeos/device_page/display.js index 8f1a163..d76c1e18 100644 --- a/chrome/browser/resources/settings/chromeos/device_page/display.js +++ b/chrome/browser/resources/settings/chromeos/device_page/display.js
@@ -318,13 +318,6 @@ this.browserProxy_.highlightDisplay(this.invalidDisplayId_); return; } - - // When navigating back into the display page, re-select a display. - if (this.selectedDisplay && opt_newRoute == settings.routes.DISPLAY && - opt_oldRoute != settings.routes.DISPLAY) { - // setSelectedDisplay_ doesn't trigger again if it is not reattaching. - this.browserProxy_.highlightDisplay(this.selectedDisplay.id); - } }, /** @@ -743,12 +736,6 @@ 'selectedZoomPref_.value', this.getSelectedDisplayZoom_(selectedDisplay)); - if (this.allowDisplayIdentificationApi_ && - this.selectedDisplay != selectedDisplay && - this.currentRoute_ == settings.routes.DISPLAY) { - this.browserProxy_.highlightDisplay(selectedDisplay.id); - } - this.updateDisplayModeStructures_(selectedDisplay); // Set |selectedDisplay| first since only the resolution slider depends
diff --git a/chrome/browser/resources/settings/chromeos/device_page/display_layout.js b/chrome/browser/resources/settings/chromeos/device_page/display_layout.js index 666d5dd1..4e51bc1 100644 --- a/chrome/browser/resources/settings/chromeos/device_page/display_layout.js +++ b/chrome/browser/resources/settings/chromeos/device_page/display_layout.js
@@ -70,6 +70,9 @@ allowDisplayAlignmentApi_: loadTimeData.getBoolean('allowDisplayAlignmentApi'), + /** @private {string} */ + invalidDisplayId_: loadTimeData.getString('invalidDisplayId'), + /** @override */ created() { if (this.allowDisplayAlignmentApi_) { @@ -272,7 +275,14 @@ this.finishUpdateDisplayBounds(id); newBounds = this.getCalculatedDisplayBounds(id); this.lastDragCoordinates_ = null; + if (this.allowDisplayIdentificationApi_) { + // When the drag stops, remove the highlight around the display. + this.browserProxy_.highlightDisplay(this.invalidDisplayId_); + } } else { + if (this.allowDisplayIdentificationApi_) { + this.browserProxy_.highlightDisplay(id); + } // Make sure the dragged display is also selected. if (id != this.selectedDisplay.id) { this.fire('select-display', id);
diff --git a/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc b/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc index f8d1ef9..f3b15d1a 100644 --- a/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/download_protection_service_unittest.cc
@@ -665,7 +665,7 @@ // browser/renderer navigations. void SimulateLinkClick(const GURL& url) { content::WebContentsTester::For(web_contents()) - ->TestDidReceiveInputEvent(blink::WebInputEvent::Type::kMouseDown); + ->TestDidReceiveMouseDownEvent(); std::unique_ptr<content::NavigationSimulator> navigation = content::NavigationSimulator::CreateRendererInitiated( url, web_contents()->GetMainFrame());
diff --git a/chrome/browser/safe_browsing/incident_reporting/state_store.cc b/chrome/browser/safe_browsing/incident_reporting/state_store.cc index 62466bc..3bc33b7 100644 --- a/chrome/browser/safe_browsing/incident_reporting/state_store.cc +++ b/chrome/browser/safe_browsing/incident_reporting/state_store.cc
@@ -64,7 +64,7 @@ const_type_dict->GetWithoutPathExpansion(key, nullptr)) { base::DictionaryValue* type_dict = nullptr; GetPrefDict()->GetDictionaryWithoutPathExpansion(type_string, &type_dict); - type_dict->RemoveWithoutPathExpansion(key, nullptr); + type_dict->RemoveKey(key); } } @@ -81,7 +81,7 @@ const base::DictionaryValue* type_dict = nullptr; if (store_->incidents_sent_->GetDictionaryWithoutPathExpansion(type_string, &type_dict)) { - GetPrefDict()->RemoveWithoutPathExpansion(type_string, nullptr); + GetPrefDict()->RemoveKey(type_string); } }
diff --git a/chrome/browser/safe_browsing/safe_browsing_navigation_observer.cc b/chrome/browser/safe_browsing/safe_browsing_navigation_observer.cc index 8eb9fb7..875baa9d 100644 --- a/chrome/browser/safe_browsing/safe_browsing_navigation_observer.cc +++ b/chrome/browser/safe_browsing/safe_browsing_navigation_observer.cc
@@ -245,7 +245,7 @@ } void SafeBrowsingNavigationObserver::DidGetUserInteraction( - const blink::WebInputEvent::Type type) { + const blink::WebInputEvent& event) { OnUserInteraction(); }
diff --git a/chrome/browser/safe_browsing/safe_browsing_navigation_observer.h b/chrome/browser/safe_browsing/safe_browsing_navigation_observer.h index 924527b2..fd79bf4 100644 --- a/chrome/browser/safe_browsing/safe_browsing_navigation_observer.h +++ b/chrome/browser/safe_browsing/safe_browsing_navigation_observer.h
@@ -126,7 +126,7 @@ content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override; + void DidGetUserInteraction(const blink::WebInputEvent& event) override; void WebContentsDestroyed() override; void DidOpenRequestedURL(content::WebContents* new_contents, content::RenderFrameHost* source_render_frame_host,
diff --git a/chrome/browser/sync/test/integration/two_client_web_apps_bmo_sync_test.cc b/chrome/browser/sync/test/integration/two_client_web_apps_bmo_sync_test.cc index 1365829..6b93ee3 100644 --- a/chrome/browser/sync/test/integration/two_client_web_apps_bmo_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_web_apps_bmo_sync_test.cc
@@ -56,7 +56,8 @@ info.app_url = url; AppId dummy_app_id = InstallApp(info, profile1); EXPECT_EQ( - WebAppInstallObserver(profile2, {dummy_app_id}).AwaitNextInstall(), + WebAppInstallObserver::CreateInstallListener(profile2, {dummy_app_id}) + ->AwaitNextInstall(), dummy_app_id); return dummy_app_id; } @@ -461,7 +462,9 @@ ASSERT_NE(app_id1, app_id2); // Wait for both of the webapps to be installed on profile 1. - WebAppInstallObserver(GetProfile(1), {app_id1, app_id2}).AwaitNextInstall(); + WebAppInstallObserver::CreateInstallListener(GetProfile(1), + {app_id1, app_id2}) + ->AwaitNextInstall(); EXPECT_TRUE(AllProfilesHaveSameWebAppIds()); syncer::StringOrdinal page_ordinal = @@ -499,5 +502,44 @@ GetAppSorting(GetProfile(0))->GetAppLaunchOrdinal(app_id2)); } +IN_PROC_BROWSER_TEST_F(TwoClientWebAppsBMOSyncTest, UninstallSynced) { + ASSERT_TRUE(SetupSync()); + ASSERT_TRUE(AllProfilesHaveSameWebAppIds()); + ASSERT_TRUE(embedded_test_server()->Start()); + + // Install & uninstall on profile 0, and validate profile 1 sees it. + AppId app_id = InstallAppAsUserInitiated(GetProfile(0)); + + // Wait for it to arrive on profile 1. + WebAppInstallObserver::CreateInstallListener(GetProfile(1), {app_id}) + ->AwaitNextInstall(); + EXPECT_TRUE(AllProfilesHaveSameWebAppIds()); + + // Uninstall the webapp. + UninstallWebApp(GetProfile(0), app_id); + + // Wait for it to uninstall on profile 1. + WebAppInstallObserver::AwaitNextUninstall( + WebAppInstallObserver::CreateUninstallListener(GetProfile(1), {app_id}) + .get()); + EXPECT_TRUE(AllProfilesHaveSameWebAppIds()); + + // Next, install on profile 1, uninstall on profile 0, and validate that + // profile 1 sees it. + app_id = InstallAppAsUserInitiated(GetProfile(1)); + WebAppInstallObserver::CreateInstallListener(GetProfile(0), {app_id}) + ->AwaitNextInstall(); + EXPECT_TRUE(AllProfilesHaveSameWebAppIds()); + + // Uninstall the webapp. + UninstallWebApp(GetProfile(0), app_id); + + // Wait for it to uninstall on profile 1. + WebAppInstallObserver::AwaitNextUninstall( + WebAppInstallObserver::CreateUninstallListener(GetProfile(1), {app_id}) + .get()); + EXPECT_TRUE(AllProfilesHaveSameWebAppIds()); +} + } // namespace } // namespace web_app
diff --git a/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc b/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc index 96c8341..b730dc9 100644 --- a/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc +++ b/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.cc
@@ -63,7 +63,7 @@ return google_apis::CancelCallback(); } -google_apis::CancelCallback DriveServiceOnWorker::DownloadFile( +google_apis::CancelCallbackOnce DriveServiceOnWorker::DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const google_apis::DownloadActionCallback& download_action_callback, @@ -83,7 +83,7 @@ RelayCallbackToTaskRunner(worker_task_runner_.get(), FROM_HERE, progress_callback))); - return google_apis::CancelCallback(); + return google_apis::CancelCallbackOnce(); } google_apis::CancelCallback DriveServiceOnWorker::GetAboutResource(
diff --git a/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.h b/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.h index 23e3b14f..d7562e8 100644 --- a/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.h +++ b/chrome/browser/sync_file_system/drive_backend/drive_service_on_worker.h
@@ -49,7 +49,7 @@ const std::string& etag, const google_apis::EntryActionCallback& callback) override; - google_apis::CancelCallback DownloadFile( + google_apis::CancelCallbackOnce DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const google_apis::DownloadActionCallback& download_action_callback,
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index b339f07d..be72731 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -963,6 +963,9 @@ "global_media_controls/media_dialog_delegate.h", "global_media_controls/media_notification_container_impl.h", "global_media_controls/media_notification_container_observer.h", + "global_media_controls/media_notification_device_provider.h", + "global_media_controls/media_notification_device_provider_impl.cc", + "global_media_controls/media_notification_device_provider_impl.h", "global_media_controls/media_notification_service.cc", "global_media_controls/media_notification_service.h", "global_media_controls/media_notification_service_factory.cc",
diff --git a/chrome/browser/ui/blocked_content/popup_opener_tab_helper_unittest.cc b/chrome/browser/ui/blocked_content/popup_opener_tab_helper_unittest.cc index dd19fc5..624fa5f 100644 --- a/chrome/browser/ui/blocked_content/popup_opener_tab_helper_unittest.cc +++ b/chrome/browser/ui/blocked_content/popup_opener_tab_helper_unittest.cc
@@ -36,6 +36,7 @@ #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_source.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/input/web_mouse_event.h" #include "ui/base/window_open_disposition.h" #include "url/gurl.h" @@ -551,7 +552,7 @@ // members. static_cast<content::WebContentsObserver*>( blocked_content::PopupOpenerTabHelper::FromWebContents(web_contents())) - ->DidGetUserInteraction(blink::WebInputEvent::Type::kMouseDown); + ->DidGetUserInteraction(blink::WebMouseEvent()); // A subsequent navigation should be allowed, even if it is classified as a // suspicious redirect.
diff --git a/chrome/browser/ui/global_media_controls/media_notification_device_provider.h b/chrome/browser/ui/global_media_controls/media_notification_device_provider.h new file mode 100644 index 0000000..fd202f6 --- /dev/null +++ b/chrome/browser/ui/global_media_controls/media_notification_device_provider.h
@@ -0,0 +1,24 @@ +// Copyright 2020 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_UI_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_DEVICE_PROVIDER_H_ +#define CHROME_BROWSER_UI_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_DEVICE_PROVIDER_H_ + +#include "base/callback_list.h" +#include "media/audio/audio_system.h" + +class MediaNotificationDeviceProvider { + public: + virtual ~MediaNotificationDeviceProvider() = default; + + using GetOutputDevicesCallbackList = + base::OnceCallbackList<void(const media::AudioDeviceDescriptions&)>; + using GetOutputDevicesCallback = GetOutputDevicesCallbackList::CallbackType; + + virtual std::unique_ptr<MediaNotificationDeviceProvider:: + GetOutputDevicesCallbackList::Subscription> + GetOutputDeviceDescriptions(GetOutputDevicesCallback cb) = 0; +}; + +#endif // CHROME_BROWSER_UI_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_DEVICE_PROVIDER_H_
diff --git a/chrome/browser/ui/global_media_controls/media_notification_device_provider_impl.cc b/chrome/browser/ui/global_media_controls/media_notification_device_provider_impl.cc new file mode 100644 index 0000000..1172e0a --- /dev/null +++ b/chrome/browser/ui/global_media_controls/media_notification_device_provider_impl.cc
@@ -0,0 +1,35 @@ +// Copyright 2020 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/ui/global_media_controls/media_notification_device_provider_impl.h" + +#include "content/public/browser/audio_service.h" + +MediaNotificationDeviceProviderImpl::MediaNotificationDeviceProviderImpl() = + default; +MediaNotificationDeviceProviderImpl::~MediaNotificationDeviceProviderImpl() = + default; + +std::unique_ptr< + MediaNotificationDeviceProvider::GetOutputDevicesCallbackList::Subscription> +MediaNotificationDeviceProviderImpl::GetOutputDeviceDescriptions( + GetOutputDevicesCallback cb) { + if (is_querying_for_output_devices_) + return output_device_callback_list_.Add(std::move(cb)); + + if (!audio_system_) + audio_system_ = content::CreateAudioSystemForAudioService(); + audio_system_->GetDeviceDescriptions( + /*for_input=*/false, + base::BindOnce( + &MediaNotificationDeviceProviderImpl::OnReceivedDeviceDescriptions, + weak_ptr_factory_.GetWeakPtr())); + return output_device_callback_list_.Add(std::move(cb)); +} + +void MediaNotificationDeviceProviderImpl::OnReceivedDeviceDescriptions( + media::AudioDeviceDescriptions descriptions) { + is_querying_for_output_devices_ = false; + output_device_callback_list_.Notify(descriptions); +}
diff --git a/chrome/browser/ui/global_media_controls/media_notification_device_provider_impl.h b/chrome/browser/ui/global_media_controls/media_notification_device_provider_impl.h new file mode 100644 index 0000000..4d28404 --- /dev/null +++ b/chrome/browser/ui/global_media_controls/media_notification_device_provider_impl.h
@@ -0,0 +1,39 @@ +// Copyright 2020 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_UI_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_DEVICE_PROVIDER_IMPL_H_ +#define CHROME_BROWSER_UI_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_DEVICE_PROVIDER_IMPL_H_ + +#include "base/memory/weak_ptr.h" +#include "chrome/browser/ui/global_media_controls/media_notification_device_provider.h" + +class MediaNotificationDeviceProviderImpl + : public MediaNotificationDeviceProvider { + public: + MediaNotificationDeviceProviderImpl(); + MediaNotificationDeviceProviderImpl( + const MediaNotificationDeviceProviderImpl&) = delete; + MediaNotificationDeviceProviderImpl& operator=( + const MediaNotificationDeviceProviderImpl&) = delete; + ~MediaNotificationDeviceProviderImpl() override; + + std::unique_ptr<MediaNotificationDeviceProvider:: + GetOutputDevicesCallbackList::Subscription> + GetOutputDeviceDescriptions( + GetOutputDevicesCallback on_descriptions_cb) override; + + private: + void OnReceivedDeviceDescriptions( + media::AudioDeviceDescriptions descriptions); + + bool is_querying_for_output_devices_ = false; + MediaNotificationDeviceProvider::GetOutputDevicesCallbackList + output_device_callback_list_; + std::unique_ptr<media::AudioSystem> audio_system_; + + base::WeakPtrFactory<MediaNotificationDeviceProviderImpl> weak_ptr_factory_{ + this}; +}; + +#endif // CHROME_BROWSER_UI_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_DEVICE_PROVIDER_IMPL_H_
diff --git a/chrome/browser/ui/global_media_controls/media_notification_service.cc b/chrome/browser/ui/global_media_controls/media_notification_service.cc index 58da4cc..789416c4 100644 --- a/chrome/browser/ui/global_media_controls/media_notification_service.cc +++ b/chrome/browser/ui/global_media_controls/media_notification_service.cc
@@ -13,6 +13,7 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/global_media_controls/media_dialog_delegate.h" #include "chrome/browser/ui/global_media_controls/media_notification_container_impl.h" +#include "chrome/browser/ui/global_media_controls/media_notification_device_provider_impl.h" #include "chrome/browser/ui/global_media_controls/media_notification_service_observer.h" #include "chrome/browser/ui/global_media_controls/overlay_media_notification.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -268,7 +269,9 @@ } MediaNotificationService::MediaNotificationService(Profile* profile) - : overlay_media_notifications_manager_(this) { + : overlay_media_notifications_manager_(this), + device_provider_( + std::make_unique<MediaNotificationDeviceProviderImpl>()) { if (base::FeatureList::IsEnabled(media::kGlobalMediaControlsForCast) && media_router::MediaRouterEnabled(profile)) { cast_notification_provider_ = @@ -696,6 +699,18 @@ HideNotification(id); } +std::unique_ptr< + MediaNotificationDeviceProvider::GetOutputDevicesCallbackList::Subscription> +MediaNotificationService::GetOutputDevices( + MediaNotificationDeviceProvider::GetOutputDevicesCallback callback) { + return device_provider_->GetOutputDeviceDescriptions(std::move(callback)); +} + +void MediaNotificationService::set_device_provider_for_testing( + std::unique_ptr<MediaNotificationDeviceProvider> device_provider) { + device_provider_ = std::move(device_provider); +} + void MediaNotificationService::OnItemUnfrozen(const std::string& id) { frozen_session_ids_.erase(id);
diff --git a/chrome/browser/ui/global_media_controls/media_notification_service.h b/chrome/browser/ui/global_media_controls/media_notification_service.h index b456cf67..dd25951 100644 --- a/chrome/browser/ui/global_media_controls/media_notification_service.h +++ b/chrome/browser/ui/global_media_controls/media_notification_service.h
@@ -17,10 +17,12 @@ #include "chrome/browser/media/router/presentation/web_contents_presentation_manager.h" #include "chrome/browser/ui/global_media_controls/cast_media_notification_provider.h" #include "chrome/browser/ui/global_media_controls/media_notification_container_observer.h" +#include "chrome/browser/ui/global_media_controls/media_notification_device_provider.h" #include "chrome/browser/ui/global_media_controls/overlay_media_notifications_manager_impl.h" #include "components/keyed_service/core/keyed_service.h" #include "components/media_message_center/media_notification_controller.h" #include "content/public/browser/web_contents_observer.h" +#include "media/audio/audio_device_description.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/audio_focus.mojom.h" @@ -104,6 +106,16 @@ // Called by a |MediaNotificationService::Session| when it becomes inactive. void OnSessionBecameInactive(const std::string& id); + // Used by a |MediaNotificationAudioDeviceSelectorView| to query the system + // for connected audio output devices. + std::unique_ptr<MediaNotificationDeviceProvider:: + GetOutputDevicesCallbackList::Subscription> + GetOutputDevices( + MediaNotificationDeviceProvider::GetOutputDevicesCallback callback); + + void set_device_provider_for_testing( + std::unique_ptr<MediaNotificationDeviceProvider> device_provider); + private: friend class MediaNotificationServiceTest; friend class MediaToolbarButtonControllerTest; @@ -280,6 +292,8 @@ // source. We use this to cap the number of UKM recordings per site. std::map<ukm::SourceId, int> actions_recorded_to_ukm_; + std::unique_ptr<MediaNotificationDeviceProvider> device_provider_; + base::WeakPtrFactory<MediaNotificationService> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc b/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc index 8583c80..967e9a1 100644 --- a/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc
@@ -64,7 +64,7 @@ const std::string& id, base::WeakPtr<media_message_center::MediaNotificationItem> item) { auto container = - std::make_unique<MediaNotificationContainerImplView>(id, item); + std::make_unique<MediaNotificationContainerImplView>(id, item, service_); MediaNotificationContainerImplView* container_ptr = container.get(); container_ptr->AddObserver(this); observed_containers_[id] = container_ptr;
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.cc b/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.cc index cc6e6b2..d962d189 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.cc
@@ -6,6 +6,7 @@ #include "base/strings/string16.h" #include "chrome/app/vector_icons/vector_icons.h" +#include "chrome/browser/ui/global_media_controls/media_notification_service.h" #include "chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.h" #include "components/vector_icons/vector_icons.h" #include "ui/gfx/paint_vector_icon.h" @@ -42,9 +43,10 @@ MediaNotificationAudioDeviceSelectorView:: MediaNotificationAudioDeviceSelectorView( MediaNotificationContainerImplView* container, + MediaNotificationService* service, gfx::Size size) - : container_(container) { - DCHECK(container_); + : container_(container), service_(service) { + DCHECK(service); SetPreferredSize(size); SetLayoutManager(std::make_unique<views::BoxLayout>( @@ -93,10 +95,23 @@ views::SetToggledImageFromVectorIconWithColor( expand_button_, kKeyboardArrowUpIcon, kExpandButtonSize, SK_ColorBLACK, SK_ColorBLACK); + + // Get a list of the connected audio output devices + audio_device_subscription_ = service_->GetOutputDevices(base::BindOnce( + &MediaNotificationAudioDeviceSelectorView::UpdateAvailableAudioDevices, + weak_ptr_factory_.GetWeakPtr())); } +MediaNotificationAudioDeviceSelectorView:: + ~MediaNotificationAudioDeviceSelectorView() = default; + void MediaNotificationAudioDeviceSelectorView::UpdateAvailableAudioDevices( - const media::AudioDeviceDescriptions& device_descriptions) {} + const media::AudioDeviceDescriptions& device_descriptions) { + device_button_container_->RemoveAllChildViews(true); + for (auto description : device_descriptions) { + CreateDeviceButton(description); + } +} void MediaNotificationAudioDeviceSelectorView::ButtonPressed( views::Button* sender,
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.h b/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.h index 2d1bf1d..8a675973 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.h +++ b/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.h
@@ -5,23 +5,26 @@ #ifndef CHROME_BROWSER_UI_VIEWS_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_AUDIO_DEVICE_SELECTOR_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_AUDIO_DEVICE_SELECTOR_VIEW_H_ +#include "chrome/browser/ui/global_media_controls/media_notification_device_provider.h" #include "media/audio/audio_device_description.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/layout/box_layout.h" class MediaNotificationContainerImplView; +class MediaNotificationService; class MediaNotificationAudioDeviceSelectorView : public views::View, public views::ButtonListener { public: - explicit MediaNotificationAudioDeviceSelectorView( + MediaNotificationAudioDeviceSelectorView( MediaNotificationContainerImplView* container, + MediaNotificationService* service, gfx::Size size); MediaNotificationAudioDeviceSelectorView( const MediaNotificationAudioDeviceSelectorView&) = delete; MediaNotificationAudioDeviceSelectorView& operator=( const MediaNotificationAudioDeviceSelectorView&) = delete; - ~MediaNotificationAudioDeviceSelectorView() override = default; + ~MediaNotificationAudioDeviceSelectorView() override; // Called when audio output devices are discovered. void UpdateAvailableAudioDevices( @@ -31,17 +34,29 @@ void ButtonPressed(views::Button* sender, const ui::Event& event) override; private: + FRIEND_TEST_ALL_PREFIXES(MediaNotificationAudioDeviceSelectorViewTest, + DeviceButtonsCreated); + void CreateDeviceButton( const media::AudioDeviceDescription& device_description); // The parent container - MediaNotificationContainerImplView* const container_ = nullptr; + MediaNotificationContainerImplView* const container_; + + MediaNotificationService* const service_; + + std::unique_ptr<MediaNotificationDeviceProvider:: + GetOutputDevicesCallbackList::Subscription> + audio_device_subscription_; // Subviews views::View* device_button_container_ = nullptr; views::View* expand_button_container_ = nullptr; views::ToggleImageButton* expand_button_ = nullptr; + + base::WeakPtrFactory<MediaNotificationAudioDeviceSelectorView> + weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_UI_VIEWS_GLOBAL_MEDIA_CONTROLS_MEDIA_NOTIFICATION_AUDIO_DEVICE_SELECTOR_VIEW_H_
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view_unittest.cc b/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view_unittest.cc new file mode 100644 index 0000000..d12990d7 --- /dev/null +++ b/chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view_unittest.cc
@@ -0,0 +1,92 @@ +// Copyright 2020 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/ui/views/global_media_controls/media_notification_audio_device_selector_view.h" + +#include "base/strings/string16.h" +#include "chrome/browser/media/router/media_router_factory.h" +#include "chrome/browser/media/router/test/mock_media_router.h" +#include "chrome/browser/ui/global_media_controls/media_notification_device_provider.h" +#include "chrome/browser/ui/global_media_controls/media_notification_service.h" +#include "chrome/test/base/testing_profile.h" +#include "chrome/test/views/chrome_views_test_base.h" +#include "media/audio/audio_device_description.h" +#include "ui/views/controls/button/label_button.h" + +namespace { + +class MockMediaNotificationDeviceProvider + : public MediaNotificationDeviceProvider { + public: + MockMediaNotificationDeviceProvider() = default; + ~MockMediaNotificationDeviceProvider() override = default; + + void AddDevice(const std::string& device_name, const std::string& device_id) { + device_descriptions.emplace_back(device_name, device_id, ""); + } + std::unique_ptr<MediaNotificationDeviceProvider:: + GetOutputDevicesCallbackList::Subscription> + GetOutputDeviceDescriptions(GetOutputDevicesCallback cb) override { + std::move(cb).Run(device_descriptions); + return std::unique_ptr<MockMediaNotificationDeviceProvider:: + GetOutputDevicesCallbackList::Subscription>( + nullptr); + } + + media::AudioDeviceDescriptions device_descriptions; +}; + +} // anonymous namespace + +class MediaNotificationAudioDeviceSelectorViewTest + : public ChromeViewsTestBase { + public: + MediaNotificationAudioDeviceSelectorViewTest() = default; + ~MediaNotificationAudioDeviceSelectorViewTest() override = default; + + // ChromeViewsTestBase + void SetUp() override { + ChromeViewsTestBase::SetUp(); + provider_ = std::make_unique<MockMediaNotificationDeviceProvider>(); + media_router::MediaRouterFactory::GetInstance()->SetTestingFactory( + &profile_, base::BindRepeating(&media_router::MockMediaRouter::Create)); + service_ = std::make_unique<MediaNotificationService>(&profile_); + } + + void TearDown() override { + view_.reset(); + service_.reset(); + provider_.reset(); + ChromeViewsTestBase::TearDown(); + } + + TestingProfile profile_; + std::unique_ptr<MockMediaNotificationDeviceProvider> provider_; + std::unique_ptr<MediaNotificationService> service_; + std::unique_ptr<MediaNotificationAudioDeviceSelectorView> view_; +}; + +TEST_F(MediaNotificationAudioDeviceSelectorViewTest, DeviceButtonsCreated) { + // Buttons should be created for every device reported by the provider + provider_->AddDevice("Speaker", "1"); + provider_->AddDevice("Headphones", "2"); + provider_->AddDevice("Earbuds", "3"); + service_->set_device_provider_for_testing(std::move(provider_)); + + view_ = std::make_unique<MediaNotificationAudioDeviceSelectorView>( + nullptr, service_.get(), gfx::Size()); + + std::vector<std::string> button_texts; + ASSERT_TRUE(view_->device_button_container_ != nullptr); + + std::transform( + view_->device_button_container_->children().cbegin(), + view_->device_button_container_->children().cend(), + std::back_inserter(button_texts), [](views::View* child) { + return base::UTF16ToASCII( + static_cast<const views::LabelButton*>(child)->GetText()); + }); + EXPECT_THAT(button_texts, testing::UnorderedElementsAre( + "Speaker", "Headphones", "Earbuds")); +}
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.cc b/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.cc index ab0dad2..021a74ce 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.cc
@@ -6,6 +6,7 @@ #include "base/feature_list.h" #include "chrome/browser/ui/global_media_controls/media_notification_container_observer.h" +#include "chrome/browser/ui/global_media_controls/media_notification_service.h" #include "chrome/browser/ui/global_media_controls/media_toolbar_button_controller.h" #include "chrome/browser/ui/views/global_media_controls/media_dialog_view.h" #include "chrome/browser/ui/views/global_media_controls/media_notification_audio_device_selector_view.h" @@ -73,11 +74,13 @@ MediaNotificationContainerImplView::MediaNotificationContainerImplView( const std::string& id, - base::WeakPtr<media_message_center::MediaNotificationItem> item) + base::WeakPtr<media_message_center::MediaNotificationItem> item, + MediaNotificationService* service) : views::Button(this), id_(id), foreground_color_(kDefaultForegroundColor), - background_color_(kDefaultBackgroundColor) { + background_color_(kDefaultBackgroundColor), + service_(service) { SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); SetPreferredSize(kNormalSize); @@ -124,7 +127,7 @@ media::kGlobalMediaControlsSeamlessTransfer)) { auto audio_device_selector_view = std::make_unique<MediaNotificationAudioDeviceSelectorView>( - this, gfx::Size(kWidth, kAudioDeviceSelectorViewHeight)); + this, service_, gfx::Size(kWidth, kAudioDeviceSelectorViewHeight)); audio_device_selector_view_ = AddChildView(std::move(audio_device_selector_view)); view_->UpdateCornerRadius(message_center::kNotificationCornerRadius, 0);
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.h b/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.h index d3012c8..3bb78d99 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.h +++ b/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view.h
@@ -29,6 +29,7 @@ class MediaNotificationAudioDeviceSelectorView; class MediaNotificationContainerObserver; +class MediaNotificationService; // MediaNotificationContainerImplView holds a media notification for display // within the MediaDialogView. The media notification shows metadata for a media @@ -43,7 +44,8 @@ public: MediaNotificationContainerImplView( const std::string& id, - base::WeakPtr<media_message_center::MediaNotificationItem> item); + base::WeakPtr<media_message_center::MediaNotificationItem> item, + MediaNotificationService* service); ~MediaNotificationContainerImplView() override; // views::Button: @@ -183,6 +185,8 @@ views::UniqueWidgetPtr drag_image_widget_; + MediaNotificationService* const service_; + DISALLOW_COPY_AND_ASSIGN(MediaNotificationContainerImplView); };
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view_unittest.cc b/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view_unittest.cc index af9e089b..f61d686 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view_unittest.cc +++ b/chrome/browser/ui/views/global_media_controls/media_notification_container_impl_view_unittest.cc
@@ -64,7 +64,7 @@ notification_container_ = widget_->SetContentsView( std::make_unique<MediaNotificationContainerImplView>( - kTestNotificationId, nullptr)); + kTestNotificationId, nullptr, nullptr)); observer_ = std::make_unique<MockMediaNotificationContainerObserver>(); notification_container_->AddObserver(observer_.get()); @@ -381,7 +381,7 @@ TEST_F(MediaNotificationContainerImplViewTest, SendsDestroyedUpdates) { auto container = std::make_unique<MediaNotificationContainerImplView>( - kOtherTestNotificationId, nullptr); + kOtherTestNotificationId, nullptr, nullptr); MockMediaNotificationContainerObserver observer; container->AddObserver(&observer);
diff --git a/chrome/browser/ui/views/global_media_controls/media_notification_list_view_unittest.cc b/chrome/browser/ui/views/global_media_controls/media_notification_list_view_unittest.cc index 57a8a15..e7c660ac 100644 --- a/chrome/browser/ui/views/global_media_controls/media_notification_list_view_unittest.cc +++ b/chrome/browser/ui/views/global_media_controls/media_notification_list_view_unittest.cc
@@ -43,7 +43,8 @@ void ShowNotification(const std::string& id) { list_view_->ShowNotification( - id, std::make_unique<MediaNotificationContainerImplView>(id, nullptr)); + id, std::make_unique<MediaNotificationContainerImplView>(id, nullptr, + nullptr)); } void HideNotification(const std::string& id) {
diff --git a/chrome/browser/ui/views/global_media_controls/overlay_media_notification_view_unittest.cc b/chrome/browser/ui/views/global_media_controls/overlay_media_notification_view_unittest.cc index 82025dc0..98472a3 100644 --- a/chrome/browser/ui/views/global_media_controls/overlay_media_notification_view_unittest.cc +++ b/chrome/browser/ui/views/global_media_controls/overlay_media_notification_view_unittest.cc
@@ -41,7 +41,7 @@ manager_ = std::make_unique<MockOverlayMediaNotificationsManager>(); auto notification = std::make_unique<MediaNotificationContainerImplView>( - kTestNotificationId, nullptr); + kTestNotificationId, nullptr, nullptr); notification->PopOut(); overlay_ = std::make_unique<OverlayMediaNotificationView>(
diff --git a/chrome/browser/ui/views/omnibox/omnibox_suggestion_button_row_view.cc b/chrome/browser/ui/views/omnibox/omnibox_suggestion_button_row_view.cc index ac47a322..70636d4 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_suggestion_button_row_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_suggestion_button_row_view.cc
@@ -38,6 +38,8 @@ ChromeLayoutProvider::Get()->GetInsetsMetric(INSETS_OMNIBOX_PILL_BUTTON)); button->SetCornerRadius(button->GetInsets().height() + GetLayoutConstant(LOCATION_BAR_ICON_SIZE)); + views::HighlightPathGenerator::Install( + button, std::make_unique<views::PillHighlightPathGenerator>()); return button; } @@ -73,18 +75,12 @@ }; }; keyword_button_focus_ring_ = views::FocusRing::Install(keyword_button_); - keyword_button_focus_ring_->SetPathGenerator( - std::make_unique<views::PillHighlightPathGenerator>()); keyword_button_focus_ring_->SetHasFocusPredicate( make_predicate(OmniboxPopupModel::FOCUSED_BUTTON_KEYWORD)); pedal_button_focus_ring_ = views::FocusRing::Install(pedal_button_); - pedal_button_focus_ring_->SetPathGenerator( - std::make_unique<views::PillHighlightPathGenerator>()); pedal_button_focus_ring_->SetHasFocusPredicate( make_predicate(OmniboxPopupModel::FOCUSED_BUTTON_PEDAL)); tab_switch_button_focus_ring_ = views::FocusRing::Install(tab_switch_button_); - tab_switch_button_focus_ring_->SetPathGenerator( - std::make_unique<views::PillHighlightPathGenerator>()); tab_switch_button_focus_ring_->SetHasFocusPredicate( make_predicate(OmniboxPopupModel::FOCUSED_BUTTON_TAB_SWITCH)); }
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc index 743d27f..87f78b20 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views.cc
@@ -1777,12 +1777,20 @@ } void OmniboxViewViews::DidGetUserInteraction( - const blink::WebInputEvent::Type type) { + const blink::WebInputEvent& event) { if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() || model()->ShouldPreventElision()) { return; } + // Exclude modifier keys to prevent keyboard shortcuts (such as switching + // tabs) from eliding the URL. We don't want to count these shortcuts as + // interactions with the page content. + if (blink::WebInputEvent::IsKeyboardEventType(event.GetType()) && + event.GetModifiers() & blink::WebInputEvent::kKeyModifiers) { + return; + } + // If there's already a hover animation running, just let it run as we will // end up at the same place. if (hover_elide_or_unelide_animation_->IsAnimating())
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views.h b/chrome/browser/ui/views/omnibox/omnibox_view_views.h index 7052352b..5e0c755 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views.h +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views.h
@@ -156,7 +156,7 @@ // content::WebContentsObserver: void DidFinishNavigation(content::NavigationHandle* navigation) override; - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override; + void DidGetUserInteraction(const blink::WebInputEvent& event) override; // For testing only. OmniboxPopupContentsView* GetPopupContentsViewForTesting() const { @@ -190,6 +190,7 @@ FRIEND_TEST_ALL_PREFIXES( OmniboxViewViewsHideOnInteractionAndRevealOnHoverTest, VerticalAndHorizontalPosition); + FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsHideOnInteractionTest, ModifierKeys); FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsHideOnInteractionTest, SameDocNavigations); FRIEND_TEST_ALL_PREFIXES(OmniboxViewViewsHideOnInteractionTest,
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc b/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc index d0a7da4c..b0e4e94 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc
@@ -36,6 +36,7 @@ #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/input/web_input_event.h" +#include "third_party/blink/public/common/input/web_keyboard_event.h" #include "third_party/metrics_proto/omnibox_event.pb.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" @@ -1683,8 +1684,7 @@ kSimplifiedDomainDisplayUrl.size()))); // Simulate a user interaction and check that the fade-out animation runs. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); EXPECT_TRUE(elide_animation->IsAnimating()); @@ -1709,8 +1709,7 @@ } // A second user interaction should not run the animation again. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); EXPECT_FALSE(omnibox_view() ->GetElideAfterInteractionAnimationForTesting() ->IsAnimating()); @@ -1776,8 +1775,7 @@ // Simulate a user interaction and change the bounds during the animation. The // animation should be cancelled and immediately transition to the animation's // end state (simplified domain). - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -1887,8 +1885,7 @@ // Simulate a user interaction and check that the URL gets elided to the // simplified domain. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); EXPECT_TRUE(elide_animation->IsAnimating()); @@ -2095,8 +2092,7 @@ render_text, gfx::Range(std::string("https://www.").size(), kFullUrl.size())); // Simulate a user interaction and check the fade-out animation. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -2141,8 +2137,7 @@ kSimplifiedDomainDisplayUrl.size()))); // Simulate a user interaction and check that the fade-out animation runs. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); EXPECT_TRUE(elide_animation->IsAnimating()); @@ -2185,8 +2180,7 @@ // Simulate a user interaction to elide to simplified domain and advance // through the animation; the vertical position should still be unchanged, and // the text should still start at the some position (the same x value). - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); gfx::AnimationContainerElement* elide_as_element = @@ -2214,6 +2208,34 @@ EXPECT_EQ(original_display_rect, unelided_display_rect); } +// Tests that modifier keys don't count as user interactions in the +// hide-on-interaction field trial. +TEST_P(OmniboxViewViewsHideOnInteractionTest, ModifierKeys) { + SetUpSimplifiedDomainTest(); + gfx::RenderText* render_text = omnibox_view()->GetRenderText(); + + content::MockNavigationHandle navigation; + navigation.set_is_same_document(false); + omnibox_view()->DidFinishNavigation(&navigation); + ASSERT_NO_FATAL_FAILURE(ExpectUnelidedFromSimplifiedDomain( + render_text, gfx::Range(kSimplifiedDomainDisplayUrlScheme.size(), + kSimplifiedDomainDisplayUrl.size()))); + + // Simulate a user interaction with a modifier key and check that the elide + // animation doesn't run. + blink::WebKeyboardEvent event( + blink::WebInputEvent::Type::kRawKeyDown, + blink::WebInputEvent::kControlKey, + blink::WebInputEvent::GetStaticTimeStampForTests()); + omnibox_view()->DidGetUserInteraction(event); + ASSERT_NO_FATAL_FAILURE(ExpectUnelidedFromSimplifiedDomain( + render_text, gfx::Range(kSimplifiedDomainDisplayUrlScheme.size(), + kSimplifiedDomainDisplayUrl.size()))); + OmniboxViewViews::ElideAnimation* elide_animation = + omnibox_view()->GetElideAfterInteractionAnimationForTesting(); + EXPECT_FALSE(elide_animation); +} + // Tests that in the hide-on-interaction field trial, the URL is simplified on // cross-document main-frame navigations, but not on same-document navigations. TEST_P(OmniboxViewViewsHideOnInteractionTest, SameDocNavigations) { @@ -2244,8 +2266,7 @@ } // Simulate a user interaction to elide to the simplified domain. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -2267,8 +2288,7 @@ // Simulate another user interaction to elide to the simplified domain, and // advance the clock all the way through the animation. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -2319,8 +2339,7 @@ kSimplifiedDomainDisplayUrl.size()))); // Simulate a user interaction to begin animating to the simplified domain. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -2382,8 +2401,7 @@ kSimplifiedDomainDisplayUrl.size()))); // Simulate a user interaction to begin animating to the simplified domain. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -2409,8 +2427,7 @@ double animation_value = elide_animation->GetAnimationForTesting()->GetCurrentValue(); - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -2441,8 +2458,7 @@ // Simulate a user interaction to elide to the simplified domain, and advance // the clock all the way through the animation. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); ASSERT_TRUE(elide_animation); @@ -2491,8 +2507,7 @@ omnibox_view()->DidFinishNavigation(&navigation); // Simulate a user interaction to fade out the path. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); OmniboxViewViews::ElideAnimation* elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); gfx::AnimationContainerElement* elide_as_element = @@ -2531,8 +2546,7 @@ // After a post-blur user interaction, the URL should animate to the // simplified domain. - omnibox_view()->DidGetUserInteraction( - blink::WebInputEvent::Type::kGestureScrollBegin); + omnibox_view()->DidGetUserInteraction(blink::WebKeyboardEvent()); elide_animation = omnibox_view()->GetElideAfterInteractionAnimationForTesting(); EXPECT_TRUE(elide_animation->IsAnimating());
diff --git a/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc b/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc index 79a536d5..ba94e5d 100644 --- a/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc +++ b/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.cc
@@ -37,13 +37,17 @@ void WebAppInternalsPageHandlerImpl::GetWebApps(GetWebAppsCallback callback) { auto* provider = web_app::WebAppProviderBase::GetProviderBase(profile_); - if (!provider) + if (!provider) { std::move(callback).Run({}); + return; + } web_app::AppRegistrar& registrar_base = provider->registrar(); web_app::WebAppRegistrar* registrar = registrar_base.AsWebAppRegistrar(); - if (!registrar) + if (!registrar) { std::move(callback).Run({}); + return; + } std::vector<mojom::web_app_internals::WebAppPtr> result; for (const web_app::WebApp& web_app : registrar->AllApps()) {
diff --git a/chrome/browser/web_applications/BUILD.gn b/chrome/browser/web_applications/BUILD.gn index 96470367..bbb09a8 100644 --- a/chrome/browser/web_applications/BUILD.gn +++ b/chrome/browser/web_applications/BUILD.gn
@@ -22,6 +22,8 @@ "manifest_update_manager.h", "manifest_update_task.cc", "manifest_update_task.h", + "os_integration_manager.cc", + "os_integration_manager.h", "system_web_app_manager.cc", "system_web_app_manager.h", "web_app_tab_helper.cc", @@ -58,8 +60,6 @@ "external_web_app_manager.h", "file_utils_wrapper.cc", "file_utils_wrapper.h", - "os_integration_manager.cc", - "os_integration_manager.h", "pending_app_install_task.cc", "pending_app_install_task.h", "pending_app_manager_impl.cc",
diff --git a/chrome/browser/web_applications/system_web_app_manager_browsertest.cc b/chrome/browser/web_applications/system_web_app_manager_browsertest.cc index 1b4b7e5..685bbab 100644 --- a/chrome/browser/web_applications/system_web_app_manager_browsertest.cc +++ b/chrome/browser/web_applications/system_web_app_manager_browsertest.cc
@@ -720,9 +720,9 @@ web_contents, "(async function() {" " let fileNames = [];" - " const files = await window.launchParams.files[0].getEntries();" - " for await (const f of files)" - " fileNames.push(f.name);" + " const files = await window.launchParams.files[0].keys();" + " for await (const name of files)" + " fileNames.push(name);" " domAutomationController.send(fileNames.sort().join(';'));" "})();", &file_names));
diff --git a/chrome/browser/web_applications/test/web_app_install_observer.cc b/chrome/browser/web_applications/test/web_app_install_observer.cc index b3291c7..6ef0687 100644 --- a/chrome/browser/web_applications/test/web_app_install_observer.cc +++ b/chrome/browser/web_applications/test/web_app_install_observer.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/web_applications/test/web_app_install_observer.h" +#include "base/run_loop.h" +#include "base/test/bind_test_util.h" #include "chrome/browser/web_applications/components/web_app_provider_base.h" namespace web_app { @@ -13,12 +15,18 @@ } WebAppInstallObserver::WebAppInstallObserver( AppRegistrar* registrar, - const std::set<AppId>& listening_for_app_ids) - : listening_for_app_ids_(listening_for_app_ids) { + const std::set<AppId>& listening_for_install_app_ids, + const std::set<AppId>& listening_for_uninstall_app_ids) + : listening_for_install_app_ids_(listening_for_install_app_ids), + listening_for_uninstall_app_ids_(listening_for_uninstall_app_ids) { observer_.Add(registrar); #if DCHECK_IS_ON() - DCHECK(!listening_for_app_ids_.empty()); - for (const AppId& id : listening_for_app_ids_) { + DCHECK(!listening_for_install_app_ids_.empty() || + !listening_for_uninstall_app_ids_.empty()); + for (const AppId& id : listening_for_install_app_ids_) { + DCHECK(!id.empty()) << "Cannot listen for empty ids."; + } + for (const AppId& id : listening_for_uninstall_app_ids_) { DCHECK(!id.empty()) << "Cannot listen for empty ids."; } #endif @@ -30,16 +38,59 @@ WebAppInstallObserver::WebAppInstallObserver( Profile* profile, - const std::set<AppId>& listening_for_app_ids) + const std::set<AppId>& listening_for_install_app_ids, + const std::set<AppId>& listening_for_uninstall_app_id) : WebAppInstallObserver( &WebAppProviderBase::GetProviderBase(profile)->registrar(), - listening_for_app_ids) {} + listening_for_install_app_ids, + listening_for_uninstall_app_id) {} WebAppInstallObserver::~WebAppInstallObserver() = default; +// static +std::unique_ptr<WebAppInstallObserver> +WebAppInstallObserver::CreateInstallListener( + Profile* registrar, + const std::set<AppId>& listening_for_install_app_ids) { + return base::WrapUnique( + new WebAppInstallObserver(registrar, listening_for_install_app_ids, {})); +} + +// static +std::unique_ptr<WebAppInstallObserver> +WebAppInstallObserver::CreateUninstallListener( + Profile* registrar, + const std::set<AppId>& listening_for_uninstall_app_ids) { + return base::WrapUnique(new WebAppInstallObserver( + registrar, {}, listening_for_uninstall_app_ids)); +} + AppId WebAppInstallObserver::AwaitNextInstall() { - run_loop_.Run(); - return std::move(app_id_); + base::RunLoop loop; + AppId id; + DCHECK(app_installed_delegate_.is_null()); + SetWebAppInstalledDelegate( + base::BindLambdaForTesting([&](const AppId& app_id) { + id = app_id; + loop.Quit(); + })); + loop.Run(); + return id; +} + +// static +AppId WebAppInstallObserver::AwaitNextUninstall( + WebAppInstallObserver* install_observer) { + base::RunLoop loop; + AppId id; + DCHECK(install_observer->app_uninstalled_delegate_.is_null()); + install_observer->SetWebAppUninstalledDelegate( + base::BindLambdaForTesting([&](const AppId& app_id) { + id = app_id; + loop.Quit(); + })); + loop.Run(); + return id; } void WebAppInstallObserver::SetWebAppInstalledDelegate( @@ -63,15 +114,12 @@ } void WebAppInstallObserver::OnWebAppInstalled(const AppId& app_id) { - listening_for_app_ids_.erase(app_id); - if (!listening_for_app_ids_.empty()) + listening_for_install_app_ids_.erase(app_id); + if (!listening_for_install_app_ids_.empty()) return; if (app_installed_delegate_) app_installed_delegate_.Run(app_id); - - app_id_ = app_id; - run_loop_.Quit(); } void WebAppInstallObserver::OnWebAppsWillBeUpdatedFromSync( @@ -81,8 +129,8 @@ } void WebAppInstallObserver::OnWebAppUninstalled(const AppId& app_id) { - listening_for_app_ids_.erase(app_id); - if (!listening_for_app_ids_.empty()) + listening_for_uninstall_app_ids_.erase(app_id); + if (!listening_for_uninstall_app_ids_.empty()) return; if (app_uninstalled_delegate_) @@ -90,10 +138,6 @@ } void WebAppInstallObserver::OnWebAppProfileWillBeDeleted(const AppId& app_id) { - listening_for_app_ids_.erase(app_id); - if (!listening_for_app_ids_.empty()) - return; - if (app_profile_will_be_deleted_delegate_) app_profile_will_be_deleted_delegate_.Run(app_id); }
diff --git a/chrome/browser/web_applications/test/web_app_install_observer.h b/chrome/browser/web_applications/test/web_app_install_observer.h index 4b27e2d..ec98a26 100644 --- a/chrome/browser/web_applications/test/web_app_install_observer.h +++ b/chrome/browser/web_applications/test/web_app_install_observer.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_WEB_APPLICATIONS_TEST_WEB_APP_INSTALL_OBSERVER_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_TEST_WEB_APP_INSTALL_OBSERVER_H_ +#include <memory> #include <set> #include "base/callback.h" #include "base/macros.h" -#include "base/run_loop.h" #include "base/scoped_observer.h" #include "chrome/browser/web_applications/components/app_registrar.h" #include "chrome/browser/web_applications/components/app_registrar_observer.h" @@ -25,15 +25,39 @@ explicit WebAppInstallObserver(AppRegistrar* registrar); explicit WebAppInstallObserver(Profile* profile); - // Restricts this observer to only listen for the given |listen_for_app_id|. - explicit WebAppInstallObserver(AppRegistrar* registrar, - const std::set<AppId>& listen_for_app_ids); - explicit WebAppInstallObserver(Profile* profile, - const std::set<AppId>& listen_for_app_ids); + // Restricts this observer to only listen for the given + // |listening_for_install_app_ids|. Settings these means that the + // WebAppInstalledDelegate doesn't get called until all of the ids in + // |listening_for_install_app_ids| are installed. This also applies to + // AwaitNextInstall(). + static std::unique_ptr<WebAppInstallObserver> CreateInstallListener( + Profile* registrar, + const std::set<AppId>& listening_for_install_app_ids); + + // Restricts this observer to only listen for the given + // |listening_for_uninstall_app_ids|. Settings these means that the + // WebAppUninstalledDelegate doesn't get called until all of the ids in + // |listening_for_uninstall_app_ids| are uninstalled. This also applies to + // AwaitNextUninstall(). + static std::unique_ptr<WebAppInstallObserver> CreateUninstallListener( + Profile* registrar, + const std::set<AppId>& listening_for_uninstall_app_ids); + ~WebAppInstallObserver() override; + // Convenience method to wait for the next install, or for all installations + // of |listening_for_install_app_ids| specified above. Calls + // SetWebAppInstalledDelegate with a base::RunLoop quit closure, and then runs + // the loop. Will DCHECK if an install delegate is already populated. + // TODO(dmurph): Refactor to be static like AwaitNextUninstall(). AppId AwaitNextInstall(); + // Convenience method to wait for the next uninstall, or for all + // uninstallations of |listening_for_uninstall_app_ids| specified above. Calls + // SetWebAppUninstalledDelegate with a base::RunLoop quit closure, and then + // runs the loop. Will DCHECK if an uninstall delegate is already populated. + static AppId AwaitNextUninstall(WebAppInstallObserver* install_observer); + using WebAppInstalledDelegate = base::RepeatingCallback<void(const AppId& app_id)>; void SetWebAppInstalledDelegate(WebAppInstalledDelegate delegate); @@ -60,9 +84,24 @@ void OnWebAppProfileWillBeDeleted(const AppId& app_id) override; private: - base::RunLoop run_loop_; - AppId app_id_; - std::set<AppId> listening_for_app_ids_; + // Restricts this observer to only listen for the given + // |listening_for_install_app_ids| and |listening_for_uninstall_app_ids|. + // Settings these means that the WebAppInstalledDelegate or the + // WebAppUninstalledDelegate don't get called until all of the ids in + // |listening_for_install_app_ids| or |listening_for_uninstall_app_ids| are + // installed or uninstalled (respectively). This also applies to + // AwaitNextInstall() and AwaitNextUninstall(). + explicit WebAppInstallObserver( + AppRegistrar* registrar, + const std::set<AppId>& listening_for_install_app_ids, + const std::set<AppId>& listening_for_uninstall_app_ids); + explicit WebAppInstallObserver( + Profile* profile, + const std::set<AppId>& listening_for_install_app_ids, + const std::set<AppId>& listening_for_uninstall_app_ids); + + std::set<AppId> listening_for_install_app_ids_; + std::set<AppId> listening_for_uninstall_app_ids_; WebAppInstalledDelegate app_installed_delegate_; WebAppWillBeUpdatedFromSyncDelegate app_will_be_updated_from_sync_delegate_;
diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index 83c7e15..4932d4d 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn
@@ -295,8 +295,6 @@ "extensions/manifest_handlers/app_launch_info.h", "extensions/manifest_handlers/app_theme_color_info.cc", "extensions/manifest_handlers/app_theme_color_info.h", - "extensions/manifest_handlers/extension_action_handler.cc", - "extensions/manifest_handlers/extension_action_handler.h", "extensions/manifest_handlers/linked_app_icons.cc", "extensions/manifest_handlers/linked_app_icons.h", "extensions/manifest_handlers/minimum_chrome_version_checker.cc",
diff --git a/chrome/common/extensions/chrome_manifest_handlers.cc b/chrome/common/extensions/chrome_manifest_handlers.cc index 94825a9..d0c56c6 100644 --- a/chrome/common/extensions/chrome_manifest_handlers.cc +++ b/chrome/common/extensions/chrome_manifest_handlers.cc
@@ -19,7 +19,6 @@ #include "chrome/common/extensions/manifest_handlers/app_icon_color_info.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/extensions/manifest_handlers/app_theme_color_info.h" -#include "chrome/common/extensions/manifest_handlers/extension_action_handler.h" #include "chrome/common/extensions/manifest_handlers/linked_app_icons.h" #include "chrome/common/extensions/manifest_handlers/minimum_chrome_version_checker.h" #include "chrome/common/extensions/manifest_handlers/natively_connectable_handler.h" @@ -53,7 +52,6 @@ registry->RegisterHandler(std::make_unique<AutomationHandler>()); registry->RegisterHandler(std::make_unique<CommandsHandler>()); registry->RegisterHandler(std::make_unique<DevToolsPageHandler>()); - registry->RegisterHandler(std::make_unique<ExtensionActionHandler>()); registry->RegisterHandler(std::make_unique<HomepageURLHandler>()); registry->RegisterHandler(std::make_unique<LinkedAppIconsHandler>()); registry->RegisterHandler(std::make_unique<MinimumChromeVersionChecker>());
diff --git a/chrome/common/extensions/docs/templates/articles/tut_debugging.html b/chrome/common/extensions/docs/templates/articles/tut_debugging.html index e7766f44..60986900 100644 --- a/chrome/common/extensions/docs/templates/articles/tut_debugging.html +++ b/chrome/common/extensions/docs/templates/articles/tut_debugging.html
@@ -2,7 +2,7 @@ <p> - Extensions are able to leverage the same debugging benifits + Extensions are able to leverage the same debugging benefits <a href="https://developers.google.com/web/tools/chrome-devtools/"> Chrome DevTools </a> provides for web pages, @@ -165,12 +165,12 @@ And... nope, the background still hasn’t changed colors! Navigate back to the Extensions Management Page and... there is no <b>Errors</b> button. - The likely culprite is the content script, + The likely culprit is the content script, which runs inside the web page. </p> <p> - Open the DevTools pannel of the web page the extension is trying to alter. + Open the DevTools panel of the web page the extension is trying to alter. </p> <img src="{{static}}/images/debugging/content_script_error.png" @@ -211,7 +211,7 @@ <p> The popup will often make all of the required network requests before even the speediest of developers can open DevTools. - To view these requests, refresh from inside the network pannel. + To view these requests, refresh from inside the network panel. It will reload the popup without closing the DevTools panel. </p> <img src="{{static}}/images/debugging/network_reload.gif" @@ -225,7 +225,7 @@ <a href="/extensions/storage">storage</a> and <a href="/extensions/xhr">Cross-Origin XMLHttpRequsts</a>. Refer to the <a href="extensions/permission_warnings">permissions article</a> - and the availabe <a href="/extensions/api_index">Chrome APIs</a> + and the available <a href="/extensions/api_index">Chrome APIs</a> to ensure an extension is requesting the correct permissions in its <a href="/extensions/manifest">manifest</a>. </p>
diff --git a/chrome/common/webui_url_constants.cc b/chrome/common/webui_url_constants.cc index 9a582be..a8b4a3f 100644 --- a/chrome/common/webui_url_constants.cc +++ b/chrome/common/webui_url_constants.cc
@@ -38,6 +38,10 @@ const char kChromeUIConflictsHost[] = "conflicts"; const char kChromeUIConstrainedHTMLTestURL[] = "chrome://constrained-test/"; const char kChromeUIContentSettingsURL[] = "chrome://settings/content"; +// TODO (crbug.com/1107816): Remove deprecated cookie URL redirection. +const char kChromeUICookieSettingsDeprecatedURL[] = + "chrome://settings/content/cookies"; +const char kChromeUICookieSettingsURL[] = "chrome://settings/cookies"; const char kChromeUICrashHost[] = "crash"; const char kChromeUICrashesHost[] = "crashes"; const char kChromeUICreditsHost[] = "credits";
diff --git a/chrome/common/webui_url_constants.h b/chrome/common/webui_url_constants.h index 998938d..b2111568 100644 --- a/chrome/common/webui_url_constants.h +++ b/chrome/common/webui_url_constants.h
@@ -46,6 +46,8 @@ extern const char kChromeUIConflictsHost[]; extern const char kChromeUIConstrainedHTMLTestURL[]; extern const char kChromeUIContentSettingsURL[]; +extern const char kChromeUICookieSettingsDeprecatedURL[]; +extern const char kChromeUICookieSettingsURL[]; extern const char kChromeUICrashHost[]; extern const char kChromeUICrashesHost[]; extern const char kChromeUICreditsHost[];
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 7330a66..0624241 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -615,17 +615,17 @@ render_frame, subresource_filter_ruleset_dealer_.get(), std::move(ad_resource_tracker)); } - if (render_frame->IsMainFrame()) { - new previews::ResourceLoadingHintsAgent( - render_frame_observer->associated_interfaces(), render_frame); - } + + if (lite_video::IsLiteVideoEnabled()) + new lite_video::LiteVideoHintAgent(render_frame); + + new previews::ResourceLoadingHintsAgent( + render_frame_observer->associated_interfaces(), render_frame); + if (translate::IsSubFrameTranslationEnabled()) { new translate::PerFrameTranslateAgent( render_frame, ISOLATED_WORLD_ID_TRANSLATE, associated_interfaces); } - if (lite_video::IsLiteVideoEnabled()) { - new lite_video::LiteVideoHintAgent(render_frame); - } #if !defined(OS_ANDROID) base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
diff --git a/chrome/renderer/lite_video/lite_video_hint_agent.cc b/chrome/renderer/lite_video/lite_video_hint_agent.cc index 74f6f49..2a5c1a6 100644 --- a/chrome/renderer/lite_video/lite_video_hint_agent.cc +++ b/chrome/renderer/lite_video/lite_video_hint_agent.cc
@@ -10,28 +10,10 @@ namespace lite_video { -// Default bandwidth and latency parameters for throttling. -constexpr uint64_t kTargetDownlinkBandwidthKBPS = 400; -constexpr base::TimeDelta kTargetDownlinkRTTLatency = - base::TimeDelta::FromMilliseconds(500); - -// How much initial media bytes should be left unthrottled to alleviate pauses -// in the initial video play. -const uint64_t kkilobytesToBufferBeforeThrottle = 10; - -// Maximum delay imposed for an response. -const base::TimeDelta kMaxResponseDelay = base::TimeDelta::FromSeconds(5); - LiteVideoHintAgent::LiteVideoHintAgent(content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame), content::RenderFrameObserverTracker<LiteVideoHintAgent>(render_frame) { DCHECK(render_frame); - DCHECK(IsLiteVideoEnabled()); - have_lite_video_hint_ = true; - target_downlink_bandwidth_kbps_ = kTargetDownlinkBandwidthKBPS; - target_downlink_rtt_latency_ = kTargetDownlinkRTTLatency; - kilobytes_to_buffer_before_throttle_ = kkilobytesToBufferBeforeThrottle; - UMA_HISTOGRAM_BOOLEAN("LiteVideo.HintAgent.HasHint", have_lite_video_hint_); } LiteVideoHintAgent::~LiteVideoHintAgent() = default; @@ -42,7 +24,7 @@ base::TimeDelta LiteVideoHintAgent::CalculateLatencyForResourceResponse( const network::mojom::URLResponseHead& response_head) { - if (!have_lite_video_hint_) + if (!HasLiteVideoHint()) return base::TimeDelta(); int64_t recv_bytes = response_head.content_length; @@ -52,7 +34,7 @@ return base::TimeDelta(); if (kilobytes_buffered_before_throttle_ < - kilobytes_to_buffer_before_throttle_) { + *kilobytes_to_buffer_before_throttle_) { kilobytes_buffered_before_throttle_ += recv_bytes / 1024; return base::TimeDelta(); } @@ -64,15 +46,33 @@ // (400/100 + 1). auto delay_for_throttled_response = base::TimeDelta::FromSecondsD( - recv_bytes / (target_downlink_bandwidth_kbps_ * 1024.0)) + - target_downlink_rtt_latency_; + recv_bytes / (*target_downlink_bandwidth_kbps_ * 1024.0)) + + *target_downlink_rtt_latency_; auto response_delay = response_head.response_time - response_head.request_time; if (delay_for_throttled_response <= response_delay) return base::TimeDelta(); return std::min(delay_for_throttled_response - response_delay, - kMaxResponseDelay); + *max_throttling_delay_); +} + +bool LiteVideoHintAgent::HasLiteVideoHint() const { + return target_downlink_bandwidth_kbps_ && target_downlink_rtt_latency_ && + kilobytes_to_buffer_before_throttle_ && max_throttling_delay_; +} + +void LiteVideoHintAgent::SetLiteVideoHint( + blink::mojom::LiteVideoHintPtr lite_video_hint) { + if (!lite_video_hint) + return; + target_downlink_bandwidth_kbps_ = + lite_video_hint->target_downlink_bandwidth_kbps; + kilobytes_to_buffer_before_throttle_ = + lite_video_hint->kilobytes_to_buffer_before_throttle; + target_downlink_rtt_latency_ = lite_video_hint->target_downlink_rtt_latency; + max_throttling_delay_ = lite_video_hint->max_throttling_delay; + LOCAL_HISTOGRAM_BOOLEAN("LiteVideo.HintAgent.HasHint", true); } } // namespace lite_video
diff --git a/chrome/renderer/lite_video/lite_video_hint_agent.h b/chrome/renderer/lite_video/lite_video_hint_agent.h index 0c43e7d..abea6da2 100644 --- a/chrome/renderer/lite_video/lite_video_hint_agent.h +++ b/chrome/renderer/lite_video/lite_video_hint_agent.h
@@ -10,6 +10,7 @@ #include "chrome/renderer/lite_video/lite_video_url_loader_throttle.h" #include "content/public/renderer/render_frame_observer.h" #include "content/public/renderer/render_frame_observer_tracker.h" +#include "third_party/blink/public/mojom/loader/previews_resource_loading_hints.mojom.h" #include "url/gurl.h" namespace lite_video { @@ -37,20 +38,36 @@ base::TimeDelta CalculateLatencyForResourceResponse( const network::mojom::URLResponseHead& response_head); - bool have_lite_video_hint() const { return have_lite_video_hint_; } + // Updates the LiteVideo throttling parameters for calculating + // the latency to add to media requests. + void SetLiteVideoHint(blink::mojom::LiteVideoHintPtr lite_video_hint); + + // Returns whether |this| has been provided a LiteVideoHint and + // has the parameters needed for calculating the throttling latency. + bool HasLiteVideoHint() const; private: // content::RenderFrameObserver overrides void OnDestruct() override; - bool have_lite_video_hint_ = false; + // The network downlink bandwidth target in kilobytes per second used to + // calculate the throttling delay on media requests + base::Optional<int> target_downlink_bandwidth_kbps_; - int target_downlink_bandwidth_kbps_; - base::TimeDelta target_downlink_rtt_latency_; - int kilobytes_to_buffer_before_throttle_; + // The network downlink rtt target latency used to calculate the + // throttling delay on media requests + base::Optional<base::TimeDelta> target_downlink_rtt_latency_; - // How many initial media KB should be left unthrottled to alleviate pauses - // in the initial video play. + // The number of kilobytes for media to be observed before starting to + // throttle requests. + base::Optional<int> kilobytes_to_buffer_before_throttle_; + + // The maximum delay a throttle can introduce for a media request in + // milliseconds. + base::Optional<base::TimeDelta> max_throttling_delay_; + + // The number of media KB that have been left unthrottled before starting + // to introduce a throttling delay. int kilobytes_buffered_before_throttle_ = 0; };
diff --git a/chrome/renderer/lite_video/lite_video_url_loader_throttle.cc b/chrome/renderer/lite_video/lite_video_url_loader_throttle.cc index e259cf0..296745c 100644 --- a/chrome/renderer/lite_video/lite_video_url_loader_throttle.cc +++ b/chrome/renderer/lite_video/lite_video_url_loader_throttle.cc
@@ -36,7 +36,7 @@ // disabled or ECT worsens. This logic should probably be in the browser // process. if (IsLiteVideoEnabled() && - GetLiteVideoHintAgent(render_frame_id)->have_lite_video_hint()) { + GetLiteVideoHintAgent(render_frame_id)->HasLiteVideoHint()) { return std::make_unique<LiteVideoURLLoaderThrottle>(render_frame_id); } return nullptr;
diff --git a/chrome/renderer/previews/resource_loading_hints_agent.cc b/chrome/renderer/previews/resource_loading_hints_agent.cc index 5e0737d..f46aad7 100644 --- a/chrome/renderer/previews/resource_loading_hints_agent.cc +++ b/chrome/renderer/previews/resource_loading_hints_agent.cc
@@ -38,8 +38,6 @@ content::RenderFrameObserverTracker<ResourceLoadingHintsAgent>( render_frame) { DCHECK(render_frame); - DCHECK(IsMainFrame()); - associated_interfaces->AddInterface(base::BindRepeating( &ResourceLoadingHintsAgent::SetReceiver, base::Unretained(this))); } @@ -51,17 +49,23 @@ void ResourceLoadingHintsAgent::DidStartNavigation( const GURL& url, base::Optional<blink::WebNavigationType> navigation_type) { + if (!IsMainFrame()) + return; subresource_redirect_hints_agent_.DidStartNavigation(); } void ResourceLoadingHintsAgent::ReadyToCommitNavigation( blink::WebDocumentLoader* document_loader) { + if (!IsMainFrame()) + return; + subresource_redirect_hints_agent_.ReadyToCommitNavigation( render_frame()->GetRoutingID()); } void ResourceLoadingHintsAgent::DidCreateNewDocument() { - DCHECK(IsMainFrame()); + if (!IsMainFrame()) + return; if (!GetDocumentURL().SchemeIsHTTPOrHTTPS()) return; @@ -101,7 +105,8 @@ void ResourceLoadingHintsAgent::SetResourceLoadingHints( blink::mojom::PreviewsResourceLoadingHintsPtr resource_loading_hints) { - DCHECK(IsMainFrame()); + if (!IsMainFrame()) + return; UMA_HISTOGRAM_COUNTS_100( "ResourceLoadingHints.CountBlockedSubresourcePatterns", @@ -117,8 +122,18 @@ void ResourceLoadingHintsAgent::SetCompressPublicImagesHints( blink::mojom::CompressPublicImagesHintsPtr images_hints) { + if (!IsMainFrame()) + return; subresource_redirect_hints_agent_.SetCompressPublicImagesHints( std::move(images_hints)); } +void ResourceLoadingHintsAgent::SetLiteVideoHint( + blink::mojom::LiteVideoHintPtr lite_video_hint) { + auto* lite_video_hint_agent = + lite_video::LiteVideoHintAgent::Get(render_frame()); + if (lite_video_hint_agent) + lite_video_hint_agent->SetLiteVideoHint(std::move(lite_video_hint)); +} + } // namespace previews
diff --git a/chrome/renderer/previews/resource_loading_hints_agent.h b/chrome/renderer/previews/resource_loading_hints_agent.h index cdc4746..f2785b7 100644 --- a/chrome/renderer/previews/resource_loading_hints_agent.h +++ b/chrome/renderer/previews/resource_loading_hints_agent.h
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/macros.h" #include "base/optional.h" +#include "chrome/renderer/lite_video/lite_video_hint_agent.h" #include "chrome/renderer/subresource_redirect/subresource_redirect_hints_agent.h" #include "content/public/renderer/render_frame_observer.h" #include "content/public/renderer/render_frame_observer_tracker.h" @@ -60,6 +61,8 @@ resource_loading_hints) override; void SetCompressPublicImagesHints( blink::mojom::CompressPublicImagesHintsPtr images_hints) override; + void SetLiteVideoHint( + blink::mojom::LiteVideoHintPtr lite_video_hint) override; void SetReceiver( mojo::PendingAssociatedReceiver<
diff --git a/chrome/services/sharing/nearby/platform_v2/BUILD.gn b/chrome/services/sharing/nearby/platform_v2/BUILD.gn index bb412ae4..45a4d09f 100644 --- a/chrome/services/sharing/nearby/platform_v2/BUILD.gn +++ b/chrome/services/sharing/nearby/platform_v2/BUILD.gn
@@ -41,6 +41,7 @@ "//chrome/services/sharing/webrtc", "//crypto", "//jingle:webrtc_glue", + "//third_party/abseil-cpp:absl", ] }
diff --git a/chrome/services/sharing/nearby/platform_v2/DEPS b/chrome/services/sharing/nearby/platform_v2/DEPS new file mode 100644 index 0000000..9c528a3 --- /dev/null +++ b/chrome/services/sharing/nearby/platform_v2/DEPS
@@ -0,0 +1,8 @@ +# Copyright 2020 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_rules = [ + '+third_party/abseil-cpp/absl/strings/string_view.h', + '+third_party/abseil-cpp/absl/time/time.h', +]
diff --git a/chrome/services/sharing/nearby/platform_v2/condition_variable.h b/chrome/services/sharing/nearby/platform_v2/condition_variable.h index 4daefe78..5f7f900a 100644 --- a/chrome/services/sharing/nearby/platform_v2/condition_variable.h +++ b/chrome/services/sharing/nearby/platform_v2/condition_variable.h
@@ -6,6 +6,7 @@ #define CHROME_SERVICES_SHARING_NEARBY_PLATFORM_V2_CONDITION_VARIABLE_H_ #include "base/synchronization/condition_variable.h" +#include "third_party/abseil-cpp/absl/time/time.h" #include "third_party/nearby/src/cpp/platform_v2/api/condition_variable.h" namespace location {
diff --git a/chrome/services/sharing/nearby/platform_v2/count_down_latch.h b/chrome/services/sharing/nearby/platform_v2/count_down_latch.h index d85e6bb..b298b2ea3 100644 --- a/chrome/services/sharing/nearby/platform_v2/count_down_latch.h +++ b/chrome/services/sharing/nearby/platform_v2/count_down_latch.h
@@ -7,6 +7,7 @@ #include "base/atomic_ref_count.h" #include "base/synchronization/waitable_event.h" +#include "third_party/abseil-cpp/absl/time/time.h" #include "third_party/nearby/src/cpp/platform_v2/api/count_down_latch.h" namespace location {
diff --git a/chrome/services/sharing/nearby/platform_v2/crypto.cc b/chrome/services/sharing/nearby/platform_v2/crypto.cc index bd6a538b..0452734 100644 --- a/chrome/services/sharing/nearby/platform_v2/crypto.cc +++ b/chrome/services/sharing/nearby/platform_v2/crypto.cc
@@ -7,6 +7,7 @@ #include "base/hash/md5.h" #include "base/memory/ptr_util.h" #include "crypto/sha2.h" +#include "third_party/abseil-cpp/absl/strings/string_view.h" #include <vector>
diff --git a/chrome/services/sharing/nearby/platform_v2/scheduled_executor.h b/chrome/services/sharing/nearby/platform_v2/scheduled_executor.h index e651321..cfe04c0e 100644 --- a/chrome/services/sharing/nearby/platform_v2/scheduled_executor.h +++ b/chrome/services/sharing/nearby/platform_v2/scheduled_executor.h
@@ -15,6 +15,7 @@ #include "base/thread_annotations.h" #include "base/timer/timer.h" #include "base/unguessable_token.h" +#include "third_party/abseil-cpp/absl/time/time.h" #include "third_party/nearby/src/cpp/platform_v2/api/scheduled_executor.h" namespace location {
diff --git a/chrome/services/sharing/nearby/platform_v2/system_clock.cc b/chrome/services/sharing/nearby/platform_v2/system_clock.cc index ffe39d7..25c5322 100644 --- a/chrome/services/sharing/nearby/platform_v2/system_clock.cc +++ b/chrome/services/sharing/nearby/platform_v2/system_clock.cc
@@ -8,6 +8,7 @@ #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "build/build_config.h" +#include "third_party/abseil-cpp/absl/time/time.h" #if defined(OS_MACOSX) #include <mach/mach_time.h>
diff --git a/chrome/services/sharing/nearby/platform_v2/webrtc.h b/chrome/services/sharing/nearby/platform_v2/webrtc.h index 9e336200..686faa7 100644 --- a/chrome/services/sharing/nearby/platform_v2/webrtc.h +++ b/chrome/services/sharing/nearby/platform_v2/webrtc.h
@@ -13,6 +13,7 @@ #include "chrome/services/sharing/public/mojom/webrtc_signaling_messenger.mojom.h" #include "services/network/public/mojom/mdns_responder.mojom.h" #include "services/network/public/mojom/p2p.mojom.h" +#include "third_party/abseil-cpp/absl/strings/string_view.h" #include "third_party/webrtc/api/peer_connection_interface.h" namespace sharing {
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 489b551..057d1160 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -4925,7 +4925,6 @@ "../common/extensions/manifest_handlers/automation_unittest.cc", "../common/extensions/manifest_handlers/content_scripts_manifest_unittest.cc", "../common/extensions/manifest_handlers/exclude_matches_manifest_unittest.cc", - "../common/extensions/manifest_handlers/extension_action_handler_unittest.cc", "../common/extensions/manifest_handlers/natively_connectable_handler_unittest.cc", "../common/extensions/manifest_handlers/settings_overrides_handler_unittest.cc", "../common/extensions/manifest_tests/chrome_manifest_test.cc", @@ -5487,6 +5486,7 @@ "../browser/ui/views/frame/test_with_browser_view.h", "../browser/ui/views/frame/web_contents_close_handler_unittest.cc", "../browser/ui/views/fullscreen_control/fullscreen_control_popup_unittest.cc", + "../browser/ui/views/global_media_controls/media_notification_audio_device_selector_view_unittest.cc", "../browser/ui/views/global_media_controls/media_notification_container_impl_view_unittest.cc", "../browser/ui/views/global_media_controls/media_notification_list_view_unittest.cc", "../browser/ui/views/global_media_controls/overlay_media_notification_view_unittest.cc",
diff --git a/chrome/test/data/nacl/BUILD.gn b/chrome/test/data/nacl/BUILD.gn index 4dc4d39..ca32f66 100644 --- a/chrome/test/data/nacl/BUILD.gn +++ b/chrome/test/data/nacl/BUILD.gn
@@ -510,6 +510,9 @@ configs -= [ "//build/config/sanitizers:default_sanitizer_flags" ] configs -= [ "//build/config/coverage:default_coverage" ] + # Do not use PGO as it also requires a few symbols. + configs -= [ "//build/config/compiler/pgo:default_pgo_flags" ] + # Disable default_init_stack_vars because it inserts memset() calls, but # memset() is not available in this libc-free context. configs -= [ "//build/config/compiler:default_init_stack_vars" ]
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index cfa02f6c..5818777 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -5645,6 +5645,20 @@ ] }, + "DevicePrinters": { + "os": ["chromeos"], + "policy_pref_mapping_test": [ + { + "policies": { + "DevicePrinters": { + "url": "https://example.com/policyfile", + "hash": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + } + } + } + ] + }, + "DevicePrintersAccessMode": { "os": ["chromeos"], "policy_pref_mapping_test": [
diff --git a/chrome/test/data/webui/settings/chromeos/device_page_tests.js b/chrome/test/data/webui/settings/chromeos/device_page_tests.js index 09d8e4b..a34d37f 100644 --- a/chrome/test/data/webui/settings/chromeos/device_page_tests.js +++ b/chrome/test/data/webui/settings/chromeos/device_page_tests.js
@@ -904,12 +904,6 @@ expectTrue(displayPage.showMirror_(false, displayPage.displays)); expectFalse(displayPage.isMirrored_(displayPage.displays)); - // Set display identification highlights for the selected display as - // there are now multiple displays. - expectEquals( - displayPage.displays[0].id, - browserProxy.lastHighlightedDisplayId_); - // Verify unified desktop only shown when enabled. expectTrue(displayPage.showUnifiedDesktop_( true, true, displayPage.displays)); @@ -983,12 +977,6 @@ displayPage.displays[1].id, displayPage.primaryDisplayId); expectEquals(90, displayPage.displays[1].rotation); - // Change the display that display identification highlight renders - // on to the newly selected display. - expectEquals( - displayPage.displays[1].id, - browserProxy.lastHighlightedDisplayId_); - // Mirror the displays. displayPage.onMirroredTap_({target: {blur: function() {}}}); fakeSystemDisplay.onDisplayChanged.callListeners(); @@ -1011,12 +999,6 @@ expectTrue(displayPage.showMirror_(false, displayPage.displays)); expectTrue(displayPage.isMirrored_(displayPage.displays)); - // setSelectedDisplay is called on a new display id even though no - // display identification highlight is generated in mirrored mode. - expectEquals( - displayPage.displays[0].id, - browserProxy.lastHighlightedDisplayId_); - // Verify that the arrangement section is shown while mirroring. expectTrue(!!displayPage.$$('#arrangement-section')); @@ -1051,13 +1033,6 @@ // Navigate back to the display page. return showAndGetDeviceSubpage('display', settings.routes.DISPLAY); - }) - .then(function() { - // Moving back into the display page should call setSelectedDisplay - // with selectedDisplay_. - expectEquals( - displayPage.selectedDisplay.id, - browserProxy.lastHighlightedDisplayId_); }); });
diff --git a/chromeos/components/media_app_ui/resources/js/launch.js b/chromeos/components/media_app_ui/resources/js/launch.js index 356e142f..707c4ca 100644 --- a/chromeos/components/media_app_ui/resources/js/launch.js +++ b/chromeos/components/media_app_ui/resources/js/launch.js
@@ -532,7 +532,7 @@ const relatedFiles = []; // TODO(b/158149714): Clear out old tokens as well? Care needs to be taken to // ensure any file currently open with unsaved changes can still be saved. - for await (const /** !FileSystemHandle */ handle of directory.getEntries()) { + for await (const /** !FileSystemHandle */ handle of directory.values()) { if (localLaunchNumber !== globalLaunchNumber) { // Abort, another more up to date launch in progress. return ProcessOtherFilesResult.ABORT; @@ -565,7 +565,7 @@ return ProcessOtherFilesResult.ABORT; } - // Iteration order is not guaranteed using `directory.getEntries()`, so we + // Iteration order is not guaranteed using `directory.entries()`, so we // sort it afterwards by modification time to ensure a consistent and logical // order. More recent (i.e. higher timestamp) files should appear first. relatedFiles.sort((a, b) => {
diff --git a/chromeos/components/media_app_ui/resources/js/web_app_file_handling.externs.js b/chromeos/components/media_app_ui/resources/js/web_app_file_handling.externs.js index 022f59fd..f784555 100644 --- a/chromeos/components/media_app_ui/resources/js/web_app_file_handling.externs.js +++ b/chromeos/components/media_app_ui/resources/js/web_app_file_handling.externs.js
@@ -140,8 +140,12 @@ */ getDirectoryHandle(name, options) {} + /** @return {!AsyncIterable<!Array<string|!FileSystemHandle>>} */ + entries() {} + /** @return {!AsyncIterable<string>} */ + keys() {} /** @return {!AsyncIterable<!FileSystemHandle>} */ - getEntries() {} + values() {} /** * @param {string} name
diff --git a/chromeos/components/media_app_ui/test/driver.js b/chromeos/components/media_app_ui/test/driver.js index d15c95a..ebe35bf 100644 --- a/chromeos/components/media_app_ui/test/driver.js +++ b/chromeos/components/media_app_ui/test/driver.js
@@ -218,11 +218,33 @@ getDirectoryHandle(name, options) {} /** * @override + * @return {!AsyncIterable<!Array<string|!FileSystemHandle>>} + * @suppress {reportUnknownTypes} suppress [JSC_UNKNOWN_EXPR_TYPE] for `yield + * [file.name, file]`. + */ + async * entries() { + for (const file of this.files) { + yield [file.name, file]; + } + } + /** + * @override + * @return {!AsyncIterable<string>} + * @suppress {reportUnknownTypes} suppress [JSC_UNKNOWN_EXPR_TYPE] for `yield + * file.name`. + */ + async * keys() { + for (const file of this.files) { + yield file.name; + } + } + /** + * @override * @return {!AsyncIterable<!FileSystemHandle>} * @suppress {reportUnknownTypes} suppress [JSC_UNKNOWN_EXPR_TYPE] for `yield * file`. */ - async * getEntries() { + async * values() { for (const file of this.files) { yield file; }
diff --git a/chromeos/network/onc/onc_signature.cc b/chromeos/network/onc/onc_signature.cc index 7cff9f65..34788a17 100644 --- a/chromeos/network/onc/onc_signature.cc +++ b/chromeos/network/onc/onc_signature.cc
@@ -232,7 +232,6 @@ {::onc::wifi::kAllowGatewayARPPolling, &kBoolSignature}, {::onc::wifi::kAutoConnect, &kBoolSignature}, {::onc::wifi::kEAP, &kEAPSignature}, - {::onc::wifi::kFTEnabled, &kBoolSignature}, {::onc::wifi::kHexSSID, &kStringSignature}, {::onc::wifi::kHiddenSSID, &kBoolSignature}, {::onc::wifi::kPassphrase, &kStringSignature},
diff --git a/chromeos/network/onc/onc_translation_tables.cc b/chromeos/network/onc/onc_translation_tables.cc index 3d3c558..47d075d 100644 --- a/chromeos/network/onc/onc_translation_tables.cc +++ b/chromeos/network/onc/onc_translation_tables.cc
@@ -147,7 +147,6 @@ // { ::onc::wifi::kEAP, shill::kEap*}, {::onc::wifi::kFrequency, shill::kWifiFrequency}, {::onc::wifi::kFrequencyList, shill::kWifiFrequencyListProperty}, - {::onc::wifi::kFTEnabled, shill::kWifiFTEnabled}, {::onc::wifi::kHexSSID, shill::kWifiHexSsid}, {::onc::wifi::kHiddenSSID, shill::kWifiHiddenSsid}, {::onc::wifi::kPassphrase, shill::kPassphraseProperty},
diff --git a/chromeos/printing/ppd_provider_v3_unittest.cc b/chromeos/printing/ppd_provider_v3_unittest.cc index ff117e32b..b374c32 100644 --- a/chromeos/printing/ppd_provider_v3_unittest.cc +++ b/chromeos/printing/ppd_provider_v3_unittest.cc
@@ -82,6 +82,38 @@ class PpdProviderTest : public ::testing::Test { public: + // * Determines where the PpdCache class runs. + // * If set to kOnTestThread, the PpdCache class will use the + // task environment of the test fixture. + // * If set to kInBackgroundThreads, the PpdCache class will + // spawn its own background threads. + // * Prefer only to run cache on the test thread if you need to + // manipulate its sequencing independently of PpdProvider; + // otherwise, allowing it spawn its own background threads + // should be safe and good for exercising its codepaths. + enum class PpdCacheRunLocation { + kOnTestThread, + kInBackgroundThreads, + }; + + // * Determines whether the browser locale given to PpdProvider + // should be propagated to the composed PpdMetadataManager as its + // metadata locale as well. + // * Useful to the caller depending on whether or not one is + // interested in the codepaths that fetch and parse the locales + // metadata. + enum class PropagateLocaleToMetadataManager { + kDoNotPropagate, + kDoPropagate, + }; + + // Options passed to CreateProvider(). + struct CreateProviderOptions { + std::string browser_locale; + PpdCacheRunLocation where_ppd_cache_runs; + PropagateLocaleToMetadataManager propagate_locale; + }; + PpdProviderTest() : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) { } @@ -90,34 +122,46 @@ ASSERT_TRUE(ppd_cache_temp_dir_.CreateUniqueTempDir()); } - // Create and return a provider for a test that uses the given |locale|. If - // run_cache_on_test_thread is true, we'll run the cache using the - // task_environment_; otherwise we'll let it spawn it's own background - // threads. You should only run the cache on the test thread if you need to - // explicitly drain cache actions independently of draining ppd provider - // actions; otherwise letting the cache spawn its own thread should be safe, - // and better exercises the code paths under test. - scoped_refptr<PpdProvider> CreateProvider(const std::string& locale, - bool run_cache_on_test_thread) { - if (run_cache_on_test_thread) { - ppd_cache_ = PpdCache::CreateForTesting( - ppd_cache_temp_dir_.GetPath(), - task_environment_.GetMainThreadTaskRunner()); - } else { - ppd_cache_ = PpdCache::Create(ppd_cache_temp_dir_.GetPath()); + // Creates and return a provider for a test that uses the given |options|. + scoped_refptr<PpdProvider> CreateProvider( + const CreateProviderOptions& options) { + switch (options.where_ppd_cache_runs) { + case PpdCacheRunLocation::kOnTestThread: + ppd_cache_ = PpdCache::CreateForTesting( + ppd_cache_temp_dir_.GetPath(), + task_environment_.GetMainThreadTaskRunner()); + break; + case PpdCacheRunLocation::kInBackgroundThreads: + default: + ppd_cache_ = PpdCache::Create(ppd_cache_temp_dir_.GetPath()); + break; } auto manager_config_cache = std::make_unique<FakePrinterConfigCache>(); provider_backdoor_.manager_config_cache = manager_config_cache.get(); - auto manager = PpdMetadataManager::Create(locale, &clock_, + auto manager = PpdMetadataManager::Create(options.browser_locale, &clock_, std::move(manager_config_cache)); provider_backdoor_.metadata_manager = manager.get(); + switch (options.propagate_locale) { + case PropagateLocaleToMetadataManager::kDoNotPropagate: + // Nothing to do; the no-propagate case allows the + // PpdMetadataManager to acquire the metadata locale (or fail to + // do so) by natural means. + break; + case PropagateLocaleToMetadataManager::kDoPropagate: + default: + provider_backdoor_.metadata_manager->SetLocaleForTesting( + options.browser_locale); + break; + } + auto config_cache = std::make_unique<FakePrinterConfigCache>(); provider_backdoor_.config_cache = config_cache.get(); - return CreateV3Provider(locale, base::Version("40.8.6753.09"), ppd_cache_, + return CreateV3Provider(options.browser_locale, + base::Version("40.8.6753.09"), ppd_cache_, std::move(manager), std::move(config_cache)); } @@ -343,7 +387,9 @@ // ResolveManufacturers() and fails the oldest call when the queue is // deemed full (implementation-specified detail). TEST_F(PpdProviderTest, FailsOldestQueuedResolveManufacturers) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); for (int i = kMethodDeferralLimitForTesting; i >= 0; i--) { provider->ResolveManufacturers(base::BindOnce( &PpdProviderTest::CaptureResolveManufacturers, base::Unretained(this))); @@ -358,7 +404,9 @@ // ReverseLookup() and fails the oldest call when the queue is deemed // full (implementation-specified detail). TEST_F(PpdProviderTest, FailsOldestQueuedReverseLookup) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); for (int i = kMethodDeferralLimitForTesting; i >= 0; i--) { provider->ReverseLookup( "some effective-make-and-model string", @@ -373,7 +421,9 @@ // Test that we get back manufacturer maps as expected. TEST_F(PpdProviderTest, ManufacturersFetch) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); // Issue two requests at the same time, both should be resolved properly. provider->ResolveManufacturers(base::BindOnce( @@ -394,7 +444,9 @@ // is almost exactly the same as the above test, we just don't bring up the fake // server first. TEST_F(PpdProviderTest, ManufacturersFetchNoServer) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); // Issue two requests at the same time, both should be resolved properly. provider->ResolveManufacturers(base::BindOnce( &PpdProviderTest::CaptureResolveManufacturers, base::Unretained(this))); @@ -413,7 +465,9 @@ // Tests that mutiples requests for make-and-model resolution can be fulfilled // simultaneously. TEST_F(PpdProviderTest, RepeatedMakeModel) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); PrinterSearchData unrecognized_printer; @@ -454,7 +508,9 @@ // Test successful and unsuccessful usb resolutions. TEST_F(PpdProviderTest, UsbResolution) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); PrinterSearchData search_data; @@ -510,7 +566,9 @@ // Test basic ResolvePrinters() functionality. At the same time, make // sure we can get the PpdReference for each of the resolved printers. TEST_F(PpdProviderTest, ResolvePrinters) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); // Grab the manufacturer list, but don't bother to save it, we know what @@ -556,7 +614,9 @@ // Test that if we give a bad reference to ResolvePrinters(), we get an // INTERNAL_ERROR. TEST_F(PpdProviderTest, ResolvePrintersBadReference) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); provider->ResolveManufacturers(base::BindOnce(&ResolveManufacturersNop)); task_environment_.RunUntilIdle(); @@ -572,7 +632,9 @@ // Test that if the server is unavailable, we get SERVER_ERRORs back out. TEST_F(PpdProviderTest, ResolvePrintersNoServer) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); provider->ResolveManufacturers(base::BindOnce(&ResolveManufacturersNop)); task_environment_.RunUntilIdle(); @@ -595,7 +657,9 @@ // Test a successful ppd resolution from an effective_make_and_model reference. TEST_F(PpdProviderTest, ResolveServerKeyPpd) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); Printer::PpdReference ref; ref.effective_make_and_model = "printer_b_ref"; @@ -618,7 +682,9 @@ // disallowed because we're not sure we completely understand the security // implications. TEST_F(PpdProviderTest, ResolveUserSuppliedUrlPpdFromNetworkFails) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); Printer::PpdReference ref; @@ -637,7 +703,9 @@ // reading from a file. Note we shouldn't need the server to be up // to do this successfully, as we should be able to do this offline. TEST_F(PpdProviderTest, ResolveUserSuppliedUrlPpdFromFile) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath filename = temp_dir.GetPath().Append("my_spiffy.ppd"); @@ -661,7 +729,9 @@ // Test that we cache ppd resolutions when we fetch them and that we can resolve // from the cache without the server available. TEST_F(PpdProviderTest, ResolvedPpdsGetCached) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); std::string user_ppd_contents = "Woohoo"; Printer::PpdReference ref; { @@ -690,7 +760,9 @@ // Recreate the provider to make sure we don't have any memory caches which // would mask problems with disk persistence. - provider = CreateProvider("en", false); + provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); // Re-resolve. provider->ResolvePpd(ref, base::BindOnce(&PpdProviderTest::CaptureResolvePpd, @@ -705,7 +777,9 @@ // Test that all entrypoints will correctly work with case-insensitve // effective-make-and-model strings. TEST_F(PpdProviderTest, CaseInsensitiveMakeAndModel) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); std::string ref = "pRiNteR_A_reF"; @@ -746,7 +820,9 @@ // determine the name of the PPD license associated with the given effecive make // and model (if any). TEST_F(PpdProviderTest, ResolvePpdLicense) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); // For this effective_make_and_model, we expect that there is associated @@ -775,7 +851,9 @@ // Verifies that we can extract the Manufacturer and Model selectison for a // given effective make and model. TEST_F(PpdProviderTest, ReverseLookup) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); std::string ref = "printer_a_ref"; provider->ReverseLookup(ref, @@ -807,7 +885,9 @@ // Explicitly *not* starting a fake server. std::string cached_ppd_contents = "These cached contents are different from what's being served"; - auto provider = CreateProvider("en", true); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kOnTestThread, + PropagateLocaleToMetadataManager::kDoNotPropagate}); Printer::PpdReference ref; ref.effective_make_and_model = "printer_a_ref"; std::string cache_key = PpdProvider::PpdReferenceToCacheKey(ref); @@ -831,7 +911,9 @@ TEST_F(PpdProviderTest, StaleCacheGetsRefreshed) { std::string cached_ppd_contents = "These cached contents are different from what's being served"; - auto provider = CreateProvider("en", true); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kOnTestThread, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); // printer_ref_a resolves to kCupsFilterPpdContents on the server. std::string expected_ppd = kCupsFilterPpdContents; @@ -875,7 +957,9 @@ // Note that we're explicitly *not* starting the Fake ppd server in this test. std::string cached_ppd_contents = "These cached contents are different from what's being served"; - auto provider = CreateProvider("en", true); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kOnTestThread, + PropagateLocaleToMetadataManager::kDoNotPropagate}); Printer::PpdReference ref; ref.effective_make_and_model = "printer_a_ref"; std::string cache_key = PpdProvider::PpdReferenceToCacheKey(ref); @@ -916,7 +1000,9 @@ base::ScopedTempDir temp_dir; std::string cached_ppd_contents = "Cached Ppd Contents"; std::string disk_ppd_contents = "Updated Ppd Contents"; - auto provider = CreateProvider("en", true); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kOnTestThread, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath filename = temp_dir.GetPath().Append("my_spiffy.ppd"); @@ -957,7 +1043,9 @@ // Test resolving usb manufacturer when failed to resolve PpdReference. TEST_F(PpdProviderTest, ResolveUsbManufacturer) { - auto provider = CreateProvider("en", false); + auto provider = + CreateProvider({"en", PpdCacheRunLocation::kInBackgroundThreads, + PropagateLocaleToMetadataManager::kDoNotPropagate}); StartFakePpdServer(); PrinterSearchData search_data;
diff --git a/chromeos/services/network_config/cros_network_config.cc b/chromeos/services/network_config/cros_network_config.cc index 2958274..31a7e53 100644 --- a/chromeos/services/network_config/cros_network_config.cc +++ b/chromeos/services/network_config/cros_network_config.cc
@@ -1432,7 +1432,6 @@ wifi->frequency = GetInt32(wifi_dict, ::onc::wifi::kFrequency); wifi->frequency_list = GetInt32List(wifi_dict, ::onc::wifi::kFrequencyList); - wifi->ft_enabled = GetManagedBoolean(wifi_dict, ::onc::wifi::kFTEnabled); wifi->hex_ssid = GetManagedString(wifi_dict, ::onc::wifi::kHexSSID); wifi->hidden_ssid = GetManagedBoolean(wifi_dict, ::onc::wifi::kHiddenSSID);
diff --git a/chromeos/services/network_config/public/mojom/cros_network_config.mojom b/chromeos/services/network_config/public/mojom/cros_network_config.mojom index ba5dc03..57f34a7 100644 --- a/chromeos/services/network_config/public/mojom/cros_network_config.mojom +++ b/chromeos/services/network_config/public/mojom/cros_network_config.mojom
@@ -536,7 +536,6 @@ ManagedEAPProperties? eap; int32 frequency = 0; array<int32>? frequency_list; - ManagedBoolean? ft_enabled; ManagedString? hex_ssid; ManagedBoolean? hidden_ssid; // Note: |passphrase| contains a placeholder if set to avoid leaking secrets.
diff --git a/chromeos/test/data/network/shill_wifi_eap_tls.json b/chromeos/test/data/network/shill_wifi_eap_tls.json index 594e6acd50..eff54f7 100644 --- a/chromeos/test/data/network/shill_wifi_eap_tls.json +++ b/chromeos/test/data/network/shill_wifi_eap_tls.json
@@ -19,5 +19,4 @@ "SaveCredentials": true, "SecurityClass": "802_1x", "Type": "wifi", - "WiFi.FTEnabled": true }
diff --git a/chromeos/test/data/network/shill_wifi_psk.json b/chromeos/test/data/network/shill_wifi_psk.json index 2717bd93..bb9268b 100644 --- a/chromeos/test/data/network/shill_wifi_psk.json +++ b/chromeos/test/data/network/shill_wifi_psk.json
@@ -10,5 +10,4 @@ "WiFi.HiddenSSID": false, "WiFi.Frequency": 2412, "WiFi.FrequencyList": [2412, 5180], - "WiFi.FTEnabled": true, }
diff --git a/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc b/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc index 976737ed..458bdb9 100644 --- a/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc +++ b/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc
@@ -4,7 +4,6 @@ "Name": "", "WiFi": { "Security": "WPA-EAP", - "FTEnabled": true, "EAP": { "ClientCertType": "PKCS11Id", "ClientCertPKCS11Id": "1:123456abcdef",
diff --git a/chromeos/test/data/network/valid_wifi_psk.onc b/chromeos/test/data/network/valid_wifi_psk.onc index ba6ffdfd..0de97810 100644 --- a/chromeos/test/data/network/valid_wifi_psk.onc +++ b/chromeos/test/data/network/valid_wifi_psk.onc
@@ -27,7 +27,6 @@ "AutoConnect": true, "Frequency": 2412, "FrequencyList": [2412, 5180], - "FTEnabled": true, "HexSSID": "4F70656E577274", // "OpenWrt" "HiddenSSID": false, "Passphrase": "some passphrase",
diff --git a/chromeos/test/data/network/wifi_eap_tls.onc b/chromeos/test/data/network/wifi_eap_tls.onc index 7ecb53b..518c1d7 100644 --- a/chromeos/test/data/network/wifi_eap_tls.onc +++ b/chromeos/test/data/network/wifi_eap_tls.onc
@@ -4,7 +4,6 @@ "Name": "WifiEapTls", "WiFi": { "Security": "WPA-EAP", - "FTEnabled": true, "EAP": { "Outer": "EAP-TLS", "Identity": "my_identity",
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index 7f9eb32..8b7c1df 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -90,6 +90,10 @@ "data_model/autofill_profile_comparator.h", "data_model/autofill_structured_address_component.cc", "data_model/autofill_structured_address_component.h", + "data_model/autofill_structured_address_constants.cc", + "data_model/autofill_structured_address_constants.h", + "data_model/autofill_structured_address_regex_provider.cc", + "data_model/autofill_structured_address_regex_provider.h", "data_model/autofill_structured_address_utils.cc", "data_model/autofill_structured_address_utils.h", "data_model/contact_info.cc", @@ -571,6 +575,7 @@ "data_model/autofill_profile_comparator_unittest.cc", "data_model/autofill_profile_unittest.cc", "data_model/autofill_structured_address_component_unittest.cc", + "data_model/autofill_structured_address_regex_provider_unittest.cc", "data_model/autofill_structured_address_utils_unittest.cc", "data_model/contact_info_unittest.cc", "data_model/credit_card_unittest.cc",
diff --git a/components/autofill/core/browser/autofill_download_manager.cc b/components/autofill/core/browser/autofill_download_manager.cc index 1fe15d7..f333742 100644 --- a/components/autofill/core/browser/autofill_download_manager.cc +++ b/components/autofill/core/browser/autofill_download_manager.cc
@@ -1055,13 +1055,13 @@ } void AutofillDownloadManager::InitActiveExperiments() { - auto* variations_http_header_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); - DCHECK(variations_http_header_provider != nullptr); + auto* variations_ids_provider = + variations::VariationsIdsProvider::GetInstance(); + DCHECK(variations_ids_provider != nullptr); delete active_experiments_; active_experiments_ = new std::vector<variations::VariationID>( - variations_http_header_provider->GetVariationsVector( + variations_ids_provider->GetVariationsVector( variations::GOOGLE_WEB_PROPERTIES_TRIGGER)); base::EraseIf(*active_experiments_, [](variations::VariationID id) { return !IsAutofillExperimentId(id);
diff --git a/components/autofill/core/browser/autofill_download_manager.h b/components/autofill/core/browser/autofill_download_manager.h index 4531f498..65270c5 100644 --- a/components/autofill/core/browser/autofill_download_manager.h +++ b/components/autofill/core/browser/autofill_download_manager.h
@@ -22,7 +22,7 @@ #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/signatures.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "net/base/backoff_entry.h" #include "services/network/public/cpp/simple_url_loader.h" #include "url/gurl.h"
diff --git a/components/autofill/core/browser/autofill_download_manager_unittest.cc b/components/autofill/core/browser/autofill_download_manager_unittest.cc index ad89862..51f8e48 100644 --- a/components/autofill/core/browser/autofill_download_manager_unittest.cc +++ b/components/autofill/core/browser/autofill_download_manager_unittest.cc
@@ -40,7 +40,7 @@ #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/signatures.h" #include "components/prefs/pref_service.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "net/http/http_status_code.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" @@ -1390,10 +1390,10 @@ if (server_.Started()) ASSERT_TRUE(server_.ShutdownAndWaitUntilComplete()); - auto* variations_http_header_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); - if (variations_http_header_provider != nullptr) - variations_http_header_provider->ResetForTesting(); + auto* variations_ids_provider = + variations::VariationsIdsProvider::GetInstance(); + if (variations_ids_provider != nullptr) + variations_ids_provider->ResetForTesting(); } // AutofillDownloadManager::Observer implementation. @@ -1632,10 +1632,10 @@ } // Add experiment/variation idd from the range reserved for autofill. - auto* variations_http_header_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); - ASSERT_TRUE(variations_http_header_provider != nullptr); - variations_http_header_provider->ForceVariationIds( + auto* variations_ids_provider = + variations::VariationsIdsProvider::GetInstance(); + ASSERT_TRUE(variations_ids_provider != nullptr); + variations_ids_provider->ForceVariationIds( {"t3314883", "t3312923", "t3314885"}, // first two valid, out-of-order {});
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_component.cc b/components/autofill/core/browser/data_model/autofill_structured_address_component.cc index 424a182..692fb5a 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address_component.cc +++ b/components/autofill/core/browser/data_model/autofill_structured_address_component.cc
@@ -307,8 +307,8 @@ return false; } -std::vector<const RE2*> AddressComponent::GetParseExpressionsByRelevance() - const { +std::vector<const RE2*> +AddressComponent::GetParseRegularExpressionsByRelevance() const { return {}; } @@ -323,15 +323,15 @@ return; // Second attempt, try to parse by expressions. - if (ParseValueAndAssignSubcomponentsByExpressions()) + if (ParseValueAndAssignSubcomponentsByRegularExpressions()) return; // As a final fallback, parse using the fallback method. ParseValueAndAssignSubcomponentsByFallbackMethod(); } -bool AddressComponent::ParseValueAndAssignSubcomponentsByExpressions() { - for (const auto* parse_expression : GetParseExpressionsByRelevance()) { +bool AddressComponent::ParseValueAndAssignSubcomponentsByRegularExpressions() { + for (const auto* parse_expression : GetParseRegularExpressionsByRelevance()) { if (!parse_expression) continue; std::map<std::string, std::string> result_map;
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_component.h b/components/autofill/core/browser/data_model/autofill_structured_address_component.h index 898bbf72..732570b 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address_component.h +++ b/components/autofill/core/browser/data_model/autofill_structured_address_component.h
@@ -197,9 +197,9 @@ // to catch special cases and may fail. The method is virtual and can be // implemented on the type level. // - // * Use |ParseValueAndAssignSubcomponentsByExpressions()|. This stage uses a - // list of regular expressions acquired by the virtual method - // |GetParseExpressionsByRelevance()|. This stage my fail. + // * Use |ParseValueAndAssignSubcomponentsByRegularExpressions()|. This stage + // uses a list of regular expressions acquired by the virtual method + // |GetParseRegularExpressionsByRelevance()|. This stage my fail. // // * Use |ParseValueAndAssignSubcomponentsByFallbackMethod()| as the last // resort to parse |value_|. This method must produce a valid result. @@ -247,8 +247,8 @@ } // Returns the parse expressions by relevance for testing. - std::vector<const RE2*> GetParseExpressionsByRelevanceForTesting() { - return GetParseExpressionsByRelevance(); + std::vector<const RE2*> GetParseRegularExpressionsByRelevanceForTesting() { + return GetParseRegularExpressionsByRelevance(); } // Returns a reference to the root node of the tree for testing. @@ -279,7 +279,7 @@ // Returns pointers to regular expressions sorted by their relevance. // This method is virtual and can be reimplemented for each type. - virtual std::vector<const RE2*> GetParseExpressionsByRelevance() const; + virtual std::vector<const RE2*> GetParseRegularExpressionsByRelevance() const; // Method to parse |value_| into the values of |subcomponents_|. The // purpose of this method is to cover special cases. This method returns true @@ -338,9 +338,9 @@ const base::string16& format) const; // This method uses regular expressions acquired by - // |GetParseExpressionsByRelevance| to parse |value_| into the values of the - // subcomponents. Returns true on success and is allowed to fail. - bool ParseValueAndAssignSubcomponentsByExpressions(); + // |GetParseRegularExpressionsByRelevance| to parse |value_| into the values + // of the subcomponents. Returns true on success and is allowed to fail. + bool ParseValueAndAssignSubcomponentsByRegularExpressions(); // Returns the maximum number of components with assigned values on the path // from the component to a leaf node.
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_component_unittest.cc b/components/autofill/core/browser/data_model/autofill_structured_address_component_unittest.cc index a585776..52d1934 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address_component_unittest.cc +++ b/components/autofill/core/browser/data_model/autofill_structured_address_component_unittest.cc
@@ -120,23 +120,21 @@ // Creates a compound name for testing purposes that uses an expression to // parse. -class TestCompoundNameExpressionParsedAddressComponent - : public AddressComponent { +class TestCompoundNameRegExParsedAddressComponent : public AddressComponent { public: - TestCompoundNameExpressionParsedAddressComponent() - : TestCompoundNameExpressionParsedAddressComponent(nullptr) { + TestCompoundNameRegExParsedAddressComponent() + : TestCompoundNameRegExParsedAddressComponent(nullptr) { expression1_ = - BuildExpressionFromPattern("(?P<NAME_FULL>(?P<NAME_MIDDLE>\\d*))"); - expression2_ = - BuildExpressionFromPattern("(?P<NAME_FULL>(?P<NAME_LAST>.*))"); + BuildRegExFromPattern("(?P<NAME_FULL>(?P<NAME_MIDDLE>\\d*))"); + expression2_ = BuildRegExFromPattern("(?P<NAME_FULL>(?P<NAME_LAST>.*))"); } - explicit TestCompoundNameExpressionParsedAddressComponent( - AddressComponent* parent) + explicit TestCompoundNameRegExParsedAddressComponent(AddressComponent* parent) : AddressComponent(NAME_FULL, parent, {&first_name_, &middle_name_, &last_name_}) {} - std::vector<const RE2*> GetParseExpressionsByRelevance() const override { + std::vector<const RE2*> GetParseRegularExpressionsByRelevance() + const override { // The first two expressions will fail and the last one will be // successful. return {nullptr, expression1_.get(), expression2_.get()}; @@ -765,8 +763,8 @@ // Tests parsing using a defined method. TEST(AutofillStructuredAddressAddressComponent, - TestParseValueAndAssignSubcomponentsByExpression) { - TestCompoundNameExpressionParsedAddressComponent compound_component; + TestParseValueAndAssignSubcomponentsByRegEx) { + TestCompoundNameRegExParsedAddressComponent compound_component; compound_component.SetValue(ASCIIToUTF16("Dr. Strangelove"), VerificationStatus::kObserved); compound_component.ParseValueAndAssignSubcomponents();
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_constants.cc b/components/autofill/core/browser/data_model/autofill_structured_address_constants.cc new file mode 100644 index 0000000..e26ec3e6 --- /dev/null +++ b/components/autofill/core/browser/data_model/autofill_structured_address_constants.cc
@@ -0,0 +1,13 @@ +// Copyright 2020 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/autofill/core/browser/data_model/autofill_structured_address_constants.h" + +namespace autofill { +namespace structured_address { + +const char kSingleWordRe[] = "(?:\\w+)"; + +} // namespace structured_address +} // namespace autofill
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_constants.h b/components/autofill/core/browser/data_model/autofill_structured_address_constants.h new file mode 100644 index 0000000..5889f7c --- /dev/null +++ b/components/autofill/core/browser/data_model/autofill_structured_address_constants.h
@@ -0,0 +1,16 @@ +// Copyright 2020 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_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_CONSTANTS_H_ +#define COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_CONSTANTS_H_ + +namespace autofill { +namespace structured_address { + +// Regular expression pattern to match a single word. +extern const char kSingleWordRe[]; + +} // namespace structured_address +} // namespace autofill +#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_CONSTANTS_H_
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider.cc b/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider.cc new file mode 100644 index 0000000..4edd7103 --- /dev/null +++ b/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider.cc
@@ -0,0 +1,50 @@ +// Copyright 2020 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/autofill/core/browser/data_model/autofill_structured_address_regex_provider.h" +#include <utility> +#include "components/autofill/core/browser/data_model/autofill_structured_address_constants.h" +#include "components/autofill/core/browser/data_model/autofill_structured_address_utils.h" + +#include "base/notreached.h" + +namespace autofill { + +namespace structured_address { + +StructuredAddressesRegExProvider::StructuredAddressesRegExProvider() = default; + +// static +StructuredAddressesRegExProvider* StructuredAddressesRegExProvider::Instance() { + static base::NoDestructor<StructuredAddressesRegExProvider> + g_expression_provider; + return g_expression_provider.get(); +} + +std::string StructuredAddressesRegExProvider::GetPattern( + RegEx expression_identifier) { + switch (expression_identifier) { + case RegEx::kSingleWord: + return kSingleWordRe; + } + NOTREACHED(); +} + +const RE2* StructuredAddressesRegExProvider::GetRegEx( + RegEx expression_identifier) { + base::AutoLock lock(lock_); + auto it = cached_expressions_.find(expression_identifier); + if (it == cached_expressions_.end()) { + std::unique_ptr<const RE2> expression = + BuildRegExFromPattern(GetPattern(expression_identifier)); + const RE2* expresstion_ptr = expression.get(); + cached_expressions_.emplace(expression_identifier, std::move(expression)); + return expresstion_ptr; + } + return it->second.get(); +} + +} // namespace structured_address + +} // namespace autofill
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider.h b/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider.h new file mode 100644 index 0000000..28c8e8c --- /dev/null +++ b/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider.h
@@ -0,0 +1,76 @@ +// Copyright 2020 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_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_REGEX_PROVIDER_H_ +#define COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_REGEX_PROVIDER_H_ + +#include <memory> +#include <string> + +#include "base/containers/flat_map.h" +#include "base/no_destructor.h" +#include "base/synchronization/lock.h" +#include "third_party/re2/src/re2/re2.h" + +namespace autofill { +namespace structured_address { + +// Enumeration of all regular expressions supported for matching and parsing +// values in an AddressComponent tree. +enum class RegEx { + kSingleWord, + kLastRegEx = kSingleWord, +}; + +// This singleton class builds and caches the regular expressions for value +// parsing and characterization of values in an AddressComponent tree. +// It also builds the foundation for acquiring expressions from different +// sources. +class StructuredAddressesRegExProvider { + public: + StructuredAddressesRegExProvider& operator=( + const StructuredAddressesRegExProvider&) = delete; + StructuredAddressesRegExProvider(const StructuredAddressesRegExProvider&) = + delete; + ~StructuredAddressesRegExProvider() = delete; + + // Returns a singleton instance of this class. + static StructuredAddressesRegExProvider* Instance(); + + // Returns the regular expression corresponding to + // |expression_identifier|. If the expression is not cached yet, it is build + // by calling |BuildRegEx(expression_identifier)|. If the expression + // can't be build, nullptr is returned. + const RE2* GetRegEx(RegEx expression_identifier); + +#if UNIT_TEST + bool IsCachedForTesting(RegEx expression_identifier) { + return cached_expressions_.count(expression_identifier) > 0; + } +#endif + + private: + StructuredAddressesRegExProvider(); + + // Since the constructor is private, |base::NoDestructor| must be a friend to + // be allowed to construct the cache. + friend class base::NoDestructor<StructuredAddressesRegExProvider>; + + // Fetches a pattern identified by |expression_identifier|. + // This method is virtual and is meant to be overridden by future + // implementations that utilize multiple sources for retrieving patterns. + virtual std::string GetPattern(RegEx expression_identifier); + + // A map to store already compiled enumerated expressions keyed by + // |RegEx|. + base::flat_map<RegEx, std::unique_ptr<const RE2>> cached_expressions_; + + // A lock to prevent concurrent access to the cached expressions map. + base::Lock lock_; +}; + +} // namespace structured_address + +} // namespace autofill +#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_DATA_MODEL_AUTOFILL_STRUCTURED_ADDRESS_PATTERN_REGEX_H_
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider_unittest.cc b/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider_unittest.cc new file mode 100644 index 0000000..ee19aca0 --- /dev/null +++ b/components/autofill/core/browser/data_model/autofill_structured_address_regex_provider_unittest.cc
@@ -0,0 +1,33 @@ +// Copyright 2020 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/autofill/core/browser/data_model/autofill_structured_address_regex_provider.h" + +#include "base/test/gtest_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace autofill { +namespace structured_address { + +// Tests the caching of a compiled regular expression. +TEST(AutofillStructuredAddressRegExProvider, IsRegExCached) { + auto* g_pattern_provider = StructuredAddressesRegExProvider::Instance(); + EXPECT_FALSE(g_pattern_provider->IsCachedForTesting(RegEx::kSingleWord)); + + ASSERT_TRUE(StructuredAddressesRegExProvider::Instance() + ->GetRegEx(RegEx::kSingleWord) + ->ok()); + EXPECT_TRUE(g_pattern_provider->IsCachedForTesting(RegEx::kSingleWord)); +} + +// Builds all expressions and verifes that the result is not a nullptr. +TEST(AutofillStructuredAddressRegExProvider, BuildAllRegExs) { + for (int i = 0; i <= static_cast<int>(RegEx::kLastRegEx); i++) { + auto* g_pattern_provider = StructuredAddressesRegExProvider::Instance(); + EXPECT_NE(g_pattern_provider->GetRegEx(static_cast<RegEx>(i)), nullptr); + } +} + +} // namespace structured_address +} // namespace autofill
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_utils.cc b/components/autofill/core/browser/data_model/autofill_structured_address_utils.cc index 4b38a9f..21db5f2a 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address_utils.cc +++ b/components/autofill/core/browser/data_model/autofill_structured_address_utils.cc
@@ -1,7 +1,6 @@ // Copyright 2020 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/autofill/core/browser/data_model/autofill_structured_address_utils.h" @@ -18,46 +17,46 @@ namespace autofill { namespace structured_address { -Re2ExpressionCache::Re2ExpressionCache() = default; +Re2RegExCache::Re2RegExCache() = default; // static -Re2ExpressionCache* Re2ExpressionCache::Instance() { - static base::NoDestructor<Re2ExpressionCache> g_re2regex_cache; +Re2RegExCache* Re2RegExCache::Instance() { + static base::NoDestructor<Re2RegExCache> g_re2regex_cache; return g_re2regex_cache.get(); } -const RE2* Re2ExpressionCache::GetExpression(const std::string& pattern) { +const RE2* Re2RegExCache::GetRegEx(const std::string& pattern) { // For thread safety, acquire a lock to prevent concurrent access. base::AutoLock lock(lock_); - auto it = expression_map_.find(pattern); - if (it != expression_map_.end()) { - const RE2* expression = it->second.get(); - return expression; + auto it = regex_map_.find(pattern); + if (it != regex_map_.end()) { + const RE2* regex = it->second.get(); + return regex; } // Build the expression and verify it is correct. - auto expression_ptr = BuildExpressionFromPattern(pattern); + auto regex_ptr = BuildRegExFromPattern(pattern); // Insert the expression into the map, check the success and return the // pointer. - auto result = expression_map_.emplace(pattern, std::move(expression_ptr)); + auto result = regex_map_.emplace(pattern, std::move(regex_ptr)); DCHECK(result.second); return result.first->second.get(); } -std::unique_ptr<const RE2> BuildExpressionFromPattern(std::string pattern) { +std::unique_ptr<const RE2> BuildRegExFromPattern(std::string pattern) { RE2::Options opt; opt.set_case_sensitive(false); - auto expression = std::make_unique<const RE2>(pattern, opt); + auto regex = std::make_unique<const RE2>(pattern, opt); - if (!expression->ok()) { + if (!regex->ok()) { DEBUG_ALIAS_FOR_CSTR(pattern_copy, pattern.c_str(), 128); base::debug::DumpWithoutCrashing(); } - return expression; + return regex; } bool ParseValueByRegularExpression( @@ -66,22 +65,21 @@ std::map<std::string, std::string>* result_map) { DCHECK(result_map); - const RE2* expression = - Re2ExpressionCache::Instance()->GetExpression(pattern); + const RE2* regex = Re2RegExCache::Instance()->GetRegEx(pattern); - return ParseValueByRegularExpression(value, expression, result_map); + return ParseValueByRegularExpression(value, regex, result_map); } bool ParseValueByRegularExpression( const std::string& value, - const RE2* expression, + const RE2* regex, std::map<std::string, std::string>* result_map) { - if (!expression || !expression->ok()) + if (!regex || !regex->ok()) return false; // Get the number of capturing groups in the expression. // Note, the capturing group for the full match is not counted. - size_t number_of_capturing_groups = expression->NumberOfCapturingGroups() + 1; + size_t number_of_capturing_groups = regex->NumberOfCapturingGroups() + 1; // Create result vectors to get the matches for the capturing groups. std::vector<std::string> results(number_of_capturing_groups); @@ -96,14 +94,14 @@ } // One capturing group is not counted since it holds the full match. - if (!RE2::FullMatchN(value, *expression, match_results_ptr.data(), + if (!RE2::FullMatchN(value, *regex, match_results_ptr.data(), number_of_capturing_groups - 1)) return false; // If successful, write the values into the results map. // Note, the capturing group for the full match creates an off-by-one scenario // in the indexing. - for (auto named_group : expression->NamedCapturingGroups()) + for (auto named_group : regex->NamedCapturingGroups()) (*result_map)[named_group.first] = std::move(results.at(named_group.second - 1)); @@ -111,24 +109,22 @@ } bool IsPartialMatch(const std::string& value, const std::string& pattern) { - const RE2* expression = - Re2ExpressionCache::Instance()->GetExpression(pattern); - if (!expression || !expression->ok()) + const RE2* regex = Re2RegExCache::Instance()->GetRegEx(pattern); + if (!regex || !regex->ok()) return false; - return RE2::PartialMatch(value, *expression); + return RE2::PartialMatch(value, *regex); } std::vector<std::string> GetAllPartialMatches(const std::string& value, const std::string& pattern) { - const RE2* expression = - Re2ExpressionCache::Instance()->GetExpression(pattern); - if (!expression || !expression->ok()) + const RE2* regex = Re2RegExCache::Instance()->GetRegEx(pattern); + if (!regex || !regex->ok()) return {}; re2::StringPiece input(value); std::string match; std::vector<std::string> matches; - while (re2::RE2::FindAndConsume(&input, *expression, &match)) { + while (re2::RE2::FindAndConsume(&input, *regex, &match)) { matches.emplace_back(match); } return matches; @@ -142,5 +138,48 @@ return base::StrCat({"${", value, "}"}); } +std::string CaptureTypeWithPattern( + const ServerFieldType& type, + std::initializer_list<base::StringPiece> pattern_span_initializer_list) { + return CaptureTypeWithPattern(type, pattern_span_initializer_list, + CaptureOptions()); +} + +std::string CaptureTypeWithPattern( + const ServerFieldType& type, + std::initializer_list<base::StringPiece> pattern_span_initializer_list, + const CaptureOptions& options) { + return CaptureTypeWithPattern( + type, base::StrCat(base::make_span(pattern_span_initializer_list)), + options); +} + +std::string CaptureTypeWithPattern(const ServerFieldType& type, + const std::string& pattern, + const CaptureOptions& options) { + std::string quantifier; + switch (options.quantifier) { + // Makes the match optional. + case MATCH_OPTIONAL: + quantifier = "?"; + break; + // Makes the match lazy meaning that it is avoided if possible. + case MATCH_LAZY_OPTIONAL: + quantifier = "??"; + break; + // Makes the match required. + case MATCH_REQUIRED: + quantifier = ""; + } + + return base::StrCat({"(?:(?P<", AutofillType(type).ToString(), ">", pattern, + ")(?:", options.separator, "))", quantifier}); +} + +std::string CaptureTypeWithPattern(const ServerFieldType& type, + const std::string& pattern) { + return CaptureTypeWithPattern(type, pattern, CaptureOptions()); +} + } // namespace structured_address } // namespace autofill
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_utils.h b/components/autofill/core/browser/data_model/autofill_structured_address_utils.h index fd6878da..4ca54819 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address_utils.h +++ b/components/autofill/core/browser/data_model/autofill_structured_address_utils.h
@@ -10,45 +10,71 @@ #include <string> #include <vector> +#include "base/containers/span.h" #include "base/macros.h" #include "base/no_destructor.h" #include "base/synchronization/lock.h" +#include "components/autofill/core/browser/autofill_type.h" +#include "components/autofill/core/browser/field_types.h" #include "third_party/re2/src/re2/re2.h" namespace autofill { namespace structured_address { +// Enum to express the few quantifiers needed to parse values. +enum MatchQuantifier { + // The capture group is required. + MATCH_REQUIRED, + // The capture group is optional. + MATCH_OPTIONAL, + // The capture group is lazy optional meaning that it is avoided if an overall + // match is possible. + MATCH_LAZY_OPTIONAL, +}; + +// Options for capturing a named group using the +// |CaptureTypeWithPattern(...)| functions. +struct CaptureOptions { + // A separator that must be matched after a capture group. + // By default, a group must be either followed by a space-like character (\s) + // or it must be the last group in the line. The separator is allowed to be + // empty. + std::string separator = "\\s|$"; + // Indicates if the group is required, optional or even lazy optional. + MatchQuantifier quantifier = MATCH_REQUIRED; +}; + // A cache for compiled RE2 regular expressions. -class Re2ExpressionCache { +class Re2RegExCache { public: - Re2ExpressionCache& operator=(const Re2ExpressionCache&) = delete; - Re2ExpressionCache(const Re2ExpressionCache&) = delete; - ~Re2ExpressionCache() = delete; + Re2RegExCache& operator=(const Re2RegExCache&) = delete; + Re2RegExCache(const Re2RegExCache&) = delete; + ~Re2RegExCache() = delete; // Returns a singleton instance. - static Re2ExpressionCache* Instance(); + static Re2RegExCache* Instance(); // Returns a pointer to a constant compiled expression that matches |pattern| // case-insensitively. - const RE2* GetExpression(const std::string& pattern); + const RE2* GetRegEx(const std::string& pattern); #ifdef UNIT_TEST // Returns true if the compiled regular expression corresponding to |pattern| // is cached. - bool IsExpressionCachedForTesting(const std::string& pattern) { - return expression_map_.count(pattern) > 0; + bool IsRegExCachedForTesting(const std::string& pattern) { + return regex_map_.count(pattern) > 0; } #endif private: - Re2ExpressionCache(); + Re2RegExCache(); // Since the constructor is private, |base::NoDestructor| must be friend to be // allowed to construct the cache. - friend class base::NoDestructor<Re2ExpressionCache>; + friend class base::NoDestructor<Re2RegExCache>; // Stores a compiled regular expression keyed by its corresponding |pattern|. - std::map<std::string, std::unique_ptr<const RE2>> expression_map_; + std::map<std::string, std::unique_ptr<const RE2>> regex_map_; // A lock to prevent concurrent access to the map. base::Lock lock_; @@ -67,11 +93,11 @@ // pattern. bool ParseValueByRegularExpression( const std::string& value, - const RE2* expression, + const RE2* regex, std::map<std::string, std::string>* result_map); // Returns a compiled case insensitive regular expression for |pattern|. -std::unique_ptr<const RE2> BuildExpressionFromPattern(std::string pattern); +std::unique_ptr<const RE2> BuildRegExFromPattern(std::string pattern); // Returns true if |value| can be matched with |pattern|. bool IsPartialMatch(const std::string& value, const std::string& pattern); @@ -86,6 +112,31 @@ // Returns |value| as a placeholder token: ${value}. std::string GetPlaceholderToken(const std::string& value); +// Returns a named capture group created by the concatenation of the +// StringPieces in |pattern_span_initializer_list|. The group is named by the +// string representation of |type| and respects |options|. +std::string CaptureTypeWithPattern( + const ServerFieldType& type, + std::initializer_list<base::StringPiece> pattern_span_initializer_list, + const CaptureOptions& options); + +// Same as |CaptureTypeWithPattern(type, pattern_span_initializer_list, +// options)| but uses default options. +std::string CaptureTypeWithPattern( + const ServerFieldType& type, + std::initializer_list<base::StringPiece> pattern_span_initializer_list); + +// Returns a capture group named by the string representation of |type| that +// matches |pattern|. +std::string CaptureTypeWithPattern(const ServerFieldType& type, + const std::string& pattern, + const CaptureOptions& options); + +// Same as |CaptureTypeWithPattern(type, pattern, options)| but uses default +// options. +std::string CaptureTypeWithPattern(const ServerFieldType& type, + const std::string& pattern); + } // namespace structured_address } // namespace autofill
diff --git a/components/autofill/core/browser/data_model/autofill_structured_address_utils_unittest.cc b/components/autofill/core/browser/data_model/autofill_structured_address_utils_unittest.cc index 35667becc7..07bfc4e 100644 --- a/components/autofill/core/browser/data_model/autofill_structured_address_utils_unittest.cc +++ b/components/autofill/core/browser/data_model/autofill_structured_address_utils_unittest.cc
@@ -92,14 +92,14 @@ } TEST(AutofillStructuredAddressUtils, - TestParseValueByRegularExpression_InvalidExpression) { + TestParseValueByRegularExpression_InvalidRegEx) { std::string regex = "(!<INVALID"; std::string value = "first middle1 middle2 middle3 last"; std::map<std::string, std::string> result_map; EXPECT_FALSE(ParseValueByRegularExpression(value, regex, &result_map)); - auto expression = BuildExpressionFromPattern(regex); + auto expression = BuildRegExFromPattern(regex); EXPECT_FALSE( ParseValueByRegularExpression(value, expression.get(), &result_map)); } @@ -121,21 +121,19 @@ } // Test the matching of a value against an invalid regular expression. -TEST(AutofillStructuredAddressUtils, TestIsPartialMatch_InvalidExpression) { +TEST(AutofillStructuredAddressUtils, TestIsPartialMatch_InvalidRegEx) { EXPECT_FALSE(IsPartialMatch("123 sdf 123", "(!<sdf")); } // Test the caching of regular expressions. -TEST(AutofillStructuredAddressUtils, TestExpressionCaching) { +TEST(AutofillStructuredAddressUtils, TestRegExCaching) { std::string pattern = "(?P<SOME_EXPRESSION>.)"; // Verify that the pattern is not cached yet. - EXPECT_FALSE( - Re2ExpressionCache::Instance()->IsExpressionCachedForTesting(pattern)); + EXPECT_FALSE(Re2RegExCache::Instance()->IsRegExCachedForTesting(pattern)); // Request the regular expression and verify that it is cached afterwards. - Re2ExpressionCache::Instance()->GetExpression(pattern); - EXPECT_TRUE( - Re2ExpressionCache::Instance()->IsExpressionCachedForTesting(pattern)); + Re2RegExCache::Instance()->GetRegEx(pattern); + EXPECT_TRUE(Re2RegExCache::Instance()->IsRegExCachedForTesting(pattern)); } TEST(AutofillStructuredAddressUtils, TestGetAllPartialMatches) { @@ -194,5 +192,20 @@ EXPECT_EQ("${VAR}", GetPlaceholderToken("VAR")); } +TEST(AutofillStructuredAddressUtils, CaptureTypeWithPattern) { + EXPECT_EQ("(?:(?P<NAME_FULL>abs\\w)(?:\\s|$))?", + CaptureTypeWithPattern(NAME_FULL, {"abs", "\\w"}, + {.quantifier = MATCH_OPTIONAL})); + EXPECT_EQ("(?:(?P<NAME_FULL>abs\\w)(?:\\s|$))", + CaptureTypeWithPattern(NAME_FULL, {"abs", "\\w"})); + EXPECT_EQ("(?:(?P<NAME_FULL>abs\\w)(?:\\s|$))??", + CaptureTypeWithPattern(NAME_FULL, "abs\\w", + {.quantifier = MATCH_LAZY_OPTIONAL})); + EXPECT_EQ("(?:(?P<NAME_FULL>abs\\w)(?:\\s|$))", + CaptureTypeWithPattern(NAME_FULL, "abs\\w")); + EXPECT_EQ("(?:(?P<NAME_FULL>abs\\w)(?:_))", + CaptureTypeWithPattern(NAME_FULL, "abs\\w", {.separator = "_"})); +} + } // namespace structured_address } // namespace autofill
diff --git a/components/autofill/core/browser/payments/payments_client_unittest.cc b/components/autofill/core/browser/payments/payments_client_unittest.cc index 821f70b..2cf54dd 100644 --- a/components/autofill/core/browser/payments/payments_client_unittest.cc +++ b/components/autofill/core/browser/payments/payments_client_unittest.cc
@@ -32,7 +32,7 @@ #include "components/signin/public/identity_manager/identity_test_environment.h" #include "components/variations/net/variations_http_headers.h" #include "components/variations/variations_associated_data.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" #include "services/network/test/test_utils.h" @@ -686,14 +686,14 @@ // Register a trial and variation id, so that there is data in variations // headers. Also, the variations header provider may have been registered to // observe some other field trial list, so reset it. - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); CreateFieldTrialWithId("AutofillTest", "Group", 369); StartGettingUploadDetails(); // Note that experiment information is stored in X-Client-Data. EXPECT_TRUE(HasVariationsHeader()); - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); } TEST_F(PaymentsClientTest, GetDetailsIncludeBillableServiceNumber) { @@ -779,7 +779,7 @@ // Register a trial and variation id, so that there is data in variations // headers. Also, the variations header provider may have been registered to // observe some other field trial list, so reset it. - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); CreateFieldTrialWithId("AutofillTest", "Group", 369); StartUploading(/*include_cvc=*/true); IssueOAuthToken(); @@ -787,14 +787,14 @@ // Note that experiment information is stored in X-Client-Data. EXPECT_TRUE(HasVariationsHeader()); - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); } TEST_F(PaymentsClientTest, UnmaskCardVariationsTest) { // Register a trial and variation id, so that there is data in variations // headers. Also, the variations header provider may have been registered to // observe some other field trial list, so reset it. - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); CreateFieldTrialWithId("AutofillTest", "Group", 369); StartUnmasking(CardUnmaskOptions()); IssueOAuthToken(); @@ -802,7 +802,7 @@ // Note that experiment information is stored in X-Client-Data. EXPECT_TRUE(HasVariationsHeader()); - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); } TEST_F(PaymentsClientTest, UploadSuccessWithoutServerId) { @@ -1047,7 +1047,7 @@ // Register a trial and variation id, so that there is data in variations // headers. Also, the variations header provider may have been registered to // observe some other field trial list, so reset it. - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); CreateFieldTrialWithId("AutofillTest", "Group", 369); StartMigrating(/*has_cardholder_name=*/true); IssueOAuthToken(); @@ -1055,7 +1055,7 @@ // Note that experiment information is stored in X-Client-Data. EXPECT_TRUE(HasVariationsHeader()); - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); } TEST_F(PaymentsClientTest, MigrationRequestIncludesUniqueId) {
diff --git a/components/autofill_assistant/browser/actions/show_generic_ui_action.cc b/components/autofill_assistant/browser/actions/show_generic_ui_action.cc index 28f2b505..accb907b 100644 --- a/components/autofill_assistant/browser/actions/show_generic_ui_action.cc +++ b/components/autofill_assistant/browser/actions/show_generic_ui_action.cc
@@ -145,6 +145,22 @@ // Note: it is important to write autofill profiles etc. to the model AFTER // the UI has been inflated, otherwise the UI won't get change notifications // for them. + for (const auto& additional_value : + proto_.show_generic_ui().request_user_data().additional_values()) { + if (!delegate_->GetUserData()->has_additional_value( + additional_value.source_identifier())) { + EndAction(ClientStatus(PRECONDITION_FAILED)); + return; + } + } + for (const auto& additional_value : + proto_.show_generic_ui().request_user_data().additional_values()) { + ValueProto value = *delegate_->GetUserData()->additional_value( + additional_value.source_identifier()); + value.set_is_client_side_only(true); + delegate_->GetUserModel()->SetValue(additional_value.model_identifier(), + value); + } if (proto_.show_generic_ui().has_request_login_options()) { auto login_options = proto_.show_generic_ui().request_login_options().login_options();
diff --git a/components/autofill_assistant/browser/actions/show_generic_ui_action_unittest.cc b/components/autofill_assistant/browser/actions/show_generic_ui_action_unittest.cc index 38f33b6..e5129d0 100644 --- a/components/autofill_assistant/browser/actions/show_generic_ui_action_unittest.cc +++ b/components/autofill_assistant/browser/actions/show_generic_ui_action_unittest.cc
@@ -57,6 +57,8 @@ ON_CALL(mock_action_delegate_, ClearGenericUi()).WillByDefault(Return()); ON_CALL(mock_action_delegate_, GetUserModel()) .WillByDefault(Return(&user_model_)); + ON_CALL(mock_action_delegate_, GetUserData()) + .WillByDefault(Return(&user_data_)); ON_CALL(mock_action_delegate_, GetPersonalDataManager) .WillByDefault(Return(&mock_personal_data_manager_)); ON_CALL(mock_action_delegate_, GetWebsiteLoginManager) @@ -83,6 +85,7 @@ return action; } + UserData user_data_; UserModel user_model_; MockPersonalDataManager mock_personal_data_manager_; MockWebsiteLoginManager mock_website_login_manager_; @@ -520,6 +523,44 @@ Run(); } +TEST_F(ShowGenericUiActionTest, RequestUserDataFailsOnMissingValues) { + auto* request_user_data = proto_.mutable_request_user_data(); + auto* additional_value = request_user_data->add_additional_values(); + additional_value->set_source_identifier("client_memory"); + additional_value->set_model_identifier("target"); + + EXPECT_CALL(callback_, Run(Pointee(Property(&ProcessedActionProto::status, + PRECONDITION_FAILED)))); + Run(); +} + +TEST_F(ShowGenericUiActionTest, RequestUserData) { + auto* request_user_data = proto_.mutable_request_user_data(); + auto* additional_value = request_user_data->add_additional_values(); + additional_value->set_source_identifier("client_memory_1"); + additional_value->set_model_identifier("target_1"); + additional_value = request_user_data->add_additional_values(); + additional_value->set_source_identifier("client_memory_2"); + additional_value->set_model_identifier("target_2"); + + user_data_.additional_values_["client_memory_1"] = + SimpleValue(std::string("value_1")); + user_data_.additional_values_["client_memory_2"] = SimpleValue(123); + + EXPECT_CALL( + callback_, + Run(Pointee(Property(&ProcessedActionProto::status, ACTION_APPLIED)))); + Run(); + + auto expected_value_1 = SimpleValue(std::string("value_1")); + expected_value_1.set_is_client_side_only(true); + auto expected_value_2 = SimpleValue(123); + expected_value_2.set_is_client_side_only(true); + + EXPECT_EQ(*user_model_.GetValue("target_1"), expected_value_1); + EXPECT_EQ(*user_model_.GetValue("target_2"), expected_value_2); +} + // TODO(b/161652848): Add test coverage for element checks and interrupts. } // namespace
diff --git a/components/autofill_assistant/browser/service.proto b/components/autofill_assistant/browser/service.proto index a94716e..2fafe2ba 100644 --- a/components/autofill_assistant/browser/service.proto +++ b/components/autofill_assistant/browser/service.proto
@@ -1321,6 +1321,16 @@ repeated LoginOption login_options = 1; optional string model_identifier = 2; } + message RequestUserData { + message AdditionalValue { + // The client memory identifier (from |UserData|). + optional string source_identifier = 1; + // The model identifier to write the value to (to |UserModel|). + optional string model_identifier = 2; + } + // Additional values to write from |UserData| to |UserModel|. + repeated AdditionalValue additional_values = 1; + } message Result { // The model containing the values for all keys specified in // |output_model_identifiers|. @@ -1365,6 +1375,11 @@ // If true, run scripts flagged with |interrupt=true| as soon as their // preconditions match, then go back to the parent action. optional bool allow_interrupt = 8; + // If specified, will write the requested values from |UserData| to + // |UserModel|. Will fail the action with PRECONDITION_FAILED if any of the + // requested values is missing. Note that all values will have + // |is_client_side_only| set to true. + optional RequestUserData request_user_data = 9; } // Allow choosing one or more possibility. If FocusElement was called just
diff --git a/components/blocked_content/popup_opener_tab_helper.cc b/components/blocked_content/popup_opener_tab_helper.cc index b070753..77a7d07 100644 --- a/components/blocked_content/popup_opener_tab_helper.cc +++ b/components/blocked_content/popup_opener_tab_helper.cc
@@ -91,7 +91,7 @@ } void PopupOpenerTabHelper::DidGetUserInteraction( - const blink::WebInputEvent::Type type) { + const blink::WebInputEvent& event) { has_opened_popup_since_last_user_gesture_ = false; }
diff --git a/components/blocked_content/popup_opener_tab_helper.h b/components/blocked_content/popup_opener_tab_helper.h index 363f0fea..9d070f3 100644 --- a/components/blocked_content/popup_opener_tab_helper.h +++ b/components/blocked_content/popup_opener_tab_helper.h
@@ -66,7 +66,7 @@ void OnVisibilityChanged(content::Visibility visibility) override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override; + void DidGetUserInteraction(const blink::WebInputEvent& event) override; // Logs user popup content settings if the last committed URL is valid and // we have not recorded the settings for the opener id of the helper's
diff --git a/components/blocked_content/popup_tracker.cc b/components/blocked_content/popup_tracker.cc index 2735f51..22cf6b9 100644 --- a/components/blocked_content/popup_tracker.cc +++ b/components/blocked_content/popup_tracker.cc
@@ -131,13 +131,12 @@ visibility_tracker_.OnShown(); } -void PopupTracker::DidGetUserInteraction( - const blink::WebInputEvent::Type type) { +void PopupTracker::DidGetUserInteraction(const blink::WebInputEvent& event) { // TODO(csharrison): It would be nice if ctrl-W could be filtered out here, // but the initial ctrl key press is registered as a kRawKeyDown. num_interactions_++; - if (type == blink::WebInputEvent::Type::kGestureScrollBegin) { + if (event.GetType() == blink::WebInputEvent::Type::kGestureScrollBegin) { num_gesture_scroll_begin_events_++; } else { num_activation_events_++;
diff --git a/components/blocked_content/popup_tracker.h b/components/blocked_content/popup_tracker.h index 8366782..2948392 100644 --- a/components/blocked_content/popup_tracker.h +++ b/components/blocked_content/popup_tracker.h
@@ -59,7 +59,7 @@ void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void OnVisibilityChanged(content::Visibility visibility) override; - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override; + void DidGetUserInteraction(const blink::WebInputEvent& event) override; // subresource_filter::SubresourceFilterObserver: void OnSafeBrowsingChecksComplete(
diff --git a/components/drive/service/drive_api_service.cc b/components/drive/service/drive_api_service.cc index c52666c..32e4960 100644 --- a/components/drive/service/drive_api_service.cc +++ b/components/drive/service/drive_api_service.cc
@@ -25,11 +25,12 @@ using google_apis::AboutResourceCallback; using google_apis::AuthStatusCallback; using google_apis::CancelCallback; +using google_apis::CancelCallbackOnce; using google_apis::ChangeList; using google_apis::ChangeListCallback; +using google_apis::DownloadActionCallback; using google_apis::DRIVE_OTHER_ERROR; using google_apis::DRIVE_PARSE_ERROR; -using google_apis::DownloadActionCallback; using google_apis::DriveApiErrorCode; using google_apis::EntryActionCallback; using google_apis::FileList; @@ -499,7 +500,7 @@ return sender_->StartRequestWithAuthRetry(std::move(request)); } -CancelCallback DriveAPIService::DownloadFile( +CancelCallbackOnce DriveAPIService::DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const DownloadActionCallback& download_action_callback,
diff --git a/components/drive/service/drive_api_service.h b/components/drive/service/drive_api_service.h index 7542de7..b0b13a7 100644 --- a/components/drive/service/drive_api_service.h +++ b/components/drive/service/drive_api_service.h
@@ -175,7 +175,7 @@ google_apis::CancelCallback TrashResource( const std::string& resource_id, const google_apis::EntryActionCallback& callback) override; - google_apis::CancelCallback DownloadFile( + google_apis::CancelCallbackOnce DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const google_apis::DownloadActionCallback& download_action_callback,
diff --git a/components/drive/service/drive_service_interface.h b/components/drive/service/drive_service_interface.h index 308bb0e5..485f67c 100644 --- a/components/drive/service/drive_service_interface.h +++ b/components/drive/service/drive_service_interface.h
@@ -426,7 +426,7 @@ // // |download_action_callback| must not be null. // |get_content_callback| and |progress_callback| may be null. - virtual google_apis::CancelCallback DownloadFile( + virtual google_apis::CancelCallbackOnce DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const google_apis::DownloadActionCallback& download_action_callback,
diff --git a/components/drive/service/dummy_drive_service.cc b/components/drive/service/dummy_drive_service.cc index df42342d..5eb9eda 100644 --- a/components/drive/service/dummy_drive_service.cc +++ b/components/drive/service/dummy_drive_service.cc
@@ -11,6 +11,7 @@ using google_apis::AboutResourceCallback; using google_apis::AuthStatusCallback; using google_apis::CancelCallback; +using google_apis::CancelCallbackOnce; using google_apis::ChangeListCallback; using google_apis::DownloadActionCallback; using google_apis::EntryActionCallback; @@ -130,7 +131,7 @@ const std::string& resource_id, const EntryActionCallback& callback) { return CancelCallback(); } -CancelCallback DummyDriveService::DownloadFile( +CancelCallbackOnce DummyDriveService::DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const DownloadActionCallback& download_action_callback,
diff --git a/components/drive/service/dummy_drive_service.h b/components/drive/service/dummy_drive_service.h index 187737c6..1795c26 100644 --- a/components/drive/service/dummy_drive_service.h +++ b/components/drive/service/dummy_drive_service.h
@@ -79,7 +79,7 @@ google_apis::CancelCallback TrashResource( const std::string& resource_id, const google_apis::EntryActionCallback& callback) override; - google_apis::CancelCallback DownloadFile( + google_apis::CancelCallbackOnce DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const google_apis::DownloadActionCallback& download_action_callback,
diff --git a/components/drive/service/fake_drive_service.cc b/components/drive/service/fake_drive_service.cc index ba76777..6b3fa57 100644 --- a/components/drive/service/fake_drive_service.cc +++ b/components/drive/service/fake_drive_service.cc
@@ -30,6 +30,7 @@ #include "components/drive/drive_api_util.h" #include "components/drive/file_system_core_util.h" #include "google_apis/drive/drive_api_parser.h" +#include "google_apis/drive/drive_common_callbacks.h" #include "google_apis/drive/test_util.h" #include "net/base/escape.h" #include "net/base/url_util.h" @@ -38,14 +39,15 @@ using google_apis::AboutResourceCallback; using google_apis::AuthStatusCallback; using google_apis::CancelCallback; +using google_apis::CancelCallbackOnce; using google_apis::ChangeList; using google_apis::ChangeListCallback; using google_apis::ChangeListOnceCallback; using google_apis::ChangeResource; +using google_apis::DownloadActionCallback; using google_apis::DRIVE_FILE_ERROR; using google_apis::DRIVE_NO_CONNECTION; using google_apis::DRIVE_OTHER_ERROR; -using google_apis::DownloadActionCallback; using google_apis::DriveApiErrorCode; using google_apis::EntryActionCallback; using google_apis::FileList; @@ -56,8 +58,8 @@ using google_apis::HTTP_BAD_REQUEST; using google_apis::HTTP_CREATED; using google_apis::HTTP_FORBIDDEN; -using google_apis::HTTP_NOT_FOUND; using google_apis::HTTP_NO_CONTENT; +using google_apis::HTTP_NOT_FOUND; using google_apis::HTTP_PRECONDITION; using google_apis::HTTP_RESUME_INCOMPLETE; using google_apis::HTTP_SUCCESS; @@ -759,7 +761,7 @@ return CancelCallback(); } -CancelCallback FakeDriveService::DownloadFile( +CancelCallbackOnce FakeDriveService::DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const DownloadActionCallback& download_action_callback, @@ -773,7 +775,7 @@ base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(download_action_callback, DRIVE_NO_CONNECTION, base::FilePath())); - return CancelCallback(); + return CancelCallbackOnce(); } EntryInfo* entry = FindEntryByResourceId(resource_id); @@ -781,7 +783,7 @@ base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(download_action_callback, HTTP_NOT_FOUND, base::FilePath())); - return CancelCallback(); + return CancelCallbackOnce(); } const FileResource* file = entry->change_resource.file(); @@ -806,7 +808,7 @@ base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(download_action_callback, DRIVE_FILE_ERROR, base::FilePath())); - return CancelCallback(); + return CancelCallbackOnce(); } if (!progress_callback.is_null()) { @@ -821,7 +823,7 @@ base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(download_action_callback, HTTP_SUCCESS, local_cache_path)); - return CancelCallback(); + return google_apis::CancelCallbackOnce(); } CancelCallback FakeDriveService::CopyResource(
diff --git a/components/drive/service/fake_drive_service.h b/components/drive/service/fake_drive_service.h index dbe786db..229fcaf 100644 --- a/components/drive/service/fake_drive_service.h +++ b/components/drive/service/fake_drive_service.h
@@ -181,7 +181,7 @@ google_apis::CancelCallback TrashResource( const std::string& resource_id, const google_apis::EntryActionCallback& callback) override; - google_apis::CancelCallback DownloadFile( + google_apis::CancelCallbackOnce DownloadFile( const base::FilePath& local_cache_path, const std::string& resource_id, const google_apis::DownloadActionCallback& download_action_callback,
diff --git a/components/exo/wayland/server.cc b/components/exo/wayland/server.cc index 7aadc0b1..66838e56 100644 --- a/components/exo/wayland/server.cc +++ b/components/exo/wayland/server.cc
@@ -60,6 +60,7 @@ #include "ui/display/screen.h" #if defined(OS_CHROMEOS) +#include "base/system/sys_info.h" #include "components/exo/wayland/wl_shell.h" #include "components/exo/wayland/xdg_shell.h" #include "components/exo/wayland/zcr_color_space.h" @@ -237,12 +238,23 @@ std::unique_ptr<Server> Server::Create(Display* display) { std::unique_ptr<Server> server(new Server(display)); - char* runtime_dir = getenv("XDG_RUNTIME_DIR"); - if (!runtime_dir) { + char* runtime_dir_str = getenv("XDG_RUNTIME_DIR"); + if (!runtime_dir_str) { LOG(ERROR) << "XDG_RUNTIME_DIR not set in the environment"; return nullptr; } + const base::FilePath runtime_dir(runtime_dir_str); +#if defined(OS_CHROMEOS) + // On debugging chromeos-chrome on linux platform, + // try to ensure the directory if missing. + if (!base::SysInfo::IsRunningOnChromeOS()) { + CHECK(base::DirectoryExists(runtime_dir) || + base::CreateDirectory(runtime_dir)) + << "Failed to create XDG_RUNTIME_DIR"; + } +#endif // defined(OS_CHROMEOS) + std::string socket_name(kSocketName); base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kWaylandServerSocket)) {
diff --git a/components/feedback/feedback_uploader_dispatch_unittest.cc b/components/feedback/feedback_uploader_dispatch_unittest.cc index 8a3068a2..3c08846a 100644 --- a/components/feedback/feedback_uploader_dispatch_unittest.cc +++ b/components/feedback/feedback_uploader_dispatch_unittest.cc
@@ -15,7 +15,7 @@ #include "components/feedback/feedback_uploader_factory.h" #include "components/variations/net/variations_http_headers.h" #include "components/variations/variations_associated_data.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" #include "net/http/http_util.h" @@ -87,7 +87,7 @@ // Register a trial and variation id, so that there is data in variations // headers. Also, the variations header provider may have been registered to // observe some other field trial list, so reset it. - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); CreateFieldTrialWithId("Test", "Group1", 123); FeedbackUploader uploader( @@ -103,7 +103,7 @@ QueueReport(&uploader, "test"); base::RunLoop().RunUntilIdle(); - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); } TEST_F(FeedbackUploaderDispatchTest, 204Response) {
diff --git a/components/flags_ui/feature_entry.h b/components/flags_ui/feature_entry.h index 167618f..11165f4 100644 --- a/components/flags_ui/feature_entry.h +++ b/components/flags_ui/feature_entry.h
@@ -124,7 +124,7 @@ const FeatureParam* params; int num_params; // A variation id number in the format of - // VariationsHttpHeaderProvider::ForceVariationIds() or nullptr if you do + // VariationsIdsProvider::ForceVariationIds() or nullptr if you do // not need to set any variation_id for this feature variation. const char* variation_id; };
diff --git a/components/gwp_asan/OWNERS b/components/gwp_asan/OWNERS index 5f52e60..3a25f76 100644 --- a/components/gwp_asan/OWNERS +++ b/components/gwp_asan/OWNERS
@@ -1,2 +1,7 @@ +mpdenton@chromium.org + +# Secondary: +file://build/config/sanitizers/OWNERS vitalybuka@chromium.org + # COMPONENT: Internals>Instrumentation
diff --git a/components/omnibox/browser/document_suggestions_service_unittest.cc b/components/omnibox/browser/document_suggestions_service_unittest.cc index 3b90353..00bf1db 100644 --- a/components/omnibox/browser/document_suggestions_service_unittest.cc +++ b/components/omnibox/browser/document_suggestions_service_unittest.cc
@@ -17,7 +17,7 @@ #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/variations/net/variations_http_headers.h" #include "components/variations/variations_associated_data.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" @@ -51,7 +51,7 @@ identity_test_env_.SetAutomaticIssueOfAccessTokens(true); // Set up a variation. - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); variations::AssociateGoogleVariationID(variations::GOOGLE_WEB_PROPERTIES, "trial name", "group name", kVariationID); @@ -72,9 +72,8 @@ test_url_loader_factory_.SetInterceptor( base::BindLambdaForTesting([](const network::ResourceRequest& request) { EXPECT_TRUE(variations::HasVariationsHeader(request)); - std::string variation = - variations::VariationsHttpHeaderProvider::GetInstance() - ->GetVariationsString(); + std::string variation = variations::VariationsIdsProvider::GetInstance() + ->GetVariationsString(); EXPECT_EQ(variation, " " + base::NumberToString(kVariationID) + " "); }));
diff --git a/components/onc/docs/onc_spec.md b/components/onc/docs/onc_spec.md index 78d2fc1..8317abee 100644 --- a/components/onc/docs/onc_spec.md +++ b/components/onc/docs/onc_spec.md
@@ -480,11 +480,6 @@ *WEP-8021X* or *WPA-EAP*, otherwise ignored) - [EAP](#EAP-type) * EAP settings. -* **FTEnabled** - * (optional, defaults to *false*) - **boolean** - * Indicating if the client should attempt to use Fast Transition with the - * network. - * **HexSSID** * (optional if **SSID** is set, if so defaults to a hex representation of **SSID**) - **string**
diff --git a/components/onc/onc_constants.cc b/components/onc/onc_constants.cc index b9f7ac0..bc96ee9 100644 --- a/components/onc/onc_constants.cc +++ b/components/onc/onc_constants.cc
@@ -223,7 +223,6 @@ const char kEAP[] = "EAP"; const char kFrequency[] = "Frequency"; const char kFrequencyList[] = "FrequencyList"; -const char kFTEnabled[] = "FTEnabled"; const char kHexSSID[] = "HexSSID"; const char kHiddenSSID[] = "HiddenSSID"; const char kPassphrase[] = "Passphrase";
diff --git a/components/onc/onc_constants.h b/components/onc/onc_constants.h index 9d4d0b8..2ac1fd7e 100644 --- a/components/onc/onc_constants.h +++ b/components/onc/onc_constants.h
@@ -236,7 +236,6 @@ ONC_EXPORT extern const char kEAP[]; ONC_EXPORT extern const char kFrequency[]; ONC_EXPORT extern const char kFrequencyList[]; -ONC_EXPORT extern const char kFTEnabled[]; ONC_EXPORT extern const char kHexSSID[]; ONC_EXPORT extern const char kHiddenSSID[]; ONC_EXPORT extern const char kPassphrase[];
diff --git a/components/paint_preview/player/android/javatests/paint_preview_test_service.cc b/components/paint_preview/player/android/javatests/paint_preview_test_service.cc index 73a7db3..3886385b 100644 --- a/components/paint_preview/player/android/javatests/paint_preview_test_service.cc +++ b/components/paint_preview/player/android/javatests/paint_preview_test_service.cc
@@ -7,80 +7,136 @@ #include <memory> #include "base/android/jni_android.h" +#include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "components/paint_preview/browser/paint_preview_base_service.h" #include "components/paint_preview/browser/test_paint_preview_policy.h" +#include "components/paint_preview/common/file_stream.h" +#include "components/paint_preview/common/file_utils.h" #include "components/paint_preview/common/proto/paint_preview.pb.h" #include "components/paint_preview/player/android/javatests_jni_headers/PaintPreviewTestService_jni.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkColor.h" +#include "third_party/skia/include/core/SkPicture.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" +#include "third_party/skia/include/core/SkRect.h" +#include "third_party/skia/include/core/SkRefCnt.h" using base::android::JavaParamRef; namespace paint_preview { -namespace { const char kPaintPreviewDir[] = "paint_preview"; const char kTestDirName[] = "PaintPreviewTestService"; -void UpdateSkpPaths(const base::FilePath& test_data_dir, - const DirectoryKey& key, - PaintPreviewBaseService::OnReadProtoCallback callback, - std::unique_ptr<PaintPreviewProto> proto) { - if (proto == nullptr) { - std::move(callback).Run(std::move(proto)); - return; - } - - // Update the file path for the root SKP to match the isolated test - // environment. - std::string root_skp_file_name = - base::FilePath(proto->root_frame().file_path()).BaseName().AsUTF8Unsafe(); - base::FilePath root_skp_file_path = - test_data_dir.AppendASCII(key.AsciiDirname()) - .AppendASCII(root_skp_file_name); - proto->mutable_root_frame()->set_file_path(root_skp_file_path.AsUTF8Unsafe()); - - // Update the file path for the subframe SKPs to match the isolated test - // environment. - for (auto& subframe : *(proto->mutable_subframes())) { - std::string subframe_skp_file_name = - base::FilePath(subframe.file_path()).BaseName().AsUTF8Unsafe(); - base::FilePath subframe_skp_file_path = - test_data_dir.AppendASCII(key.AsciiDirname()) - .AppendASCII(subframe_skp_file_name); - subframe.set_file_path(subframe_skp_file_path.AsUTF8Unsafe()); - } - std::move(callback).Run(std::move(proto)); -} -} // namespace - jlong JNI_PaintPreviewTestService_GetInstance( JNIEnv* env, - const JavaParamRef<jstring>& j_test_data_dir) { - base::FilePath file_path( - base::android::ConvertJavaStringToUTF8(env, j_test_data_dir)); + const JavaParamRef<jstring>& j_path) { + base::FilePath file_path(base::android::ConvertJavaStringToUTF8(env, j_path)); PaintPreviewTestService* service = new PaintPreviewTestService(file_path); return reinterpret_cast<intptr_t>(service); } -PaintPreviewTestService::PaintPreviewTestService( - const base::FilePath& test_data_dir) - : PaintPreviewBaseService(test_data_dir, +PaintPreviewTestService::PaintPreviewTestService(const base::FilePath& path) + : PaintPreviewBaseService(path, kTestDirName, std::make_unique<TestPaintPreviewPolicy>(), false), - test_data_dir_(test_data_dir.AppendASCII(kPaintPreviewDir) - .AppendASCII(kTestDirName)) {} + test_data_dir_( + path.AppendASCII(kPaintPreviewDir).AppendASCII(kTestDirName)) {} PaintPreviewTestService::~PaintPreviewTestService() = default; -void PaintPreviewTestService::GetCapturedPaintPreviewProto( - const DirectoryKey& key, - OnReadProtoCallback on_read_proto_callback) { - PaintPreviewBaseService::GetCapturedPaintPreviewProto( - key, base::BindOnce(&UpdateSkpPaths, test_data_dir_, key, - std::move(on_read_proto_callback))); +jboolean PaintPreviewTestService::CreateSingleSkpForKey( + JNIEnv* env, + const JavaParamRef<jstring>& j_key, + const JavaParamRef<jstring>& j_url, + jint j_width, + jint j_height, + const JavaParamRef<jintArray>& j_link_rects, + const JavaParamRef<jobjectArray>& j_link_urls) { + base::ScopedAllowBlockingForTesting allow_blocking; + if (!base::PathExists(test_data_dir_)) { + base::File::Error error; + if (!base::CreateDirectoryAndGetError(test_data_dir_, &error)) { + LOG(ERROR) << "Failed to create dir: " + << base::File::ErrorToString(error); + return false; + } + } + + base::FilePath path = test_data_dir_.AppendASCII( + base::android::ConvertJavaStringToUTF8(env, j_key)); + if (!base::CreateDirectory(path)) { + LOG(ERROR) << "Failed to create directory."; + return false; + } + + uint32_t width = static_cast<uint32_t>(j_width); + uint32_t height = static_cast<uint32_t>(j_height); + + SkPictureRecorder recorder; + auto* canvas = recorder.beginRecording(SkRect::MakeWH(width, height)); + SkPaint paint; + paint.setColor(SK_ColorWHITE); + canvas->drawRect(SkRect::MakeWH(width, height), paint); + paint.setColor(SK_ColorGRAY); + const int kSquareSideLen = 50; + for (uint32_t j = 0; j * kSquareSideLen < height; ++j) { + for (uint32_t i = (j % 2); i * kSquareSideLen < width; i += 2) { + canvas->drawRect(SkRect::MakeXYWH(i * kSquareSideLen, j * kSquareSideLen, + kSquareSideLen, kSquareSideLen), + paint); + } + } + auto skp = recorder.finishRecordingAsPicture(); + auto skp_path = path.AppendASCII("test_file.skp"); + FileWStream wstream(base::File( + skp_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE)); + skp->serialize(&wstream); + wstream.Close(); + if (wstream.DidWriteFail()) { + LOG(ERROR) << "SKP Write failed"; + return false; + } + LOG(INFO) << "Wrote SKP " << wstream.ActualBytesWritten() << " bytes"; + + PaintPreviewProto paint_preview; + auto* metadata = paint_preview.mutable_metadata(); + metadata->set_url(base::android::ConvertJavaStringToUTF8(env, j_url)); + + auto* root_frame = paint_preview.mutable_root_frame(); + auto token = base::UnguessableToken::Create(); + root_frame->set_file_path(skp_path.AsUTF8Unsafe()); + root_frame->set_embedding_token_low(token.GetLowForSerialization()); + root_frame->set_embedding_token_high(token.GetHighForSerialization()); + root_frame->set_is_main_frame(true); + // No initial offset. + root_frame->set_scroll_offset_x(0); + root_frame->set_scroll_offset_y(0); + + std::vector<std::string> link_urls; + base::android::AppendJavaStringArrayToStringVector(env, j_link_urls, + &link_urls); + std::vector<int> link_rects; + base::android::JavaIntArrayToIntVector(env, j_link_rects, &link_rects); + for (size_t i = 0; i < link_urls.size(); ++i) { + auto* link_proto = root_frame->add_links(); + link_proto->set_url(link_urls[i]); + auto* rect = link_proto->mutable_rect(); + rect->set_x(link_rects[i * 4]); + rect->set_y(link_rects[i * 4 + 1]); + rect->set_width(link_rects[i * 4 + 2]); + rect->set_height(link_rects[i * 4 + 3]); + } + if (!WriteProtoToFile(path.AppendASCII("proto.pb"), paint_preview)) { + LOG(ERROR) << "Failed to write proto to file."; + return false; + } + return true; } } // namespace paint_preview
diff --git a/components/paint_preview/player/android/javatests/paint_preview_test_service.h b/components/paint_preview/player/android/javatests/paint_preview_test_service.h index c16d30a..0966c45 100644 --- a/components/paint_preview/player/android/javatests/paint_preview_test_service.h +++ b/components/paint_preview/player/android/javatests/paint_preview_test_service.h
@@ -14,15 +14,20 @@ // A simple implementation of PaintPreviewBaseService used in tests. class PaintPreviewTestService : public PaintPreviewBaseService { public: - PaintPreviewTestService(const base::FilePath& test_data_dir); + PaintPreviewTestService(const base::FilePath& path); ~PaintPreviewTestService() override; PaintPreviewTestService(const PaintPreviewTestService&) = delete; PaintPreviewTestService& operator=(const PaintPreviewTestService&) = delete; - void GetCapturedPaintPreviewProto( - const DirectoryKey& key, - OnReadProtoCallback on_read_proto_callback) override; + jboolean CreateSingleSkpForKey( + JNIEnv* env, + const base::android::JavaParamRef<jstring>& j_key, + const base::android::JavaParamRef<jstring>& j_url, + jint j_width, + jint j_height, + const base::android::JavaParamRef<jintArray>& j_link_rects, + const base::android::JavaParamRef<jobjectArray>& j_link_urls); private: base::FilePath test_data_dir_;
diff --git a/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewPlayerTest.java b/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewPlayerTest.java index 69a7554a..6fc2a7f9 100644 --- a/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewPlayerTest.java +++ b/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewPlayerTest.java
@@ -16,14 +16,13 @@ import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.chromium.base.task.PostTask; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.CallbackHelper; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.ScalableTimeout; -import org.chromium.base.test.util.UrlUtils; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.browser.test.util.Criteria; import org.chromium.content_public.browser.test.util.CriteriaHelper; @@ -37,15 +36,12 @@ public class PaintPreviewPlayerTest extends DummyUiActivityTestCase { private static final long TIMEOUT_MS = ScalableTimeout.scaleTimeout(5000); - private static final String TEST_DATA_DIR = "components/test/data/"; - private static final String TEST_DIRECTORY_KEY = "wikipedia"; - private static final String TEST_URL = "https://en.m.wikipedia.org/wiki/Main_Page"; - private static final String TEST_MAIN_PICTURE_LINK_URL = - "https://en.m.wikipedia.org/wiki/File:Volc%C3%A1n_Ubinas,_Arequipa,_Per%C3%BA,_2015-08-02,_DD_50.JPG"; - private static final String TEST_IN_VIEWPORT_LINK_URL = - "https://en.m.wikipedia.org/wiki/Arequipa"; - private static final String TEST_OUT_OF_VIEWPORT_LINK_URL = - "https://foundation.wikimedia.org/wiki/Privacy_policy"; + private static final String TEST_DIRECTORY_KEY = "test_dir"; + private static final String TEST_URL = "https://www.chromium.org"; + private static final String TEST_IN_VIEWPORT_LINK_URL = "http://www.google.com/"; + private static final String TEST_OUT_OF_VIEWPORT_LINK_URL = "http://example.com/"; + private final Rect mInViewportLinkRect = new Rect(700, 650, 900, 700); + private final Rect mOutOfViewportLinkRect = new Rect(300, 4900, 450, 5000); private static final int TEST_PAGE_WIDTH = 1082; private static final int TEST_PAGE_HEIGHT = 5019; @@ -53,6 +49,9 @@ @Rule public PaintPreviewTestRule mPaintPreviewTestRule = new PaintPreviewTestRule(); + @Rule + public TemporaryFolder mTempFolder = new TemporaryFolder(); + private PlayerManager mPlayerManager; private TestLinkClickHandler mLinkClickHandler; private CallbackHelper mRefreshedCallback; @@ -85,7 +84,6 @@ */ @Test @MediumTest - @DisabledTest(message = "crbug.com/1106035") public void singleFrameDisplayTest() { initPlayerManager(); final View playerHostView = mPlayerManager.getView(); @@ -107,32 +105,24 @@ */ @Test @MediumTest - @DisabledTest(message = "crbug.com/1106035") public void linkClickTest() { initPlayerManager(); final View playerHostView = mPlayerManager.getView(); - // Click on the top left picture and assert it directs to the correct link. - assertLinkUrl(playerHostView, 92, 424, TEST_MAIN_PICTURE_LINK_URL); - assertLinkUrl(playerHostView, 67, 527, TEST_MAIN_PICTURE_LINK_URL); - assertLinkUrl(playerHostView, 466, 668, TEST_MAIN_PICTURE_LINK_URL); - assertLinkUrl(playerHostView, 412, 432, TEST_MAIN_PICTURE_LINK_URL); - // Click on a link that is visible in the default viewport. - assertLinkUrl(playerHostView, 732, 698, TEST_IN_VIEWPORT_LINK_URL); - assertLinkUrl(playerHostView, 876, 716, TEST_IN_VIEWPORT_LINK_URL); - assertLinkUrl(playerHostView, 798, 711, TEST_IN_VIEWPORT_LINK_URL); + assertLinkUrl(playerHostView, 720, 670, TEST_IN_VIEWPORT_LINK_URL); + assertLinkUrl(playerHostView, 880, 675, TEST_IN_VIEWPORT_LINK_URL); + assertLinkUrl(playerHostView, 800, 680, TEST_IN_VIEWPORT_LINK_URL); // Scroll to the bottom, and click on a link. scrollToBottom(); - assertLinkUrl(playerHostView, 322, 4946, TEST_OUT_OF_VIEWPORT_LINK_URL); - assertLinkUrl(playerHostView, 376, 4954, TEST_OUT_OF_VIEWPORT_LINK_URL); - assertLinkUrl(playerHostView, 422, 4965, TEST_OUT_OF_VIEWPORT_LINK_URL); + assertLinkUrl(playerHostView, 320, 4920, TEST_OUT_OF_VIEWPORT_LINK_URL); + assertLinkUrl(playerHostView, 375, 4950, TEST_OUT_OF_VIEWPORT_LINK_URL); + assertLinkUrl(playerHostView, 430, 4980, TEST_OUT_OF_VIEWPORT_LINK_URL); } @Test @MediumTest - @DisabledTest(message = "crbug.com/1106035") public void overscrollRefreshTest() throws Exception { initPlayerManager(); UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); @@ -157,7 +147,7 @@ mLinkClickHandler = new TestLinkClickHandler(); PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> { PaintPreviewTestService service = - new PaintPreviewTestService(UrlUtils.getIsolatedTestFilePath(TEST_DATA_DIR)); + new PaintPreviewTestService(mTempFolder.getRoot().getPath()); // Use the wrong URL to simulate a failure. mPlayerManager = new PlayerManager(new GURL("about:blank"), getActivity(), service, TEST_DIRECTORY_KEY, mLinkClickHandler, @@ -217,7 +207,11 @@ CallbackHelper viewReady = new CallbackHelper(); PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> { PaintPreviewTestService service = - new PaintPreviewTestService(UrlUtils.getIsolatedTestFilePath(TEST_DATA_DIR)); + new PaintPreviewTestService(mTempFolder.getRoot().getPath()); + Assert.assertTrue(service.createSingleSkpForKey(TEST_DIRECTORY_KEY, TEST_URL, + TEST_PAGE_WIDTH, TEST_PAGE_HEIGHT, + new Rect[] {mInViewportLinkRect, mOutOfViewportLinkRect}, + new String[] {TEST_IN_VIEWPORT_LINK_URL, TEST_OUT_OF_VIEWPORT_LINK_URL})); mPlayerManager = new PlayerManager(new GURL(TEST_URL), getActivity(), service, TEST_DIRECTORY_KEY, mLinkClickHandler, () -> { mRefreshedCallback.notifyCalled(); },
diff --git a/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewTestService.java b/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewTestService.java index ce6ac7fa..88a865b7 100644 --- a/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewTestService.java +++ b/components/paint_preview/player/android/javatests/src/org/chromium/components/paintpreview/player/PaintPreviewTestService.java
@@ -4,6 +4,9 @@ package org.chromium.components.paintpreview.player; +import android.graphics.Rect; + +import org.chromium.base.Log; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.components.paintpreview.browser.NativePaintPreviewServiceProvider; @@ -13,10 +16,11 @@ */ @JNINamespace("paint_preview") public class PaintPreviewTestService implements NativePaintPreviewServiceProvider { + private static final String TAG = "PPTestService"; private long mNativePaintPreviewTestService; - public PaintPreviewTestService(String testDataDir) { - mNativePaintPreviewTestService = PaintPreviewTestServiceJni.get().getInstance(testDataDir); + public PaintPreviewTestService(String path) { + mNativePaintPreviewTestService = PaintPreviewTestServiceJni.get().getInstance(path); } @Override @@ -24,8 +28,35 @@ return mNativePaintPreviewTestService; } + public boolean createSingleSkpForKey( + String key, String url, int width, int height, Rect[] linkRects, String[] links) { + if (mNativePaintPreviewTestService == 0) { + Log.e(TAG, "No native service."); + return false; + } + + assert linkRects.length == links.length; + + int flattenedRects[] = new int[linkRects.length * 4]; + for (int i = 0; i < linkRects.length; i++) { + flattenedRects[i * 4] = linkRects[i].left; + flattenedRects[i * 4 + 1] = linkRects[i].top; + flattenedRects[i * 4 + 2] = linkRects[i].width(); + flattenedRects[i * 4 + 3] = linkRects[i].height(); + } + + boolean ret = PaintPreviewTestServiceJni.get().createSingleSkpForKey( + mNativePaintPreviewTestService, key, url, width, height, flattenedRects, links); + if (!ret) { + Log.e(TAG, "Native failed to setup files for testing."); + } + return ret; + } + @NativeMethods interface Natives { - long getInstance(String testDataDir); + long getInstance(String path); + boolean createSingleSkpForKey(long nativePaintPreviewTestService, String key, String url, + int width, int height, int[] flattenedRects, String[] links); } }
diff --git a/components/payments/content/android/BUILD.gn b/components/payments/content/android/BUILD.gn index 2e44dea1..5a09b32f 100644 --- a/components/payments/content/android/BUILD.gn +++ b/components/payments/content/android/BUILD.gn
@@ -90,6 +90,8 @@ "java/src/org/chromium/components/payments/PaymentManifestDownloader.java", "java/src/org/chromium/components/payments/PaymentManifestParser.java", "java/src/org/chromium/components/payments/PaymentManifestWebDataService.java", + "java/src/org/chromium/components/payments/PaymentRequestLifecycleObserver.java", + "java/src/org/chromium/components/payments/PaymentRequestParams.java", "java/src/org/chromium/components/payments/PaymentRequestSpec.java", "java/src/org/chromium/components/payments/PaymentRequestUpdateEventListener.java", "java/src/org/chromium/components/payments/PaymentValidator.java",
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/ComponentPaymentRequestImpl.java b/components/payments/content/android/java/src/org/chromium/components/payments/ComponentPaymentRequestImpl.java index e7b9549..a3d1c96 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/ComponentPaymentRequestImpl.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/ComponentPaymentRequestImpl.java
@@ -23,6 +23,7 @@ public class ComponentPaymentRequestImpl implements PaymentRequest { private final ComponentPaymentRequestDelegate mDelegate; private PaymentRequestClient mClient; + private PaymentRequestLifecycleObserver mPaymentRequestLifecycleObserver; /** * The delegate of {@link ComponentPaymentRequestImpl}. @@ -160,4 +161,18 @@ if (mClient != null) mClient.close(); mClient = null; } + + /** + * Register an observer for the PaymentRequest lifecycle. + * @param paymentRequestLifecycleObserver The observer. + */ + public void registerPaymentRequestLifecycleObserver( + PaymentRequestLifecycleObserver paymentRequestLifecycleObserver) { + mPaymentRequestLifecycleObserver = paymentRequestLifecycleObserver; + } + + /** @return The observer for the PaymentRequest lifecycle. */ + public PaymentRequestLifecycleObserver getPaymentRequestLifecycleObserver() { + return mPaymentRequestLifecycleObserver; + } }
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestLifecycleObserver.java b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestLifecycleObserver.java new file mode 100644 index 0000000..00065bb --- /dev/null +++ b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestLifecycleObserver.java
@@ -0,0 +1,14 @@ +// Copyright 2020 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.payments; + +/** Observe the lifecycle of the PaymentRequest. */ +public interface PaymentRequestLifecycleObserver { + /** + * Called when all of the PaymentRequest parameters have been initiated and validated. + * @param params The parameters. + */ + void onPaymentRequestParamsInitiated(PaymentRequestParams params); +}
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestParams.java b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestParams.java new file mode 100644 index 0000000..1443293c --- /dev/null +++ b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestParams.java
@@ -0,0 +1,32 @@ +// Copyright 2020 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.payments; + +import org.chromium.payments.mojom.PaymentMethodData; + +import java.util.Map; + +/** + * The parameters of PaymentRequest specified by the merchant. + */ +public interface PaymentRequestParams { + /** @return The requestShipping set by the merchant. */ + boolean requestShipping(); + + /** @return The requestPayerName set by the merchant. */ + boolean requestPayerName(); + + /** @return The requestPayerEmail set by the merchant. */ + boolean requestPayerEmail(); + + /** @return The requestPayerPhone set by the merchant. */ + boolean requestPayerPhone(); + + /** + * @return The unmodifiable mapping of payment method identifier to the method-specific data in + * the payment request. + */ + Map<String, PaymentMethodData> getMethodDataMap(); +}
diff --git a/components/policy/content/policy_blacklist_navigation_throttle.cc b/components/policy/content/policy_blacklist_navigation_throttle.cc index 9a7b34b..66ca261 100644 --- a/components/policy/content/policy_blacklist_navigation_throttle.cc +++ b/components/policy/content/policy_blacklist_navigation_throttle.cc
@@ -17,22 +17,23 @@ #include "content/public/browser/navigation_handle.h" #include "url/gurl.h" -using URLBlacklistState = policy::URLBlacklist::URLBlacklistState; +using URLBlocklistState = policy::URLBlocklist::URLBlocklistState; using SafeSitesFilterBehavior = policy::SafeSitesFilterBehavior; -PolicyBlacklistNavigationThrottle::PolicyBlacklistNavigationThrottle( +PolicyBlocklistNavigationThrottle::PolicyBlocklistNavigationThrottle( content::NavigationHandle* navigation_handle, content::BrowserContext* context) : NavigationThrottle(navigation_handle) { - blacklist_service_ = PolicyBlacklistFactory::GetForBrowserContext(context); + blocklist_service_ = PolicyBlocklistFactory::GetForBrowserContext(context); prefs_ = user_prefs::UserPrefs::Get(context); DCHECK(prefs_); } -PolicyBlacklistNavigationThrottle::~PolicyBlacklistNavigationThrottle() {} +PolicyBlocklistNavigationThrottle::~PolicyBlocklistNavigationThrottle() = + default; content::NavigationThrottle::ThrottleCheckResult -PolicyBlacklistNavigationThrottle::WillStartRequest() { +PolicyBlocklistNavigationThrottle::WillStartRequest() { GURL url = navigation_handle()->GetURL(); // Ignore blob scheme because we may use it to deliver navigation responses @@ -40,14 +41,14 @@ if (url.SchemeIs(url::kBlobScheme)) return PROCEED; - URLBlacklistState blacklist_state = - blacklist_service_->GetURLBlacklistState(url); - if (blacklist_state == URLBlacklistState::URL_IN_BLACKLIST) { + URLBlocklistState blocklist_state = + blocklist_service_->GetURLBlocklistState(url); + if (blocklist_state == URLBlocklistState::URL_IN_BLOCKLIST) { return ThrottleCheckResult(BLOCK_REQUEST, net::ERR_BLOCKED_BY_ADMINISTRATOR); } - if (blacklist_state == URLBlacklistState::URL_IN_WHITELIST) + if (blocklist_state == URLBlocklistState::URL_IN_ALLOWLIST) return PROCEED; // Safe Sites filter applies to top-level HTTP[S] requests. @@ -66,10 +67,10 @@ if (!effective_url.is_valid()) effective_url = url; - bool synchronous = blacklist_service_->CheckSafeSearchURL( + bool synchronous = blocklist_service_->CheckSafeSearchURL( effective_url, base::BindOnce( - &PolicyBlacklistNavigationThrottle::CheckSafeSearchCallback, + &PolicyBlocklistNavigationThrottle::CheckSafeSearchCallback, weak_ptr_factory_.GetWeakPtr())); if (!synchronous) { deferred_ = true; @@ -82,15 +83,15 @@ } content::NavigationThrottle::ThrottleCheckResult -PolicyBlacklistNavigationThrottle::WillRedirectRequest() { +PolicyBlocklistNavigationThrottle::WillRedirectRequest() { return WillStartRequest(); } -const char* PolicyBlacklistNavigationThrottle::GetNameForLogging() { - return "PolicyBlacklistNavigationThrottle"; +const char* PolicyBlocklistNavigationThrottle::GetNameForLogging() { + return "PolicyBlocklistNavigationThrottle"; } -void PolicyBlacklistNavigationThrottle::CheckSafeSearchCallback(bool is_safe) { +void PolicyBlocklistNavigationThrottle::CheckSafeSearchCallback(bool is_safe) { if (!deferred_) { should_cancel_ = !is_safe; return;
diff --git a/components/policy/content/policy_blacklist_navigation_throttle.h b/components/policy/content/policy_blacklist_navigation_throttle.h index 8e35a46b..0a53fee 100644 --- a/components/policy/content/policy_blacklist_navigation_throttle.h +++ b/components/policy/content/policy_blacklist_navigation_throttle.h
@@ -9,7 +9,7 @@ #include "base/memory/weak_ptr.h" #include "content/public/browser/navigation_throttle.h" -class PolicyBlacklistService; +class PolicyBlocklistService; class PrefService; namespace content { @@ -17,18 +17,18 @@ class NavigationHandle; } // namespace content -// PolicyBlacklistNavigationThrottle provides a simple way to block a navigation -// based on the URLBlacklistManager and Safe Search API. If the URL is -// blacklisted or whitelisted, the throttle will immediately block or allow the +// PolicyBlocklistNavigationThrottle provides a simple way to block a navigation +// based on the URLBlocklistManager and Safe Search API. If the URL is on the +// blocklist or allowlist, the throttle will immediately block or allow the // navigation. Otherwise, the URL will be checked against the Safe Search API if // the SafeSitesFilterBehavior policy is enabled. This final check may be // asynchronous if the result hasn't been cached yet. -class PolicyBlacklistNavigationThrottle : public content::NavigationThrottle { +class PolicyBlocklistNavigationThrottle : public content::NavigationThrottle { public: - PolicyBlacklistNavigationThrottle( + PolicyBlocklistNavigationThrottle( content::NavigationHandle* navigation_handle, content::BrowserContext* context); - ~PolicyBlacklistNavigationThrottle() override; + ~PolicyBlocklistNavigationThrottle() override; // NavigationThrottle overrides. ThrottleCheckResult WillStartRequest() override; @@ -37,10 +37,10 @@ const char* GetNameForLogging() override; private: - // Callback from PolicyBlacklistService. + // Callback from PolicyBlocklistService. void CheckSafeSearchCallback(bool is_safe); - PolicyBlacklistService* blacklist_service_; + PolicyBlocklistService* blocklist_service_; PrefService* prefs_; @@ -51,10 +51,10 @@ // should be canceled. bool should_cancel_ = false; - base::WeakPtrFactory<PolicyBlacklistNavigationThrottle> weak_ptr_factory_{ + base::WeakPtrFactory<PolicyBlocklistNavigationThrottle> weak_ptr_factory_{ this}; - DISALLOW_COPY_AND_ASSIGN(PolicyBlacklistNavigationThrottle); + DISALLOW_COPY_AND_ASSIGN(PolicyBlocklistNavigationThrottle); }; #endif // COMPONENTS_POLICY_CONTENT_POLICY_BLACKLIST_NAVIGATION_THROTTLE_H_
diff --git a/components/policy/content/policy_blacklist_navigation_throttle_unittest.cc b/components/policy/content/policy_blacklist_navigation_throttle_unittest.cc index ed7de57d..b6afebb9 100644 --- a/components/policy/content/policy_blacklist_navigation_throttle_unittest.cc +++ b/components/policy/content/policy_blacklist_navigation_throttle_unittest.cc
@@ -36,19 +36,19 @@ } // namespace -class PolicyBlacklistNavigationThrottleTest +class PolicyBlocklistNavigationThrottleTest : public content::RenderViewHostTestHarness, public content::WebContentsObserver { public: - PolicyBlacklistNavigationThrottleTest() = default; - ~PolicyBlacklistNavigationThrottleTest() override = default; + PolicyBlocklistNavigationThrottleTest() = default; + ~PolicyBlocklistNavigationThrottleTest() override = default; // content::RenderViewHostTestHarness: void SetUp() override { content::RenderViewHostTestHarness::SetUp(); user_prefs::UserPrefs::Set(browser_context(), &pref_service_); - policy::URLBlacklistManager::RegisterProfilePrefs(pref_service_.registry()); + policy::URLBlocklistManager::RegisterProfilePrefs(pref_service_.registry()); // Prevent crashes in BrowserContextDependencyManager caused when tests // that run in serial happen to reuse a memory address for a BrowserContext @@ -58,7 +58,7 @@ BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive( browser_context()); - PolicyBlacklistFactory::GetInstance() + PolicyBlocklistFactory::GetInstance() ->GetForBrowserContext(browser_context()) ->SetSafeSearchURLCheckerForTest( stub_url_checker_.BuildURLChecker(kCacheSize)); @@ -76,7 +76,7 @@ // content::WebContentsObserver: void DidStartNavigation( content::NavigationHandle* navigation_handle) override { - auto throttle = std::make_unique<PolicyBlacklistNavigationThrottle>( + auto throttle = std::make_unique<PolicyBlocklistNavigationThrottle>( navigation_handle, browser_context()); navigation_handle->RegisterThrottleForTesting(std::move(throttle)); @@ -93,7 +93,7 @@ return navigation_simulator; } - void SetBlacklistUrlPattern(const std::string& pattern) { + void SetBlocklistUrlPattern(const std::string& pattern) { auto value = std::make_unique<base::Value>(base::Value::Type::LIST); value->Append(base::Value(pattern)); pref_service_.SetManagedPref(policy::policy_prefs::kUrlBlacklist, @@ -101,7 +101,7 @@ task_environment()->RunUntilIdle(); } - void SetWhitelistUrlPattern(const std::string& pattern) { + void SetAllowlistUrlPattern(const std::string& pattern) { auto value = std::make_unique<base::Value>(base::Value::Type::LIST); value->Append(base::Value(pattern)); pref_service_.SetManagedPref(policy::policy_prefs::kUrlWhitelist, @@ -120,31 +120,31 @@ safe_search_api::StubURLChecker stub_url_checker_; private: - DISALLOW_COPY_AND_ASSIGN(PolicyBlacklistNavigationThrottleTest); + DISALLOW_COPY_AND_ASSIGN(PolicyBlocklistNavigationThrottleTest); }; -TEST_F(PolicyBlacklistNavigationThrottleTest, Blacklist) { - SetBlacklistUrlPattern("example.com"); +TEST_F(PolicyBlocklistNavigationThrottleTest, Blocklist) { + SetBlocklistUrlPattern("example.com"); - // Block a blacklisted site. + // Block a blocklisted site. auto navigation_simulator = StartNavigation(GURL("http://www.example.com/")); ASSERT_FALSE(navigation_simulator->IsDeferred()); EXPECT_EQ(content::NavigationThrottle::BLOCK_REQUEST, navigation_simulator->GetLastThrottleCheckResult()); } -TEST_F(PolicyBlacklistNavigationThrottleTest, Whitelist) { - SetWhitelistUrlPattern("www.example.com"); - SetBlacklistUrlPattern("example.com"); +TEST_F(PolicyBlocklistNavigationThrottleTest, Whitelist) { + SetAllowlistUrlPattern("www.example.com"); + SetBlocklistUrlPattern("example.com"); - // Allow a whitelisted exception to a blacklisted domain. + // Allow a allowlisted exception to a blocklisted domain. auto navigation_simulator = StartNavigation(GURL("http://www.example.com/")); ASSERT_FALSE(navigation_simulator->IsDeferred()); EXPECT_EQ(content::NavigationThrottle::PROCEED, navigation_simulator->GetLastThrottleCheckResult()); } -TEST_F(PolicyBlacklistNavigationThrottleTest, Safe) { +TEST_F(PolicyBlocklistNavigationThrottleTest, Safe) { SetSafeSitesFilterBehavior(SafeSitesFilterBehavior::kSafeSitesFilterEnabled); stub_url_checker_.SetUpValidResponse(false /* is_porn */); @@ -156,7 +156,7 @@ navigation_simulator->GetLastThrottleCheckResult()); } -TEST_F(PolicyBlacklistNavigationThrottleTest, Porn) { +TEST_F(PolicyBlocklistNavigationThrottleTest, Porn) { SetSafeSitesFilterBehavior(SafeSitesFilterBehavior::kSafeSitesFilterEnabled); stub_url_checker_.SetUpValidResponse(true /* is_porn */); @@ -168,19 +168,19 @@ navigation_simulator->GetLastThrottleCheckResult()); } -TEST_F(PolicyBlacklistNavigationThrottleTest, Whitelisted) { - SetWhitelistUrlPattern("example.com"); +TEST_F(PolicyBlocklistNavigationThrottleTest, Allowlisted) { + SetAllowlistUrlPattern("example.com"); SetSafeSitesFilterBehavior(SafeSitesFilterBehavior::kSafeSitesFilterEnabled); stub_url_checker_.SetUpValidResponse(true /* is_porn */); - // Even with SafeSites enabled, a whitelisted site is immediately allowed. + // Even with SafeSites enabled, a allowlisted site is immediately allowed. auto navigation_simulator = StartNavigation(GURL("http://example.com/")); ASSERT_FALSE(navigation_simulator->IsDeferred()); EXPECT_EQ(content::NavigationThrottle::PROCEED, navigation_simulator->GetLastThrottleCheckResult()); } -TEST_F(PolicyBlacklistNavigationThrottleTest, Schemes) { +TEST_F(PolicyBlocklistNavigationThrottleTest, Schemes) { SetSafeSitesFilterBehavior(SafeSitesFilterBehavior::kSafeSitesFilterEnabled); stub_url_checker_.SetUpValidResponse(true /* is_porn */); @@ -197,7 +197,7 @@ navigation_simulator->GetLastThrottleCheckResult()); } -TEST_F(PolicyBlacklistNavigationThrottleTest, PolicyChange) { +TEST_F(PolicyBlocklistNavigationThrottleTest, PolicyChange) { stub_url_checker_.SetUpValidResponse(true /* is_porn */); // The safe sites filter is initially disabled. @@ -228,7 +228,7 @@ } } -TEST_F(PolicyBlacklistNavigationThrottleTest, DISABLED_Failure) { +TEST_F(PolicyBlocklistNavigationThrottleTest, DISABLED_Failure) { SetSafeSitesFilterBehavior(SafeSitesFilterBehavior::kSafeSitesFilterEnabled); stub_url_checker_.SetUpFailedResponse(); @@ -240,7 +240,7 @@ navigation_simulator->GetLastThrottleCheckResult()); } -TEST_F(PolicyBlacklistNavigationThrottleTest, CachedSites) { +TEST_F(PolicyBlocklistNavigationThrottleTest, CachedSites) { SetSafeSitesFilterBehavior(SafeSitesFilterBehavior::kSafeSitesFilterEnabled); // Check a couple of sites.
diff --git a/components/policy/content/policy_blacklist_service.cc b/components/policy/content/policy_blacklist_service.cc index 2d80667..bc435de 100644 --- a/components/policy/content/policy_blacklist_service.cc +++ b/components/policy/content/policy_blacklist_service.cc
@@ -19,9 +19,9 @@ namespace { -// Calls the PolicyBlacklistService callback with the result of the Safe Search +// Calls the PolicyBlocklistService callback with the result of the Safe Search // API check. -void OnCheckURLDone(PolicyBlacklistService::CheckSafeSearchCallback callback, +void OnCheckURLDone(PolicyBlocklistService::CheckSafeSearchCallback callback, const GURL& /* url */, safe_search_api::Classification classification, bool /* uncertain */) { @@ -31,20 +31,20 @@ } // namespace -PolicyBlacklistService::PolicyBlacklistService( +PolicyBlocklistService::PolicyBlocklistService( content::BrowserContext* browser_context, - std::unique_ptr<policy::URLBlacklistManager> url_blacklist_manager) + std::unique_ptr<policy::URLBlocklistManager> url_blocklist_manager) : browser_context_(browser_context), - url_blacklist_manager_(std::move(url_blacklist_manager)) {} + url_blocklist_manager_(std::move(url_blocklist_manager)) {} -PolicyBlacklistService::~PolicyBlacklistService() = default; +PolicyBlocklistService::~PolicyBlocklistService() = default; -policy::URLBlacklist::URLBlacklistState -PolicyBlacklistService::GetURLBlacklistState(const GURL& url) const { - return url_blacklist_manager_->GetURLBlacklistState(url); +policy::URLBlocklist::URLBlocklistState +PolicyBlocklistService::GetURLBlocklistState(const GURL& url) const { + return url_blocklist_manager_->GetURLBlocklistState(url); } -bool PolicyBlacklistService::CheckSafeSearchURL( +bool PolicyBlocklistService::CheckSafeSearchURL( const GURL& url, CheckSafeSearchCallback callback) { if (!safe_search_url_checker_) { @@ -86,39 +86,39 @@ base::BindOnce(&OnCheckURLDone, std::move(callback))); } -void PolicyBlacklistService::SetSafeSearchURLCheckerForTest( +void PolicyBlocklistService::SetSafeSearchURLCheckerForTest( std::unique_ptr<safe_search_api::URLChecker> safe_search_url_checker) { safe_search_url_checker_ = std::move(safe_search_url_checker); } // static -PolicyBlacklistFactory* PolicyBlacklistFactory::GetInstance() { - return base::Singleton<PolicyBlacklistFactory>::get(); +PolicyBlocklistFactory* PolicyBlocklistFactory::GetInstance() { + return base::Singleton<PolicyBlocklistFactory>::get(); } // static -PolicyBlacklistService* PolicyBlacklistFactory::GetForBrowserContext( +PolicyBlocklistService* PolicyBlocklistFactory::GetForBrowserContext( content::BrowserContext* context) { - return static_cast<PolicyBlacklistService*>( + return static_cast<PolicyBlocklistService*>( GetInstance()->GetServiceForBrowserContext(context, true)); } -PolicyBlacklistFactory::PolicyBlacklistFactory() +PolicyBlocklistFactory::PolicyBlocklistFactory() : BrowserContextKeyedServiceFactory( - "PolicyBlacklist", + "PolicyBlocklist", BrowserContextDependencyManager::GetInstance()) {} -PolicyBlacklistFactory::~PolicyBlacklistFactory() = default; +PolicyBlocklistFactory::~PolicyBlocklistFactory() = default; -KeyedService* PolicyBlacklistFactory::BuildServiceInstanceFor( +KeyedService* PolicyBlocklistFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { PrefService* pref_service = user_prefs::UserPrefs::Get(context); - auto url_blacklist_manager = - std::make_unique<policy::URLBlacklistManager>(pref_service); - return new PolicyBlacklistService(context, std::move(url_blacklist_manager)); + auto url_blocklist_manager = + std::make_unique<policy::URLBlocklistManager>(pref_service); + return new PolicyBlocklistService(context, std::move(url_blocklist_manager)); } -content::BrowserContext* PolicyBlacklistFactory::GetBrowserContextToUse( +content::BrowserContext* PolicyBlocklistFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return context; }
diff --git a/components/policy/content/policy_blacklist_service.h b/components/policy/content/policy_blacklist_service.h index b294f86..db637b8 100644 --- a/components/policy/content/policy_blacklist_service.h +++ b/components/policy/content/policy_blacklist_service.h
@@ -18,20 +18,20 @@ class URLChecker; } // namespace safe_search_api -// PolicyBlacklistService and PolicyBlacklistFactory provide a way for -// us to access URLBlacklistManager, a policy block list service based on -// the Preference Service. The URLBlacklistManager responds to permission +// PolicyBlocklistService and PolicyBlocklistFactory provide a way for +// us to access URLBlocklistManager, a policy block list service based on +// the Preference Service. The URLBlocklistManager responds to permission // changes and is per-Profile. -class PolicyBlacklistService : public KeyedService { +class PolicyBlocklistService : public KeyedService { public: using CheckSafeSearchCallback = base::OnceCallback<void(bool is_safe)>; - PolicyBlacklistService( + PolicyBlocklistService( content::BrowserContext* browser_context, - std::unique_ptr<policy::URLBlacklistManager> url_blacklist_manager); - ~PolicyBlacklistService() override; + std::unique_ptr<policy::URLBlocklistManager> url_blocklist_manager); + ~PolicyBlocklistService() override; - policy::URLBlacklist::URLBlacklistState GetURLBlacklistState( + policy::URLBlocklist::URLBlocklistState GetURLBlocklistState( const GURL& url) const; // Starts a call to the Safe Search API for the given URL to determine whether @@ -45,22 +45,22 @@ private: content::BrowserContext* const browser_context_; - std::unique_ptr<policy::URLBlacklistManager> url_blacklist_manager_; + std::unique_ptr<policy::URLBlocklistManager> url_blocklist_manager_; std::unique_ptr<safe_search_api::URLChecker> safe_search_url_checker_; - DISALLOW_COPY_AND_ASSIGN(PolicyBlacklistService); + DISALLOW_COPY_AND_ASSIGN(PolicyBlocklistService); }; -class PolicyBlacklistFactory : public BrowserContextKeyedServiceFactory { +class PolicyBlocklistFactory : public BrowserContextKeyedServiceFactory { public: - static PolicyBlacklistFactory* GetInstance(); - static PolicyBlacklistService* GetForBrowserContext( + static PolicyBlocklistFactory* GetInstance(); + static PolicyBlocklistService* GetForBrowserContext( content::BrowserContext* context); private: - PolicyBlacklistFactory(); - ~PolicyBlacklistFactory() override; - friend struct base::DefaultSingletonTraits<PolicyBlacklistFactory>; + PolicyBlocklistFactory(); + ~PolicyBlocklistFactory() override; + friend struct base::DefaultSingletonTraits<PolicyBlocklistFactory>; // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( @@ -70,7 +70,7 @@ content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; - DISALLOW_COPY_AND_ASSIGN(PolicyBlacklistFactory); + DISALLOW_COPY_AND_ASSIGN(PolicyBlocklistFactory); }; #endif // COMPONENTS_POLICY_CONTENT_POLICY_BLACKLIST_SERVICE_H_
diff --git a/components/policy/core/browser/url_blacklist_manager.cc b/components/policy/core/browser/url_blacklist_manager.cc index 5f50fce8..15445b0 100644 --- a/components/policy/core/browser/url_blacklist_manager.cc +++ b/components/policy/core/browser/url_blacklist_manager.cc
@@ -55,20 +55,20 @@ namespace { // List of schemes of URLs that should not be blocked by the "*" wildcard in -// the blacklist. Note that URLs with these schemes can still be blocked with +// the blocklist. Note that URLs with these schemes can still be blocked with // a more specific filter e.g. "chrome-extension://*". // The schemes are hardcoded here to avoid dependencies on //extensions and // //chrome. -const char* kBypassBlacklistWildcardForSchemes[] = { - // For internal extension URLs e.g. the Bookmark Manager and the File - // Manager on Chrome OS. - "chrome-extension", +const char* kBypassBlocklistWildcardForSchemes[] = { + // For internal extension URLs e.g. the Bookmark Manager and the File + // Manager on Chrome OS. + "chrome-extension", - // NTP on Android. - "chrome-native", + // NTP on Android. + "chrome-native", - // NTP on other platforms. - "chrome-search", + // NTP on other platforms. + "chrome-search", }; #if defined(OS_IOS) @@ -79,19 +79,19 @@ constexpr char kIosNtpHost[] = "newtab"; #endif -// Returns a blacklist based on the given |block| and |allow| pattern lists. -std::unique_ptr<URLBlacklist> BuildBlacklist(const base::ListValue* block, +// Returns a blocklist based on the given |block| and |allow| pattern lists. +std::unique_ptr<URLBlocklist> BuildBlocklist(const base::ListValue* block, const base::ListValue* allow) { - auto blacklist = std::make_unique<URLBlacklist>(); - blacklist->Block(block); - blacklist->Allow(allow); - return blacklist; + auto blocklist = std::make_unique<URLBlocklist>(); + blocklist->Block(block); + blocklist->Allow(allow); + return blocklist; } -bool BypassBlacklistWildcardForURL(const GURL& url) { +bool BypassBlocklistWildcardForURL(const GURL& url) { const std::string& scheme = url.scheme(); - for (size_t i = 0; i < base::size(kBypassBlacklistWildcardForSchemes); ++i) { - if (scheme == kBypassBlacklistWildcardForSchemes[i]) + for (const char* bypass_scheme : kBypassBlocklistWildcardForSchemes) { + if (scheme == bypass_scheme) return true; } #if defined(OS_IOS) @@ -114,24 +114,24 @@ } // namespace -URLBlacklist::URLBlacklist() : id_(0), url_matcher_(new URLMatcher) {} +URLBlocklist::URLBlocklist() : id_(0), url_matcher_(new URLMatcher) {} -URLBlacklist::~URLBlacklist() {} +URLBlocklist::~URLBlocklist() = default; -void URLBlacklist::Block(const base::ListValue* filters) { +void URLBlocklist::Block(const base::ListValue* filters) { url_util::AddFilters(url_matcher_.get(), false, &id_, filters, &filters_); } -void URLBlacklist::Allow(const base::ListValue* filters) { +void URLBlocklist::Allow(const base::ListValue* filters) { url_util::AddFilters(url_matcher_.get(), true, &id_, filters, &filters_); } -bool URLBlacklist::IsURLBlocked(const GURL& url) const { - return URLBlacklist::GetURLBlacklistState(url) == - URLBlacklist::URLBlacklistState::URL_IN_BLACKLIST; +bool URLBlocklist::IsURLBlocked(const GURL& url) const { + return URLBlocklist::GetURLBlocklistState(url) == + URLBlocklist::URLBlocklistState::URL_IN_BLOCKLIST; } -URLBlacklist::URLBlacklistState URLBlacklist::GetURLBlacklistState( +URLBlocklist::URLBlocklistState URLBlocklist::GetURLBlocklistState( const GURL& url) const { std::set<URLMatcherConditionSet::ID> matching_ids = url_matcher_->MatchURL(url); @@ -147,28 +147,27 @@ // Default neutral. if (!max) - return URLBlacklist::URLBlacklistState::URL_NEUTRAL_STATE; + return URLBlocklist::URLBlocklistState::URL_NEUTRAL_STATE; // Some of the internal Chrome URLs are not affected by the "*" in the - // blacklist. Note that the "*" is the lowest priority filter possible, so + // blocklist. Note that the "*" is the lowest priority filter possible, so // any higher priority filter will be applied first. - if (max->IsBlacklistWildcard() && BypassBlacklistWildcardForURL(url)) - return URLBlacklist::URLBlacklistState::URL_IN_WHITELIST; + if (max->IsBlocklistWildcard() && BypassBlocklistWildcardForURL(url)) + return URLBlocklist::URLBlocklistState::URL_IN_ALLOWLIST; - return max->allow ? - URLBlacklist::URLBlacklistState::URL_IN_WHITELIST : - URLBlacklist::URLBlacklistState::URL_IN_BLACKLIST; + return max->allow ? URLBlocklist::URLBlocklistState::URL_IN_ALLOWLIST + : URLBlocklist::URLBlocklistState::URL_IN_BLOCKLIST; } -size_t URLBlacklist::Size() const { +size_t URLBlocklist::Size() const { return filters_.size(); } // static -bool URLBlacklist::FilterTakesPrecedence(const FilterComponents& lhs, +bool URLBlocklist::FilterTakesPrecedence(const FilterComponents& lhs, const FilterComponents& rhs) { // The "*" wildcard is the lowest priority filter. - if (rhs.IsBlacklistWildcard()) + if (rhs.IsBlocklistWildcard()) return true; if (lhs.match_subdomains && !rhs.match_subdomains) @@ -195,8 +194,8 @@ return false; } -URLBlacklistManager::URLBlacklistManager(PrefService* pref_service) - : pref_service_(pref_service), blacklist_(new URLBlacklist) { +URLBlocklistManager::URLBlocklistManager(PrefService* pref_service) + : pref_service_(pref_service), blocklist_(new URLBlocklist) { // This class assumes that it is created on the same thread that // |pref_service_| lives on. ui_task_runner_ = base::SequencedTaskRunnerHandle::Get(); @@ -205,7 +204,7 @@ pref_change_registrar_.Init(pref_service_); base::RepeatingClosure callback = base::BindRepeating( - &URLBlacklistManager::ScheduleUpdate, base::Unretained(this)); + &URLBlocklistManager::ScheduleUpdate, base::Unretained(this)); pref_change_registrar_.Add(policy_prefs::kUrlBlacklist, callback); pref_change_registrar_.Add(policy_prefs::kUrlWhitelist, callback); @@ -213,67 +212,67 @@ // startup. if (pref_service_->HasPrefPath(policy_prefs::kUrlBlacklist) || pref_service_->HasPrefPath(policy_prefs::kUrlWhitelist)) { - SetBlacklist( - BuildBlacklist(pref_service_->GetList(policy_prefs::kUrlBlacklist), + SetBlocklist( + BuildBlocklist(pref_service_->GetList(policy_prefs::kUrlBlacklist), pref_service_->GetList(policy_prefs::kUrlWhitelist))); } } -URLBlacklistManager::~URLBlacklistManager() { +URLBlocklistManager::~URLBlocklistManager() { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); pref_change_registrar_.RemoveAll(); } -void URLBlacklistManager::ScheduleUpdate() { +void URLBlocklistManager::ScheduleUpdate() { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); // Cancel pending updates, if any. This can happen if two preferences that - // change the blacklist are updated in one message loop cycle. In those cases, - // only rebuild the blacklist after all the preference updates are processed. + // change the blocklist are updated in one message loop cycle. In those cases, + // only rebuild the blocklist after all the preference updates are processed. ui_weak_ptr_factory_.InvalidateWeakPtrs(); ui_task_runner_->PostTask(FROM_HERE, - base::BindOnce(&URLBlacklistManager::Update, + base::BindOnce(&URLBlocklistManager::Update, ui_weak_ptr_factory_.GetWeakPtr())); } -void URLBlacklistManager::Update() { +void URLBlocklistManager::Update() { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); - // The URLBlacklist is built in the background. Once it's ready, it is passed - // to the URLBlacklistManager back on ui_task_runner_. + // The URLBlocklist is built in the background. Once it's ready, it is passed + // to the URLBlocklistManager back on ui_task_runner_. base::PostTaskAndReplyWithResult( background_task_runner_.get(), FROM_HERE, base::BindOnce( - &BuildBlacklist, + &BuildBlocklist, base::Owned( pref_service_->GetList(policy_prefs::kUrlBlacklist)->DeepCopy()), base::Owned( pref_service_->GetList(policy_prefs::kUrlWhitelist)->DeepCopy())), - base::BindOnce(&URLBlacklistManager::SetBlacklist, + base::BindOnce(&URLBlocklistManager::SetBlocklist, ui_weak_ptr_factory_.GetWeakPtr())); } -void URLBlacklistManager::SetBlacklist( - std::unique_ptr<URLBlacklist> blacklist) { +void URLBlocklistManager::SetBlocklist( + std::unique_ptr<URLBlocklist> blocklist) { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); - blacklist_ = std::move(blacklist); + blocklist_ = std::move(blocklist); } -bool URLBlacklistManager::IsURLBlocked(const GURL& url) const { +bool URLBlocklistManager::IsURLBlocked(const GURL& url) const { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); // Ignore blob scheme for two reasons: // 1) Its used to deliver the response to the renderer. - // 2) A whitelisted page can use blob URLs internally. - return !url.SchemeIs(url::kBlobScheme) && blacklist_->IsURLBlocked(url); + // 2) A page on the allowlist can use blob URLs internally. + return !url.SchemeIs(url::kBlobScheme) && blocklist_->IsURLBlocked(url); } -URLBlacklist::URLBlacklistState URLBlacklistManager::GetURLBlacklistState( +URLBlocklist::URLBlocklistState URLBlocklistManager::GetURLBlocklistState( const GURL& url) const { DCHECK(ui_task_runner_->RunsTasksInCurrentSequence()); - return blacklist_->GetURLBlacklistState(url); + return blocklist_->GetURLBlocklistState(url); } // static -void URLBlacklistManager::RegisterProfilePrefs( +void URLBlocklistManager::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterListPref(policy_prefs::kUrlBlacklist); registry->RegisterListPref(policy_prefs::kUrlWhitelist);
diff --git a/components/policy/core/browser/url_blacklist_manager.h b/components/policy/core/browser/url_blacklist_manager.h index 66d3c4e..654679b 100644 --- a/components/policy/core/browser/url_blacklist_manager.h +++ b/components/policy/core/browser/url_blacklist_manager.h
@@ -37,19 +37,19 @@ // Contains a set of filters to block and allow certain URLs, and matches GURLs // against this set. The filters are currently kept in memory. -class POLICY_EXPORT URLBlacklist { +class POLICY_EXPORT URLBlocklist { public: - // Indicates if the URL matches a pattern defined in blacklist, in whitelist - // or doesn't match anything in either list as defined in URLBlacklist and - // URLWhitelist policies. - enum URLBlacklistState { - URL_IN_WHITELIST, - URL_IN_BLACKLIST, + // Indicates if the URL matches a pattern defined in blocklist, in allowlist + // or doesn't match anything in either list as defined in URLBlocklist and + // URLAllowlist policies. + enum URLBlocklistState { + URL_IN_ALLOWLIST, + URL_IN_BLOCKLIST, URL_NEUTRAL_STATE, }; - URLBlacklist(); - virtual ~URLBlacklist(); + URLBlocklist(); + virtual ~URLBlocklist(); // URLs matching one of the |filters| will be blocked. The filter format is // documented at @@ -63,7 +63,7 @@ // Returns true if the URL is blocked. bool IsURLBlocked(const GURL& url) const; - URLBlacklistState GetURLBlacklistState(const GURL& url) const; + URLBlocklistState GetURLBlocklistState(const GURL& url) const; // Returns the number of items in the list. size_t Size() const; @@ -79,39 +79,39 @@ filters_; std::unique_ptr<url_matcher::URLMatcher> url_matcher_; - DISALLOW_COPY_AND_ASSIGN(URLBlacklist); + DISALLOW_COPY_AND_ASSIGN(URLBlocklist); }; -// Tracks the blacklist policies for a given profile, and updates it on changes. -class POLICY_EXPORT URLBlacklistManager { +// Tracks the blocklist policies for a given profile, and updates it on changes. +class POLICY_EXPORT URLBlocklistManager { public: // Must be constructed on the UI thread. - explicit URLBlacklistManager(PrefService* pref_service); - virtual ~URLBlacklistManager(); + explicit URLBlocklistManager(PrefService* pref_service); + virtual ~URLBlocklistManager(); - // Returns true if |url| is blocked by the current blacklist. + // Returns true if |url| is blocked by the current blocklist. bool IsURLBlocked(const GURL& url) const; - URLBlacklist::URLBlacklistState GetURLBlacklistState(const GURL& url) const; + URLBlocklist::URLBlocklistState GetURLBlocklistState(const GURL& url) const; - // Replaces the current blacklist. + // Replaces the current blocklist. // Virtual for testing. - virtual void SetBlacklist(std::unique_ptr<URLBlacklist> blacklist); + virtual void SetBlocklist(std::unique_ptr<URLBlocklist> blocklist); - // Registers the preferences related to blacklisting in the given PrefService. + // Registers the preferences related to blocklisting in the given PrefService. static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); protected: - // Used to delay updating the blacklist while the preferences are + // Used to delay updating the blocklist while the preferences are // changing, and execute only one update per simultaneous prefs changes. void ScheduleUpdate(); - // Updates the blacklist using the current preference values. + // Updates the blocklist using the current preference values. // Virtual for testing. virtual void Update(); private: - // Used to track the policies and update the blacklist on changes. + // Used to track the policies and update the blocklist on changes. PrefChangeRegistrar pref_change_registrar_; PrefService* pref_service_; // Weak. @@ -120,19 +120,19 @@ // Used to schedule tasks on the main loop to avoid rebuilding the blocklist // multiple times during a message loop process. This can happen if two - // preferences that change the blacklist are updated in one message loop + // preferences that change the blocklist are updated in one message loop // cycle. In addition, we use this task runner to ensure that the // URLBlocklistManager is only access from the thread call the constructor for // data accesses. scoped_refptr<base::SequencedTaskRunner> ui_task_runner_; - // The current blacklist. - std::unique_ptr<URLBlacklist> blacklist_; + // The current blocklist. + std::unique_ptr<URLBlocklist> blocklist_; // Used to post update tasks to the UI thread. - base::WeakPtrFactory<URLBlacklistManager> ui_weak_ptr_factory_{this}; + base::WeakPtrFactory<URLBlocklistManager> ui_weak_ptr_factory_{this}; - DISALLOW_COPY_AND_ASSIGN(URLBlacklistManager); + DISALLOW_COPY_AND_ASSIGN(URLBlocklistManager); }; } // namespace policy
diff --git a/components/policy/core/browser/url_blacklist_manager_unittest.cc b/components/policy/core/browser/url_blacklist_manager_unittest.cc index 63fd1c1..16310b624 100644 --- a/components/policy/core/browser/url_blacklist_manager_unittest.cc +++ b/components/policy/core/browser/url_blacklist_manager_unittest.cc
@@ -30,58 +30,59 @@ namespace { -class TestingURLBlacklistManager : public URLBlacklistManager { +class TestingURLBlocklistManager : public URLBlocklistManager { public: - explicit TestingURLBlacklistManager(PrefService* pref_service) - : URLBlacklistManager(pref_service), + explicit TestingURLBlocklistManager(PrefService* pref_service) + : URLBlocklistManager(pref_service), update_called_(0), - set_blacklist_called_(false) {} + set_blocklist_called_(false) {} - ~TestingURLBlacklistManager() override {} + ~TestingURLBlocklistManager() override = default; // Make this method public for testing. - using URLBlacklistManager::ScheduleUpdate; + using URLBlocklistManager::ScheduleUpdate; - // URLBlacklistManager overrides: - void SetBlacklist(std::unique_ptr<URLBlacklist> blacklist) override { - set_blacklist_called_ = true; - URLBlacklistManager::SetBlacklist(std::move(blacklist)); + // URLBlocklistManager overrides: + void SetBlocklist(std::unique_ptr<URLBlocklist> blocklist) override { + set_blocklist_called_ = true; + URLBlocklistManager::SetBlocklist(std::move(blocklist)); } void Update() override { update_called_++; - URLBlacklistManager::Update(); + URLBlocklistManager::Update(); } int update_called() const { return update_called_; } - bool set_blacklist_called() const { return set_blacklist_called_; } + bool set_blocklist_called() const { return set_blocklist_called_; } private: int update_called_; - bool set_blacklist_called_; + bool set_blocklist_called_; - DISALLOW_COPY_AND_ASSIGN(TestingURLBlacklistManager); + DISALLOW_COPY_AND_ASSIGN(TestingURLBlocklistManager); }; -class URLBlacklistManagerTest : public testing::Test { +class URLBlocklistManagerTest : public testing::Test { protected: - URLBlacklistManagerTest() {} + URLBlocklistManagerTest() = default; void SetUp() override { pref_service_.registry()->RegisterListPref(policy_prefs::kUrlBlacklist); pref_service_.registry()->RegisterListPref(policy_prefs::kUrlWhitelist); - blacklist_manager_.reset(new TestingURLBlacklistManager(&pref_service_)); + blocklist_manager_ = + std::make_unique<TestingURLBlocklistManager>(&pref_service_); task_environment_.RunUntilIdle(); } void TearDown() override { - if (blacklist_manager_) + if (blocklist_manager_) task_environment_.RunUntilIdle(); - blacklist_manager_.reset(); + blocklist_manager_.reset(); } TestingPrefServiceSimple pref_service_; - std::unique_ptr<TestingURLBlacklistManager> blacklist_manager_; + std::unique_ptr<TestingURLBlocklistManager> blocklist_manager_; base::test::TaskEnvironment task_environment_; }; @@ -90,72 +91,72 @@ // Returns whether |url| matches the |pattern|. bool IsMatch(const std::string& pattern, const std::string& url) { - URLBlacklist blacklist; + URLBlocklist blocklist; - // Add the pattern to blacklist. + // Add the pattern to blocklist. std::unique_ptr<base::ListValue> blocked(new base::ListValue); blocked->AppendString(pattern); - blacklist.Block(blocked.get()); + blocklist.Block(blocked.get()); - return blacklist.IsURLBlocked(GURL(url)); + return blocklist.IsURLBlocked(GURL(url)); } -// Returns the state from blacklist after adding |pattern| to be blocked or -// allowed depending on |use_whitelist| and checking |url|. -policy::URLBlacklist::URLBlacklistState GetMatch(const std::string& pattern, +// Returns the state from blocklist after adding |pattern| to be blocked or +// allowed depending on |use_allowlist| and checking |url|. +policy::URLBlocklist::URLBlocklistState GetMatch(const std::string& pattern, const std::string& url, - const bool use_whitelist) { - URLBlacklist blacklist; + const bool use_allowlist) { + URLBlocklist blocklist; // Add the pattern to list. std::unique_ptr<base::ListValue> blocked(new base::ListValue); blocked->AppendString(pattern); - if (use_whitelist) { - blacklist.Allow(blocked.get()); + if (use_allowlist) { + blocklist.Allow(blocked.get()); } else { - blacklist.Block(blocked.get()); + blocklist.Block(blocked.get()); } - return blacklist.GetURLBlacklistState(GURL(url)); + return blocklist.GetURLBlocklistState(GURL(url)); } -TEST_F(URLBlacklistManagerTest, LoadBlacklistOnCreate) { +TEST_F(URLBlocklistManagerTest, LoadBlocklistOnCreate) { auto list = std::make_unique<base::ListValue>(); list->AppendString("example.com"); pref_service_.SetManagedPref(policy_prefs::kUrlBlacklist, std::move(list)); - auto manager = std::make_unique<URLBlacklistManager>(&pref_service_); + auto manager = std::make_unique<URLBlocklistManager>(&pref_service_); task_environment_.RunUntilIdle(); - EXPECT_EQ(URLBlacklist::URL_IN_BLACKLIST, - manager->GetURLBlacklistState(GURL("http://example.com"))); + EXPECT_EQ(URLBlocklist::URL_IN_BLOCKLIST, + manager->GetURLBlocklistState(GURL("http://example.com"))); } -TEST_F(URLBlacklistManagerTest, LoadWhitelistOnCreate) { +TEST_F(URLBlocklistManagerTest, LoadAllowlistOnCreate) { auto list = std::make_unique<base::ListValue>(); list->AppendString("example.com"); pref_service_.SetManagedPref(policy_prefs::kUrlWhitelist, std::move(list)); - auto manager = std::make_unique<URLBlacklistManager>(&pref_service_); + auto manager = std::make_unique<URLBlocklistManager>(&pref_service_); task_environment_.RunUntilIdle(); - EXPECT_EQ(URLBlacklist::URL_IN_WHITELIST, - manager->GetURLBlacklistState(GURL("http://example.com"))); + EXPECT_EQ(URLBlocklist::URL_IN_ALLOWLIST, + manager->GetURLBlocklistState(GURL("http://example.com"))); } -TEST_F(URLBlacklistManagerTest, SingleUpdateForTwoPrefChanges) { - auto blacklist = std::make_unique<base::ListValue>(); - blacklist->AppendString("*.google.com"); - auto whitelist = std::make_unique<base::ListValue>(); - whitelist->AppendString("mail.google.com"); +TEST_F(URLBlocklistManagerTest, SingleUpdateForTwoPrefChanges) { + auto blocklist = std::make_unique<base::ListValue>(); + blocklist->AppendString("*.google.com"); + auto allowlist = std::make_unique<base::ListValue>(); + allowlist->AppendString("mail.google.com"); pref_service_.SetManagedPref(policy_prefs::kUrlBlacklist, - std::move(blacklist)); + std::move(blocklist)); pref_service_.SetManagedPref(policy_prefs::kUrlBlacklist, - std::move(whitelist)); + std::move(allowlist)); task_environment_.RunUntilIdle(); - EXPECT_EQ(1, blacklist_manager_->update_called()); + EXPECT_EQ(1, blocklist_manager_->update_called()); } -TEST_F(URLBlacklistManagerTest, Filtering) { - URLBlacklist blacklist; +TEST_F(URLBlocklistManagerTest, Filtering) { + URLBlocklist blocklist; // Block domain and all subdomains, for any filtered scheme. EXPECT_TRUE(IsMatch("google.com", "http://google.com")); @@ -217,227 +218,227 @@ allowed->AppendString("s.xxx.com/a/b"); blocked->AppendString("https://s.xxx.com/a/b/c"); allowed->AppendString("https://s.xxx.com/a/b/c/d"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/x"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/x"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/x"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/x"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/d"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c/d"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/d/x"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c/d/x"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://xxx.com/a"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://xxx.com/a/b"))); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://s.xxx.com/a"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://s.xxx.com/a/x"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("https://s.xxx.com/a/x"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://s.xxx.com/a/b"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("https://s.xxx.com/a/b"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/x"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/x"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/d"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c/d"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/d/x"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c/d/x"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://xxx.com/a"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://xxx.com/a/b"))); // Open an exception. - blocked.reset(new base::ListValue); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("google.com"); - allowed.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString("plus.google.com"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com/"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com/"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://plus.google.com/"))); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://google.com/"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://www.google.com/"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://plus.google.com/"))); // Open an exception only when using https for mail. - allowed.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString("https://mail.google.com"); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com/"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://mail.google.com/"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com/"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://www.google.com/"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://mail.google.com/"))); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://google.com/"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://mail.google.com/"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://www.google.com/"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("https://www.google.com/"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("https://mail.google.com/"))); // Match exactly "google.com", only for http. Subdomains without exceptions // are still blocked. - allowed.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString("http://.google.com"); - blacklist.Allow(allowed.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://google.com/"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://google.com/"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com/"))); + blocklist.Allow(allowed.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://google.com/"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("https://google.com/"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://www.google.com/"))); // A smaller path match in an exact host overrides a longer path for hosts // that also match subdomains. - blocked.reset(new base::ListValue); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("yyy.com/aaa"); - blacklist.Block(blocked.get()); - allowed.reset(new base::ListValue); + blocklist.Block(blocked.get()); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString(".yyy.com/a"); - blacklist.Allow(allowed.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://yyy.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://yyy.com/aaa"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://yyy.com/aaa2"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://www.yyy.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.yyy.com/aaa"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.yyy.com/aaa2"))); + blocklist.Allow(allowed.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://yyy.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://yyy.com/aaa"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://yyy.com/aaa2"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://www.yyy.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://www.yyy.com/aaa"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://www.yyy.com/aaa2"))); // If the exact entry is both allowed and blocked, allowing takes precedence. - blocked.reset(new base::ListValue); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("example.com"); - blacklist.Block(blocked.get()); - allowed.reset(new base::ListValue); + blocklist.Block(blocked.get()); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString("example.com"); - blacklist.Allow(allowed.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://example.com"))); + blocklist.Allow(allowed.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://example.com"))); // Devtools should not be blocked. - blocked.reset(new base::ListValue); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("*"); - blacklist.Block(blocked.get()); - allowed.reset(new base::ListValue); + blocklist.Block(blocked.get()); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString("devtools://*"); - blacklist.Allow(allowed.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("devtools://something.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://something.com"))); + blocklist.Allow(allowed.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("devtools://something.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("https://something.com"))); } -TEST_F(URLBlacklistManagerTest, QueryParameters) { - URLBlacklist blacklist; +TEST_F(URLBlocklistManagerTest, QueryParameters) { + URLBlocklist blocklist; std::unique_ptr<base::ListValue> blocked(new base::ListValue); std::unique_ptr<base::ListValue> allowed(new base::ListValue); // Block domain and all subdomains, for any filtered scheme. blocked->AppendString("youtube.com"); allowed->AppendString("youtube.com/watch?v=XYZ"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=123"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com/watch?v=123"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=123&v=XYZ"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?v=123&v=XYZ"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ&v=123"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ&v=123"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ&foo=bar"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ&foo=bar"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?foo=bar&v=XYZ"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?foo=bar&v=XYZ"))); - allowed.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString("youtube.com/watch?av=XYZ&ag=123"); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=123"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=XYZ"))); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com/watch?av=123"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com/watch?av=XYZ"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=123&ag=XYZ"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?av=123&ag=XYZ"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?ag=XYZ&av=123"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?ag=XYZ&av=123"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=XYZ&ag=123"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?av=XYZ&ag=123"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?ag=123&av=XYZ"))); - EXPECT_TRUE(blacklist.IsURLBlocked( + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?ag=123&av=XYZ"))); + EXPECT_TRUE(blocklist.IsURLBlocked( GURL("http://youtube.com/watch?av=XYZ&ag=123&av=123"))); - EXPECT_TRUE(blacklist.IsURLBlocked( + EXPECT_TRUE(blocklist.IsURLBlocked( GURL("http://youtube.com/watch?av=XYZ&ag=123&ag=1234"))); - allowed.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); allowed->AppendString("youtube.com/watch?foo=bar*&vid=2*"); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?foo=bar"))); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube.com/watch?foo=bar"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2&foo=bar"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2&foo=bar"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2&foo=bar1"))); + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2&foo=bar1"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=234&foo=bar"))); - EXPECT_FALSE(blacklist.IsURLBlocked( + blocklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=234&foo=bar"))); + EXPECT_FALSE(blocklist.IsURLBlocked( GURL("http://youtube.com/watch?vid=234&foo=bar23"))); - blocked.reset(new base::ListValue); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("youtube1.com/disallow?v=44678"); - blacklist.Block(blocked.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com?v=123"))); + blocklist.Block(blocked.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube1.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube1.com?v=123"))); // Path does not match - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com?v=44678"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube1.com?v=44678"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?v=44678"))); + blocklist.IsURLBlocked(GURL("http://youtube1.com/disallow?v=44678"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?v=4467"))); - EXPECT_FALSE(blacklist.IsURLBlocked( + blocklist.IsURLBlocked(GURL("http://youtube1.com/disallow?v=4467"))); + EXPECT_FALSE(blocklist.IsURLBlocked( GURL("http://youtube1.com/disallow?v=4467&v=123"))); - EXPECT_TRUE(blacklist.IsURLBlocked( + EXPECT_TRUE(blocklist.IsURLBlocked( GURL("http://youtube1.com/disallow?v=4467&v=123&v=44678"))); - blocked.reset(new base::ListValue); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("youtube1.com/disallow?g=*"); - blacklist.Block(blocked.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com?ag=123"))); + blocklist.Block(blocked.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube1.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube1.com?ag=123"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?g=123"))); + blocklist.IsURLBlocked(GURL("http://youtube1.com/disallow?g=123"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?ag=13&g=123"))); + blocklist.IsURLBlocked(GURL("http://youtube1.com/disallow?ag=13&g=123"))); - blocked.reset(new base::ListValue); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("youtube2.com/disallow?a*"); - blacklist.Block(blocked.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube2.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked( + blocklist.Block(blocked.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube2.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked( GURL("http://youtube2.com/disallow?b=123&a21=467"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube2.com/disallow?abba=true"))); + blocklist.IsURLBlocked(GURL("http://youtube2.com/disallow?abba=true"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube2.com/disallow?baba=true"))); + blocklist.IsURLBlocked(GURL("http://youtube2.com/disallow?baba=true"))); - allowed.reset(new base::ListValue); - blocked.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("youtube3.com"); allowed->AppendString("youtube3.com/watch?fo*"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube3.com"))); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube3.com"))); EXPECT_TRUE( - blacklist.IsURLBlocked(GURL("http://youtube3.com/watch?b=123&a21=467"))); - EXPECT_FALSE(blacklist.IsURLBlocked( + blocklist.IsURLBlocked(GURL("http://youtube3.com/watch?b=123&a21=467"))); + EXPECT_FALSE(blocklist.IsURLBlocked( GURL("http://youtube3.com/watch?b=123&a21=467&foo1"))); - EXPECT_FALSE(blacklist.IsURLBlocked( + EXPECT_FALSE(blocklist.IsURLBlocked( GURL("http://youtube3.com/watch?b=123&a21=467&foo=bar"))); - EXPECT_FALSE(blacklist.IsURLBlocked( + EXPECT_FALSE(blocklist.IsURLBlocked( GURL("http://youtube3.com/watch?b=123&a21=467&fo=ba"))); EXPECT_FALSE( - blacklist.IsURLBlocked(GURL("http://youtube3.com/watch?foriegn=true"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube3.com/watch?fold"))); + blocklist.IsURLBlocked(GURL("http://youtube3.com/watch?foreign=true"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube3.com/watch?fold"))); - allowed.reset(new base::ListValue); - blocked.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("youtube4.com"); allowed->AppendString("youtube4.com?*"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube4.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube4.com/?hello"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube4.com/?foo"))); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube4.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube4.com/?hello"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube4.com/?foo"))); - allowed.reset(new base::ListValue); - blocked.reset(new base::ListValue); + allowed = std::make_unique<base::ListValue>(); + blocked = std::make_unique<base::ListValue>(); blocked->AppendString("youtube5.com?foo=bar"); allowed->AppendString("youtube5.com?foo1=bar1&foo2=bar2&"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube5.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube5.com/?foo=bar&a=b"))); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://youtube5.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://youtube5.com/?foo=bar&a=b"))); // More specific filter is given precedence. - EXPECT_FALSE(blacklist.IsURLBlocked( + EXPECT_FALSE(blocklist.IsURLBlocked( GURL("http://youtube5.com/?a=b&foo=bar&foo1=bar1&foo2=bar2"))); } -TEST_F(URLBlacklistManagerTest, BlockAllWithExceptions) { - URLBlacklist blacklist; +TEST_F(URLBlocklistManagerTest, BlockAllWithExceptions) { + URLBlocklist blocklist; std::unique_ptr<base::ListValue> blocked(new base::ListValue); std::unique_ptr<base::ListValue> allowed(new base::ListValue); @@ -446,63 +447,63 @@ allowed->AppendString("plus.google.com"); allowed->AppendString("https://mail.google.com"); allowed->AppendString("https://very.safe/path"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://random.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://s.www.google.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://www.google.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://plus.google.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.plus.google.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://mail.google.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://mail.google.com"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.mail.google.com"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://very.safe/"))); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://very.safe/path"))); - EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://very.safe/path"))); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://random.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://google.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://s.www.google.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://www.google.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://plus.google.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("http://s.plus.google.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://mail.google.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("https://mail.google.com"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("https://s.mail.google.com"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("https://very.safe/"))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://very.safe/path"))); + EXPECT_FALSE(blocklist.IsURLBlocked(GURL("https://very.safe/path"))); } -TEST_F(URLBlacklistManagerTest, DefaultBlacklistExceptions) { - URLBlacklist blacklist; +TEST_F(URLBlocklistManagerTest, DefaultBlocklistExceptions) { + URLBlocklist blocklist; std::unique_ptr<base::ListValue> blocked(new base::ListValue); - // Blacklist everything: + // Blocklist everything: blocked->AppendString("*"); - blacklist.Block(blocked.get()); + blocklist.Block(blocked.get()); // Internal NTP and extension URLs are not blocked by the "*": - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com"))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-extension://xyz")))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-search://local-ntp")))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-native://ntp")))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://www.google.com"))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("chrome-extension://xyz")))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("chrome-search://local-ntp")))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("chrome-native://ntp")))); #if defined(OS_IOS) // Ensure that the NTP is not blocked on iOS by "*". // TODO(crbug.com/1073291): On iOS, the NTP can not be blocked even by // explicitly listing it as a blocked URL. This is due to the usage of // "about:newtab" as its URL which is not recognized and filtered by the - // URLBlacklist code. - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("about:newtab")))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("about://newtab/")))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome://newtab")))); + // URLBlocklist code. + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("about:newtab")))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("about://newtab/")))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("chrome://newtab")))); #endif - // Unless they are explicitly blacklisted: + // Unless they are explicitly on the blocklist: blocked->AppendString("chrome-extension://*"); std::unique_ptr<base::ListValue> allowed(new base::ListValue); allowed->AppendString("chrome-extension://abc"); - blacklist.Block(blocked.get()); - blacklist.Allow(allowed.get()); + blocklist.Block(blocked.get()); + blocklist.Allow(allowed.get()); - EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com"))); - EXPECT_TRUE((blacklist.IsURLBlocked(GURL("chrome-extension://xyz")))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-extension://abc")))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-search://local-ntp")))); - EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-native://ntp")))); + EXPECT_TRUE(blocklist.IsURLBlocked(GURL("http://www.google.com"))); + EXPECT_TRUE((blocklist.IsURLBlocked(GURL("chrome-extension://xyz")))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("chrome-extension://abc")))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("chrome-search://local-ntp")))); + EXPECT_FALSE((blocklist.IsURLBlocked(GURL("chrome-native://ntp")))); } -TEST_F(URLBlacklistManagerTest, BlacklistBasicCoverage) { +TEST_F(URLBlocklistManagerTest, BlocklistBasicCoverage) { // Tests to cover the documentation from - // http://www.chromium.org/administrators/url-blacklist-filter-format + // http://www.chromium.org/administrators/url-blocklist-filter-format // [scheme://][.]host[:port][/path][@query] // Scheme can be http, https, ftp, chrome, etc. This field is optional, and @@ -616,23 +617,23 @@ EXPECT_FALSE(IsMatch("host/path?Query=1", "http://host/path?query=1")); } -// Test for GetURLBlacklistState method. -TEST_F(URLBlacklistManagerTest, UseBlacklistState) { - const policy::URLBlacklist::URLBlacklistState in_blacklist = - policy::URLBlacklist::URLBlacklistState::URL_IN_BLACKLIST; - const policy::URLBlacklist::URLBlacklistState in_whitelist = - policy::URLBlacklist::URLBlacklistState::URL_IN_WHITELIST; - const policy::URLBlacklist::URLBlacklistState neutral_state = - policy::URLBlacklist::URLBlacklistState::URL_NEUTRAL_STATE; +// Test for GetURLBlocklistState method. +TEST_F(URLBlocklistManagerTest, UseBlocklistState) { + const policy::URLBlocklist::URLBlocklistState in_blocklist = + policy::URLBlocklist::URLBlocklistState::URL_IN_BLOCKLIST; + const policy::URLBlocklist::URLBlocklistState in_allowlist = + policy::URLBlocklist::URLBlocklistState::URL_IN_ALLOWLIST; + const policy::URLBlocklist::URLBlocklistState neutral_state = + policy::URLBlocklist::URLBlocklistState::URL_NEUTRAL_STATE; - // Test whitelist states. - EXPECT_EQ(in_whitelist, GetMatch("example.com", "http://example.com", true)); - EXPECT_EQ(in_whitelist, GetMatch("http://*", "http://example.com", true)); - EXPECT_EQ(in_whitelist, GetMatch("custom://*", "custom://app", true)); - EXPECT_EQ(in_whitelist, GetMatch("custom:*", "custom://app/play", true)); - EXPECT_EQ(in_whitelist, GetMatch("custom:*", "custom://app:8080", true)); - // Test blacklist states. - EXPECT_EQ(in_blacklist, GetMatch("ftp:*", "ftp://server", false)); + // Test allowlist states. + EXPECT_EQ(in_allowlist, GetMatch("example.com", "http://example.com", true)); + EXPECT_EQ(in_allowlist, GetMatch("http://*", "http://example.com", true)); + EXPECT_EQ(in_allowlist, GetMatch("custom://*", "custom://app", true)); + EXPECT_EQ(in_allowlist, GetMatch("custom:*", "custom://app/play", true)); + EXPECT_EQ(in_allowlist, GetMatch("custom:*", "custom://app:8080", true)); + // Test blocklist states. + EXPECT_EQ(in_blocklist, GetMatch("ftp:*", "ftp://server", false)); // Test neutral states. EXPECT_EQ(neutral_state, GetMatch("file:*", "http://example.com", true)); EXPECT_EQ(neutral_state, GetMatch("https://*", "http://example.com", false));
diff --git a/components/policy/core/browser/url_blacklist_policy_handler.cc b/components/policy/core/browser/url_blacklist_policy_handler.cc index 86c8dba1..04b4309a 100644 --- a/components/policy/core/browser/url_blacklist_policy_handler.cc +++ b/components/policy/core/browser/url_blacklist_policy_handler.cc
@@ -18,12 +18,12 @@ namespace policy { -URLBlacklistPolicyHandler::URLBlacklistPolicyHandler(const char* policy_name) +URLBlocklistPolicyHandler::URLBlocklistPolicyHandler(const char* policy_name) : TypeCheckingPolicyHandler(policy_name, base::Value::Type::LIST) {} -URLBlacklistPolicyHandler::~URLBlacklistPolicyHandler() {} +URLBlocklistPolicyHandler::~URLBlocklistPolicyHandler() = default; -bool URLBlacklistPolicyHandler::CheckPolicySettings(const PolicyMap& policies, +bool URLBlocklistPolicyHandler::CheckPolicySettings(const PolicyMap& policies, PolicyErrorMap* errors) { // This policy is deprecated but still supported so check it first. const base::Value* disabled_schemes = @@ -44,7 +44,7 @@ return true; } -void URLBlacklistPolicyHandler::ApplyPolicySettings(const PolicyMap& policies, +void URLBlocklistPolicyHandler::ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) { const base::Value* url_blocklist_policy = policies.GetValue(policy_name()); const base::ListValue* url_blocklist = nullptr;
diff --git a/components/policy/core/browser/url_blacklist_policy_handler.h b/components/policy/core/browser/url_blacklist_policy_handler.h index 2113fec..8d494cf 100644 --- a/components/policy/core/browser/url_blacklist_policy_handler.h +++ b/components/policy/core/browser/url_blacklist_policy_handler.h
@@ -19,12 +19,12 @@ kSafeSitesFilterEnabled = 1, }; -// Handles URLBlacklist policies. -class POLICY_EXPORT URLBlacklistPolicyHandler +// Handles URLBlocklist policies. +class POLICY_EXPORT URLBlocklistPolicyHandler : public TypeCheckingPolicyHandler { public: - explicit URLBlacklistPolicyHandler(const char* policy_name); - ~URLBlacklistPolicyHandler() override; + explicit URLBlocklistPolicyHandler(const char* policy_name); + ~URLBlocklistPolicyHandler() override; // ConfigurationPolicyHandler methods: bool CheckPolicySettings(const PolicyMap& policies, @@ -33,7 +33,7 @@ PrefValueMap* prefs) override; private: - DISALLOW_COPY_AND_ASSIGN(URLBlacklistPolicyHandler); + DISALLOW_COPY_AND_ASSIGN(URLBlocklistPolicyHandler); }; } // namespace policy
diff --git a/components/policy/core/browser/url_blacklist_policy_handler_unittest.cc b/components/policy/core/browser/url_blacklist_policy_handler_unittest.cc index 2aad1d6..217d43e 100644 --- a/components/policy/core/browser/url_blacklist_policy_handler_unittest.cc +++ b/components/policy/core/browser/url_blacklist_policy_handler_unittest.cc
@@ -26,14 +26,14 @@ namespace { const char kTestDisabledScheme[] = "kTestDisabledScheme"; -const char kTestBlacklistValue[] = "kTestBlacklistValue"; +const char kTestBlocklistValue[] = "kTestBlocklistValue"; } // namespace -class URLBlacklistPolicyHandlerTest : public testing::Test { +class URLBlocklistPolicyHandlerTest : public testing::Test { public: void SetUp() override { - handler_ = std::make_unique<URLBlacklistPolicyHandler>(key::kURLBlocklist); + handler_ = std::make_unique<URLBlocklistPolicyHandler>(key::kURLBlocklist); } protected: @@ -47,27 +47,27 @@ } void ApplyPolicies() { handler_->ApplyPolicySettings(policies_, &prefs_); } - std::unique_ptr<URLBlacklistPolicyHandler> handler_; + std::unique_ptr<URLBlocklistPolicyHandler> handler_; PolicyErrorMap errors_; PolicyMap policies_; PrefValueMap prefs_; }; -TEST_F(URLBlacklistPolicyHandlerTest, +TEST_F(URLBlocklistPolicyHandlerTest, CheckPolicySettings_DisabledSchemesUnspecified) { EXPECT_TRUE( CheckPolicy(key::kURLBlocklist, base::Value(base::Value::Type::LIST))); EXPECT_EQ(0U, errors_.size()); } -TEST_F(URLBlacklistPolicyHandlerTest, - CheckPolicySettings_URLBlacklistUnspecified) { +TEST_F(URLBlocklistPolicyHandlerTest, + CheckPolicySettings_URLBlocklistUnspecified) { EXPECT_TRUE( CheckPolicy(key::kDisabledSchemes, base::Value(base::Value::Type::LIST))); EXPECT_EQ(0U, errors_.size()); } -TEST_F(URLBlacklistPolicyHandlerTest, +TEST_F(URLBlocklistPolicyHandlerTest, CheckPolicySettings_DisabledSchemesWrongType) { // The policy expects a list. Give it a boolean. EXPECT_TRUE(CheckPolicy(key::kDisabledSchemes, base::Value(false))); @@ -77,8 +77,8 @@ EXPECT_EQ(expected, actual); } -TEST_F(URLBlacklistPolicyHandlerTest, - CheckPolicySettings_URLBlacklistWrongType) { +TEST_F(URLBlocklistPolicyHandlerTest, + CheckPolicySettings_URLBlocklistWrongType) { // The policy expects a list. Give it a boolean. EXPECT_TRUE(CheckPolicy(key::kURLBlocklist, base::Value(false))); EXPECT_EQ(1U, errors_.size()); @@ -87,12 +87,12 @@ EXPECT_EQ(expected, actual); } -TEST_F(URLBlacklistPolicyHandlerTest, ApplyPolicySettings_NothingSpecified) { +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_NothingSpecified) { ApplyPolicies(); EXPECT_FALSE(prefs_.GetValue(policy_prefs::kUrlBlacklist, nullptr)); } -TEST_F(URLBlacklistPolicyHandlerTest, +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_DisabledSchemesWrongType) { // The policy expects a list. Give it a boolean. SetPolicy(key::kDisabledSchemes, base::Value(false)); @@ -100,15 +100,15 @@ EXPECT_FALSE(prefs_.GetValue(policy_prefs::kUrlBlacklist, nullptr)); } -TEST_F(URLBlacklistPolicyHandlerTest, - ApplyPolicySettings_URLBlacklistWrongType) { +TEST_F(URLBlocklistPolicyHandlerTest, + ApplyPolicySettings_URLBlocklistWrongType) { // The policy expects a list. Give it a boolean. SetPolicy(key::kURLBlocklist, base::Value(false)); ApplyPolicies(); EXPECT_FALSE(prefs_.GetValue(policy_prefs::kUrlBlacklist, nullptr)); } -TEST_F(URLBlacklistPolicyHandlerTest, +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_DisabledSchemesEmpty) { SetPolicy(key::kDisabledSchemes, base::Value(base::Value::Type::LIST)); ApplyPolicies(); @@ -119,8 +119,7 @@ EXPECT_EQ(0U, out_list->GetSize()); } -TEST_F(URLBlacklistPolicyHandlerTest, - ApplyPolicySettings_URLBlacklistEmpty) { +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_URLBlocklistEmpty) { SetPolicy(key::kURLBlocklist, base::Value(base::Value::Type::LIST)); ApplyPolicies(); base::Value* out; @@ -130,7 +129,7 @@ EXPECT_EQ(0U, out_list->GetSize()); } -TEST_F(URLBlacklistPolicyHandlerTest, +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_DisabledSchemesWrongElementType) { // The policy expects string-valued elements. Give it booleans. base::Value in(base::Value::Type::LIST); @@ -146,8 +145,8 @@ EXPECT_EQ(0U, out_list->GetSize()); } -TEST_F(URLBlacklistPolicyHandlerTest, - ApplyPolicySettings_URLBlacklistWrongElementType) { +TEST_F(URLBlocklistPolicyHandlerTest, + ApplyPolicySettings_URLBlocklistWrongElementType) { // The policy expects string-valued elements. Give it booleans. base::Value in(base::Value::Type::LIST); in.Append(false); @@ -162,7 +161,7 @@ EXPECT_EQ(0U, out_list->GetSize()); } -TEST_F(URLBlacklistPolicyHandlerTest, +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_DisabledSchemesSuccessful) { base::Value in_disabled_schemes(base::Value::Type::LIST); in_disabled_schemes.Append(kTestDisabledScheme); @@ -180,11 +179,11 @@ EXPECT_EQ(kTestDisabledScheme + std::string("://*"), out_string); } -TEST_F(URLBlacklistPolicyHandlerTest, +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_URLBlocklistSuccessful) { - base::Value in_url_blacklist(base::Value::Type::LIST); - in_url_blacklist.Append(kTestBlacklistValue); - SetPolicy(key::kURLBlocklist, std::move(in_url_blacklist)); + base::Value in_url_blocklist(base::Value::Type::LIST); + in_url_blocklist.Append(kTestBlocklistValue); + SetPolicy(key::kURLBlocklist, std::move(in_url_blocklist)); ApplyPolicies(); base::Value* out; @@ -195,18 +194,17 @@ std::string out_string; EXPECT_TRUE(out_list->GetString(0U, &out_string)); - EXPECT_EQ(kTestBlacklistValue, out_string); + EXPECT_EQ(kTestBlocklistValue, out_string); } -TEST_F(URLBlacklistPolicyHandlerTest, ApplyPolicySettings_MergeSuccessful) { +TEST_F(URLBlocklistPolicyHandlerTest, ApplyPolicySettings_MergeSuccessful) { base::Value in_disabled_schemes(base::Value::Type::LIST); in_disabled_schemes.Append(kTestDisabledScheme); SetPolicy(key::kDisabledSchemes, std::move(in_disabled_schemes)); - base::Value in_url_blacklist(base::Value::Type::LIST); - in_url_blacklist.Append(kTestBlacklistValue); - SetPolicy(key::kURLBlocklist, std::move(in_url_blacklist)); - + base::Value in_url_blocklist(base::Value::Type::LIST); + in_url_blocklist.Append(kTestBlocklistValue); + SetPolicy(key::kURLBlocklist, std::move(in_url_blocklist)); ApplyPolicies(); base::Value* out; @@ -221,7 +219,7 @@ std::string out2; EXPECT_TRUE(out_list->GetString(1U, &out2)); - EXPECT_EQ(kTestBlacklistValue, out2); + EXPECT_EQ(kTestBlocklistValue, out2); } } // namespace policy
diff --git a/components/policy/core/browser/url_util.cc b/components/policy/core/browser/url_util.cc index eb9ee30..2d777545 100644 --- a/components/policy/core/browser/url_util.cc +++ b/components/policy/core/browser/url_util.cc
@@ -69,11 +69,11 @@ url::Component query_left = url::MakeRange(0, query.length()); url::Component key; url::Component value; - // Depending on the filter type being black-list or white-list, the matcher - // choose any or every match. The idea is a URL should be black-listed if - // there is any occurrence of the key value pair. It should be white-listed + // Depending on the filter type being block-list or allow-list, the matcher + // choose any or every match. The idea is a URL should be blocked if + // there is any occurrence of the key value pair. It should be allowed // only if every occurrence of the key is followed by the value. This avoids - // situations such as a user appending a white-listed video parameter in the + // situations such as a user appending an allowed video parameter in the // end of the query and watching a video of their choice (the last parameter // is ignored by some web servers like youtube's). URLQueryElementMatcherCondition::Type match_type = @@ -234,7 +234,7 @@ FilterComponents::~FilterComponents() = default; FilterComponents::FilterComponents(FilterComponents&&) = default; -bool FilterComponents::IsBlacklistWildcard() const { +bool FilterComponents::IsBlocklistWildcard() const { return !allow && host.empty() && scheme.empty() && path.empty() && query.empty() && port == 0 && number_of_key_value_pairs == 0 && match_subdomains;
diff --git a/components/policy/core/browser/url_util.h b/components/policy/core/browser/url_util.h index 3a7b7f4..3b1990da 100644 --- a/components/policy/core/browser/url_util.h +++ b/components/policy/core/browser/url_util.h
@@ -32,8 +32,8 @@ ~FilterComponents(); - // Returns true if |this| represents the "*" filter in the blacklist. - bool IsBlacklistWildcard() const; + // Returns true if |this| represents the "*" filter in the blocklist. + bool IsBlocklistWildcard() const; std::string scheme; std::string host; @@ -47,8 +47,8 @@ // Creates a condition set that can be used with the |url_matcher|. |id| needs // to be a unique number that will be returned by the |url_matcher| if the URL -// matches that condition set. |allow| indicates if it is a white-list (true) -// or black-list (false) filter. +// matches that condition set. |allow| indicates if it is an allow-list (true) +// or block-list (false) filter. POLICY_EXPORT scoped_refptr<url_matcher::URLMatcherConditionSet> CreateConditionSet(url_matcher::URLMatcher* url_matcher, url_matcher::URLMatcherConditionSet::ID id,
diff --git a/components/policy/proto/chrome_device_policy.proto b/components/policy/proto/chrome_device_policy.proto index 0b1000b4..d54c9e7f 100644 --- a/components/policy/proto/chrome_device_policy.proto +++ b/components/policy/proto/chrome_device_policy.proto
@@ -1291,6 +1291,13 @@ repeated string whitelist = 1; } +// The url and hash specified in JSON format that can be used to retrieve +// the device-level printers configuration file. +message DevicePrintersProto { + // External policy blob encoded as JSON. + optional string external_policy = 1; +} + // A collection of ids for the list of print servers which are accessible. // The policy which determines the type of access restriction that is applied to // the devicel-level printers list. @@ -1799,4 +1806,5 @@ optional DevicePrintersAccessModeProto device_printers_access_mode = 107; optional DevicePrintersBlocklistProto device_printers_blocklist = 108; optional DevicePrintersAllowlistProto device_printers_allowlist = 109; + optional DevicePrintersProto device_printers = 110; }
diff --git a/components/policy/proto/device_management_backend.proto b/components/policy/proto/device_management_backend.proto index fdcf42a..fd3337ce 100644 --- a/components/policy/proto/device_management_backend.proto +++ b/components/policy/proto/device_management_backend.proto
@@ -677,6 +677,7 @@ K12 = 1; UNIVERSITY = 2; NONPROFIT = 3; + ENTERPRISE = 4; } // Indicates the segment the user's metrics should be logged under,
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 4221904..5f35c98 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -1021,6 +1021,7 @@ 'DeviceNativePrintersAccessMode', 'DeviceNativePrintersBlacklist', 'DeviceNativePrintersWhitelist', + 'DevicePrinters', 'DevicePrintersAccessMode', 'DevicePrintersBlocklist', 'DevicePrintersAllowlist', @@ -14596,6 +14597,7 @@ 'dynamic_refresh': True, 'per_profile': False, }, + 'deprecated': True, 'example_value': { "url": "https://example.com/printerpolicy", "hash": "deadbeefdeadbeefdeadbeefdeadbeefdeafdeadbeefdeadbeef" @@ -14611,13 +14613,15 @@ The file is downloaded and cached. It will be re-downloaded whenever the URL or the hash changes. - If this policy is set, <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph> will download the file for printer configurations and make printers available in accordance with <ph name="DEVICE_PRINTERS_ACCESS_MODE">DeviceNativePrintersAccessMode</ph>, <ph name="DEVICE_PRINTERS_ALLOWLIST">DevicePrintersAllowlist</ph>, and <ph name="DEVICE_PRINTERS_BLOCKLIST">DevicePrintersBlocklist</ph>. + If this policy is set, <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph> will download the file for printer configurations and make printers available in accordance with <ph name="DEVICE_NATIVE_PRINTERS_ACCESS_MODE">DeviceNativePrintersAccessMode</ph>, <ph name="DEVICE_PRINTERS_ALLOWLIST">DevicePrintersAllowlist</ph>, and <ph name="DEVICE_PRINTERS_BLOCKLIST">DevicePrintersBlocklist</ph>. This policy has no effect on whether users can configure printers on individual devices. It is intended to be supplementary to the configuration of printers by individual users. This policy is additive to the <ph name="BULK_PRINTERS_POLICY">NativePrintersBulkConfiguration</ph>. - If this policy is unset, there will be no device printers and the other <ph name="DEVICE_PRINTERS_POLICY_PATTERN">DeviceNativePrinter*</ph> policies will be ignored. + If this policy is unset, there will be no device printers and the other <ph name="DEVICE_NATIVE_PRINTERS_POLICY_PATTERN">DeviceNativePrinter*</ph> policies will be ignored. + + This policy is deprecated, please use <ph name="DEVICE_PRINTERS">DevicePrinters</ph> instead. ''', }, { @@ -14721,6 +14725,48 @@ ''', }, { + 'name': 'DevicePrinters', + 'owners': ['skau@chromium.org', 'nikitapodguzov@chromium.org', 'bmalcolm@chromium.org'], + 'id': 743, + 'device_only': True, + 'type': 'external', + 'schema': { + 'type': 'object', + 'properties': { + 'url': { 'type': 'string' }, + 'hash': { 'type': 'string' } + }, + }, + 'supported_on': ['chrome_os:86-'], + 'features': { + 'dynamic_refresh': True, + 'per_profile': False, + }, + 'example_value': { + "url": "https://example.com/printerpolicy", + "hash": "deadbeefdeadbeefdeadbeefdeadbeefdeafdeadbeefdeadbeef" + }, + 'max_size': 5242880, + 'caption': '''Enterprise printer configuration file for devices''', + 'tags': [], + 'desc': '''Provides configurations for enterprise printers bound to devices. + + This policy allows you to provide printer configurations to <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph> devices. The format is the same as the NativePrinters dictionary, with an additional required "id" or "guid" field per printer for whitelisting or blacklisting. + + The size of the file must not exceed 5MB and must be encoded in JSON. It is estimated that a file containing approximately 21,000 printers will encode as a 5MB file. The cryptographic hash is used to verify the integrity of the download. + + The file is downloaded and cached. It will be re-downloaded whenever the URL or the hash changes. + + If this policy is set, <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph> will download the file for printer configurations and make printers available in accordance with <ph name="DEVICE_PRINTERS_ACCESS_MODE">DevicePrintersAccessMode</ph>, <ph name="DEVICE_PRINTERS_ALLOWLIST">DevicePrintersAllowlist</ph>, and <ph name="DEVICE_PRINTERS_BLOCKLIST">DevicePrintersBlocklist</ph>. + + This policy has no effect on whether users can configure printers on individual devices. It is intended to be supplementary to the configuration of printers by individual users. + + This policy is additive to the <ph name="BULK_PRINTERS_POLICY">NativePrintersBulkConfiguration</ph>. + + If this policy is unset, there will be no device printers and the other <ph name="DEVICE_PRINTERS_POLICY_PATTERN">DevicePrinter*</ph> policies will be ignored. + ''', + }, + { 'name': 'DevicePrintersAccessMode', 'owners': ['skau@chromium.org', 'nikitapodguzov@chromium.org'], 'id': 733, @@ -22361,7 +22407,6 @@ 'DeviceSecondFactorAuthentication': 'device_second_factor_authentication.mode', 'CastReceiverName': 'cast_receiver_name.name', 'DeviceNativePrintersAccessMode': 'native_device_printers_access_mode.access_mode', - 'DevicePrintersAccessMode': 'device_printers_access_mode.access_mode', 'MinimumRequiredChromeVersion': 'minimum_required_version.chrome_version', 'DeviceUserPolicyLoopbackProcessingMode': 'device_user_policy_loopback_processing_mode.mode', 'DeviceLoginScreenIsolateOrigins': 'device_login_screen_isolate_origins.isolate_origins', @@ -22369,6 +22414,8 @@ 'DeviceMachinePasswordChangeRate': 'device_machine_password_change_rate.rate_days', 'DeviceNativePrintersBlacklist': 'native_device_printers_blacklist.blacklist', 'DeviceNativePrintersWhitelist': 'native_device_printers_whitelist.whitelist', + 'DevicePrinters': 'device_printers.external_policy', + 'DevicePrintersAccessMode': 'device_printers_access_mode.access_mode', 'DevicePrintersBlocklist': 'device_printers_blocklist.blocklist', 'DevicePrintersAllowlist': 'device_printers_allowlist.allowlist', 'HeartbeatEnabled': 'device_heartbeat_settings.heartbeat_enabled', @@ -22955,6 +23002,6 @@ ], 'placeholders': [], 'deleted_policy_ids': [412, 476, 546, 562, 569, 578], - 'highest_id_currently_used': 742, + 'highest_id_currently_used': 743, 'highest_atomic_group_id_currently_used': 38 }
diff --git a/components/translate/core/browser/translate_script_unittest.cc b/components/translate/core/browser/translate_script_unittest.cc index 694c9594..341b7ea7 100644 --- a/components/translate/core/browser/translate_script_unittest.cc +++ b/components/translate/core/browser/translate_script_unittest.cc
@@ -14,7 +14,7 @@ #include "build/build_config.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/common/translate_switches.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "net/base/load_flags.h" #include "net/base/url_util.h" #include "net/http/http_request_headers.h" @@ -34,7 +34,7 @@ protected: void SetUp() override { - variations::VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + variations::VariationsIdsProvider::GetInstance()->ResetForTesting(); script_ = std::make_unique<TranslateScript>(); auto* translate_download_manager = TranslateDownloadManager::GetInstance(); translate_download_manager->set_application_locale("en");
diff --git a/components/update_client/update_client.cc b/components/update_client/update_client.cc index d45af8b..20c33976 100644 --- a/components/update_client/update_client.cc +++ b/components/update_client/update_client.cc
@@ -65,8 +65,7 @@ scoped_refptr<PingManager> ping_manager, UpdateChecker::Factory update_checker_factory, CrxDownloader::Factory crx_downloader_factory) - : is_stopped_(false), - config_(config), + : config_(config), ping_manager_(ping_manager), update_engine_(base::MakeRefCounted<UpdateEngine>( config,
diff --git a/components/variations/BUILD.gn b/components/variations/BUILD.gn index 00b7349..a8f2ea1 100644 --- a/components/variations/BUILD.gn +++ b/components/variations/BUILD.gn
@@ -45,10 +45,10 @@ "variations_client.h", "variations_crash_keys.cc", "variations_crash_keys.h", - "variations_http_header_provider.cc", - "variations_http_header_provider.h", "variations_id_collection.cc", "variations_id_collection.h", + "variations_ids_provider.cc", + "variations_ids_provider.h", "variations_murmur_hash.cc", "variations_murmur_hash.h", "variations_request_scheduler.cc", @@ -135,8 +135,8 @@ "synthetic_trial_registry_unittest.cc", "variations_associated_data_unittest.cc", "variations_crash_keys_unittest.cc", - "variations_http_header_provider_unittest.cc", "variations_id_collection_unittest.cc", + "variations_ids_provider_unittest.cc", "variations_murmur_hash_unittest.cc", "variations_request_scheduler_unittest.cc", "variations_seed_processor_unittest.cc",
diff --git a/components/variations/android/variations_associated_data_android.cc b/components/variations/android/variations_associated_data_android.cc index 6b12a306..cd40b92 100644 --- a/components/variations/android/variations_associated_data_android.cc +++ b/components/variations/android/variations_associated_data_android.cc
@@ -7,7 +7,7 @@ #include "base/android/jni_string.h" #include "components/variations/jni/VariationsAssociatedData_jni.h" #include "components/variations/variations_associated_data.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; @@ -31,14 +31,14 @@ ScopedJavaLocalRef<jstring> JNI_VariationsAssociatedData_GetFeedbackVariations( JNIEnv* env) { const std::string values = - VariationsHttpHeaderProvider::GetInstance()->GetVariationsString(); + VariationsIdsProvider::GetInstance()->GetVariationsString(); return ConvertUTF8ToJavaString(env, values); } ScopedJavaLocalRef<jstring> JNI_VariationsAssociatedData_GetGoogleAppVariations( JNIEnv* env) { - const std::string values = VariationsHttpHeaderProvider::GetInstance() - ->GetGoogleAppVariationsString(); + const std::string values = + VariationsIdsProvider::GetInstance()->GetGoogleAppVariationsString(); return ConvertUTF8ToJavaString(env, values); }
diff --git a/components/variations/net/variations_http_headers.cc b/components/variations/net/variations_http_headers.cc index cfcff18d..a55d1de 100644 --- a/components/variations/net/variations_http_headers.cc +++ b/components/variations/net/variations_http_headers.cc
@@ -16,7 +16,7 @@ #include "base/strings/string_util.h" #include "components/google/core/common/google_util.h" #include "components/variations/net/omnibox_http_headers.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "net/base/isolation_info.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/redirect_info.h" @@ -235,7 +235,7 @@ private: static std::string CreateVariationsHeader(SignedIn signed_in) { - return VariationsHttpHeaderProvider::GetInstance()->GetClientDataHeader( + return VariationsIdsProvider::GetInstance()->GetClientDataHeader( signed_in == SignedIn::kYes); }
diff --git a/components/variations/net/variations_http_headers_unittest.cc b/components/variations/net/variations_http_headers_unittest.cc index bf3ccdc..560e67d 100644 --- a/components/variations/net/variations_http_headers_unittest.cc +++ b/components/variations/net/variations_http_headers_unittest.cc
@@ -224,8 +224,8 @@ // Required to use ObserverListThreadSafe::AddObserver() from: // base::FieldTrialList::AddObserver - // variations::VariationsHttpHeaderProvider::InitVariationIDsCacheIfNeeded - // variations::VariationsHttpHeaderProvider::GetClientDataHeader + // variations::VariationsIdsProvider::InitVariationIDsCacheIfNeeded + // variations::VariationsIdsProvider::GetClientDataHeader // variations::VariationsHeaderHelper::VariationsHeaderHelper // variations::AppendVariationsHeaderUnknownSignedIn base::test::SingleThreadTaskEnvironment task_environment_;
diff --git a/components/variations/net/variations_url_loader_throttle.cc b/components/variations/net/variations_url_loader_throttle.cc index c0e6b5d..665eb9ee 100644 --- a/components/variations/net/variations_url_loader_throttle.cc +++ b/components/variations/net/variations_url_loader_throttle.cc
@@ -7,7 +7,7 @@ #include "components/google/core/common/google_util.h" #include "components/variations/net/variations_http_headers.h" #include "components/variations/variations_client.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "url/gurl.h"
diff --git a/components/variations/service/variations_field_trial_creator.cc b/components/variations/service/variations_field_trial_creator.cc index 386b858..d585338 100644 --- a/components/variations/service/variations_field_trial_creator.cc +++ b/components/variations/service/variations_field_trial_creator.cc
@@ -36,7 +36,7 @@ #include "components/variations/service/safe_seed_manager.h" #include "components/variations/service/variations_service.h" #include "components/variations/service/variations_service_client.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "components/variations/variations_seed_processor.h" #include "components/variations/variations_switches.h" #include "ui/base/device_form_factor.h" @@ -481,24 +481,24 @@ } } - VariationsHttpHeaderProvider* http_header_provider = - VariationsHttpHeaderProvider::GetInstance(); + VariationsIdsProvider* http_header_provider = + VariationsIdsProvider::GetInstance(); // Force the variation ids selected in chrome://flags and/or specified using // the command-line flag. auto result = http_header_provider->ForceVariationIds( variation_ids, command_line->GetSwitchValueASCII(switches::kForceVariationIds)); switch (result) { - case VariationsHttpHeaderProvider::ForceIdsResult::INVALID_SWITCH_ENTRY: + case VariationsIdsProvider::ForceIdsResult::INVALID_SWITCH_ENTRY: ExitWithMessage(base::StringPrintf("Invalid --%s list specified.", switches::kForceVariationIds)); break; - case VariationsHttpHeaderProvider::ForceIdsResult::INVALID_VECTOR_ENTRY: + case VariationsIdsProvider::ForceIdsResult::INVALID_VECTOR_ENTRY: // It should not be possible to have invalid variation ids from the // vector param (which corresponds to chrome://flags). NOTREACHED(); break; - case VariationsHttpHeaderProvider::ForceIdsResult::SUCCESS: + case VariationsIdsProvider::ForceIdsResult::SUCCESS: break; }
diff --git a/components/variations/variations_associated_data.cc b/components/variations/variations_associated_data.cc index 5ca29b0..7dc9ae2 100644 --- a/components/variations/variations_associated_data.cc +++ b/components/variations/variations_associated_data.cc
@@ -14,7 +14,7 @@ #include "base/metrics/field_trial_param_associator.h" #include "base/metrics/field_trial_params.h" #include "base/strings/string_split.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" namespace variations {
diff --git a/components/variations/variations_http_header_provider.cc b/components/variations/variations_ids_provider.cc similarity index 85% rename from components/variations/variations_http_header_provider.cc rename to components/variations/variations_ids_provider.cc index 7433a3a6..a1b6e92 100644 --- a/components/variations/variations_http_header_provider.cc +++ b/components/variations/variations_ids_provider.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/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include <stddef.h> @@ -36,12 +36,11 @@ // function variations::CreateSimpleURLLoaderWithVariationsHeader(). // static -VariationsHttpHeaderProvider* VariationsHttpHeaderProvider::GetInstance() { - return base::Singleton<VariationsHttpHeaderProvider>::get(); +VariationsIdsProvider* VariationsIdsProvider::GetInstance() { + return base::Singleton<VariationsIdsProvider>::get(); } -std::string VariationsHttpHeaderProvider::GetClientDataHeader( - bool is_signed_in) { +std::string VariationsIdsProvider::GetClientDataHeader(bool is_signed_in) { // Lazily initialize the header, if not already done, before attempting to // transmit it. InitVariationIDsCacheIfNeeded(); @@ -56,8 +55,7 @@ return variation_ids_header_copy; } -std::string VariationsHttpHeaderProvider::GetVariationsString( - IDCollectionKey key) { +std::string VariationsIdsProvider::GetVariationsString(IDCollectionKey key) { InitVariationIDsCacheIfNeeded(); // Construct a space-separated string with leading and trailing spaces from @@ -76,21 +74,21 @@ return ids_string; } -std::string VariationsHttpHeaderProvider::GetGoogleAppVariationsString() { +std::string VariationsIdsProvider::GetGoogleAppVariationsString() { return GetVariationsString(GOOGLE_APP); } -std::string VariationsHttpHeaderProvider::GetVariationsString() { +std::string VariationsIdsProvider::GetVariationsString() { return GetVariationsString(GOOGLE_WEB_PROPERTIES); } -std::vector<VariationID> VariationsHttpHeaderProvider::GetVariationsVector( +std::vector<VariationID> VariationsIdsProvider::GetVariationsVector( IDCollectionKey key) { return GetVariationsVectorImpl(std::set<IDCollectionKey>{key}); } std::vector<VariationID> -VariationsHttpHeaderProvider::GetVariationsVectorForWebPropertiesKeys() { +VariationsIdsProvider::GetVariationsVectorForWebPropertiesKeys() { const std::set<IDCollectionKey> web_properties_keys{ variations::GOOGLE_WEB_PROPERTIES, variations::GOOGLE_WEB_PROPERTIES_SIGNED_IN, @@ -98,8 +96,7 @@ return GetVariationsVectorImpl(web_properties_keys); } -VariationsHttpHeaderProvider::ForceIdsResult -VariationsHttpHeaderProvider::ForceVariationIds( +VariationsIdsProvider::ForceIdsResult VariationsIdsProvider::ForceVariationIds( const std::vector<std::string>& variation_ids, const std::string& command_line_variation_ids) { default_variation_ids_set_.clear(); @@ -114,22 +111,22 @@ return ForceIdsResult::SUCCESS; } -bool VariationsHttpHeaderProvider::ForceDisableVariationIds( +bool VariationsIdsProvider::ForceDisableVariationIds( const std::string& command_line_variation_ids) { force_disabled_ids_set_.clear(); return ParseVariationIdsParameter(command_line_variation_ids, &force_disabled_ids_set_); } -void VariationsHttpHeaderProvider::AddObserver(Observer* observer) { +void VariationsIdsProvider::AddObserver(Observer* observer) { observer_list_.AddObserver(observer); } -void VariationsHttpHeaderProvider::RemoveObserver(Observer* observer) { +void VariationsIdsProvider::RemoveObserver(Observer* observer) { observer_list_.RemoveObserver(observer); } -void VariationsHttpHeaderProvider::ResetForTesting() { +void VariationsIdsProvider::ResetForTesting() { base::AutoLock scoped_lock(lock_); // Stop observing field trials so that it can be restarted when this is @@ -144,14 +141,14 @@ cached_variation_ids_header_signed_in_.clear(); } -VariationsHttpHeaderProvider::VariationsHttpHeaderProvider() +VariationsIdsProvider::VariationsIdsProvider() : variation_ids_cache_initialized_(false) {} -VariationsHttpHeaderProvider::~VariationsHttpHeaderProvider() { +VariationsIdsProvider::~VariationsIdsProvider() { base::FieldTrialList::RemoveObserver(this); } -void VariationsHttpHeaderProvider::OnFieldTrialGroupFinalized( +void VariationsIdsProvider::OnFieldTrialGroupFinalized( const std::string& trial_name, const std::string& group_name) { base::AutoLock scoped_lock(lock_); @@ -164,7 +161,7 @@ UpdateVariationIDsHeaderValue(); } -void VariationsHttpHeaderProvider::OnSyntheticTrialsChanged( +void VariationsIdsProvider::OnSyntheticTrialsChanged( const std::vector<SyntheticTrialGroup>& groups) { base::AutoLock scoped_lock(lock_); @@ -188,7 +185,7 @@ UpdateVariationIDsHeaderValue(); } -void VariationsHttpHeaderProvider::InitVariationIDsCacheIfNeeded() { +void VariationsIdsProvider::InitVariationIDsCacheIfNeeded() { base::AutoLock scoped_lock(lock_); if (variation_ids_cache_initialized_) return; @@ -215,16 +212,15 @@ variation_ids_cache_initialized_ = true; } -void VariationsHttpHeaderProvider::CacheVariationsId( - const std::string& trial_name, - const std::string& group_name, - IDCollectionKey key) { +void VariationsIdsProvider::CacheVariationsId(const std::string& trial_name, + const std::string& group_name, + IDCollectionKey key) { const VariationID id = GetGoogleVariationID(key, trial_name, group_name); if (id != EMPTY_ID) variation_ids_set_.insert(VariationIDEntry(id, key)); } -void VariationsHttpHeaderProvider::UpdateVariationIDsHeaderValue() { +void VariationsIdsProvider::UpdateVariationIDsHeaderValue() { lock_.AssertAcquired(); // The header value is a serialized protobuffer of Variation IDs which is @@ -244,7 +240,7 @@ } } -std::string VariationsHttpHeaderProvider::GenerateBase64EncodedProto( +std::string VariationsIdsProvider::GenerateBase64EncodedProto( bool is_signed_in) { std::set<VariationIDEntry> all_variation_ids_set = GetAllVariationIds(); @@ -295,7 +291,7 @@ } // static -bool VariationsHttpHeaderProvider::AddVariationIdsToSet( +bool VariationsIdsProvider::AddVariationIdsToSet( const std::vector<std::string>& variation_ids, std::set<VariationIDEntry>* target_set) { for (const std::string& entry : variation_ids) { @@ -321,7 +317,7 @@ } // static -bool VariationsHttpHeaderProvider::ParseVariationIdsParameter( +bool VariationsIdsProvider::ParseVariationIdsParameter( const std::string& command_line_variation_ids, std::set<VariationIDEntry>* target_set) { if (command_line_variation_ids.empty()) @@ -333,8 +329,8 @@ return AddVariationIdsToSet(variation_ids_from_command_line, target_set); } -std::set<VariationsHttpHeaderProvider::VariationIDEntry> -VariationsHttpHeaderProvider::GetAllVariationIds() { +std::set<VariationsIdsProvider::VariationIDEntry> +VariationsIdsProvider::GetAllVariationIds() { lock_.AssertAcquired(); std::set<VariationIDEntry> all_variation_ids_set = default_variation_ids_set_; @@ -350,7 +346,7 @@ return all_variation_ids_set; } -std::vector<VariationID> VariationsHttpHeaderProvider::GetVariationsVectorImpl( +std::vector<VariationID> VariationsIdsProvider::GetVariationsVectorImpl( const std::set<IDCollectionKey>& keys) { InitVariationIDsCacheIfNeeded();
diff --git a/components/variations/variations_http_header_provider.h b/components/variations/variations_ids_provider.h similarity index 84% rename from components/variations/variations_http_header_provider.h rename to components/variations/variations_ids_provider.h index 206fdbaa..1743c9a 100644 --- a/components/variations/variations_http_header_provider.h +++ b/components/variations/variations_ids_provider.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_VARIATIONS_VARIATIONS_HTTP_HEADER_PROVIDER_H_ -#define COMPONENTS_VARIATIONS_VARIATIONS_HTTP_HEADER_PROVIDER_H_ +#ifndef COMPONENTS_VARIATIONS_VARIATIONS_IDS_PROVIDER_H_ +#define COMPONENTS_VARIATIONS_VARIATIONS_IDS_PROVIDER_H_ #include <set> #include <string> @@ -29,8 +29,8 @@ // A helper class for maintaining client experiments and metrics state // transmitted in custom HTTP request headers. // This class is a thread-safe singleton. -class VariationsHttpHeaderProvider : public base::FieldTrialList::Observer, - public SyntheticTrialObserver { +class VariationsIdsProvider : public base::FieldTrialList::Observer, + public SyntheticTrialObserver { public: class Observer { public: @@ -41,7 +41,7 @@ virtual ~Observer() {} }; - static VariationsHttpHeaderProvider* GetInstance(); + static VariationsIdsProvider* GetInstance(); // Returns the value of the client data header, computing and caching it if // necessary. If |is_signed_in| is false, variation ids that should only be @@ -103,35 +103,31 @@ void ResetForTesting(); private: - friend struct base::DefaultSingletonTraits<VariationsHttpHeaderProvider>; + friend struct base::DefaultSingletonTraits<VariationsIdsProvider>; typedef std::pair<VariationID, IDCollectionKey> VariationIDEntry; - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, - ForceVariationIds_Valid); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, ForceVariationIds_Valid); + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, ForceVariationIds_ValidCommandLine); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, ForceVariationIds_Invalid); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, ForceDisableVariationIds_ValidCommandLine); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, ForceDisableVariationIds_Invalid); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, OnFieldTrialGroupFinalized); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, GetGoogleAppVariationsString); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, - GetVariationsString); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, - GetVariationsVector); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, GetVariationsString); + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, GetVariationsVector); + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, GetVariationsVectorForWebPropertiesKeys); - FRIEND_TEST_ALL_PREFIXES(VariationsHttpHeaderProviderTest, - GetVariationsVectorImpl); + FRIEND_TEST_ALL_PREFIXES(VariationsIdsProviderTest, GetVariationsVectorImpl); - VariationsHttpHeaderProvider(); - ~VariationsHttpHeaderProvider() override; + VariationsIdsProvider(); + ~VariationsIdsProvider() override; // Returns a space-separated string containing the list of current active // variations (as would be reported in the |variation_id| repeated field of @@ -217,9 +213,9 @@ const VariationsClient* variations_client_ = nullptr; - DISALLOW_COPY_AND_ASSIGN(VariationsHttpHeaderProvider); + DISALLOW_COPY_AND_ASSIGN(VariationsIdsProvider); }; } // namespace variations -#endif // COMPONENTS_VARIATIONS_VARIATIONS_HTTP_HEADER_PROVIDER_H_ +#endif // COMPONENTS_VARIATIONS_VARIATIONS_IDS_PROVIDER_H_
diff --git a/components/variations/variations_http_header_provider_unittest.cc b/components/variations/variations_ids_provider_unittest.cc similarity index 84% rename from components/variations/variations_http_header_provider_unittest.cc rename to components/variations/variations_ids_provider_unittest.cc index 5f864eb..18e25ce7 100644 --- a/components/variations/variations_http_header_provider_unittest.cc +++ b/components/variations/variations_ids_provider_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/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include <string> @@ -57,22 +57,22 @@ } // namespace -class VariationsHttpHeaderProviderTest : public ::testing::Test { +class VariationsIdsProviderTest : public ::testing::Test { public: - VariationsHttpHeaderProviderTest() {} + VariationsIdsProviderTest() {} - ~VariationsHttpHeaderProviderTest() override {} + ~VariationsIdsProviderTest() override {} void TearDown() override { testing::ClearAllVariationIDs(); } base::test::SingleThreadTaskEnvironment task_environment_; }; -TEST_F(VariationsHttpHeaderProviderTest, ForceVariationIds_Valid) { - VariationsHttpHeaderProvider provider; +TEST_F(VariationsIdsProviderTest, ForceVariationIds_Valid) { + VariationsIdsProvider provider; // Valid experiment ids. - EXPECT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::SUCCESS, + EXPECT_EQ(VariationsIdsProvider::ForceIdsResult::SUCCESS, provider.ForceVariationIds({"12", "456", "t789"}, "")); provider.InitVariationIDsCacheIfNeeded(); std::string variations = provider.GetClientDataHeader(false); @@ -86,11 +86,11 @@ EXPECT_FALSE(variation_ids.find(789) != variation_ids.end()); } -TEST_F(VariationsHttpHeaderProviderTest, ForceVariationIds_ValidCommandLine) { - VariationsHttpHeaderProvider provider; +TEST_F(VariationsIdsProviderTest, ForceVariationIds_ValidCommandLine) { + VariationsIdsProvider provider; // Valid experiment ids. - EXPECT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::SUCCESS, + EXPECT_EQ(VariationsIdsProvider::ForceIdsResult::SUCCESS, provider.ForceVariationIds({"12"}, "456,t789")); provider.InitVariationIDsCacheIfNeeded(); std::string variations = provider.GetClientDataHeader(false); @@ -104,34 +104,33 @@ EXPECT_FALSE(variation_ids.find(789) != variation_ids.end()); } -TEST_F(VariationsHttpHeaderProviderTest, ForceVariationIds_Invalid) { - VariationsHttpHeaderProvider provider; +TEST_F(VariationsIdsProviderTest, ForceVariationIds_Invalid) { + VariationsIdsProvider provider; // Invalid experiment ids. - EXPECT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::INVALID_VECTOR_ENTRY, + EXPECT_EQ(VariationsIdsProvider::ForceIdsResult::INVALID_VECTOR_ENTRY, provider.ForceVariationIds({"abcd12", "456"}, "")); provider.InitVariationIDsCacheIfNeeded(); EXPECT_TRUE(provider.GetClientDataHeader(false).empty()); // Invalid trigger experiment id - EXPECT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::INVALID_VECTOR_ENTRY, + EXPECT_EQ(VariationsIdsProvider::ForceIdsResult::INVALID_VECTOR_ENTRY, provider.ForceVariationIds({"12", "tabc456"}, "")); provider.InitVariationIDsCacheIfNeeded(); EXPECT_TRUE(provider.GetClientDataHeader(false).empty()); // Invalid command-line ids. - EXPECT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::INVALID_SWITCH_ENTRY, + EXPECT_EQ(VariationsIdsProvider::ForceIdsResult::INVALID_SWITCH_ENTRY, provider.ForceVariationIds({"12", "50"}, "tabc456")); provider.InitVariationIDsCacheIfNeeded(); EXPECT_TRUE(provider.GetClientDataHeader(false).empty()); } -TEST_F(VariationsHttpHeaderProviderTest, - ForceDisableVariationIds_ValidCommandLine) { - VariationsHttpHeaderProvider provider; +TEST_F(VariationsIdsProviderTest, ForceDisableVariationIds_ValidCommandLine) { + VariationsIdsProvider provider; // Valid experiment ids. - EXPECT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::SUCCESS, + EXPECT_EQ(VariationsIdsProvider::ForceIdsResult::SUCCESS, provider.ForceVariationIds({"1", "2", "t3", "t4"}, "5,6,t7,t8")); EXPECT_TRUE(provider.ForceDisableVariationIds("2,t4,6,t8")); provider.InitVariationIDsCacheIfNeeded(); @@ -150,8 +149,8 @@ EXPECT_FALSE(trigger_ids.find(8) != trigger_ids.end()); } -TEST_F(VariationsHttpHeaderProviderTest, ForceDisableVariationIds_Invalid) { - VariationsHttpHeaderProvider provider; +TEST_F(VariationsIdsProviderTest, ForceDisableVariationIds_Invalid) { + VariationsIdsProvider provider; // Invalid command-line ids. EXPECT_FALSE(provider.ForceDisableVariationIds("abc")); @@ -160,8 +159,8 @@ EXPECT_TRUE(provider.GetClientDataHeader(false).empty()); } -TEST_F(VariationsHttpHeaderProviderTest, OnFieldTrialGroupFinalized) { - VariationsHttpHeaderProvider provider; +TEST_F(VariationsIdsProviderTest, OnFieldTrialGroupFinalized) { + VariationsIdsProvider provider; provider.InitVariationIDsCacheIfNeeded(); const std::string default_name = "default"; @@ -207,7 +206,7 @@ } } -TEST_F(VariationsHttpHeaderProviderTest, GetGoogleAppVariationsString) { +TEST_F(VariationsIdsProviderTest, GetGoogleAppVariationsString) { // All GOOGLE_WEB_PROPERTIES(_X) ids shouldn't be included. CreateTrialAndAssociateId("t1", "g1", GOOGLE_WEB_PROPERTIES, 123); CreateTrialAndAssociateId("t2", "g2", GOOGLE_WEB_PROPERTIES, 124); @@ -216,12 +215,12 @@ // GOOGLE_APP ids should be included. CreateTrialAndAssociateId("t4", "g4", GOOGLE_APP, 126); - VariationsHttpHeaderProvider provider; + VariationsIdsProvider provider; provider.ForceVariationIds({"100", "200"}, ""); EXPECT_EQ(" 126 ", provider.GetGoogleAppVariationsString()); } -TEST_F(VariationsHttpHeaderProviderTest, GetVariationsString) { +TEST_F(VariationsIdsProviderTest, GetVariationsString) { CreateTrialAndAssociateId("t1", "g1", GOOGLE_WEB_PROPERTIES, 123); CreateTrialAndAssociateId("t2", "g2", GOOGLE_WEB_PROPERTIES, 124); // SIGNED_IN ids shouldn't be included. @@ -229,12 +228,12 @@ // GOOGLE_APP ids shouldn't be included. CreateTrialAndAssociateId("t4", "g4", GOOGLE_APP, 126); - VariationsHttpHeaderProvider provider; + VariationsIdsProvider provider; provider.ForceVariationIds({"100", "200"}, ""); EXPECT_EQ(" 100 123 124 200 ", provider.GetVariationsString()); } -TEST_F(VariationsHttpHeaderProviderTest, GetVariationsVector) { +TEST_F(VariationsIdsProviderTest, GetVariationsVector) { CreateTrialAndAssociateId("t1", "g1", GOOGLE_WEB_PROPERTIES, 121); CreateTrialAndAssociateId("t2", "g2", GOOGLE_WEB_PROPERTIES, 122); CreateTrialAndAssociateId("t3", "g3", GOOGLE_WEB_PROPERTIES_TRIGGER, 123); @@ -242,7 +241,7 @@ CreateTrialAndAssociateId("t5", "g5", GOOGLE_WEB_PROPERTIES_SIGNED_IN, 125); CreateTrialAndAssociateId("t6", "g6", GOOGLE_APP, 126); - VariationsHttpHeaderProvider provider; + VariationsIdsProvider provider; provider.ForceVariationIds({"100", "200", "t101"}, ""); EXPECT_EQ((std::vector<VariationID>{100, 121, 122, 200}), @@ -255,19 +254,18 @@ provider.GetVariationsVector(GOOGLE_APP)); } -TEST_F(VariationsHttpHeaderProviderTest, - GetVariationsVectorForWebPropertiesKeys) { +TEST_F(VariationsIdsProviderTest, GetVariationsVectorForWebPropertiesKeys) { CreateTrialAndAssociateId("t1", "g1", GOOGLE_WEB_PROPERTIES, 121); CreateTrialAndAssociateId("t2", "g2", GOOGLE_WEB_PROPERTIES_TRIGGER, 122); CreateTrialAndAssociateId("t3", "g3", GOOGLE_WEB_PROPERTIES_SIGNED_IN, 123); CreateTrialAndAssociateId("t4", "g4", GOOGLE_APP, 124); // Will be excluded. - VariationsHttpHeaderProvider provider; + VariationsIdsProvider provider; provider.ForceVariationIds({"100", "t101"}, ""); EXPECT_EQ((std::vector<VariationID>{100, 101, 121, 122, 123}), provider.GetVariationsVectorForWebPropertiesKeys()); } -TEST_F(VariationsHttpHeaderProviderTest, GetVariationsVectorImpl) { +TEST_F(VariationsIdsProviderTest, GetVariationsVectorImpl) { CreateTrialAndAssociateId("t1", "g1", GOOGLE_WEB_PROPERTIES, 121); CreateTrialAndAssociateId("t2", "g2", GOOGLE_WEB_PROPERTIES, 122); CreateTrialAndAssociateId("t3", "g3", GOOGLE_WEB_PROPERTIES_TRIGGER, 123); @@ -277,7 +275,7 @@ 124); // Note: Duplicate. CreateTrialAndAssociateId("t7", "g7", GOOGLE_APP, 126); - VariationsHttpHeaderProvider provider; + VariationsIdsProvider provider; provider.ForceVariationIds({"100", "200", "t101"}, ""); EXPECT_EQ((std::vector<VariationID>{100, 101, 121, 122, 123, 124, 200}),
diff --git a/content/app_shim_remote_cocoa/render_widget_host_view_cocoa.mm b/content/app_shim_remote_cocoa/render_widget_host_view_cocoa.mm index bd3c6c1..eae6d8c3 100644 --- a/content/app_shim_remote_cocoa/render_widget_host_view_cocoa.mm +++ b/content/app_shim_remote_cocoa/render_widget_host_view_cocoa.mm
@@ -120,78 +120,6 @@ base::ClampToRange(static_cast<int>(lroundf(255.0f * b)), 0, 255); } -// TODO(bokan): Added temporarily to debug https://crbug.com/1039833. -// Needed only in temporary method below. -CommandDispatcher* GetCommandDispatcher(NSWindow* theWindow) { - if ([theWindow conformsToProtocol:@protocol(CommandDispatchingWindow)]) { - return [static_cast<NSObject<CommandDispatchingWindow>*>(theWindow) - commandDispatcher]; - } - return nil; -} - -// TODO(bokan): Added temporarily to debug https://crbug.com/1039833. -// Returns a string with class names of each ancestor view of this one -// (inclusive). -std::string GetViewHierarchyString(NSView* thisView) { - std::string ret = ""; - NSView* view = thisView; - while (view) { - ret += base::SysNSStringToUTF8(NSStringFromClass([view class])) + "->"; - view = [view superview]; - } - - return ret; -} - -// TODO(bokan): Added temporarily to debug https://crbug.com/1039833. -// Returns a string with information about all the app's windows and current -// event redispatch state of this window and the event's window. -std::string GetWindowInfoString(NSWindow* thisWindow, NSEvent* theEvent) { - std::string windowInfoStr = "["; - NSArray* windows = [NSApp windows]; - bool foundEventWindow = false; - for (unsigned int i = 0; i < [windows count]; ++i) { - NSWindow* window = windows[i]; - if (thisWindow == window) - windowInfoStr += "S-"; - if ([NSApp keyWindow] == window) - windowInfoStr += "K-"; - if ([NSApp mainWindow] == window) - windowInfoStr += "M-"; - if ([theEvent windowNumber] == [window windowNumber]) { - foundEventWindow = true; - windowInfoStr += "E-"; - } - - std::string className = - base::SysNSStringToUTF8(NSStringFromClass([window class])); - NSRect rect = [window frame]; - windowInfoStr += base::StringPrintf( - "%ld<%s - %dx%d>, ", static_cast<long>([window windowNumber]), - className.c_str(), static_cast<int>(NSWidth(rect)), - static_cast<int>(NSHeight(rect))); - } - windowInfoStr += "]"; - - if (!foundEventWindow) - windowInfoStr += base::StringPrintf( - " E: %ld", static_cast<long>([theEvent windowNumber])); - - windowInfoStr += base::StringPrintf( - " R[t:%d e:%d]", - GetCommandDispatcher(thisWindow) == nil - ? -1 - : static_cast<int>( - [GetCommandDispatcher(thisWindow) isRedispatchingKeyEvent]), - GetCommandDispatcher([theEvent window]) == nil - ? -1 - : static_cast<int>([GetCommandDispatcher([theEvent window]) - isRedispatchingKeyEvent])); - - return windowInfoStr; -} - // Extract underline information from an attributed string. Mostly copied from // third_party/WebKit/Source/WebKit/mac/WebView/WebHTMLView.mm void ExtractUnderlines(NSAttributedString* string, @@ -1006,16 +934,6 @@ - (void)keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv { TRACE_EVENT1("browser", "RenderWidgetHostViewCocoa::keyEvent", "WindowNum", [[self window] windowNumber]); - // TODO(bokan): Added temporarily to debug https://crbug.com/1039833. - static auto* windowInfoKey = base::debug::AllocateCrashKeyString( - "window-info", base::debug::CrashKeySize::Size256); - static auto* viewInfoKey = base::debug::AllocateCrashKeyString( - "view-info", base::debug::CrashKeySize::Size256); - base::debug::ScopedCrashKeyString scopedKeyWindow( - windowInfoKey, GetWindowInfoString([self window], theEvent)); - base::debug::ScopedCrashKeyString scopedKeyView(viewInfoKey, - GetViewHierarchyString(self)); - NSEventType eventType = [theEvent type]; NSEventModifierFlags modifierFlags = [theEvent modifierFlags]; int keyCode = [theEvent keyCode];
diff --git a/content/browser/DEPS b/content/browser/DEPS index 3ed4033..3b03c6f1 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -35,7 +35,7 @@ "+components/ukm", "+components/url_formatter", "+components/variations/variations_client.h", - "+components/variations/variations_http_header_provider.h", + "+components/variations/variations_ids_provider.h", "+components/variations/net", "+components/viz", "+components/web_package", @@ -123,7 +123,7 @@ "+third_party/blink/public/web/web_ax_enums.h", "+third_party/blink/public/web/web_console_message.h", "+third_party/blink/public/web/web_context_menu_data.h", - "+third_party/blink/public/web/web_device_emulation_params.h", + "+third_party/blink/public/common/widget/device_emulation_params.h", "+third_party/blink/public/web/web_drag_status.h", "+third_party/blink/public/web/web_serialized_script_value_version.h", "+third_party/blink/public/mojom/frame/tree_scope_type.mojom.h",
diff --git a/content/browser/accessibility/browser_accessibility_manager_mac.mm b/content/browser/accessibility/browser_accessibility_manager_mac.mm index aaf53dd..fa74e328 100644 --- a/content/browser/accessibility/browser_accessibility_manager_mac.mm +++ b/content/browser/accessibility/browser_accessibility_manager_mac.mm
@@ -140,11 +140,6 @@ if (!focus) return nullptr; - // For editable combo boxes, focus should stay on the combo box so the user - // will not be taken out of the combo box while typing. - if (focus->GetRole() == ax::mojom::Role::kTextFieldWithComboBox) - return focus; - // Otherwise, follow the active descendant. return GetActiveDescendant(focus); }
diff --git a/content/browser/devtools/protocol/emulation_handler.cc b/content/browser/devtools/protocol/emulation_handler.cc index a6ffaf2..d6a569c 100644 --- a/content/browser/devtools/protocol/emulation_handler.cc +++ b/content/browser/devtools/protocol/emulation_handler.cc
@@ -281,9 +281,9 @@ } } - blink::WebDeviceEmulationParams params; - params.screen_position = mobile ? blink::WebDeviceEmulationParams::kMobile - : blink::WebDeviceEmulationParams::kDesktop; + blink::DeviceEmulationParams params; + params.screen_type = mobile ? blink::mojom::EmulatedScreenType::kMobile + : blink::mojom::EmulatedScreenType::kDesktop; params.screen_size = blink::WebSize(screen_width.fromMaybe(0), screen_height.fromMaybe(0)); if (position_x.isJust() && position_y.isJust()) { @@ -356,7 +356,7 @@ return Response::ServerError("Can't find the associated web contents"); GetWebContents()->ClearDeviceEmulationSize(); device_emulation_enabled_ = false; - device_emulation_params_ = blink::WebDeviceEmulationParams(); + device_emulation_params_ = blink::DeviceEmulationParams(); UpdateDeviceEmulationState(); // Renderer should answer after emulation was disabled, so that the response // is only sent to the client once updates were applied. @@ -459,13 +459,13 @@ return Response::FallThrough(); } -blink::WebDeviceEmulationParams EmulationHandler::GetDeviceEmulationParams() { +blink::DeviceEmulationParams EmulationHandler::GetDeviceEmulationParams() { return device_emulation_params_; } void EmulationHandler::SetDeviceEmulationParams( - const blink::WebDeviceEmulationParams& params) { - bool enabled = params != blink::WebDeviceEmulationParams(); + const blink::DeviceEmulationParams& params) { + bool enabled = params != blink::DeviceEmulationParams(); bool enable_changed = enabled != device_emulation_enabled_; bool params_changed = params != device_emulation_params_; if (!device_emulation_enabled_ && !enable_changed)
diff --git a/content/browser/devtools/protocol/emulation_handler.h b/content/browser/devtools/protocol/emulation_handler.h index 35428c4..77c155d 100644 --- a/content/browser/devtools/protocol/emulation_handler.h +++ b/content/browser/devtools/protocol/emulation_handler.h
@@ -9,7 +9,7 @@ #include "content/browser/devtools/protocol/devtools_domain_handler.h" #include "content/browser/devtools/protocol/emulation.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" namespace net { class HttpRequestHeaders; @@ -75,8 +75,8 @@ Response SetFocusEmulationEnabled(bool) override; - blink::WebDeviceEmulationParams GetDeviceEmulationParams(); - void SetDeviceEmulationParams(const blink::WebDeviceEmulationParams& params); + blink::DeviceEmulationParams GetDeviceEmulationParams(); + void SetDeviceEmulationParams(const blink::DeviceEmulationParams& params); bool device_emulation_enabled() { return device_emulation_enabled_; } @@ -95,7 +95,7 @@ std::string touch_emulation_configuration_; bool device_emulation_enabled_; bool focus_emulation_enabled_; - blink::WebDeviceEmulationParams device_emulation_params_; + blink::DeviceEmulationParams device_emulation_params_; std::string user_agent_; // |user_agent_metadata_| is meaningful if |user_agent_| is non-empty.
diff --git a/content/browser/devtools/protocol/network_handler.cc b/content/browser/devtools/protocol/network_handler.cc index 55cbbdf..eb62416 100644 --- a/content/browser/devtools/protocol/network_handler.cc +++ b/content/browser/devtools/protocol/network_handler.cc
@@ -494,8 +494,10 @@ return protocol; } -bool GetPostData(const network::ResourceRequestBody& request_body, - std::string* result) { +bool GetPostData( + const network::ResourceRequestBody& request_body, + protocol::Array<protocol::Network::PostDataEntry>* data_entries, + std::string* result) { const std::vector<network::DataElement>* elements = request_body.elements(); if (elements->empty()) return false; @@ -503,7 +505,11 @@ // TODO(caseq): Also support blobs. if (element.type() != network::mojom::DataElementType::kBytes) return false; - // TODO(caseq): This should rather be sent as Binary. + auto bytes = protocol::Binary::fromSpan( + reinterpret_cast<const uint8_t*>(element.bytes()), element.length()); + auto data_entry = protocol::Network::PostDataEntry::Create().Build(); + data_entry->SetBytes(std::move(bytes)); + data_entries->push_back(std::move(data_entry)); result->append(element.bytes(), element.length()); } return true; @@ -1630,10 +1636,17 @@ if (!url_fragment.empty()) request->SetUrlFragment(url_fragment); - std::string post_data; - if (common_params.post_data && - GetPostData(*common_params.post_data, &post_data)) { - request->SetPostData(post_data); + if (common_params.post_data) { + std::string post_data; + auto data_entries = + std::make_unique<protocol::Array<protocol::Network::PostDataEntry>>(); + if (GetPostData(*common_params.post_data, data_entries.get(), &post_data)) { + if (!post_data.empty()) + request->SetPostData(post_data); + if (data_entries->size()) + request->SetPostDataEntries(std::move(data_entries)); + request->SetHasPostData(true); + } } // TODO(caseq): report potentially blockable types request->SetMixedContentType(Security::MixedContentTypeEnum::None); @@ -2040,9 +2053,18 @@ .Build(); if (!url_fragment.empty()) request_object->SetUrlFragment(url_fragment); - std::string post_data; - if (request.request_body && GetPostData(*request.request_body, &post_data)) - request_object->SetPostData(std::move(post_data)); + if (request.request_body) { + std::string post_data; + auto data_entries = + std::make_unique<protocol::Array<protocol::Network::PostDataEntry>>(); + if (GetPostData(*request.request_body, data_entries.get(), &post_data)) { + if (!post_data.empty()) + request_object->SetPostData(std::move(post_data)); + if (data_entries->size()) + request_object->SetPostDataEntries(std::move(data_entries)); + request_object->SetHasPostData(true); + } + } return request_object; }
diff --git a/content/browser/devtools/protocol/page_handler.cc b/content/browser/devtools/protocol/page_handler.cc index 45a735b9..27ea920 100644 --- a/content/browser/devtools/protocol/page_handler.cc +++ b/content/browser/devtools/protocol/page_handler.cc
@@ -704,7 +704,7 @@ base::BindOnce(&PageHandler::ScreenshotCaptured, weak_factory_.GetWeakPtr(), std::move(callback), screenshot_format, screenshot_quality, gfx::Size(), - gfx::Size(), blink::WebDeviceEmulationParams()), + gfx::Size(), blink::DeviceEmulationParams()), false); return; } @@ -712,9 +712,9 @@ // Welcome to the neural net of capturing screenshot while emulating device // metrics! bool emulation_enabled = emulation_handler_->device_emulation_enabled(); - blink::WebDeviceEmulationParams original_params = + blink::DeviceEmulationParams original_params = emulation_handler_->GetDeviceEmulationParams(); - blink::WebDeviceEmulationParams modified_params = original_params; + blink::DeviceEmulationParams modified_params = original_params; // Capture original view size if we know we are going to destroy it. We use // it in ScreenshotCaptured to restore. @@ -732,11 +732,11 @@ // size. float original_scale = original_params.scale > 0 ? original_params.scale : 1; - if (!modified_params.view_size.width) { + if (!modified_params.view_size.width()) { emulated_view_size.set_width( ceil(original_view_size.width() / original_scale)); } - if (!modified_params.view_size.height) { + if (!modified_params.view_size.height()) { emulated_view_size.set_height( ceil(original_view_size.height() / original_scale)); } @@ -748,14 +748,11 @@ // When clip is specified, we scale viewport via clip, otherwise we use // scale. modified_params.scale = clip.isJust() ? 1 : dpfactor; - modified_params.view_size.width = emulated_view_size.width(); - modified_params.view_size.height = emulated_view_size.height(); + modified_params.view_size = emulated_view_size; } else if (clip.isJust()) { // When not emulating, still need to emulate the page size. - modified_params.view_size.width = original_view_size.width(); - modified_params.view_size.height = original_view_size.height(); - modified_params.screen_size.width = 0; - modified_params.screen_size.height = 0; + modified_params.view_size = original_view_size; + modified_params.screen_size = gfx::Size(); modified_params.device_scale_factor = 0; modified_params.scale = 1; } @@ -770,7 +767,7 @@ } } - // We use WebDeviceEmulationParams to either emulate, set viewport or both. + // We use DeviceEmulationParams to either emulate, set viewport or both. emulation_handler_->SetDeviceEmulationParams(modified_params); // Set view size for the screenshot right after emulating. @@ -1094,7 +1091,7 @@ int quality, const gfx::Size& original_view_size, const gfx::Size& requested_image_size, - const blink::WebDeviceEmulationParams& original_emulation_params, + const blink::DeviceEmulationParams& original_emulation_params, const gfx::Image& image) { if (original_view_size.width()) { RenderWidgetHostImpl* widget_host = host_->GetRenderWidgetHost();
diff --git a/content/browser/devtools/protocol/page_handler.h b/content/browser/devtools/protocol/page_handler.h index 1115a60..58ae91e 100644 --- a/content/browser/devtools/protocol/page_handler.h +++ b/content/browser/devtools/protocol/page_handler.h
@@ -42,7 +42,7 @@ } // namespace gfx namespace blink { -struct WebDeviceEmulationParams; +struct DeviceEmulationParams; } namespace content { @@ -186,14 +186,13 @@ std::unique_ptr<Page::ScreencastFrameMetadata> metadata, const protocol::Binary& data); - void ScreenshotCaptured( - std::unique_ptr<CaptureScreenshotCallback> callback, - const std::string& format, - int quality, - const gfx::Size& original_view_size, - const gfx::Size& requested_image_size, - const blink::WebDeviceEmulationParams& original_params, - const gfx::Image& image); + void ScreenshotCaptured(std::unique_ptr<CaptureScreenshotCallback> callback, + const std::string& format, + int quality, + const gfx::Size& original_view_size, + const gfx::Size& requested_image_size, + const blink::DeviceEmulationParams& original_params, + const gfx::Image& image); void GotManifest(std::unique_ptr<GetAppManifestCallback> callback, const GURL& manifest_url,
diff --git a/content/browser/field_trial_synchronizer.cc b/content/browser/field_trial_synchronizer.cc index ab456955..10cbf7b4 100644 --- a/content/browser/field_trial_synchronizer.cc +++ b/content/browser/field_trial_synchronizer.cc
@@ -36,7 +36,7 @@ // Ensure the observer was actually registered. DCHECK(success); - variations::VariationsHttpHeaderProvider::GetInstance()->AddObserver(this); + variations::VariationsIdsProvider::GetInstance()->AddObserver(this); NotifyAllRenderersOfVariationsHeader(); } @@ -131,7 +131,7 @@ FieldTrialSynchronizer::~FieldTrialSynchronizer() { base::FieldTrialList::RemoveObserver(this); - variations::VariationsHttpHeaderProvider::GetInstance()->RemoveObserver(this); + variations::VariationsIdsProvider::GetInstance()->RemoveObserver(this); } } // namespace content
diff --git a/content/browser/field_trial_synchronizer.h b/content/browser/field_trial_synchronizer.h index 08e035d..9a6bd7c5 100644 --- a/content/browser/field_trial_synchronizer.h +++ b/content/browser/field_trial_synchronizer.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/metrics/field_trial.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" namespace content { class RenderProcessHost; @@ -26,13 +26,13 @@ // method sends the FieldTrial's name and the group to all renderer processes. // Each renderer process creates the FieldTrial, and by using a 100% probability // for the FieldTrial, forces the FieldTrial to have the same group string. -// This class also registers itself as a VariationsHttpHeaderProvider Observer +// This class also registers itself as a VariationsIdsProvider Observer // and updates the renderers if the variations header changes. class FieldTrialSynchronizer : public base::RefCountedThreadSafe<FieldTrialSynchronizer>, public base::FieldTrialList::Observer, - public variations::VariationsHttpHeaderProvider::Observer { + public variations::VariationsIdsProvider::Observer { public: // Construction also sets up the global singleton instance. This instance is // used to communicate between the UI and other threads, and is destroyed only @@ -51,7 +51,7 @@ void OnFieldTrialGroupFinalized(const std::string& name, const std::string& group_name) override; - // VariationsHttpHeaderProvider::Observer methods: + // VariationsIdsProvider::Observer methods: void VariationIdsHeaderUpdated() override; // Sends the current variations header to |host|'s renderer.
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index 11cd02d..23637bb 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -4003,6 +4003,16 @@ common_params_->url = params.url; did_replace_entry_ = did_replace_entry; should_update_history_ = params.should_update_history; + // A same document navigation with the same url, and no user-gesture is + // typically the result of 'history.replaceState().' As the page is + // controlling this, the user doesn't really think of this as a navigation + // and it doesn't make sense to log this in history. Logging this in history + // would lead to lots of visits to a particular page, which impacts the + // visit count. + if (should_update_history_ && IsSameDocument() && !HasUserGesture() && + params.url == previous_url) { + should_update_history_ = false; + } previous_url_ = previous_url; navigation_type_ = navigation_type;
diff --git a/content/browser/renderer_host/input/web_input_event_builders_mac.mm b/content/browser/renderer_host/input/web_input_event_builders_mac.mm index 536cb236..4dd7d7e 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_mac.mm +++ b/content/browser/renderer_host/input/web_input_event_builders_mac.mm
@@ -35,7 +35,6 @@ #include <stdint.h> -#include "base/debug/dump_without_crashing.h" #include "base/mac/mac_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" @@ -257,12 +256,6 @@ blink::WebKeyboardEvent WebKeyboardEventBuilder::Build(NSEvent* event, bool record_debug_uma) { - // TODO(bokan) Temporary to debug crbug.com/1039833. - // It's assumed that some clients may fall into a bad state and produce these - // bad timestamps on lots of subsequent events. To prevent sending an - // overwhelming amount of crash reports stop after sending 5. - static int dump_without_crashing_throttle = 5; - ui::ComputeEventLatencyOS(event); base::TimeTicks now = ui::EventTimeForNow(); base::TimeTicks hardware_timestamp = @@ -274,18 +267,9 @@ "Event.Latency.OS_NO_VALIDATION.POSITIVE.KEY_PRESSED", diff, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromSeconds(60), 50); - - // TODO(bokan) Temporary to debug crbug.com/1039833. We've seen in UMA - // that we often receive key press events with the OS timestamp differing - // from the current timestamp by 60+ seconds. Try to capture a few crash - // reports from the wild to see if we can find some pattern. - if (diff.magnitude() > base::TimeDelta::FromSeconds(60) && - dump_without_crashing_throttle > 0) { - --dump_without_crashing_throttle; - base::debug::DumpWithoutCrashing(); - } } } + ui::DomCode dom_code = ui::DomCodeFromNSEvent(event); int modifiers = ModifiersFromEvent(event) | ui::DomCodeToWebInputEventModifiers(dom_code);
diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index d34b836b..a96686e0 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc
@@ -414,7 +414,20 @@ params->devtools_main_frame_token = frame_tree_node->devtools_frame_token(); // GuestViews in the same StoragePartition need to find each other's frames. params->renderer_wide_named_frame_lookup = GetSiteInstance()->IsGuest(); - params->inside_portal = delegate_->IsPortal(); + + bool is_portal = delegate_->IsPortal(); + bool is_guest_view = GetSiteInstance()->IsGuest(); + + // A view cannot be inside both a <portal> and inside a <webview>. + DCHECK(!is_portal || !is_guest_view); + if (is_portal) { + params->type = mojom::ViewWidgetType::kPortal; + } else if (is_guest_view) { + params->type = mojom::ViewWidgetType::kGuestView; + } else { + params->type = mojom::ViewWidgetType::kTopLevel; + } + // RenderViweHostImpls is reused after a crash, so reset any endpoint that // might be a leftover from a crash. page_broadcast_.reset();
diff --git a/content/browser/renderer_host/render_widget_host_delegate.h b/content/browser/renderer_host/render_widget_host_delegate.h index 1feca3a..b11e574d 100644 --- a/content/browser/renderer_host/render_widget_host_delegate.h +++ b/content/browser/renderer_host/render_widget_host_delegate.h
@@ -124,7 +124,7 @@ // Notification that an input event from the user was dispatched to the // widget. virtual void DidReceiveInputEvent(RenderWidgetHostImpl* render_widget_host, - const blink::WebInputEvent::Type type) {} + const blink::WebInputEvent& event) {} // Asks whether the page is in a state of ignoring input events. virtual bool ShouldIgnoreInputEvents();
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 0579758..2e88af9 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -2813,7 +2813,7 @@ event.GetType() == WebInputEvent::Type::kGestureTap) { delegate_->FocusOwningWebContents(this); } - delegate_->DidReceiveInputEvent(this, event.GetType()); + delegate_->DidReceiveInputEvent(this, event); } return view_ ? view_->FilterInputEvent(event)
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 7fd99b1..97de10c 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -393,7 +393,7 @@ private: // WebContentsObserver - void DidGetUserInteraction(const blink::WebInputEvent::Type type) override { + void DidGetUserInteraction(const blink::WebInputEvent& event) override { user_interaction_received_ = true; }
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 3d2866b..62da188 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -6504,19 +6504,19 @@ void WebContentsImpl::DidReceiveInputEvent( RenderWidgetHostImpl* render_widget_host, - const blink::WebInputEvent::Type type) { - if (!IsUserInteractionInputType(type)) + const blink::WebInputEvent& event) { + if (!IsUserInteractionInputType(event.GetType())) return; // Ignore unless the widget is currently in the frame tree. if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host)) return; - if (type != blink::WebInputEvent::Type::kGestureScrollBegin) + if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin) last_interactive_input_event_time_ = ui::EventTimeForNow(); for (auto& observer : observers_) - observer.DidGetUserInteraction(type); + observer.DidGetUserInteraction(event); } bool WebContentsImpl::ShouldIgnoreInputEvents() {
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 94e5e22b..c160494 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -780,7 +780,7 @@ blink::mojom::RendererPreferences GetRendererPrefs( BrowserContext* browser_context) const override; void DidReceiveInputEvent(RenderWidgetHostImpl* render_widget_host, - const blink::WebInputEvent::Type type) override; + const blink::WebInputEvent& event) override; bool ShouldIgnoreInputEvents() override; void OnIgnoredUIEvent() override; void Activate() override;
diff --git a/content/common/DEPS b/content/common/DEPS index f80aac4..9bbfb47 100644 --- a/content/common/DEPS +++ b/content/common/DEPS
@@ -39,7 +39,7 @@ "+third_party/blink/public/platform/modules/remoteplayback/web_remote_playback_availability.h", "+third_party/blink/public/platform/modules/service_worker/web_service_worker_error.h", "+third_party/blink/public/web/web_ax_enums.h", - "+third_party/blink/public/web/web_device_emulation_params.h", + "+third_party/blink/public/common/widget/device_emulation_params.h", "+third_party/blink/public/web/web_drag_status.h", "+third_party/blink/public/web/web_frame_owner_properties.h", "+third_party/blink/public/web/win/web_font_rendering.h",
diff --git a/content/common/common_param_traits_macros.h b/content/common/common_param_traits_macros.h index c1baffb..1dee4da 100644 --- a/content/common/common_param_traits_macros.h +++ b/content/common/common_param_traits_macros.h
@@ -12,15 +12,15 @@ #include "content/common/frame_messages.h" #include "ipc/ipc_message_macros.h" #include "services/device/public/mojom/screen_orientation_lock_types.mojom-shared.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/common/widget/visual_properties.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT // Traits for VisualProperties. -IPC_ENUM_TRAITS_MAX_VALUE(blink::WebDeviceEmulationParams::ScreenPosition, - blink::WebDeviceEmulationParams::kScreenPositionLast) +IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::EmulatedScreenType, + blink::mojom::EmulatedScreenType::kMaxValue) IPC_ENUM_TRAITS_MAX_VALUE(device::mojom::ScreenOrientationLockType, device::mojom::ScreenOrientationLockType::kMaxValue)
diff --git a/content/common/renderer.mojom b/content/common/renderer.mojom index 02c9492..727a069 100644 --- a/content/common/renderer.mojom +++ b/content/common/renderer.mojom
@@ -21,6 +21,17 @@ import "third_party/blink/public/mojom/user_agent/user_agent_metadata.mojom"; import "ui/gfx/geometry/mojom/geometry.mojom"; +// A View (i.e. a "main frame") can be created for a few different cases, these +// values are used to specify which it is. +enum ViewWidgetType { + // A standard view that's the top-level widget in a frame hierarchy. + kTopLevel, + // A GuestView used to render contents inside a <webview> element. + kGuestView, + // A view used to render contents inside a <portal> element. + kPortal +}; + struct CreateViewParams { // Renderer-wide preferences. blink.mojom.RendererPreferences renderer_preferences; @@ -109,8 +120,9 @@ // beyond the usual opener-relationship-based BrowsingInstance boundaries). bool renderer_wide_named_frame_lookup; - // Set this to true when creating a RenderView inside a portal. - bool inside_portal; + // Indicates whether the view is a regular top-level widget or some other + // nested "main frame" widget type. + ViewWidgetType type; // Endpoint for any messages that are broadcast to all views in a WebContents. pending_associated_receiver<blink.mojom.PageBroadcast> blink_page_broadcast;
diff --git a/content/common/widget_messages.h b/content/common/widget_messages.h index 2888ae16..603b179e 100644 --- a/content/common/widget_messages.h +++ b/content/common/widget_messages.h
@@ -29,7 +29,7 @@ #define IPC_MESSAGE_START WidgetMsgStart -// Traits for WebDeviceEmulationParams. +// Traits for DeviceEmulationParams. IPC_STRUCT_TRAITS_BEGIN(blink::WebFloatRect) IPC_STRUCT_TRAITS_MEMBER(x) IPC_STRUCT_TRAITS_MEMBER(y) @@ -42,8 +42,8 @@ IPC_STRUCT_TRAITS_MEMBER(height) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_TRAITS_BEGIN(blink::WebDeviceEmulationParams) - IPC_STRUCT_TRAITS_MEMBER(screen_position) +IPC_STRUCT_TRAITS_BEGIN(blink::DeviceEmulationParams) + IPC_STRUCT_TRAITS_MEMBER(screen_type) IPC_STRUCT_TRAITS_MEMBER(screen_size) IPC_STRUCT_TRAITS_MEMBER(view_position) IPC_STRUCT_TRAITS_MEMBER(device_scale_factor) @@ -64,9 +64,9 @@ // Expects a Close_ACK message when finished. IPC_MESSAGE_ROUTED0(WidgetMsg_Close) -// Enables device emulation. See WebDeviceEmulationParams for description. +// Enables device emulation. See DeviceEmulationParams for description. IPC_MESSAGE_ROUTED1(WidgetMsg_EnableDeviceEmulation, - blink::WebDeviceEmulationParams /* params */) + blink::DeviceEmulationParams /* params */) // Disables device emulation, enabled previously by EnableDeviceEmulation. IPC_MESSAGE_ROUTED0(WidgetMsg_DisableDeviceEmulation)
diff --git a/content/public/browser/navigation_handle.h b/content/public/browser/navigation_handle.h index c679ff6..8a1d8de 100644 --- a/content/public/browser/navigation_handle.h +++ b/content/public/browser/navigation_handle.h
@@ -246,7 +246,9 @@ virtual bool DidReplaceEntry() = 0; // Returns true if the browser history should be updated. Otherwise only - // the session history will be updated. E.g., on unreachable urls. + // the session history will be updated. E.g., on unreachable urls or other + // navigations that the users may not think of as navigations (such as + // happens with 'history.replaceState()'). virtual bool ShouldUpdateHistory() = 0; // The previous main frame URL that the user was on. This may be empty if
diff --git a/content/public/browser/web_contents_observer.h b/content/public/browser/web_contents_observer.h index a6e33a28..b85c57bc 100644 --- a/content/public/browser/web_contents_observer.h +++ b/content/public/browser/web_contents_observer.h
@@ -357,13 +357,13 @@ virtual void NavigationStopped() {} // Called when there has been direct user interaction with the WebContents. - // The type argument specifies the kind of interaction. Direct user input + // The type of the event specifies the kind of interaction. Direct user input // signalled through this callback includes: // 1) any mouse down event (blink::WebInputEvent::MouseDown); // 2) the start of a scroll (blink::WebInputEvent::GestureScrollBegin); // 3) any raw key down event (blink::WebInputEvent::RawKeyDown); and // 4) any touch event (inc. scrolls) (blink::WebInputEvent::TouchStart). - virtual void DidGetUserInteraction(const blink::WebInputEvent::Type type) {} + virtual void DidGetUserInteraction(const blink::WebInputEvent& event) {} // This method is invoked when a RenderViewHost of this WebContents was // configured to ignore UI events, and an UI event took place.
diff --git a/content/public/test/url_loader_interceptor.cc b/content/public/test/url_loader_interceptor.cc index 0dde003..ca21fac24 100644 --- a/content/public/test/url_loader_interceptor.cc +++ b/content/public/test/url_loader_interceptor.cc
@@ -587,16 +587,8 @@ if (headers) { headers_str = *headers; } else { - base::FilePath::StringPieceType mock_headers_extension; -#if defined(OS_WIN) - base::string16 temp = - base::ASCIIToUTF16(net::test_server::kMockHttpHeadersExtension); - mock_headers_extension = temp; -#else - mock_headers_extension = net::test_server::kMockHttpHeadersExtension; -#endif - - base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); + base::FilePath headers_path( + file_path.AddExtension(net::test_server::kMockHttpHeadersExtension)); if (base::PathExists(headers_path)) { headers_str = ReadFile(headers_path); } else {
diff --git a/content/public/test/web_contents_tester.h b/content/public/test/web_contents_tester.h index c761e00..8803e3e 100644 --- a/content/public/test/web_contents_tester.h +++ b/content/public/test/web_contents_tester.h
@@ -158,7 +158,7 @@ virtual void SetIsCurrentlyAudible(bool audible) = 0; // Simulates an input event from the user. - virtual void TestDidReceiveInputEvent(blink::WebInputEvent::Type type) = 0; + virtual void TestDidReceiveMouseDownEvent() = 0; // Simulates successfully finishing a load. virtual void TestDidFinishLoad(const GURL& url) = 0;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index c571b07..0e3db59 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -1458,7 +1458,6 @@ std::unique_ptr<RenderWidget> render_widget = RenderWidget::CreateForFrame( params->main_frame_widget_routing_id, compositor_deps, render_view->widgets_never_composited()); - render_widget->set_delegate(render_view); // Non-owning pointer that is self-referencing and destroyed by calling // Close(). The RenderViewImpl has a RenderWidget already, but not a @@ -1469,7 +1468,8 @@ std::move(params->widget)); render_widget->InitForMainFrame(std::move(show_callback), web_frame_widget, - params->visual_properties.screen_info); + params->visual_properties.screen_info, + params->type, *render_view); // The WebFrame created here was already attached to the Page as its main // frame, and the WebFrameWidget has been initialized, so we can call @@ -1620,7 +1620,6 @@ std::unique_ptr<RenderWidget> render_widget = RenderWidget::CreateForFrame( widget_params->routing_id, compositor_deps, render_view->widgets_never_composited()); - render_widget->set_delegate(render_view); // Non-owning pointer that is self-referencing and destroyed by calling // Close(). The RenderViewImpl has a RenderWidget already, but not a @@ -1634,7 +1633,8 @@ render_widget->InitForMainFrame( RenderWidget::ShowCallback(), web_frame_widget, - widget_params->visual_properties.screen_info); + widget_params->visual_properties.screen_info, + mojom::ViewWidgetType::kTopLevel, *render_view); // The RenderWidget should start with valid VisualProperties, including a // non-zero size. While RenderWidget would not normally receive IPCs and // thus would not get VisualProperty updates while the frame is provisional,
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 1e1f828..fe6164b 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -75,6 +75,7 @@ #include "third_party/blink/public/common/origin_trials/origin_trial_policy.h" #include "third_party/blink/public/common/origin_trials/trial_token_validator.h" #include "third_party/blink/public/common/page/page_zoom.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h" #include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h" @@ -84,7 +85,6 @@ #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url_response.h" #include "third_party/blink/public/web/web_autofill_client.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_document_loader.h" #include "third_party/blink/public/web/web_frame_content_dumper.h" #include "third_party/blink/public/web/web_frame_widget.h" @@ -294,7 +294,7 @@ void ReceiveEnableDeviceEmulation( RenderViewImpl* view, - const blink::WebDeviceEmulationParams& params) { + const blink::DeviceEmulationParams& params) { // Emulates receiving an IPC message. RenderWidget* widget = view->GetMainRenderFrame()->GetLocalRootRenderWidget(); @@ -548,9 +548,8 @@ int emulated_width, emulated_height; int emulated_dpr; - blink::WebDeviceEmulationParams params; - params.view_size.width = width; - params.view_size.height = height; + blink::DeviceEmulationParams params; + params.view_size = gfx::Size(width, height); params.device_scale_factor = dpr; ReceiveEnableDeviceEmulation(view(), params); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &emulated_width)); @@ -709,11 +708,11 @@ } // Enable device emulation on the parent widget. - blink::WebDeviceEmulationParams emulation_params; + blink::DeviceEmulationParams emulation_params; gfx::Rect emulated_widget_rect(150, 160, 980, 1200); // In mobile emulation the WindowScreenRect and ScreenRect are both set to // match the WidgetScreenRect, which we set here. - emulation_params.screen_position = blink::WebDeviceEmulationParams::kMobile; + emulation_params.screen_type = blink::mojom::EmulatedScreenType::kMobile; emulation_params.view_size = emulated_widget_rect.size(); emulation_params.view_position = emulated_widget_rect.origin(); { @@ -1154,7 +1153,7 @@ ReceiveDisableDeviceEmulation(view()); - blink::WebDeviceEmulationParams params; + blink::DeviceEmulationParams params; ReceiveEnableDeviceEmulation(view(), params); // Don't disable here to test that emulation is being shutdown properly. } @@ -3148,7 +3147,7 @@ ReceiveDisableDeviceEmulation(view()); - blink::WebDeviceEmulationParams params; + blink::DeviceEmulationParams params; ReceiveEnableDeviceEmulation(view(), params); // Don't disable here to test that emulation is being shutdown properly. } @@ -3177,7 +3176,7 @@ ReceiveDisableDeviceEmulation(view()); - blink::WebDeviceEmulationParams params; + blink::DeviceEmulationParams params; ReceiveEnableDeviceEmulation(view(), params); // Don't disable here to test that emulation is being shutdown properly. }
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 6c2ad75..ba428a0 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -475,7 +475,7 @@ // We pass this state to Page, but it's only used by the main frame in the // page. - if (params->inside_portal) + if (params->type == mojom::ViewWidgetType::kPortal) GetWebView()->SetInsidePortal(true); #if defined(OS_ANDROID) @@ -1089,7 +1089,7 @@ void RenderViewImpl::SetScreenMetricsEmulationParametersForWidget( bool enabled, - const blink::WebDeviceEmulationParams& params) { + const blink::DeviceEmulationParams& params) { if (enabled) GetWebView()->EnableDeviceEmulation(params); else
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 8f81196..547b1105 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -89,6 +89,12 @@ // When the main frame is part of this RenderViewImpl's frame tree, then this // object acts as the RenderWidgetDelegate for that frame's RenderWidget. Other // RenderWidgets would have a null RenderWidgetDelegate. +// +// Note: There are cases where there may be multiple main frames in tab. For +// example, both Portals and GuestViews create their own RenderView that's +// nested within another RenderView's frame tree. In these cases, the +// RenderWidget for the nested view will have a non-null RenderWidgetDelegate, +// despite the fact that it isn't the root of the hierarchy. class CONTENT_EXPORT RenderViewImpl : public blink::WebViewClient, public IPC::Listener, public RenderWidgetDelegate, @@ -361,7 +367,7 @@ cc::BrowserControlsParams browser_controls_params) override; void SetScreenMetricsEmulationParametersForWidget( bool enabled, - const blink::WebDeviceEmulationParams& params) override; + const blink::DeviceEmulationParams& params) override; // Old WebLocalFrameClient implementations // ----------------------------------------
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 3a97c49..4ffec2a 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -79,6 +79,7 @@ #include "third_party/blink/public/common/input/web_mouse_event.h" #include "third_party/blink/public/common/page/web_drag_operation.h" #include "third_party/blink/public/common/switches.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/platform/file_path_conversion.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/scheduler/web_render_widget_scheduling_state.h" @@ -89,7 +90,6 @@ #include "third_party/blink/public/platform/web_size.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/web/web_autofill_client.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_frame_widget.h" #include "third_party/blink/public/web/web_input_method_controller.h" #include "third_party/blink/public/web/web_local_frame.h" @@ -127,10 +127,10 @@ #include "third_party/skia/include/core/SkPixelRef.h" #endif // defined(OS_POSIX) -using blink::WebDeviceEmulationParams; +using blink::DeviceEmulationParams; +using blink::WebDragData; using blink::WebDragOperation; using blink::WebDragOperationsMask; -using blink::WebDragData; using blink::WebFrameWidget; using blink::WebGestureEvent; using blink::WebInputEvent; @@ -342,7 +342,7 @@ RenderWidget* opener_widget, blink::WebPagePopup* web_page_popup, const blink::ScreenInfo& screen_info) { - popup_ = true; + for_popup_ = true; Initialize(std::move(show_callback), web_page_popup, screen_info); if (opener_widget->device_emulator_) { @@ -358,13 +358,17 @@ ShowCallback show_callback, blink::WebWidget* web_widget, const blink::ScreenInfo& screen_info) { - pepper_fullscreen_ = true; + for_pepper_fullscreen_ = true; Initialize(std::move(show_callback), web_widget, screen_info); } void RenderWidget::InitForMainFrame(ShowCallback show_callback, blink::WebFrameWidget* web_frame_widget, - const blink::ScreenInfo& screen_info) { + const blink::ScreenInfo& screen_info, + mojom::ViewWidgetType view_widget_type, + RenderWidgetDelegate& delegate) { + delegate_ = &delegate; + for_nested_main_frame_ = view_widget_type != mojom::ViewWidgetType::kTopLevel; Initialize(std::move(show_callback), web_frame_widget, screen_info); } @@ -467,7 +471,7 @@ } void RenderWidget::OnClose() { - DCHECK(popup_ || pepper_fullscreen_); + DCHECK(for_popup_ || for_pepper_fullscreen_); Close(base::WrapUnique(this)); } @@ -756,7 +760,7 @@ } void RenderWidget::OnEnableDeviceEmulation( - const blink::WebDeviceEmulationParams& params) { + const blink::DeviceEmulationParams& params) { // Device emulation can only be applied to the local main frame render widget. // TODO(https://crbug.com/1006052): We should move emulation into the browser // and send consistent ScreenInfo and ScreenRects to all RenderWidgets based @@ -1168,7 +1172,7 @@ void RenderWidget::SetScreenMetricsEmulationParameters( bool enabled, - const blink::WebDeviceEmulationParams& params) { + const blink::DeviceEmulationParams& params) { // This is only supported in RenderView, which has an delegate(). DCHECK(delegate()); delegate()->SetScreenMetricsEmulationParametersForWidget(enabled, params); @@ -1389,7 +1393,7 @@ // Popup widgets aren't emulated, but the WindowRect (aka WindowScreenRect) // given to them should be. if (opener_emulator_scale_) { - DCHECK(popup_); + DCHECK(for_popup_); ScreenRectToEmulated(&rect); } return rect; @@ -1401,7 +1405,7 @@ // Popup widgets aren't emulated, but the ViewRect (aka WidgetScreenRect) // given to them should be. if (opener_emulator_scale_) { - DCHECK(popup_); + DCHECK(for_popup_); ScreenRectToEmulated(&rect); } return rect; @@ -1422,7 +1426,7 @@ // given to them are. When they set the WindowScreenRect it is based on those // emulated values, so we reverse the emulation. if (opener_emulator_scale_) { - DCHECK(popup_); + DCHECK(for_popup_); EmulatedToScreenRect(&window_rect); } @@ -1491,6 +1495,12 @@ #endif } +void RenderWidget::SetIsNestedMainFrameWidget(bool is_nested) { + DCHECK(delegate_) + << "Must be in a main frame widget when setting for_nested_main_frame_"; + for_nested_main_frame_ = is_nested; +} + void RenderWidget::UpdateSurfaceAndScreenInfo( const viz::LocalSurfaceIdAllocation& new_local_surface_id_allocation, const gfx::Rect& compositor_viewport_pixel_rect,
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index 294803164..7c6a246 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -34,6 +34,7 @@ #include "content/common/content_export.h" #include "content/common/content_to_visible_time_reporter.h" #include "content/common/drag_event_source_info.h" +#include "content/common/renderer.mojom-forward.h" #include "content/public/common/drop_data.h" #include "content/renderer/mouse_lock_dispatcher.h" #include "content/renderer/render_widget_delegate.h" @@ -71,7 +72,7 @@ namespace blink { struct VisualProperties; -struct WebDeviceEmulationParams; +struct DeviceEmulationParams; class WebDragData; class WebFrameWidget; class WebInputMethodController; @@ -190,7 +191,9 @@ // the WebFrameWidget), for a frame that is a main frame. void InitForMainFrame(ShowCallback show_callback, blink::WebFrameWidget* web_frame_widget, - const blink::ScreenInfo& screen_info); + const blink::ScreenInfo& screen_info, + mojom::ViewWidgetType view_widget_type, + RenderWidgetDelegate& delegate); // Initialize a new RenderWidget that will be attached to a RenderFrame (via // the WebFrameWidget), for a frame that is a local root, but not the main @@ -198,13 +201,6 @@ void InitForChildLocalRoot(blink::WebFrameWidget* web_frame_widget, const blink::ScreenInfo& screen_info); - // Sets a delegate to handle certain RenderWidget operations that need an - // escape to the RenderView. - void set_delegate(RenderWidgetDelegate* delegate) { - DCHECK(!delegate_); - delegate_ = delegate; - } - RenderWidgetDelegate* delegate() const { return delegate_; } // Closes a RenderWidget that was created by |CreateForFrame|. Ownership is @@ -257,7 +253,7 @@ // RenderWidgetScreenMetricsEmulatorDelegate void SetScreenMetricsEmulationParameters( bool enabled, - const blink::WebDeviceEmulationParams& params) override; + const blink::DeviceEmulationParams& params) override; void SetScreenInfoAndSize(const blink::ScreenInfo& screen_info, const gfx::Size& widget_size, const gfx::Size& visible_viewport_size) override; @@ -330,6 +326,7 @@ const blink::VisualProperties& properties) override; void UpdateScreenRects(const gfx::Rect& widget_screen_rect, const gfx::Rect& window_screen_rect) override; + void SetIsNestedMainFrameWidget(bool is_nested) override; // Returns the scale being applied to the document in blink by the device // emulator. Returns 1 if there is no emulation active. Use this to position @@ -466,7 +463,7 @@ // RenderWidget IPC message handlers. void OnClose(); void OnCreatingNewAck(); - void OnEnableDeviceEmulation(const blink::WebDeviceEmulationParams& params); + void OnEnableDeviceEmulation(const blink::DeviceEmulationParams& params); void OnDisableDeviceEmulation(); void OnWasHidden(); void OnWasShown( @@ -711,8 +708,13 @@ // unique_ptr back in Close(). In the latter cases, the browser process takes // ownership via IPC. These booleans exist to allow us to confirm than an IPC // message to kill the render widget is coming for a popup or fullscreen. - bool popup_ = false; - bool pepper_fullscreen_ = false; + bool for_popup_ = false; + bool for_pepper_fullscreen_ = false; + // If this widget is for a main frame (i.e. has a delegate_), this bit is + // used to tell if this is a nested widget (an "inner web contents") like a + // <webview> or <portal> widget. If false, the widget is either not a main + // frame (delegate_ == nullptr) or it is the top level widget. + bool for_nested_main_frame_ = false; // A callback into the creator/opener of this widget, to be executed when // WebWidgetClient::Show() occurs.
diff --git a/content/renderer/render_widget_delegate.h b/content/renderer/render_widget_delegate.h index 50bc8b8..ee0951a 100644 --- a/content/renderer/render_widget_delegate.h +++ b/content/renderer/render_widget_delegate.h
@@ -9,7 +9,7 @@ namespace blink { class WebWidget; -struct WebDeviceEmulationParams; +struct DeviceEmulationParams; } // namespace blink namespace content { @@ -72,7 +72,7 @@ // SetScreenMetricsEmulationParameters(). virtual void SetScreenMetricsEmulationParametersForWidget( bool enabled, - const blink::WebDeviceEmulationParams& params) = 0; + const blink::DeviceEmulationParams& params) = 0; }; } // namespace content
diff --git a/content/renderer/render_widget_screen_metrics_emulator.cc b/content/renderer/render_widget_screen_metrics_emulator.cc index 1e76cca..1aae1c8c 100644 --- a/content/renderer/render_widget_screen_metrics_emulator.cc +++ b/content/renderer/render_widget_screen_metrics_emulator.cc
@@ -37,7 +37,7 @@ } void RenderWidgetScreenMetricsEmulator::ChangeEmulationParams( - const blink::WebDeviceEmulationParams& params) { + const blink::DeviceEmulationParams& params) { emulation_params_ = params; Apply(); } @@ -61,14 +61,14 @@ // If either the width or height are specified by the emulator, then we use // that size, and assume that they have the scale pre-applied to them. - if (emulation_params_.view_size.width) { - widget_size.set_width(emulation_params_.view_size.width); + if (emulation_params_.view_size.width()) { + widget_size.set_width(emulation_params_.view_size.width()); } else { widget_size.set_width( base::ClampRound(widget_size.width() / emulation_params_.scale)); } - if (emulation_params_.view_size.height) { - widget_size.set_height(emulation_params_.view_size.height); + if (emulation_params_.view_size.height()) { + widget_size.set_height(emulation_params_.view_size.height()); } else { widget_size.set_height( base::ClampRound(widget_size.height() / emulation_params_.scale)); @@ -122,7 +122,7 @@ // Pass three emulation parameters to the blink side: // - we keep the real device scale factor in compositor to produce sharp image // even when emulating different scale factor; - blink::WebDeviceEmulationParams modified_emulation_params = emulation_params_; + blink::DeviceEmulationParams modified_emulation_params = emulation_params_; modified_emulation_params.device_scale_factor = original_screen_info().device_scale_factor; delegate_->SetScreenMetricsEmulationParameters(true,
diff --git a/content/renderer/render_widget_screen_metrics_emulator.h b/content/renderer/render_widget_screen_metrics_emulator.h index d40108fa..56a14748 100644 --- a/content/renderer/render_widget_screen_metrics_emulator.h +++ b/content/renderer/render_widget_screen_metrics_emulator.h
@@ -8,8 +8,8 @@ #include <memory> #include "content/common/content_export.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/common/widget/screen_info.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" @@ -57,7 +57,7 @@ void DisableAndApply(); // Sets new parameters and applies them to the RenderWidget. - void ChangeEmulationParams(const blink::WebDeviceEmulationParams& params); + void ChangeEmulationParams(const blink::DeviceEmulationParams& params); void OnSynchronizeVisualProperties( const blink::ScreenInfo& screen_info, @@ -70,8 +70,8 @@ private: bool emulating_desktop() const { - return emulation_params_.screen_position == - blink::WebDeviceEmulationParams::kDesktop; + return emulation_params_.screen_type == + blink::mojom::EmulatedScreenType::kDesktop; } // Applies emulated values to the RenderWidget. @@ -80,7 +80,7 @@ RenderWidgetScreenMetricsEmulatorDelegate* const delegate_; // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation. - blink::WebDeviceEmulationParams emulation_params_; + blink::DeviceEmulationParams emulation_params_; // Original values to restore back after emulation ends. blink::ScreenInfo original_screen_info_;
diff --git a/content/renderer/render_widget_screen_metrics_emulator_delegate.h b/content/renderer/render_widget_screen_metrics_emulator_delegate.h index 1e12de88..48890d6 100644 --- a/content/renderer/render_widget_screen_metrics_emulator_delegate.h +++ b/content/renderer/render_widget_screen_metrics_emulator_delegate.h
@@ -9,7 +9,7 @@ #include "third_party/blink/public/common/widget/screen_info.h" namespace blink { -struct WebDeviceEmulationParams; +struct DeviceEmulationParams; } namespace content { @@ -21,7 +21,7 @@ // Passes device emulation parameters to the delegate. virtual void SetScreenMetricsEmulationParameters( bool enabled, - const blink::WebDeviceEmulationParams& params) = 0; + const blink::DeviceEmulationParams& params) = 0; // Passes an updated ScreenInfo and sizes to the delegate. virtual void SetScreenInfoAndSize(const blink::ScreenInfo& screen_info,
diff --git a/content/renderer/render_widget_unittest.cc b/content/renderer/render_widget_unittest.cc index 2f77c32..44897d12 100644 --- a/content/renderer/render_widget_unittest.cc +++ b/content/renderer/render_widget_unittest.cc
@@ -39,11 +39,11 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/input/synthetic_web_input_event_builders.h" #include "third_party/blink/public/common/input/web_coalesced_input_event.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/common/widget/visual_properties.h" #include "third_party/blink/public/mojom/input/input_handler.mojom.h" #include "third_party/blink/public/mojom/page/widget.mojom-test-utils.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_external_widget.h" #include "third_party/blink/public/web/web_external_widget_client.h" #include "third_party/blink/public/web/web_frame_widget.h" @@ -579,7 +579,7 @@ cc::BrowserControlsParams) override {} void SetScreenMetricsEmulationParametersForWidget( bool enabled, - const blink::WebDeviceEmulationParams& params) override {} + const blink::DeviceEmulationParams& params) override {} }; // Tests that the value of VisualProperties::is_pinch_gesture_active is
diff --git a/content/shell/BUILD.gn b/content/shell/BUILD.gn index 8f162f75..6d7b698 100644 --- a/content/shell/BUILD.gn +++ b/content/shell/BUILD.gn
@@ -154,6 +154,8 @@ "browser/web_test/web_test_push_messaging_service.h", "browser/web_test/web_test_shell_platform_delegate.cc", "browser/web_test/web_test_shell_platform_delegate.h", + "browser/web_test/web_test_storage_access_manager.cc", + "browser/web_test/web_test_storage_access_manager.h", "browser/web_test/web_test_tts_platform.cc", "browser/web_test/web_test_tts_platform.h", ]
diff --git a/content/shell/browser/web_test/DEPS b/content/shell/browser/web_test/DEPS index b662c4d..8ed0cf0 100644 --- a/content/shell/browser/web_test/DEPS +++ b/content/shell/browser/web_test/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+components/content_settings/core/common", "+content/shell/common/web_test", ]
diff --git a/content/shell/browser/web_test/web_test_browser_context.cc b/content/shell/browser/web_test/web_test_browser_context.cc index 5c9276f..d0738e6 100644 --- a/content/shell/browser/web_test/web_test_browser_context.cc +++ b/content/shell/browser/web_test/web_test_browser_context.cc
@@ -20,6 +20,7 @@ #include "content/shell/browser/web_test/web_test_download_manager_delegate.h" #include "content/shell/browser/web_test/web_test_permission_manager.h" #include "content/shell/browser/web_test/web_test_push_messaging_service.h" +#include "content/shell/browser/web_test/web_test_storage_access_manager.h" #include "content/test/mock_background_sync_controller.h" #include "content/test/mock_client_hints_controller_delegate.h" #include "services/device/public/cpp/test/scoped_geolocation_overrider.h" @@ -92,6 +93,13 @@ GetPermissionControllerDelegate()); } +WebTestStorageAccessManager* +WebTestBrowserContext::GetWebTestStorageAccessManager() { + if (!storage_access_.get()) + storage_access_ = std::make_unique<WebTestStorageAccessManager>(this); + return storage_access_.get(); +} + ClientHintsControllerDelegate* WebTestBrowserContext::GetClientHintsControllerDelegate() { if (!client_hints_controller_delegate_) {
diff --git a/content/shell/browser/web_test/web_test_browser_context.h b/content/shell/browser/web_test/web_test_browser_context.h index 1a1e7dd6..6b6ee775 100644 --- a/content/shell/browser/web_test/web_test_browser_context.h +++ b/content/shell/browser/web_test/web_test_browser_context.h
@@ -22,6 +22,7 @@ class WebTestBackgroundFetchDelegate; class WebTestPermissionManager; class WebTestPushMessagingService; +class WebTestStorageAccessManager; class WebTestBrowserContext final : public ShellBrowserContext { public: @@ -37,6 +38,7 @@ ClientHintsControllerDelegate* GetClientHintsControllerDelegate() override; WebTestPermissionManager* GetWebTestPermissionManager(); + WebTestStorageAccessManager* GetWebTestStorageAccessManager(); private: std::unique_ptr<WebTestPushMessagingService> push_messaging_service_; @@ -46,6 +48,7 @@ std::unique_ptr<device::ScopedGeolocationOverrider> geolocation_overrider_; std::unique_ptr<ClientHintsControllerDelegate> client_hints_controller_delegate_; + std::unique_ptr<WebTestStorageAccessManager> storage_access_; DISALLOW_COPY_AND_ASSIGN(WebTestBrowserContext); };
diff --git a/content/shell/browser/web_test/web_test_content_browser_client.cc b/content/shell/browser/web_test/web_test_content_browser_client.cc index 955bec3a..42b90b2 100644 --- a/content/shell/browser/web_test/web_test_content_browser_client.cc +++ b/content/shell/browser/web_test/web_test_content_browser_client.cc
@@ -40,6 +40,7 @@ #include "content/shell/browser/web_test/web_test_client_impl.h" #include "content/shell/browser/web_test/web_test_control_host.h" #include "content/shell/browser/web_test/web_test_permission_manager.h" +#include "content/shell/browser/web_test/web_test_storage_access_manager.h" #include "content/shell/browser/web_test/web_test_tts_platform.h" #include "content/shell/common/web_test/web_test_bluetooth_fake_adapter_setter.mojom.h" #include "content/shell/common/web_test/web_test_switches.h" @@ -225,6 +226,12 @@ base::Unretained(this)), ui_task_runner); + registry->AddInterface( + base::BindRepeating( + &WebTestContentBrowserClient::BindStorageAccessAutomation, + base::Unretained(this)), + ui_task_runner); + associated_registry->AddInterface( base::BindRepeating(&WebTestContentBrowserClient::BindWebTestControlHost, base::Unretained(this))); @@ -240,6 +247,13 @@ std::move(receiver)); } +void WebTestContentBrowserClient::BindStorageAccessAutomation( + mojo::PendingReceiver<blink::test::mojom::StorageAccessAutomation> + receiver) { + GetWebTestBrowserContext()->GetWebTestStorageAccessManager()->Bind( + std::move(receiver)); +} + void WebTestContentBrowserClient::OverrideWebkitPrefs( RenderViewHost* render_view_host, WebPreferences* prefs) {
diff --git a/content/shell/browser/web_test/web_test_content_browser_client.h b/content/shell/browser/web_test/web_test_content_browser_client.h index 150d1a8..a79ff68c 100644 --- a/content/shell/browser/web_test/web_test_content_browser_client.h +++ b/content/shell/browser/web_test/web_test_content_browser_client.h
@@ -21,6 +21,7 @@ #include "third_party/blink/public/mojom/clipboard/clipboard.mojom.h" #include "third_party/blink/public/mojom/clipboard/raw_clipboard.mojom.h" #include "third_party/blink/public/mojom/permissions/permission_automation.mojom-forward.h" +#include "third_party/blink/public/mojom/storage_access/storage_access_automation.mojom-forward.h" namespace content { class FakeBluetoothChooser; @@ -126,6 +127,10 @@ void BindPermissionAutomation( mojo::PendingReceiver<blink::test::mojom::PermissionAutomation> receiver); + void BindStorageAccessAutomation( + mojo::PendingReceiver<blink::test::mojom::StorageAccessAutomation> + receiver); + void BindWebTestControlHost( mojo::PendingAssociatedReceiver<mojom::WebTestControlHost> receiver);
diff --git a/content/shell/browser/web_test/web_test_storage_access_manager.cc b/content/shell/browser/web_test/web_test_storage_access_manager.cc new file mode 100644 index 0000000..37aee01 --- /dev/null +++ b/content/shell/browser/web_test/web_test_storage_access_manager.cc
@@ -0,0 +1,86 @@ +// Copyright 2020 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 "content/shell/browser/web_test/web_test_storage_access_manager.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/storage_partition.h" + +#include <list> +#include <memory> +#include <utility> + +#include "base/bind.h" +#include "base/callback.h" + +namespace content { + +WebTestStorageAccessManager::WebTestStorageAccessManager( + BrowserContext* browser_context) + : browser_context_(browser_context) {} + +WebTestStorageAccessManager::~WebTestStorageAccessManager() = default; + +void WebTestStorageAccessManager::SetStorageAccess( + const std::string& origin, + const std::string& embedding_origin, + const bool blocked, + blink::test::mojom::StorageAccessAutomation::SetStorageAccessCallback + callback) { + const ContentSetting setting = + blocked ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW; + + auto primary_pattern = ContentSettingsPattern::FromString(origin); + if (!primary_pattern.IsValid()) { + std::move(callback).Run(false); + } + + auto secondary_pattern = ContentSettingsPattern::FromString(embedding_origin); + if (!secondary_pattern.IsValid()) { + std::move(callback).Run(false); + } + + content_settings_for_automation_.push_back( + ContentSettingPatternSource(primary_pattern, secondary_pattern, + base::Value(setting), std::string(), false)); + + // TODO(https://crbug.com/1106098) - Storage Access API should support all + // storage types in content shell + + // Storage access API (SAA) settings for cookies are implemented in the + // network::CookieSettings class. Settings for other storage types such as + // local storage and indexeddb are implemented in + // content_settings::CookieSettings. Content Shell does not + // use the content_settings::CookieSettings class so SAA affects only + // cookie access here. Other storage types are always allowed in + // Content Shell. + + // Since cookies are the only storage type governed by SAA in Content Shell, + // this class handles cookie rules only. If Content Shell or SAA are + // updated in the future so that more storage types are governed by SAA in + // Content Shell, then we should update this class to handle those other + // types are well. + + auto* storage_partition = + BrowserContext::GetDefaultStoragePartition(browser_context_); + auto* cookie_manager = storage_partition->GetCookieManagerForBrowserProcess(); + + // Enable third-party cookies blocking if we have not done so yet. This will + // cause the content settings to take effect. + if (!third_party_cookies_blocked_) { + cookie_manager->BlockThirdPartyCookies(true); + third_party_cookies_blocked_ = true; + } + + // Update the cookie manager's copy of the content settings. + cookie_manager->SetContentSettings(content_settings_for_automation_); + std::move(callback).Run(true); +} + +void WebTestStorageAccessManager::Bind( + mojo::PendingReceiver<blink::test::mojom::StorageAccessAutomation> + receiver) { + receivers_.Add(this, std::move(receiver)); +} + +} // namespace content
diff --git a/content/shell/browser/web_test/web_test_storage_access_manager.h b/content/shell/browser/web_test/web_test_storage_access_manager.h new file mode 100644 index 0000000..e3c99c8 --- /dev/null +++ b/content/shell/browser/web_test/web_test_storage_access_manager.h
@@ -0,0 +1,52 @@ +// Copyright 2020 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 CONTENT_SHELL_BROWSER_WEB_TEST_WEB_TEST_STORAGE_ACCESS_MANAGER_H_ +#define CONTENT_SHELL_BROWSER_WEB_TEST_WEB_TEST_STORAGE_ACCESS_MANAGER_H_ + +#include <stddef.h> + +#include "base/callback_forward.h" +#include "base/containers/id_map.h" +#include "base/macros.h" +#include "base/synchronization/lock.h" +#include "components/content_settings/core/common/content_settings.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "third_party/blink/public/mojom/storage_access/storage_access_automation.mojom.h" + +namespace content { + +class BrowserContext; + +class WebTestStorageAccessManager + : public blink::test::mojom::StorageAccessAutomation { + public: + explicit WebTestStorageAccessManager(BrowserContext* browser_context); + ~WebTestStorageAccessManager() override; + + // blink::test::mojom::StorageAccessAutomation + void SetStorageAccess( + const std::string& origin, + const std::string& embedding_origin, + const bool blocked, + blink::test::mojom::StorageAccessAutomation::SetStorageAccessCallback) + override; + + void Bind(mojo::PendingReceiver<blink::test::mojom::StorageAccessAutomation> + receiver); + + private: + BrowserContext* browser_context_; + + mojo::ReceiverSet<blink::test::mojom::StorageAccessAutomation> receivers_; + + ContentSettingsForOneType content_settings_for_automation_; + bool third_party_cookies_blocked_ = false; + + DISALLOW_COPY_AND_ASSIGN(WebTestStorageAccessManager); +}; + +} // namespace content + +#endif // CONTENT_SHELL_BROWSER_WEB_TEST_WEB_TEST_STORAGE_ACCESS_MANAGER_H_
diff --git a/content/test/data/accessibility/aria/aria-combobox-expected-mac.txt b/content/test/data/accessibility/aria/aria-combobox-expected-mac.txt index 05121ca..802bf53 100644 --- a/content/test/data/accessibility/aria/aria-combobox-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-combobox-expected-mac.txt
@@ -1,7 +1,7 @@ AXWebArea ++AXGroup ++++AXStaticText AXValue='State' -++AXComboBox AXAutocompleteValue='list' AXFocused=1 AXTitle='State' +++AXComboBox AXAutocompleteValue='list' AXTitle='State' ++AXList ++++AXStaticText AXValue='Alabama' -++++AXStaticText AXValue='Alaska' +++++AXStaticText AXFocused=1 AXValue='Alaska' \ No newline at end of file
diff --git a/content/test/data/accessibility/event/aria-combo-box-collapse-expected-mac.txt b/content/test/data/accessibility/event/aria-combo-box-collapse-expected-mac.txt index 97c3c41..93ef79e 100644 --- a/content/test/data/accessibility/event/aria-combo-box-collapse-expected-mac.txt +++ b/content/test/data/accessibility/event/aria-combo-box-collapse-expected-mac.txt
@@ -1,2 +1,3 @@ AXExpandedChanged on AXComboBox -AXSelectedChildrenChanged on AXComboBox +AXFocusedUIElementChanged on AXComboBox +AXSelectedChildrenChanged on AXComboBox \ No newline at end of file
diff --git a/content/test/data/accessibility/event/aria-combo-box-delay-add-list-expected-mac.txt b/content/test/data/accessibility/event/aria-combo-box-delay-add-list-expected-mac.txt index 47ff72a..f7d4c30 100644 --- a/content/test/data/accessibility/event/aria-combo-box-delay-add-list-expected-mac.txt +++ b/content/test/data/accessibility/event/aria-combo-box-delay-add-list-expected-mac.txt
@@ -1 +1,2 @@ -AXSelectedChildrenChanged on AXComboBox +AXFocusedUIElementChanged on AXStaticText AXValue="Apple" +AXSelectedChildrenChanged on AXComboBox \ No newline at end of file
diff --git a/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-mac.txt b/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-mac.txt index ec6b5552..4de438ff 100644 --- a/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-mac.txt +++ b/content/test/data/accessibility/event/aria-combo-box-delay-show-list-expected-mac.txt
@@ -1,2 +1,3 @@ +AXFocusedUIElementChanged on AXStaticText AXValue="Apple" AXSelectedChildrenChanged on AXComboBox AXSelectedChildrenChanged on AXList \ No newline at end of file
diff --git a/content/test/data/accessibility/event/aria-combo-box-expand-expected-mac.txt b/content/test/data/accessibility/event/aria-combo-box-expand-expected-mac.txt index 97cdb8b..343feae3 100644 --- a/content/test/data/accessibility/event/aria-combo-box-expand-expected-mac.txt +++ b/content/test/data/accessibility/event/aria-combo-box-expand-expected-mac.txt
@@ -1,3 +1,4 @@ AXExpandedChanged on AXComboBox +AXFocusedUIElementChanged on AXStaticText AXValue="Apple" AXSelectedChildrenChanged on AXComboBox -AXSelectedChildrenChanged on AXList +AXSelectedChildrenChanged on AXList \ No newline at end of file
diff --git a/content/test/data/accessibility/event/aria-combo-box-focus-expected-mac.txt b/content/test/data/accessibility/event/aria-combo-box-focus-expected-mac.txt index 2bfc70f5..ad5e2bf2 100644 --- a/content/test/data/accessibility/event/aria-combo-box-focus-expected-mac.txt +++ b/content/test/data/accessibility/event/aria-combo-box-focus-expected-mac.txt
@@ -1,3 +1,3 @@ -AXFocusedUIElementChanged on AXComboBox -AXSelectedTextChanged on AXComboBox -AXSelectedTextChanged on AXWebArea +AXFocusedUIElementChanged on AXStaticText AXValue="Apple not selected" +AXSelectedTextChanged on AXStaticText AXValue="Apple not selected" +AXSelectedTextChanged on AXWebArea \ No newline at end of file
diff --git a/content/test/data/accessibility/event/aria-combo-box-next-expected-mac.txt b/content/test/data/accessibility/event/aria-combo-box-next-expected-mac.txt index d5f21183..9e7d0c0 100644 --- a/content/test/data/accessibility/event/aria-combo-box-next-expected-mac.txt +++ b/content/test/data/accessibility/event/aria-combo-box-next-expected-mac.txt
@@ -1,5 +1,7 @@ +AXFocusedUIElementChanged on AXStaticText AXValue="Orange" AXSelectedChildrenChanged on AXComboBox AXSelectedChildrenChanged on AXList === Start Continuation === +AXFocusedUIElementChanged on AXStaticText AXValue="Banana" AXSelectedChildrenChanged on AXComboBox -AXSelectedChildrenChanged on AXList +AXSelectedChildrenChanged on AXList \ No newline at end of file
diff --git a/content/test/test_web_contents.cc b/content/test/test_web_contents.cc index 714f9c0..24d5501 100644 --- a/content/test/test_web_contents.cc +++ b/content/test/test_web_contents.cc
@@ -243,15 +243,16 @@ OnAudioStateChanged(); } -void TestWebContents::TestDidReceiveInputEvent( - blink::WebInputEvent::Type type) { +void TestWebContents::TestDidReceiveMouseDownEvent() { + blink::WebMouseEvent event; + event.SetType(blink::WebInputEvent::Type::kMouseDown); // Use the first RenderWidgetHost from the frame tree to make sure that the // interaction doesn't get ignored. DCHECK(frame_tree_.Nodes().begin() != frame_tree_.Nodes().end()); RenderWidgetHostImpl* render_widget_host = (*frame_tree_.Nodes().begin()) ->current_frame_host() ->GetRenderWidgetHost(); - DidReceiveInputEvent(render_widget_host, type); + DidReceiveInputEvent(render_widget_host, event); } void TestWebContents::TestDidFinishLoad(const GURL& url) {
diff --git a/content/test/test_web_contents.h b/content/test/test_web_contents.h index 7967c46d6..3ae1cc90 100644 --- a/content/test/test_web_contents.h +++ b/content/test/test_web_contents.h
@@ -112,7 +112,7 @@ void SetMainFrameMimeType(const std::string& mime_type) override; const std::string& GetContentsMimeType() override; void SetIsCurrentlyAudible(bool audible) override; - void TestDidReceiveInputEvent(blink::WebInputEvent::Type type) override; + void TestDidReceiveMouseDownEvent() override; void TestDidFinishLoad(const GURL& url) override; void TestDidFailLoadWithError(const GURL& url, int error_code) override;
diff --git a/device/vr/openxr/openxr_controller.cc b/device/vr/openxr/openxr_controller.cc index bb74ea4..6c1c2df 100644 --- a/device/vr/openxr/openxr_controller.cc +++ b/device/vr/openxr/openxr_controller.cc
@@ -236,10 +236,8 @@ path_helper_->GetInputProfiles(interaction_profile_); } - if (!description_->input_from_pointer) { - description_->input_from_pointer = - GetPointerFromGripTransform(predicted_display_time); - } + description_->input_from_pointer = + GetPointerFromGripTransform(predicted_display_time); return description_.Clone(); }
diff --git a/docs/gpu/pixel_wrangling.md b/docs/gpu/pixel_wrangling.md index 37b64ca..06ff5af 100644 --- a/docs/gpu/pixel_wrangling.md +++ b/docs/gpu/pixel_wrangling.md
@@ -46,11 +46,20 @@ compare the `got_angle_revision` buildbot property on the GPU builders or `parent_got_angle_revision` on the testers. This revision can be used to do a `git log` in the `third_party/angle` repository. +* [Chromium SwANGLE] + * These bots run GPU tests on top of ANGLE's GLES implementation running + on top of SwiftShader's Vulkan implementation purely in software. + Regressions should mostly be handled by the [ANGLE Wrangler], but some + failures fall into Pixel Wrangler's domain, for example, WebGL failures + due to Chromium-side and WebGL-side changes on + linux-swangle-chromium-x64, mac-swangle-chromium-x64 and + win-swangle-chromium-x86 bots. <!-- TODO(kainino): update link when the page is migrated --> [Tour of the Chromium Buildbot Waterfall]: http://www.chromium.org/developers/testing/chromium-build-infrastructure/tour-of-the-chromium-buildbot [Chromium GPU]: https://ci.chromium.org/p/chromium/g/chromium.gpu/console?reload=120 [Chromium GPU FYI]: https://ci.chromium.org/p/chromium/g/chromium.gpu.fyi/console?reload=120 +[Chromium SwANGLE]: https://ci.chromium.org/p/chromium/g/chromium.swangle/console?reload=120 [ANGLE tryservers]: https://build.chromium.org/p/tryserver.chromium.angle/waterfall [ANGLE Wrangler]: https://chromium.googlesource.com/angle/angle/+/master/infra/ANGLEWrangling.md @@ -128,9 +137,9 @@ ### How to Keep the Bots Green 1. Watch for redness on the tree. - 1. [Sheriff-O-Matic now has support for the chromium.gpu.fyi waterfall]! - 1. The chromium.gpu bots are covered under Sheriff-O-Matic's [Chromium - tab]. As pixel wrangler, ignore any non-GPU test failures in this tab. + 1. [Sheriff-O-Matic] now has support for all the + [GPU Bots' Waterfalls](#GPU-Bots_Waterfalls) under the + [Chromium GPU][Sheriff-O-Matic] tab! 1. The bots are expected to be green all the time. Flakiness on these bots is neither expected nor acceptable. 1. If a bot goes consistently red, it's necessary to figure out whether a @@ -259,8 +268,7 @@ 1. For the remaining Gtest-style tests, use the [`DISABLED_` modifier][gtest-DISABLED] to suppress any failures if necessary. -[Sheriff-O-Matic now has support for the chromium.gpu.fyi waterfall]: https://sheriff-o-matic.appspot.com/chromium.gpu.fyi -[Chromium tab]: https://sheriff-o-matic.appspot.com/chromium +[Sheriff-O-Matic]: https://sheriff-o-matic.appspot.com/chromium.gpu [tree sheriffing page]: https://sites.google.com/a/chromium.org/dev/developers/tree-sheriffs [linux-rel]: https://ci.chromium.org/p/chromium/builders/luci.chromium.try/linux-rel [luci.chromium.try]: https://ci.chromium.org/p/chromium/g/luci.chromium.try/builders
diff --git a/extensions/common/BUILD.gn b/extensions/common/BUILD.gn index 9230a03..70bed1f 100644 --- a/extensions/common/BUILD.gn +++ b/extensions/common/BUILD.gn
@@ -212,6 +212,8 @@ "manifest_handlers/csp_info.h", "manifest_handlers/default_locale_handler.cc", "manifest_handlers/default_locale_handler.h", + "manifest_handlers/extension_action_handler.cc", + "manifest_handlers/extension_action_handler.h", "manifest_handlers/externally_connectable.cc", "manifest_handlers/externally_connectable.h", "manifest_handlers/file_handler_info.cc", @@ -444,6 +446,7 @@ "manifest_handlers/content_capabilities_manifest_unittest.cc", "manifest_handlers/csp_info_unittest.cc", "manifest_handlers/default_locale_manifest_unittest.cc", + "manifest_handlers/extension_action_handler_unittest.cc", "manifest_handlers/externally_connectable_unittest.cc", "manifest_handlers/file_handler_manifest_unittest.cc", "manifest_handlers/icons_handler_unittest.cc",
diff --git a/extensions/common/api/networking_private.idl b/extensions/common/api/networking_private.idl index 48088b6..2de0aa04 100644 --- a/extensions/common/api/networking_private.idl +++ b/extensions/common/api/networking_private.idl
@@ -648,7 +648,6 @@ EAPProperties? EAP; long? Frequency; long[]? FrequencyList; - boolean? FTEnabled; DOMString? HexSSID; boolean? HiddenSSID; DOMString? Passphrase; @@ -665,7 +664,6 @@ ManagedEAPProperties? EAP; long? Frequency; long[]? FrequencyList; - ManagedBoolean? FTEnabled; ManagedDOMString? HexSSID; ManagedBoolean? HiddenSSID; ManagedDOMString? Passphrase;
diff --git a/extensions/common/common_manifest_handlers.cc b/extensions/common/common_manifest_handlers.cc index e1416e2..fee09bd 100644 --- a/extensions/common/common_manifest_handlers.cc +++ b/extensions/common/common_manifest_handlers.cc
@@ -18,6 +18,7 @@ #include "extensions/common/manifest_handlers/content_scripts_handler.h" #include "extensions/common/manifest_handlers/csp_info.h" #include "extensions/common/manifest_handlers/default_locale_handler.h" +#include "extensions/common/manifest_handlers/extension_action_handler.h" #include "extensions/common/manifest_handlers/externally_connectable.h" #include "extensions/common/manifest_handlers/file_handler_info.h" #include "extensions/common/manifest_handlers/icons_handler.h" @@ -62,6 +63,7 @@ registry->RegisterHandler(std::make_unique<DeclarativeManifestHandler>()); registry->RegisterHandler(std::make_unique<DefaultLocaleHandler>()); registry->RegisterHandler(std::make_unique<ExternallyConnectableHandler>()); + registry->RegisterHandler(std::make_unique<ExtensionActionHandler>()); registry->RegisterHandler(std::make_unique<FileHandlersParser>()); registry->RegisterHandler(std::make_unique<IconsHandler>()); registry->RegisterHandler(std::make_unique<IncognitoHandler>());
diff --git a/chrome/common/extensions/manifest_handlers/extension_action_handler.cc b/extensions/common/manifest_handlers/extension_action_handler.cc similarity index 94% rename from chrome/common/extensions/manifest_handlers/extension_action_handler.cc rename to extensions/common/manifest_handlers/extension_action_handler.cc index 1f7378bd..cc4f22b 100644 --- a/chrome/common/extensions/manifest_handlers/extension_action_handler.cc +++ b/extensions/common/manifest_handlers/extension_action_handler.cc
@@ -2,13 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/common/extensions/manifest_handlers/extension_action_handler.h" +#include "extensions/common/manifest_handlers/extension_action_handler.h" #include <memory> #include "base/strings/utf_string_conversions.h" #include "base/values.h" -#include "chrome/common/extensions/extension_constants.h" #include "extensions/common/api/extension_action/action_info.h" #include "extensions/common/extension.h" #include "extensions/common/file_util.h" @@ -17,11 +16,9 @@ namespace extensions { -ExtensionActionHandler::ExtensionActionHandler() { -} +ExtensionActionHandler::ExtensionActionHandler() {} -ExtensionActionHandler::~ExtensionActionHandler() { -} +ExtensionActionHandler::~ExtensionActionHandler() {} bool ExtensionActionHandler::Parse(Extension* extension, base::string16* error) {
diff --git a/chrome/common/extensions/manifest_handlers/extension_action_handler.h b/extensions/common/manifest_handlers/extension_action_handler.h similarity index 78% rename from chrome/common/extensions/manifest_handlers/extension_action_handler.h rename to extensions/common/manifest_handlers/extension_action_handler.h index 295c424..69be27b 100644 --- a/chrome/common/extensions/manifest_handlers/extension_action_handler.h +++ b/extensions/common/manifest_handlers/extension_action_handler.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_COMMON_EXTENSIONS_MANIFEST_HANDLERS_EXTENSION_ACTION_HANDLER_H_ -#define CHROME_COMMON_EXTENSIONS_MANIFEST_HANDLERS_EXTENSION_ACTION_HANDLER_H_ +#ifndef EXTENSIONS_COMMON_MANIFEST_HANDLERS_EXTENSION_ACTION_HANDLER_H_ +#define EXTENSIONS_COMMON_MANIFEST_HANDLERS_EXTENSION_ACTION_HANDLER_H_ #include <string> @@ -32,4 +32,4 @@ } // namespace extensions -#endif // CHROME_COMMON_EXTENSIONS_MANIFEST_HANDLERS_EXTENSION_ACTION_HANDLER_H_ +#endif // EXTENSIONS_COMMON_MANIFEST_HANDLERS_EXTENSION_ACTION_HANDLER_H_
diff --git a/chrome/common/extensions/manifest_handlers/extension_action_handler_unittest.cc b/extensions/common/manifest_handlers/extension_action_handler_unittest.cc similarity index 97% rename from chrome/common/extensions/manifest_handlers/extension_action_handler_unittest.cc rename to extensions/common/manifest_handlers/extension_action_handler_unittest.cc index 80f46b46..02bcdde 100644 --- a/chrome/common/extensions/manifest_handlers/extension_action_handler_unittest.cc +++ b/extensions/common/manifest_handlers/extension_action_handler_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 "chrome/common/extensions/manifest_handlers/extension_action_handler.h" +#include "extensions/common/manifest_handlers/extension_action_handler.h" #include "base/files/file_path.h" #include "base/path_service.h" @@ -10,13 +10,13 @@ #include "base/strings/stringprintf.h" #include "base/test/values_test_util.h" #include "base/values.h" -#include "chrome/common/chrome_paths.h" #include "components/version_info/channel.h" #include "extensions/common/api/extension_action/action_info.h" #include "extensions/common/api/extension_action/action_info_test_util.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_icon_set.h" +#include "extensions/common/extension_paths.h" #include "extensions/common/features/feature_channel.h" #include "extensions/common/file_util.h" #include "extensions/common/manifest.h" @@ -30,8 +30,8 @@ base::FilePath GetTestDataDir() { base::FilePath path; - base::PathService::Get(chrome::DIR_TEST_DATA, &path); - return path.AppendASCII("extensions").AppendASCII("manifest_handlers"); + base::PathService::Get(DIR_TEST_DATA, &path); + return path.AppendASCII("manifest_handlers"); } } // namespace
diff --git a/chrome/test/data/extensions/manifest_handlers/browser_action_invisible_icon/README b/extensions/test/data/manifest_handlers/browser_action_invisible_icon/README similarity index 100% rename from chrome/test/data/extensions/manifest_handlers/browser_action_invisible_icon/README rename to extensions/test/data/manifest_handlers/browser_action_invisible_icon/README
diff --git a/chrome/test/data/extensions/manifest_handlers/browser_action_invisible_icon/invisible_icon.png b/extensions/test/data/manifest_handlers/browser_action_invisible_icon/invisible_icon.png similarity index 100% rename from chrome/test/data/extensions/manifest_handlers/browser_action_invisible_icon/invisible_icon.png rename to extensions/test/data/manifest_handlers/browser_action_invisible_icon/invisible_icon.png Binary files differ
diff --git a/chrome/test/data/extensions/manifest_handlers/browser_action_invisible_icon/manifest.json b/extensions/test/data/manifest_handlers/browser_action_invisible_icon/manifest.json similarity index 100% rename from chrome/test/data/extensions/manifest_handlers/browser_action_invisible_icon/manifest.json rename to extensions/test/data/manifest_handlers/browser_action_invisible_icon/manifest.json
diff --git a/chrome/test/data/extensions/manifest_handlers/page_action_invisible_icon/README b/extensions/test/data/manifest_handlers/page_action_invisible_icon/README similarity index 100% rename from chrome/test/data/extensions/manifest_handlers/page_action_invisible_icon/README rename to extensions/test/data/manifest_handlers/page_action_invisible_icon/README
diff --git a/chrome/test/data/extensions/manifest_handlers/page_action_invisible_icon/invisible_icon.png b/extensions/test/data/manifest_handlers/page_action_invisible_icon/invisible_icon.png similarity index 100% rename from chrome/test/data/extensions/manifest_handlers/page_action_invisible_icon/invisible_icon.png rename to extensions/test/data/manifest_handlers/page_action_invisible_icon/invisible_icon.png Binary files differ
diff --git a/chrome/test/data/extensions/manifest_handlers/page_action_invisible_icon/manifest.json b/extensions/test/data/manifest_handlers/page_action_invisible_icon/manifest.json similarity index 100% rename from chrome/test/data/extensions/manifest_handlers/page_action_invisible_icon/manifest.json rename to extensions/test/data/manifest_handlers/page_action_invisible_icon/manifest.json
diff --git a/gpu/command_buffer/client/BUILD.gn b/gpu/command_buffer/client/BUILD.gn index ed85181a..23be1a2 100644 --- a/gpu/command_buffer/client/BUILD.gn +++ b/gpu/command_buffer/client/BUILD.gn
@@ -205,6 +205,7 @@ "//base", "//components/viz/common:resource_format", "//gpu/command_buffer/common", + "//skia:skia", "//ui/gfx:buffer_types", ] }
diff --git a/ios/chrome/app/DEPS b/ios/chrome/app/DEPS index 5891cb7..2cc969cf 100644 --- a/ios/chrome/app/DEPS +++ b/ios/chrome/app/DEPS
@@ -20,6 +20,7 @@ "+components/search_engines", "+components/suggestions", "+components/sync/driver", + "+components/version_info", "+components/ukm/ios", "+components/unified_consent", "+components/url_formatter",
diff --git a/ios/chrome/app/application_delegate/BUILD.gn b/ios/chrome/app/application_delegate/BUILD.gn index 07b6c38..13ac47c 100644 --- a/ios/chrome/app/application_delegate/BUILD.gn +++ b/ios/chrome/app/application_delegate/BUILD.gn
@@ -138,6 +138,7 @@ deps = [ ":ios_enable_metrickit_buildflags", "//base", + "//components/version_info", ] } @@ -234,6 +235,8 @@ "fake_startup_information.h", "fake_startup_information.mm", "metrics_mediator_testing.h", + "mock_metrickit_metric_payload.h", + "mock_metrickit_metric_payload.mm", "mock_tab_opener.h", "mock_tab_opener.mm", ] @@ -242,14 +245,19 @@ ":tab_opening", "//base", "//base/test:test_support", + "//components/version_info", "//ios/chrome/app", "//ios/chrome/app:app_internal", "//ios/chrome/app:mode", "//ios/chrome/browser", "//ios/chrome/browser/url_loading", "//net", + "//third_party/ocmock", "//ui/base", "//url", ] - frameworks = [ "UIKit.framework" ] + frameworks = [ + "MetricKit.framework", + "UIKit.framework", + ] }
diff --git a/ios/chrome/app/application_delegate/app_state.h b/ios/chrome/app/application_delegate/app_state.h index 02e498c..9e9d41e1 100644 --- a/ios/chrome/app/application_delegate/app_state.h +++ b/ios/chrome/app/application_delegate/app_state.h
@@ -54,6 +54,9 @@ // application has been woken up by the system for background work. @property(nonatomic, readonly) BOOL userInteracted; +// YES if the sign-in upgrade promo has been presented to the user, once. +@property(nonatomic) BOOL signinUpgradePromoPresentedOnce; + // When multiwindow is unavailable, this is the only scene state. It is created // by the app delegate. @property(nonatomic, strong) SceneState* mainSceneState;
diff --git a/ios/chrome/app/application_delegate/metric_kit_subscriber.mm b/ios/chrome/app/application_delegate/metric_kit_subscriber.mm index 8154e3b..29c9643 100644 --- a/ios/chrome/app/application_delegate/metric_kit_subscriber.mm +++ b/ios/chrome/app/application_delegate/metric_kit_subscriber.mm
@@ -6,9 +6,14 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/metrics/histogram_base.h" +#include "base/metrics/histogram_functions.h" +#include "base/numerics/safe_conversions.h" #include "base/strings/sys_string_conversions.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" +#include "base/version.h" +#include "components/version_info/version_info.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -16,8 +21,63 @@ NSString* const kChromeMetricKitPayloadsDirectory = @"ChromeMetricKitPayloads"; +// The different causes of app exit as reported by MetricKit. +// This enum is used in UMA. Do not change the order. +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum MetricKitExitReason { + kNormalAppExit = 0, + kAbnormalAppExit = 1, + kWatchdogExit = 2, + kCPUResourceLimitExit = 3, + kMemoryResourceLimitExit = 4, + kMemoryPressureExit = 5, + kSuspendedWithLockedFileExit = 6, + kBadAccessExit = 7, + kIllegalInstructionExit = 8, + kBackgroundTaskAssertionTimeoutExit = 9, + + // Must be the last enum entries. + kMetricKitExitReasonMaxValue = kBackgroundTaskAssertionTimeoutExit, + kMetricKitExitReasonCount = kMetricKitExitReasonMaxValue + 1 +}; + namespace { +#if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 +void ReportExitReason(base::HistogramBase* histogram, + MetricKitExitReason bucket, + NSUInteger count) { + if (!count) { + return; + } + histogram->AddCount(bucket, count); +} +#endif + +void ReportDuration(const char* histogram_name, NSMeasurement* measurement) + API_AVAILABLE(ios(13.0)) { + if (!measurement) { + return; + } + double value = + [measurement measurementByConvertingToUnit:NSUnitDuration.seconds] + .doubleValue; + base::UmaHistogramTimes(histogram_name, base::TimeDelta::FromSecondsD(value)); +} + +void ReportMemory(const char* histogram_name, NSMeasurement* measurement) + API_AVAILABLE(ios(13.0)) { + if (!measurement) { + return; + } + double value = + [measurement + measurementByConvertingToUnit:NSUnitInformationStorage.megabytes] + .doubleValue; + base::UmaHistogramMemoryLargeMB(histogram_name, value); +} + void WriteMetricPayloads(NSArray<MXMetricPayload*>* payloads) API_AVAILABLE(ios(13.0)) { NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, @@ -95,6 +155,141 @@ base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::ThreadPolicy::PREFER_BACKGROUND, base::MayBlock()}, base::BindOnce(WriteMetricPayloads, payloads)); + for (MXMetricPayload* payload : payloads) { + [self processPayload:payload]; + } +} + +- (void)logStartupDurationMXHistogram:(MXHistogram*)histogram + toUMAHistogram:(const char*)histogramUMAName + API_AVAILABLE(ios(13.0)) { + if (!histogram || !histogram.totalBucketCount) { + return; + } + // It should take less than 1 minute to startup. + // Histogram is defined in millisecond granularity. + base::HistogramBase* histogramUMA = base::Histogram::FactoryTimeGet( + histogramUMAName, base::TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMinutes(1), 50, + base::HistogramBase::kUmaTargetedHistogramFlag); + MXHistogramBucket* bucket; + NSEnumerator* enumerator = [histogram bucketEnumerator]; + while (bucket = [enumerator nextObject]) { + // MXHistogram structure is linear and the bucket size is not guaranteed to + // never change. As the granularity is small in the current iOS version, + // (10ms) they are reported using a representative value of the bucket. + // DCHECK on the size of the bucket to detect if the resolution decrease. + + // Time based MXHistogram report their values using |UnitDuration| which has + // seconds as base unit. Hence, start and end are given in seconds. + double start = + [bucket.bucketStart + measurementByConvertingToUnit:NSUnitDuration.milliseconds] + .doubleValue; + double end = [bucket.bucketEnd + measurementByConvertingToUnit:NSUnitDuration.milliseconds] + .doubleValue; + // DCHECKS that resolution is less than 10ms. + // Note: Real paylods use 10ms resolution but the simulated payload in XCode + // uses 100ms resolution so it will trigger this DCHECK. + DCHECK_LE(end - start, 10); + double sample = (end + start) / 2; + histogramUMA->AddCount( + base::saturated_cast<base::HistogramBase::Sample>(sample), + bucket.bucketCount); + } +} + +#if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 +- (void)logForegroundExit:(MXForegroundExitData*)exitData + API_AVAILABLE(ios(14.0)) { + base::HistogramBase* histogramUMA = base::LinearHistogram::FactoryGet( + "IOS.MetricKit.ForegroundExitData", 1, kMetricKitExitReasonCount, + kMetricKitExitReasonCount + 1, + base::HistogramBase::kUmaTargetedHistogramFlag); + ReportExitReason(histogramUMA, kNormalAppExit, + exitData.cumulativeNormalAppExitCount); + ReportExitReason(histogramUMA, kAbnormalAppExit, + exitData.cumulativeAbnormalExitCount); + ReportExitReason(histogramUMA, kWatchdogExit, + exitData.cumulativeAppWatchdogExitCount); + ReportExitReason(histogramUMA, kMemoryResourceLimitExit, + exitData.cumulativeMemoryResourceLimitExitCount); + ReportExitReason(histogramUMA, kBadAccessExit, + exitData.cumulativeBadAccessExitCount); + ReportExitReason(histogramUMA, kIllegalInstructionExit, + exitData.cumulativeIllegalInstructionExitCount); +} + +- (void)logBackgroundExit:(MXBackgroundExitData*)exitData + API_AVAILABLE(ios(14.0)) { + base::HistogramBase* histogramUMA = base::LinearHistogram::FactoryGet( + "IOS.MetricKit.BackgroundExitData", 1, kMetricKitExitReasonCount, + kMetricKitExitReasonCount + 1, + base::HistogramBase::kUmaTargetedHistogramFlag); + ReportExitReason(histogramUMA, kNormalAppExit, + exitData.cumulativeNormalAppExitCount); + ReportExitReason(histogramUMA, kAbnormalAppExit, + exitData.cumulativeAbnormalExitCount); + ReportExitReason(histogramUMA, kWatchdogExit, + exitData.cumulativeAppWatchdogExitCount); + ReportExitReason(histogramUMA, kCPUResourceLimitExit, + exitData.cumulativeCPUResourceLimitExitCount); + ReportExitReason(histogramUMA, kMemoryResourceLimitExit, + exitData.cumulativeMemoryResourceLimitExitCount); + ReportExitReason(histogramUMA, kMemoryPressureExit, + exitData.cumulativeMemoryPressureExitCount); + ReportExitReason(histogramUMA, kSuspendedWithLockedFileExit, + exitData.cumulativeSuspendedWithLockedFileExitCount); + ReportExitReason(histogramUMA, kBadAccessExit, + exitData.cumulativeBadAccessExitCount); + ReportExitReason(histogramUMA, kIllegalInstructionExit, + exitData.cumulativeIllegalInstructionExitCount); + ReportExitReason(histogramUMA, kBackgroundTaskAssertionTimeoutExit, + exitData.cumulativeBackgroundTaskAssertionTimeoutExitCount); +} +#endif + +- (void)processPayload:(MXMetricPayload*)payload API_AVAILABLE(ios(13.0)) { + if (payload.includesMultipleApplicationVersions || + base::SysNSStringToUTF8(payload.metaData.applicationBuildVersion) != + version_info::GetVersionNumber()) { + // The metrics will be reported on the current version of Chrome. + // Ignore any report that contains data from another version to avoid + // confusion. + return; + } + + ReportDuration("IOS.MetricKit.ForegroundTimePerDay", + payload.applicationTimeMetrics.cumulativeForegroundTime); + ReportDuration("IOS.MetricKit.BackgroundTimePerDay", + payload.applicationTimeMetrics.cumulativeBackgroundTime); + ReportMemory("IOS.MetricKit.AverageSuspendedMemory", + payload.memoryMetrics.averageSuspendedMemory.averageMeasurement); + ReportMemory("IOS.MetricKit.PeakMemoryUsage", + payload.memoryMetrics.peakMemoryUsage); + + MXHistogram* histogrammedApplicationResumeTime = + payload.applicationLaunchMetrics.histogrammedApplicationResumeTime; + [self logStartupDurationMXHistogram:histogrammedApplicationResumeTime + toUMAHistogram:"IOS.MetricKit.ApplicationResumeTime"]; + + MXHistogram* histogrammedTimeToFirstDraw = + payload.applicationLaunchMetrics.histogrammedTimeToFirstDraw; + [self logStartupDurationMXHistogram:histogrammedTimeToFirstDraw + toUMAHistogram:"IOS.MetricKit.TimeToFirstDraw"]; + + MXHistogram* histogrammedApplicationHangTime = + payload.applicationResponsivenessMetrics.histogrammedApplicationHangTime; + [self logStartupDurationMXHistogram:histogrammedApplicationHangTime + toUMAHistogram:"IOS.MetricKit.ApplicationHangTime"]; + +#if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 + if (@available(iOS 14, *)) { + [self logForegroundExit:payload.applicationExitMetrics.foregroundExitData]; + [self logBackgroundExit:payload.applicationExitMetrics.backgroundExitData]; + } +#endif } #if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0
diff --git a/ios/chrome/app/application_delegate/metric_kit_subscriber_unittest.mm b/ios/chrome/app/application_delegate/metric_kit_subscriber_unittest.mm index 9aa6a6b3..e315ab4 100644 --- a/ios/chrome/app/application_delegate/metric_kit_subscriber_unittest.mm +++ b/ios/chrome/app/application_delegate/metric_kit_subscriber_unittest.mm
@@ -9,10 +9,13 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/ios/ios_util.h" #include "base/run_loop.h" #include "base/strings/sys_string_conversions.h" #include "base/test/ios/wait_util.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" +#include "ios/chrome/app/application_delegate/mock_metrickit_metric_payload.h" #include "testing/platform_test.h" #import "third_party/ocmock/OCMock/OCMock.h" #include "third_party/ocmock/gtest_support.h" @@ -47,6 +50,88 @@ base::test::TaskEnvironment task_environment_; }; +TEST_F(MetricKitSubscriberTest, Metrics) { + base::HistogramTester tester; + if (@available(iOS 13, *)) { + MXMetricPayload* mock_report = MockMetricPayload(@{ + @"applicationTimeMetrics" : + @{@"cumulativeForegroundTime" : @1, @"cumulativeBackgroundTime" : @2}, + @"memoryMetrics" : + @{@"peakMemoryUsage" : @3, @"averageSuspendedMemory" : @4}, + @"applicationLaunchMetrics" : @{ + @"histogrammedResumeTime" : @{@25 : @5, @35 : @7}, + @"histogrammedTimeToFirstDrawKey" : @{@5 : @2, @15 : @4} + }, + @"applicationExitMetrics" : @{ + @"backgroundExitData" : @{ + @"cumulativeAppWatchdogExitCount" : @1, + @"cumulativeMemoryResourceLimitExitCount" : @2, + // These two entries are present in the simulated payload but not in + // the SDK. + // @"cumulativeBackgroundURLSessionCompletionTimeoutExitCount" : @3, + // @"cumulativeBackgroundFetchCompletionTimeoutExitCount" : @4, + @"cumulativeAbnormalExitCount" : @5, + @"cumulativeSuspendedWithLockedFileExitCount" : @6, + @"cumulativeIllegalInstructionExitCount" : @7, + @"cumulativeMemoryPressureExitCount" : @8, + @"cumulativeBadAccessExitCount" : @9, + @"cumulativeCPUResourceLimitExitCount" : @10, + @"cumulativeBackgroundTaskAssertionTimeoutExitCount" : @11, + @"cumulativeNormalAppExitCount" : @12 + }, + @"foregroundExitData" : @{ + @"cumulativeBadAccessExitCount" : @13, + @"cumulativeAbnormalExitCount" : @14, + @"cumulativeMemoryResourceLimitExitCount" : @15, + @"cumulativeNormalAppExitCount" : @16, + // This entry is present in the simulated payload but not in the SDK. + // @"cumulativeCPUResourceLimitExitCount" : @17, + @"cumulativeIllegalInstructionExitCount" : @18, + @"cumulativeAppWatchdogExitCount" : @19 + } + }, + }); + NSArray* array = @[ mock_report ]; + [[MetricKitSubscriber sharedInstance] didReceiveMetricPayloads:array]; + tester.ExpectUniqueTimeSample("IOS.MetricKit.ForegroundTimePerDay", + base::TimeDelta::FromSeconds(1), 1); + tester.ExpectUniqueTimeSample("IOS.MetricKit.BackgroundTimePerDay", + base::TimeDelta::FromSeconds(2), 1); + tester.ExpectUniqueSample("IOS.MetricKit.PeakMemoryUsage", 3, 1); + tester.ExpectUniqueSample("IOS.MetricKit.AverageSuspendedMemory", 4, 1); + + tester.ExpectTotalCount("IOS.MetricKit.ApplicationResumeTime", 12); + tester.ExpectBucketCount("IOS.MetricKit.ApplicationResumeTime", 25, 5); + tester.ExpectBucketCount("IOS.MetricKit.ApplicationResumeTime", 35, 7); + + tester.ExpectTotalCount("IOS.MetricKit.TimeToFirstDraw", 6); + tester.ExpectBucketCount("IOS.MetricKit.TimeToFirstDraw", 5, 2); + tester.ExpectBucketCount("IOS.MetricKit.TimeToFirstDraw", 15, 4); + + if (base::ios::IsRunningOnIOS14OrLater()) { + tester.ExpectTotalCount("IOS.MetricKit.BackgroundExitData", 71); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 2, 1); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 4, 2); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 1, 5); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 6, 6); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 8, 7); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 5, 8); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 7, 9); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 3, 10); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 9, 11); + tester.ExpectBucketCount("IOS.MetricKit.BackgroundExitData", 0, 12); + + tester.ExpectTotalCount("IOS.MetricKit.ForegroundExitData", 95); + tester.ExpectBucketCount("IOS.MetricKit.ForegroundExitData", 7, 13); + tester.ExpectBucketCount("IOS.MetricKit.ForegroundExitData", 1, 14); + tester.ExpectBucketCount("IOS.MetricKit.ForegroundExitData", 4, 15); + tester.ExpectBucketCount("IOS.MetricKit.ForegroundExitData", 0, 16); + tester.ExpectBucketCount("IOS.MetricKit.ForegroundExitData", 8, 18); + tester.ExpectBucketCount("IOS.MetricKit.ForegroundExitData", 2, 19); + } + } +} + // Tests that Metrickit reports are correctly saved in the document directory. TEST_F(MetricKitSubscriberTest, SaveMetricsReport) { if (@available(iOS 13, *)) {
diff --git a/ios/chrome/app/application_delegate/mock_metrickit_metric_payload.h b/ios/chrome/app/application_delegate/mock_metrickit_metric_payload.h new file mode 100644 index 0000000..5be49c9 --- /dev/null +++ b/ios/chrome/app/application_delegate/mock_metrickit_metric_payload.h
@@ -0,0 +1,21 @@ +// Copyright 2020 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_APP_APPLICATION_DELEGATE_MOCK_METRICKIT_METRIC_PAYLOAD_H_ +#define IOS_CHROME_APP_APPLICATION_DELEGATE_MOCK_METRICKIT_METRIC_PAYLOAD_H_ + +#import <Foundation/Foundation.h> + +// Returns a mock MXMetricPayload given its description as an NSDictionary. +// Keys in the dictionary are the same in the JSON export of an MXMetricPayload. +// Values are simplified: +// - An NSMeasurement and MXAverage are just an NSNumber with the value +// - An MXHistogram is given by a dictionary where keys is the bucket and value +// is the bucket count. E.g. +// @"histogrammedTimeToFirstDrawKey" : @{@5 : @2, @15 : @4} +// will report 2 startup in bucket [0,10] and 4 in bucket [10,20]. +// Only the values currently reported in Chrome are mocked. +id MockMetricPayload(NSDictionary* dictionary) API_AVAILABLE(ios(13.0)); + +#endif // IOS_CHROME_APP_APPLICATION_DELEGATE_MOCK_METRICKIT_METRIC_PAYLOAD_H_
diff --git a/ios/chrome/app/application_delegate/mock_metrickit_metric_payload.mm b/ios/chrome/app/application_delegate/mock_metrickit_metric_payload.mm new file mode 100644 index 0000000..1f1a730 --- /dev/null +++ b/ios/chrome/app/application_delegate/mock_metrickit_metric_payload.mm
@@ -0,0 +1,244 @@ +// Copyright 2020 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/app/application_delegate/mock_metrickit_metric_payload.h" + +#import <Foundation/Foundation.h> +#import <MetricKit/MetricKit.h> + +#include "base/strings/sys_string_conversions.h" +#include "components/version_info/version_info.h" +#import "third_party/ocmock/OCMock/OCMock.h" +#include "third_party/ocmock/gtest_support.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +id MockMXMetadata() API_AVAILABLE(ios(13.0)) { + id metadata = OCMClassMock([MXMetaData class]); + OCMStub([metadata applicationBuildVersion]) + .andReturn(base::SysUTF8ToNSString(version_info::GetVersionNumber())); + return metadata; +} + +id MockNSMeasurement(double value) { + id mock_measurement = OCMClassMock([NSMeasurement class]); + // Conversion is not supported. + OCMStub([mock_measurement measurementByConvertingToUnit:[OCMArg any]]) + .andReturn(mock_measurement); + OCMStub([mock_measurement doubleValue]).andReturn(value); + return mock_measurement; +} + +id MockMXMemoryMetric(NSDictionary* dictionary) API_AVAILABLE(ios(13.0)) { + id memory_metric = OCMClassMock([MXMemoryMetric class]); + NSNumber* suspended_memory = + [dictionary objectForKey:@"averageSuspendedMemory"]; + if (suspended_memory) { + id mock_average = OCMClassMock([MXAverage class]); + id mock_measurement = MockNSMeasurement(suspended_memory.doubleValue); + OCMClassMock([NSMeasurement class]); + // Conversion is not supported. + OCMStub([mock_average averageMeasurement]).andReturn(mock_measurement); + OCMStub([memory_metric averageSuspendedMemory]).andReturn(mock_average); + } + + NSNumber* peak_memory = [dictionary objectForKey:@"peakMemoryUsage"]; + if (peak_memory) { + id mock_measurement = OCMClassMock([NSMeasurement class]); + // Conversion is not supported. + OCMStub([mock_measurement measurementByConvertingToUnit:[OCMArg any]]) + .andReturn(mock_measurement); + OCMStub([mock_measurement doubleValue]).andReturn(peak_memory.doubleValue); + OCMStub([memory_metric peakMemoryUsage]).andReturn(mock_measurement); + } + return memory_metric; +} + +id MockMXAppRunTimeMetric(NSDictionary* dictionary) API_AVAILABLE(ios(13.0)) { + id app_run_time = OCMClassMock([MXAppRunTimeMetric class]); + NSNumber* cumulative_foreground = + [dictionary objectForKey:@"cumulativeForegroundTime"]; + if (cumulative_foreground) { + id mock_measurement = OCMClassMock([NSMeasurement class]); + // Conversion is not supported. + OCMStub([mock_measurement measurementByConvertingToUnit:[OCMArg any]]) + .andReturn(mock_measurement); + OCMStub([mock_measurement doubleValue]) + .andReturn(cumulative_foreground.doubleValue); + OCMStub([app_run_time cumulativeForegroundTime]) + .andReturn(mock_measurement); + } + NSNumber* cumulative_background = + [dictionary objectForKey:@"cumulativeBackgroundTime"]; + if (cumulative_background) { + id mock_measurement = MockNSMeasurement(cumulative_background.doubleValue); + OCMStub([app_run_time cumulativeBackgroundTime]) + .andReturn(mock_measurement); + } + return app_run_time; +} + +id MockMXHistogram(NSDictionary* dictionary, int delta) + API_AVAILABLE(ios(13.0)) { + id histogram = OCMClassMock([MXHistogram class]); + OCMStub([histogram totalBucketCount]).andReturn(dictionary.count); + NSMutableArray* buckets = [[NSMutableArray alloc] init]; + for (NSNumber* key in dictionary) { + id bucket = OCMClassMock([MXHistogramBucket class]); + OCMStub([bucket bucketStart]) + .andReturn(MockNSMeasurement(key.doubleValue - delta)); + OCMStub([bucket bucketEnd]) + .andReturn(MockNSMeasurement(key.doubleValue + delta)); + NSNumber* value = dictionary[key]; + OCMStub([bucket bucketCount]).andReturn(value.intValue); + [buckets addObject:bucket]; + } + OCMStub([histogram bucketEnumerator]).andReturn(buckets.objectEnumerator); + return histogram; +} + +id MockMXAppLaunchMetric(NSDictionary* dictionary) API_AVAILABLE(ios(13.0)) { + id app_launch = OCMClassMock([MXAppLaunchMetric class]); + NSDictionary* first_draw = + [dictionary objectForKey:@"histogrammedTimeToFirstDrawKey"]; + if (first_draw) { + id first_draw_histogram = MockMXHistogram(first_draw, 5); + OCMStub([app_launch histogrammedTimeToFirstDraw]) + .andReturn(first_draw_histogram); + } + + NSDictionary* resume_time = + [dictionary objectForKey:@"histogrammedResumeTime"]; + if (resume_time) { + id resume_time_histogram = MockMXHistogram(resume_time, 5); + OCMStub([app_launch histogrammedApplicationResumeTime]) + .andReturn(resume_time_histogram); + } + + return app_launch; +} + +id MockMXAppResponsivenessMetric(NSDictionary* dictionary) + API_AVAILABLE(ios(13.0)) { + id responsiveness = OCMClassMock([MXAppResponsivenessMetric class]); + NSDictionary* hang_time = + [dictionary objectForKey:@"histogrammedAppHangTime"]; + if (hang_time) { + id hang_time_histogram = MockMXHistogram(hang_time, 5); + OCMStub([responsiveness histogrammedApplicationHangTime]) + .andReturn(hang_time_histogram); + } + return responsiveness; +} + +#if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 +id MockMXAppExitMetric(NSDictionary* dictionary) API_AVAILABLE(ios(14.0)) { + id app_exit_metric = OCMClassMock([MXAppExitMetric class]); + id foreground = OCMClassMock([MXForegroundExitData class]); + NSDictionary* foreground_dict = dictionary[@"foregroundExitData"]; + OCMStub([foreground cumulativeNormalAppExitCount]) + .andReturn( + [foreground_dict[@"cumulativeNormalAppExitCount"] integerValue]); + OCMStub([foreground cumulativeAbnormalExitCount]) + .andReturn( + [foreground_dict[@"cumulativeAbnormalExitCount"] integerValue]); + OCMStub([foreground cumulativeAppWatchdogExitCount]) + .andReturn( + [foreground_dict[@"cumulativeAppWatchdogExitCount"] integerValue]); + OCMStub([foreground cumulativeMemoryResourceLimitExitCount]) + .andReturn([foreground_dict[@"cumulativeMemoryResourceLimitExitCount"] + integerValue]); + OCMStub([foreground cumulativeBadAccessExitCount]) + .andReturn( + [foreground_dict[@"cumulativeBadAccessExitCount"] integerValue]); + OCMStub([foreground cumulativeIllegalInstructionExitCount]) + .andReturn([foreground_dict[@"cumulativeIllegalInstructionExitCount"] + integerValue]); + OCMStub([app_exit_metric foregroundExitData]).andReturn(foreground); + + id background = OCMClassMock([MXBackgroundExitData class]); + NSDictionary* background_dict = dictionary[@"backgroundExitData"]; + OCMStub([background cumulativeNormalAppExitCount]) + .andReturn( + [background_dict[@"cumulativeNormalAppExitCount"] integerValue]); + OCMStub([background cumulativeAbnormalExitCount]) + .andReturn( + [background_dict[@"cumulativeAbnormalExitCount"] integerValue]); + OCMStub([background cumulativeAppWatchdogExitCount]) + .andReturn( + [background_dict[@"cumulativeAppWatchdogExitCount"] integerValue]); + OCMStub([background cumulativeCPUResourceLimitExitCount]) + .andReturn([background_dict[@"cumulativeCPUResourceLimitExitCount"] + integerValue]); + OCMStub([background cumulativeMemoryResourceLimitExitCount]) + .andReturn([background_dict[@"cumulativeMemoryResourceLimitExitCount"] + integerValue]); + OCMStub([background cumulativeMemoryPressureExitCount]) + .andReturn( + [background_dict[@"cumulativeMemoryPressureExitCount"] integerValue]); + OCMStub([background cumulativeSuspendedWithLockedFileExitCount]) + .andReturn([background_dict[@"cumulativeSuspendedWithLockedFileExitCount"] + integerValue]); + OCMStub([background cumulativeBadAccessExitCount]) + .andReturn( + [background_dict[@"cumulativeBadAccessExitCount"] integerValue]); + OCMStub([background cumulativeIllegalInstructionExitCount]) + .andReturn([background_dict[@"cumulativeIllegalInstructionExitCount"] + integerValue]); + OCMStub([background cumulativeBackgroundTaskAssertionTimeoutExitCount]) + .andReturn( + [background_dict[@"cumulativeBackgroundTaskAssertionTimeoutExitCount"] + integerValue]); + OCMStub([app_exit_metric backgroundExitData]).andReturn(background); + + return app_exit_metric; +} +#endif + +id MockMetricPayload(NSDictionary* dictionary) API_AVAILABLE(ios(13.0)) { + id mock_report = OCMClassMock([MXMetricPayload class]); + NSDictionary* application_time_metrics_dict = + [dictionary objectForKey:@"applicationTimeMetrics"]; + if (application_time_metrics_dict) { + id application_time_metrics = + MockMXAppRunTimeMetric(application_time_metrics_dict); + OCMStub([mock_report applicationTimeMetrics]) + .andReturn(application_time_metrics); + } + NSDictionary* memory_metrics_dict = + [dictionary objectForKey:@"memoryMetrics"]; + if (memory_metrics_dict) { + id memory_metrics = MockMXMemoryMetric(memory_metrics_dict); + OCMStub([mock_report memoryMetrics]).andReturn(memory_metrics); + } + NSDictionary* launch_metrics_dict = + [dictionary objectForKey:@"applicationLaunchMetrics"]; + if (memory_metrics_dict) { + id launch_metrics = MockMXAppLaunchMetric(launch_metrics_dict); + OCMStub([mock_report applicationLaunchMetrics]).andReturn(launch_metrics); + } + NSDictionary* responsiveness_metrics_dict = + [dictionary objectForKey:@"applicationResponsivenessMetrics"]; + if (responsiveness_metrics_dict) { + id responsiveness_metrics = + MockMXAppResponsivenessMetric(responsiveness_metrics_dict); + OCMStub([mock_report applicationResponsivenessMetrics]) + .andReturn(responsiveness_metrics); + } +#if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 + if (@available(iOS 14, *)) { + NSDictionary* exit_metrics_dict = + [dictionary objectForKey:@"applicationExitMetrics"]; + if (exit_metrics_dict) { + id exit_metrics = MockMXAppExitMetric(exit_metrics_dict); + OCMStub([mock_report applicationExitMetrics]).andReturn(exit_metrics); + } + } +#endif + + OCMStub([mock_report metaData]).andReturn(MockMXMetadata()); + return mock_report; +}
diff --git a/ios/chrome/browser/app_launcher/app_launcher_tab_helper.mm b/ios/chrome/browser/app_launcher/app_launcher_tab_helper.mm index 3f207a9d..ec61ba0e 100644 --- a/ios/chrome/browser/app_launcher/app_launcher_tab_helper.mm +++ b/ios/chrome/browser/app_launcher/app_launcher_tab_helper.mm
@@ -178,7 +178,7 @@ PolicyBlocklistServiceFactory::GetForBrowserState( web_state()->GetBrowserState()); if (blocklistService->GetURLBlocklistState(request_url) == - policy::URLBlacklist::URLBlacklistState::URL_IN_BLACKLIST) { + policy::URLBlocklist::URLBlocklistState::URL_IN_BLOCKLIST) { return web::WebStatePolicyDecider::PolicyDecision::CancelAndDisplayError( policy_url_blocking_util::CreateBlockedUrlError()); }
diff --git a/ios/chrome/browser/crash_report/BUILD.gn b/ios/chrome/browser/crash_report/BUILD.gn index e771205e..ba25345b 100644 --- a/ios/chrome/browser/crash_report/BUILD.gn +++ b/ios/chrome/browser/crash_report/BUILD.gn
@@ -18,8 +18,12 @@ "crash_reporter_breadcrumb_observer.mm", "crash_upload_list.cc", "crash_upload_list.h", + "features.cc", + "features.h", "main_thread_freeze_detector.h", "main_thread_freeze_detector.mm", + "synthetic_crash_report_util.cc", + "synthetic_crash_report_util.h", ] configs += [ "//build/config/compiler:enable_arc" ] @@ -88,6 +92,7 @@ "crash_reporter_breadcrumb_observer_unittest.mm", "crash_reporter_url_observer_unittest.mm", "crash_restore_helper_unittest.mm", + "synthetic_crash_report_util_unittest.mm", ] deps = [ ":constants",
diff --git a/ios/chrome/browser/crash_report/features.cc b/ios/chrome/browser/crash_report/features.cc new file mode 100644 index 0000000..c05d574 --- /dev/null +++ b/ios/chrome/browser/crash_report/features.cc
@@ -0,0 +1,8 @@ +// Copyright 2020 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/crash_report/features.h" + +const base::Feature kSyntheticCrashReportsForUte{ + "SyntheticCrashReportsForUte", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ios/chrome/browser/crash_report/features.h b/ios/chrome/browser/crash_report/features.h new file mode 100644 index 0000000..5f8180f --- /dev/null +++ b/ios/chrome/browser/crash_report/features.h
@@ -0,0 +1,12 @@ +// Copyright 2020 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_CRASH_REPORT_FEATURES_H_ +#define IOS_CHROME_BROWSER_CRASH_REPORT_FEATURES_H_ + +#include "base/feature_list.h" + +extern const base::Feature kSyntheticCrashReportsForUte; + +#endif // IOS_CHROME_BROWSER_CRASH_REPORT_FEATURES_H_
diff --git a/ios/chrome/browser/crash_report/synthetic_crash_report_util.cc b/ios/chrome/browser/crash_report/synthetic_crash_report_util.cc new file mode 100644 index 0000000..4517834 --- /dev/null +++ b/ios/chrome/browser/crash_report/synthetic_crash_report_util.cc
@@ -0,0 +1,88 @@ +// Copyright 2020 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/crash_report/synthetic_crash_report_util.h" + +#include <stdlib.h> + +#include "base/files/memory_mapped_file.h" +#include "base/ios/device_util.h" +#include "base/notreached.h" +#include "base/rand_util.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/strings/sys_string_conversions.h" +#include "base/system/sys_info.h" + +namespace { + +// Appends |config| vector with key value pair, respecting max value length. +void AppendConfig(std::vector<std::string>& config, + std::string key, + std::string value) { + const size_t kMaxValueLen = 255; + if (value.size() <= kMaxValueLen) { + config.push_back(key); + config.push_back(base::NumberToString(value.size())); + config.push_back(value); + return; + } + + // Recursively split the value into chunks. + int key_index = 1; + size_t val_offset = 0; + for (; val_offset < value.size(); val_offset += kMaxValueLen, key_index++) { + AppendConfig(config, base::StringPrintf("%s__%d", key.c_str(), key_index), + value.substr(val_offset, kMaxValueLen)); + } +} + +} // namespace + +void CreateSyntheticCrashReportForUte( + const base::FilePath& path, + const std::string& breakpad_product_display, + const std::string& breakpad_product, + const std::string& breakpad_version, + const std::string& breakpad_url) { + std::vector<std::string> config; + + AppendConfig(config, "MinidumpDir", path.value()); + std::string minidump_id = ios::device_util::GetRandomId(); + AppendConfig(config, "MinidumpID", minidump_id); + AppendConfig(config, "BreakpadProductDisplay", breakpad_product_display); + AppendConfig(config, "BreakpadProduct", breakpad_product); + // UTE is not reported if app was upgrated, so the previous session had the + // same version. + AppendConfig(config, "BreakpadVersion", breakpad_version); + AppendConfig(config, "BreakpadURL", breakpad_url); + AppendConfig(config, "BreakpadMinidumpLocation", path.value()); + AppendConfig(config, "BreakpadServerParameterPrefix_platform", + base::SysInfo::HardwareModelName()); + + // Write empty minidump file, as Breakpad can't upload config without the + // minidump. + base::File minidump_file( + path.Append(minidump_id).AddExtension("dmp"), + base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); + + base::FilePath config_file_path = path.Append("Config-XXXXXX"); + // const_cast is OK since mkstemp just replaces characters in place. + base::ScopedFD config_fd( + mkstemp(const_cast<char*>(config_file_path.value().c_str()))); + + std::string config_string = base::JoinString(config, "\n"); + + // Write config into memory mapped file after minidump is written, otherwise + // Breakpad may fail to upload config without minidump. + base::MemoryMappedFile mapped_config_file; + const base::MemoryMappedFile::Region region = {0, config_string.size()}; + if (mapped_config_file.Initialize( + base::File(std::move(config_fd)), region, + base::MemoryMappedFile::READ_WRITE_EXTEND)) { + std::strcpy(reinterpret_cast<char*>(mapped_config_file.data()), + config_string.data()); + } +}
diff --git a/ios/chrome/browser/crash_report/synthetic_crash_report_util.h b/ios/chrome/browser/crash_report/synthetic_crash_report_util.h new file mode 100644 index 0000000..c02a6aa --- /dev/null +++ b/ios/chrome/browser/crash_report/synthetic_crash_report_util.h
@@ -0,0 +1,24 @@ +// Copyright 2020 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_CRASH_REPORT_SYNTHETIC_CRASH_REPORT_UTIL_H_ +#define IOS_CHROME_BROWSER_CRASH_REPORT_SYNTHETIC_CRASH_REPORT_UTIL_H_ + +#include <string> + +namespace base { +class FilePath; +} + +// Creates Synthetic Crash Report for Unexplained Termination Event to be +// uploaded by Breakpad. |path| should be a path to Breakpad directory and +// the rest of the arguments are Breakpad specific values. +void CreateSyntheticCrashReportForUte( + const base::FilePath& path, + const std::string& breakpad_product_display, + const std::string& breakpad_product, + const std::string& breakpad_version, + const std::string& breakpad_url); + +#endif // IOS_CHROME_BROWSER_CRASH_REPORT_SYNTHETIC_CRASH_REPORT_UTIL_H_
diff --git a/ios/chrome/browser/crash_report/synthetic_crash_report_util_unittest.mm b/ios/chrome/browser/crash_report/synthetic_crash_report_util_unittest.mm new file mode 100644 index 0000000..6cc983f --- /dev/null +++ b/ios/chrome/browser/crash_report/synthetic_crash_report_util_unittest.mm
@@ -0,0 +1,133 @@ +// Copyright 2020 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/crash_report/synthetic_crash_report_util.h" + +#import <Foundation/Foundation.h> + +#include "base/files/file.h" +#include "base/files/file_enumerator.h" +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/path_service.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" +#include "base/strings/sys_string_conversions.h" +#include "base/system/sys_info.h" +#include "testing/platform_test.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +typedef PlatformTest SyntheticCrashReportUtilTest; + +// Tests that CreateSyntheticCrashReportForUte correctly generates config and +// minidump files. +TEST_F(SyntheticCrashReportUtilTest, CreateSyntheticCrashReportForUte) { + // Create crash report. + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + std::string product_display = std::string(255, 'a') + std::string(1, 'b'); + CreateSyntheticCrashReportForUte(temp_dir.GetPath(), product_display, + "Product", "Version", "URL"); + // CreateSyntheticCrashReportForUte creates config and empty minidump file. + // locate both files and ensure there are no other files in the directory. + base::FileEnumerator traversal(temp_dir.GetPath(), /*recursive=*/false, + base::FileEnumerator::FILES); + base::FilePath new_file_path = traversal.Next(); + base::FilePath config_file_path; + base::FilePath minidump_file_path; + if (new_file_path.Extension() == ".dmp") { + // First file is minidump. Next one should be config. + minidump_file_path = new_file_path; + config_file_path = traversal.Next(); + } else { + // First file is confix. Next one should be minidump. + config_file_path = new_file_path; + minidump_file_path = traversal.Next(); + } + ASSERT_EQ("", traversal.Next().value()); + + // Config file name is "Config-<6 random characters>" (f.e. Config-S0Zl1r). + std::vector<std::string> config_file_path_components; + config_file_path.GetComponents(&config_file_path_components); + ASSERT_FALSE(config_file_path_components.empty()); + std::string config_file_name = config_file_path_components.back(); + ASSERT_EQ(13U, config_file_name.size()) << config_file_name; + EXPECT_EQ(0U, config_file_name.find("Config-")); + + // Minidump file name is "<UUID>.dmp" (f.e. + // f83dfc0a-771e-4a99-8540-e430ab995307.dmp). + std::vector<std::string> minidump_file_path_components; + minidump_file_path.GetComponents(&minidump_file_path_components); + ASSERT_FALSE(minidump_file_path_components.empty()); + std::string minidump_file_name = minidump_file_path_components.back(); + ASSERT_EQ(40U, minidump_file_name.size()) << minidump_file_name; + + // Read config file + base::File config_file(config_file_path, + base::File::FLAG_OPEN | base::File::FLAG_READ); + ASSERT_TRUE(config_file.IsValid()); + ASSERT_GE(config_file.GetLength(), 0U); + + std::vector<uint8_t> data; + data.resize(config_file.GetLength()); + ASSERT_TRUE(config_file.ReadAndCheck(/*offset=*/0, data)); + std::string config_content(data.begin(), data.end()); + std::vector<std::string> config_lines = base::SplitString( + config_content, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + + // Verify config file content. Config file has the following format: + // Key1\nValue1Length\nValue1\n...KeyN\nValueNLength\nValueN + ASSERT_EQ(27U, config_lines.size()) + << "<content>" << config_content << "</content>"; + + EXPECT_EQ("MinidumpDir", config_lines[0]); + EXPECT_EQ(base::NumberToString(temp_dir.GetPath().value().size()), + config_lines[1]); + EXPECT_EQ(temp_dir.GetPath().value(), config_lines[2]); + + // Verify that MinidumpID is a proper UUID and used in minidump file name. + EXPECT_EQ("MinidumpID", config_lines[3]); + EXPECT_EQ("36", config_lines[4]); + EXPECT_TRUE([[NSUUID alloc] + initWithUUIDString:base::SysUTF8ToNSString(config_lines[5])]); + EXPECT_EQ(0U, minidump_file_name.find(config_lines[5])); + + // BreakpadProductDisplay value is too long and split into 2 chunks. + EXPECT_EQ("BreakpadProductDisplay__1", config_lines[6]); + EXPECT_EQ("255", config_lines[7]); + EXPECT_EQ(product_display, config_lines[8] + config_lines[11]); + EXPECT_EQ("BreakpadProductDisplay__2", config_lines[9]); + EXPECT_EQ("1", config_lines[10]); + + EXPECT_EQ("BreakpadProduct", config_lines[12]); + EXPECT_EQ("7", config_lines[13]); + EXPECT_EQ("Product", config_lines[14]); + + EXPECT_EQ("BreakpadVersion", config_lines[15]); + EXPECT_EQ("7", config_lines[16]); + EXPECT_EQ("Version", config_lines[17]); + + EXPECT_EQ("BreakpadURL", config_lines[18]); + EXPECT_EQ("3", config_lines[19]); + EXPECT_EQ("URL", config_lines[20]); + + EXPECT_EQ("BreakpadMinidumpLocation", config_lines[21]); + EXPECT_EQ(base::NumberToString(temp_dir.GetPath().value().size()), + config_lines[22]); + EXPECT_EQ(temp_dir.GetPath().value(), config_lines[23]); + + EXPECT_EQ("BreakpadServerParameterPrefix_platform", config_lines[24]); + EXPECT_EQ("12", config_lines[25]); + EXPECT_EQ(base::SysInfo::HardwareModelName(), config_lines[26]); + + // Read minidump file. It must be empty as there is no stack trace, but + // Breakpad will not upload config without minidump file. + base::File minidump_file(minidump_file_path, + base::File::FLAG_OPEN | base::File::FLAG_READ); + ASSERT_TRUE(minidump_file.IsValid()); + EXPECT_EQ(0U, minidump_file.GetLength()); +}
diff --git a/ios/chrome/browser/flags/BUILD.gn b/ios/chrome/browser/flags/BUILD.gn index ea21852..07664d300 100644 --- a/ios/chrome/browser/flags/BUILD.gn +++ b/ios/chrome/browser/flags/BUILD.gn
@@ -44,6 +44,7 @@ "//ios/chrome/app/strings:ios_strings", "//ios/chrome/browser", "//ios/chrome/browser/browsing_data:feature_flags", + "//ios/chrome/browser/crash_report", "//ios/chrome/browser/crash_report/breadcrumbs:feature_flags", "//ios/chrome/browser/drag_and_drop", "//ios/chrome/browser/passwords:feature_flags",
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index bc3c98f6..0a7fe36 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -56,6 +56,7 @@ #include "ios/chrome/browser/browsing_data/browsing_data_features.h" #include "ios/chrome/browser/chrome_switches.h" #include "ios/chrome/browser/crash_report/breadcrumbs/features.h" +#include "ios/chrome/browser/crash_report/features.h" #include "ios/chrome/browser/drag_and_drop/drag_and_drop_flag.h" #include "ios/chrome/browser/flags/ios_chrome_flag_descriptions.h" #include "ios/chrome/browser/passwords/password_manager_features.h" @@ -470,6 +471,10 @@ {"ios-breadcrumbs", flag_descriptions::kLogBreadcrumbsName, flag_descriptions::kLogBreadcrumbsDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kLogBreadcrumbs)}, + {"ios-synthetic-crash-reports", + flag_descriptions::kSyntheticCrashReportsForUteName, + flag_descriptions::kSyntheticCrashReportsForUteDescription, + flags_ui::kOsIos, FEATURE_VALUE_TYPE(kSyntheticCrashReportsForUte)}, {"force-startup-signin-promo", flag_descriptions::kForceStartupSigninPromoName, flag_descriptions::kForceStartupSigninPromoDescription, flags_ui::kOsIos,
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index e81b744..0e913d0 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -136,6 +136,12 @@ extern const char kLogBreadcrumbsDescription[] = "When enabled, breadcrumb events will be logged."; +const char kSyntheticCrashReportsForUteName[] = + "Generate synthetic crash reports for UTE"; +const char kSyntheticCrashReportsForUteDescription[] = + "When enabled the app will create synthetic crash report when chrome " + "starts up after Unexplained Termination Event (UTE)."; + const char kBreakpadNoDelayInitialUploadName[] = "Remove delay on initial crash upload"; const char kBreakpadNoDelayInitialUploadDescription[] =
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 3af260c..1aacd88 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -106,6 +106,11 @@ extern const char kLogBreadcrumbsName[]; extern const char kLogBreadcrumbsDescription[]; +// Title and description for the flag that controls synthetic crash reports +// generation for Unexplained Termination Events. +extern const char kSyntheticCrashReportsForUteName[]; +extern const char kSyntheticCrashReportsForUteDescription[]; + // Title and description for the flag to control if initial uploading of crash // reports is delayed. extern const char kBreakpadNoDelayInitialUploadName[];
diff --git a/ios/chrome/browser/ios_chrome_main_parts.mm b/ios/chrome/browser/ios_chrome_main_parts.mm index ef7fa81..b38a5af 100644 --- a/ios/chrome/browser/ios_chrome_main_parts.mm +++ b/ios/chrome/browser/ios_chrome_main_parts.mm
@@ -37,7 +37,7 @@ #include "components/variations/service/variations_service.h" #include "components/variations/synthetic_trials_active_group_id_provider.h" #include "components/variations/variations_crash_keys.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "ios/chrome/browser/application_context_impl.h" #include "ios/chrome/browser/browser_state/browser_state_keyed_service_factories.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" @@ -285,7 +285,7 @@ void IOSChromeMainParts::SetupMetrics() { metrics::MetricsService* metrics = application_context_->GetMetricsService(); metrics->synthetic_trial_registry()->AddSyntheticTrialObserver( - variations::VariationsHttpHeaderProvider::GetInstance()); + variations::VariationsIdsProvider::GetInstance()); metrics->synthetic_trial_registry()->AddSyntheticTrialObserver( variations::SyntheticTrialsActiveGroupIdProvider::GetInstance()); // Now that field trials have been created, initializes metrics recording.
diff --git a/ios/chrome/browser/metrics/mobile_session_shutdown_metrics_provider.mm b/ios/chrome/browser/metrics/mobile_session_shutdown_metrics_provider.mm index f284f15..4f8cb1f 100644 --- a/ios/chrome/browser/metrics/mobile_session_shutdown_metrics_provider.mm +++ b/ios/chrome/browser/metrics/mobile_session_shutdown_metrics_provider.mm
@@ -8,13 +8,19 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" +#include "base/path_service.h" #include "base/strings/sys_string_conversions.h" #include "base/system/sys_info.h" +#include "base/task/post_task.h" #include "base/version.h" +#include "components/metrics/metrics_pref_names.h" #include "components/metrics/metrics_service.h" #include "components/version_info/version_info.h" +#include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/crash_report/breakpad_helper.h" +#include "ios/chrome/browser/crash_report/features.h" #include "ios/chrome/browser/crash_report/main_thread_freeze_detector.h" +#include "ios/chrome/browser/crash_report/synthetic_crash_report_util.h" #import "ios/chrome/browser/metrics/previous_session_info.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -220,6 +226,29 @@ "Stability.iOS.UTE.MobileSessionOOMShutdownHint", GetMobileSessionOomShutdownHint(possible_explanation), MobileSessionOomShutdownHint::kMaxValue); + if (!possible_explanation && + base::FeatureList::IsEnabled(kSyntheticCrashReportsForUte) && + GetApplicationContext()->GetLocalState()->GetBoolean( + metrics::prefs::kMetricsReportingEnabled)) { + // UTEs are so common that there will be a little or no value from + // generating crash reports for XTEs. + + base::FilePath cache_dir_path; + base::PathService::Get(base::DIR_CACHE, &cache_dir_path); + NSDictionary* info_dict = NSBundle.mainBundle.infoDictionary; + + base::ThreadPool::PostTask( + FROM_HERE, {base::MayBlock()}, + base::BindOnce( + &CreateSyntheticCrashReportForUte, + cache_dir_path.Append(FILE_PATH_LITERAL("Breakpad")), + base::SysNSStringToUTF8(info_dict[@"BreakpadProductDisplay"]), + base::SysNSStringToUTF8(info_dict[@"BreakpadVersion"]), + // Separate product makes throttling on the server easier. + base::SysNSStringToUTF8([NSString + stringWithFormat:@"%@_UTE", info_dict[@"BreakpadProduct"]]), + base::SysNSStringToUTF8(info_dict[@"BreakpadURL"]))); + } } [session_info resetSessionRestorationFlag]; }
diff --git a/ios/chrome/browser/policy/configuration_policy_handler_list_factory.mm b/ios/chrome/browser/policy/configuration_policy_handler_list_factory.mm index 0a879677..9f33503 100644 --- a/ios/chrome/browser/policy/configuration_policy_handler_list_factory.mm +++ b/ios/chrome/browser/policy/configuration_policy_handler_list_factory.mm
@@ -119,7 +119,7 @@ } if (ShouldInstallURLBlocklistPolicyHandlers()) { - handlers->AddHandler(std::make_unique<policy::URLBlacklistPolicyHandler>( + handlers->AddHandler(std::make_unique<policy::URLBlocklistPolicyHandler>( policy::key::kURLBlocklist)); }
diff --git a/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.cc b/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.cc index e62cdbd8..bb5d1c57 100644 --- a/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.cc +++ b/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.cc
@@ -11,14 +11,14 @@ PolicyBlocklistService::PolicyBlocklistService( web::BrowserState* browser_state, - std::unique_ptr<policy::URLBlacklistManager> url_blacklist_manager) - : url_blacklist_manager_(std::move(url_blacklist_manager)) {} + std::unique_ptr<policy::URLBlocklistManager> url_blocklist_manager) + : url_blocklist_manager_(std::move(url_blocklist_manager)) {} PolicyBlocklistService::~PolicyBlocklistService() = default; -policy::URLBlacklist::URLBlacklistState +policy::URLBlocklist::URLBlocklistState PolicyBlocklistService::GetURLBlocklistState(const GURL& url) const { - return url_blacklist_manager_->GetURLBlacklistState(url); + return url_blocklist_manager_->GetURLBlocklistState(url); } // static @@ -46,10 +46,10 @@ web::BrowserState* browser_state) const { PrefService* prefs = ChromeBrowserState::FromBrowserState(browser_state)->GetPrefs(); - auto url_blacklist_manager = - std::make_unique<policy::URLBlacklistManager>(prefs); + auto url_blocklist_manager = + std::make_unique<policy::URLBlocklistManager>(prefs); return std::make_unique<PolicyBlocklistService>( - browser_state, std::move(url_blacklist_manager)); + browser_state, std::move(url_blocklist_manager)); } web::BrowserState* PolicyBlocklistServiceFactory::GetBrowserStateToUse(
diff --git a/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.h b/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.h index ecfa44b..16f794d 100644 --- a/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.h +++ b/ios/chrome/browser/policy_url_blocking/policy_url_blocking_service.h
@@ -14,21 +14,21 @@ class BrowserState; } -// Associates a policy::URLBlacklistManager instance with a BrowserState. +// Associates a policy::URLBlocklistManager instance with a BrowserState. class PolicyBlocklistService : public KeyedService { public: explicit PolicyBlocklistService( web::BrowserState* browser_state, - std::unique_ptr<policy::URLBlacklistManager> url_blacklist_manager); + std::unique_ptr<policy::URLBlocklistManager> url_blocklist_manager); ~PolicyBlocklistService() override; // Returns the blocking state for |url|. - policy::URLBlacklist::URLBlacklistState GetURLBlocklistState( + policy::URLBlocklist::URLBlocklistState GetURLBlocklistState( const GURL& url) const; private: - // The URLBlacklistManager associated with |browser_state|. - std::unique_ptr<policy::URLBlacklistManager> url_blacklist_manager_; + // The URLBlocklistManager associated with |browser_state|. + std::unique_ptr<policy::URLBlocklistManager> url_blocklist_manager_; PolicyBlocklistService(const PolicyBlocklistService&) = delete; PolicyBlocklistService& operator=(const PolicyBlocklistService&) = delete;
diff --git a/ios/chrome/browser/policy_url_blocking/policy_url_blocking_tab_helper.mm b/ios/chrome/browser/policy_url_blocking/policy_url_blocking_tab_helper.mm index e0959de..e26a009b 100644 --- a/ios/chrome/browser/policy_url_blocking/policy_url_blocking_tab_helper.mm +++ b/ios/chrome/browser/policy_url_blocking/policy_url_blocking_tab_helper.mm
@@ -28,7 +28,7 @@ PolicyBlocklistServiceFactory::GetForBrowserState( web_state()->GetBrowserState()); if (blocklistService->GetURLBlocklistState(gurl) == - policy::URLBlacklist::URLBlacklistState::URL_IN_BLACKLIST) { + policy::URLBlocklist::URLBlocklistState::URL_IN_BLOCKLIST) { return web::WebStatePolicyDecider::PolicyDecision::CancelAndDisplayError( policy_url_blocking_util::CreateBlockedUrlError()); }
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index 76e3e49..da08837 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -157,7 +157,7 @@ ntp_tiles::PopularSitesImpl::RegisterProfilePrefs(registry); password_manager::PasswordManager::RegisterProfilePrefs(registry); payments::RegisterProfilePrefs(registry); - policy::URLBlacklistManager::RegisterProfilePrefs(registry); + policy::URLBlocklistManager::RegisterProfilePrefs(registry); PrefProxyConfigTrackerImpl::RegisterProfilePrefs(registry); RegisterVoiceSearchBrowserStatePrefs(registry); safe_browsing::RegisterProfilePrefs(registry);
diff --git a/ios/chrome/browser/reading_list/url_downloader_unittest.mm b/ios/chrome/browser/reading_list/url_downloader_unittest.mm index 3df5af7..d767861 100644 --- a/ios/chrome/browser/reading_list/url_downloader_unittest.mm +++ b/ios/chrome/browser/reading_list/url_downloader_unittest.mm
@@ -60,8 +60,8 @@ }; void RemoveOfflineFilesDirectory(base::FilePath base_directory) { - base::DeleteFile(reading_list::OfflineRootDirectoryPath(base_directory), - true); + base::DeletePathRecursively( + reading_list::OfflineRootDirectoryPath(base_directory)); } } // namespace
diff --git a/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm b/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm index dd429d96..3137cc6 100644 --- a/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm +++ b/ios/chrome/browser/safe_browsing/safe_browsing_egtest.mm
@@ -428,7 +428,8 @@ // Tests that performing session restoration to a Safe Browsing warning page // preserves navigation history. -- (void)testRestoreToWarningPagePreservesHistory { +// TODO(crbug.com/1106498): Re-enable this test after fixing flakiness. +- (void)DISABLED_testRestoreToWarningPagePreservesHistory { // Build up navigation history that consists of a safe URL, a warning page, // and another safe URL. [ChromeEarlGrey loadURL:_safeURL1];
diff --git a/ios/chrome/browser/ssl/ios_ssl_error_handler.mm b/ios/chrome/browser/ssl/ios_ssl_error_handler.mm index b3c14ee6..095683d 100644 --- a/ios/chrome/browser/ssl/ios_ssl_error_handler.mm +++ b/ios/chrome/browser/ssl/ios_ssl_error_handler.mm
@@ -102,18 +102,28 @@ CaptivePortalDetectorTabHelper::FromWebState(web_state_); // TODO(crbug.com/760873): replace test with DCHECK when this method is only // called on WebStates attached to tabs. - if (tab_helper) { - base::WeakPtr<IOSSSLErrorHandler> weak_error_handler = - weak_factory_.GetWeakPtr(); - - tab_helper->detector()->DetectCaptivePortal( - GURL(CaptivePortalDetector::kDefaultURL), - base::BindRepeating( - &IOSSSLErrorHandler::HandleCaptivePortalDetectionResult, - weak_error_handler), - NO_TRAFFIC_ANNOTATION_YET); + if (!tab_helper) { + // This WebState has not been inserted into a WebStateList. This can + // happen, for example, when a reading list entry is being loaded in the + // background. Since this WebState is not visible to the user, it doesn't + // make sense to display an interstitial, since the interstitial will not + // be seen. + if (!callback_.is_null()) { + std::move(callback_).Run(/*proceed=*/false); + } + return; } + base::WeakPtr<IOSSSLErrorHandler> weak_error_handler = + weak_factory_.GetWeakPtr(); + + tab_helper->detector()->DetectCaptivePortal( + GURL(CaptivePortalDetector::kDefaultURL), + base::BindRepeating( + &IOSSSLErrorHandler::HandleCaptivePortalDetectionResult, + weak_error_handler), + NO_TRAFFIC_ANNOTATION_YET); + // Default to presenting the SSL interstitial if Captive Portal detection // takes too long. timer_.Start(FROM_HERE, @@ -140,11 +150,7 @@ // the case if |timer_| triggered the call of this method. CaptivePortalDetectorTabHelper* tab_helper = CaptivePortalDetectorTabHelper::FromWebState(web_state_); - // TODO(crbug.com/760873): replace test with DCHECK when this method is only - // called on WebStates attached to tabs. - if (tab_helper) { - tab_helper->detector()->Cancel(); - } + tab_helper->detector()->Cancel(); int options_mask = overridable_
diff --git a/ios/chrome/browser/ssl/ios_ssl_error_handler_unittest.mm b/ios/chrome/browser/ssl/ios_ssl_error_handler_unittest.mm index 791918a0..3d86119 100644 --- a/ios/chrome/browser/ssl/ios_ssl_error_handler_unittest.mm +++ b/ios/chrome/browser/ssl/ios_ssl_error_handler_unittest.mm
@@ -183,3 +183,46 @@ EXPECT_FALSE(WaitForInterstitialDisplayed()); EXPECT_TRUE(blocking_page_callback_called); } + +// Test fixture for IOSSSLErrorHander when used with a WebState that hasn't +// been inserted into a WebStateList and hence doesn't have the usual set of +// tab helpers. +class IOSSSLErrorHandlerWithoutTabHelpersTest + : public web::WebTestWithWebState { + protected: + IOSSSLErrorHandlerWithoutTabHelpersTest() + : cert_(net::ImportCertFromFile(net::GetTestCertsDirectory(), + kTestCertFileName)) {} + + // Returns certificate. + scoped_refptr<net::X509Certificate> cert() { return cert_; } + + private: + scoped_refptr<net::X509Certificate> cert_; +}; + +// Tests that error handling is short-circuited when the associated WebState +// isn't in a WebStateList. +TEST_F(IOSSSLErrorHandlerWithoutTabHelpersTest, HandleError) { + net::SSLInfo ssl_info; + ssl_info.cert = cert(); + GURL url(kTestHostName); + __block bool proceed_callback_called = false; + __block bool should_proceed = false; + __block bool blocking_page_callback_called = false; + base::OnceCallback<void(bool)> proceed_callback = + base::BindOnce(^(bool proceed) { + proceed_callback_called = true; + should_proceed = proceed; + }); + base::OnceCallback<void(NSString*)> blocking_page_callback = + base::BindOnce(^(NSString* blocking_page) { + blocking_page_callback_called = true; + }); + IOSSSLErrorHandler::HandleSSLError( + web_state(), net::ERR_CERT_AUTHORITY_INVALID, ssl_info, url, true, 0, + std::move(proceed_callback), std::move(blocking_page_callback)); + EXPECT_TRUE(proceed_callback_called); + EXPECT_FALSE(should_proceed); + EXPECT_FALSE(blocking_page_callback_called); +}
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm index dd838749..b6fd3685 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm
@@ -16,8 +16,7 @@ #include "components/prefs/pref_service.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/drag_and_drop/drag_and_drop_flag.h" -#import "ios/chrome/browser/drag_and_drop/drop_and_navigate_delegate.h" -#import "ios/chrome/browser/drag_and_drop/drop_and_navigate_interaction.h" +#import "ios/chrome/browser/drag_and_drop/url_drag_drop_handler.h" #include "ios/chrome/browser/favicon/ios_chrome_large_icon_cache_factory.h" #include "ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h" #include "ios/chrome/browser/favicon/large_icon_cache.h" @@ -49,11 +48,10 @@ #import "ios/chrome/browser/ui/settings/utils/pref_backed_boolean.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #import "ios/chrome/browser/url_loading/url_loading_browser_agent.h" +#import "ios/chrome/browser/url_loading/url_loading_params.h" #import "ios/chrome/browser/voice/voice_search_availability.h" #import "ios/public/provider/chrome/browser/chrome_browser_provider.h" #import "ios/public/provider/chrome/browser/discover_feed/discover_feed_provider.h" -#import "ios/web/public/navigation/navigation_manager.h" -#import "ios/web/public/web_state.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -61,8 +59,8 @@ @interface ContentSuggestionsCoordinator () < ContentSuggestionsViewControllerAudience, - DropAndNavigateDelegate, - OverscrollActionsControllerDelegate> { + OverscrollActionsControllerDelegate, + URLDropDelegate> { // Helper object managing the availability of the voice search feature. VoiceSearchAvailability _voiceSearchAvailability; } @@ -76,6 +74,7 @@ @property(nonatomic, strong) ContentSuggestionsMetricsRecorder* metricsRecorder; @property(nonatomic, strong) NTPHomeMediator* NTPMediator; @property(nonatomic, strong) UIViewController* discoverFeedViewController; +@property(nonatomic, strong) URLDragDropHandler* dragDropHandler; // Redefined as readwrite. @property(nonatomic, strong, readwrite) @@ -239,9 +238,11 @@ self.headerCollectionInteractionHandler; if (DragAndDropIsEnabled()) { + self.dragDropHandler = [[URLDragDropHandler alloc] init]; + self.dragDropHandler.dropDelegate = self; [self.suggestionsViewController.collectionView - addInteraction:[[DropAndNavigateInteraction alloc] - initWithDelegate:self]]; + addInteraction:[[UIDropInteraction alloc] + initWithDelegate:self.dragDropHandler]]; } } @@ -327,12 +328,15 @@ return nullptr; } -#pragma mark - DropAndNavigateDelegate +#pragma mark - URLDropDelegate -- (void)URLWasDropped:(GURL const&)URL { - web::NavigationManager::WebLoadParams params(URL); - params.transition_type = ui::PAGE_TRANSITION_TYPED; - self.webState->GetNavigationManager()->LoadURLWithParams(params); +- (BOOL)canHandleURLDropInView:(UIView*)view { + return YES; +} + +- (void)view:(UIView*)view didDropURL:(const GURL&)URL atPoint:(CGPoint)point { + UrlLoadingBrowserAgent::FromBrowser(self.browser) + ->Load(UrlLoadParams::InCurrentTab(URL)); } #pragma mark - Public methods
diff --git a/ios/chrome/browser/ui/fullscreen/fullscreen_egtest.mm b/ios/chrome/browser/ui/fullscreen/fullscreen_egtest.mm index f250e4a..8807533 100644 --- a/ios/chrome/browser/ui/fullscreen/fullscreen_egtest.mm +++ b/ios/chrome/browser/ui/fullscreen/fullscreen_egtest.mm
@@ -61,6 +61,23 @@ description); } +// A PDF itself can take a little longer to appear even after the page is loaded. Instead, do an +// additional wait for the internal PDF class to appear in the view hierarchy. +void WaitforPDFExtensionView() { + ConditionBlock condition = ^{ + NSError* error = nil; + [[EarlGrey selectElementWithMatcher:grey_kindOfClass(NSClassFromString( + @"PDFExtensionTopView"))] + assertWithMatcher:grey_notNil() + error:&error]; + return error == nil; + }; + + NSString* errorMessage = @"PDFExtensionTopView was not visible"; + GREYAssert(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, condition), + errorMessage); +} + } // namespace #pragma mark - Tests @@ -84,25 +101,9 @@ GURL URL = web::test::HttpServer::MakeUrl( "http://ios/testing/data/http_server_files/two_pages.pdf"); [ChromeEarlGrey loadURL:URL]; - + WaitforPDFExtensionView(); [ChromeEarlGreyUI waitForToolbarVisible:YES]; - // Waiting for the toolbar to be visible is not enough -- the PDF itself can - // take a little longer to load. Instead, wait for an internal PDF class to - // appear in the view hierarchy. - ConditionBlock condition = ^{ - NSError* error = nil; - [[EarlGrey selectElementWithMatcher:grey_kindOfClass(NSClassFromString( - @"PDFExtensionTopView"))] - assertWithMatcher:grey_notNil() - error:&error]; - return error == nil; - }; - - NSString* errorMessage = @"PDFExtensionTopView was not visible"; - GREYAssert(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, condition), - errorMessage); - // Initial y scroll positions are set to make room for the toolbar. CGFloat yOffset = -[FullscreenAppInterface currentViewportInsets].top; DCHECK_LT(yOffset, 0); @@ -130,6 +131,7 @@ GURL URL = web::test::HttpServer::MakeUrl( "http://ios/testing/data/http_server_files/single_page_wide.pdf"); [ChromeEarlGrey loadURL:URL]; + WaitforPDFExtensionView(); { // TODO(crbug.com/852393): Investigate why synchronization isn't working. Is @@ -163,6 +165,7 @@ GURL URL = web::test::HttpServer::MakeUrl( "http://ios/testing/data/http_server_files/two_pages.pdf"); [ChromeEarlGrey loadURL:URL]; + WaitforPDFExtensionView(); // Test that the toolbar is hidden after a user swipes up. HideToolbarUsingUI();
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm b/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm index d9840268..ef31fb1 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_coordinator_unittest.mm
@@ -10,7 +10,7 @@ #include "base/files/scoped_temp_dir.h" #include "components/omnibox/browser/test_location_bar_model.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "ios/chrome/browser/autocomplete/autocomplete_classifier_factory.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #include "ios/chrome/browser/favicon/favicon_service_factory.h" @@ -33,7 +33,7 @@ #error "This file requires ARC support." #endif -using variations::VariationsHttpHeaderProvider; +using variations::VariationsIdsProvider; @interface TestToolbarCoordinatorDelegate : NSObject<ToolbarCoordinatorDelegate> @@ -117,7 +117,7 @@ // Started coordinator has to be stopped before WebStateList destruction. [coordinator_ stop]; - VariationsHttpHeaderProvider::GetInstance()->ResetForTesting(); + VariationsIdsProvider::GetInstance()->ResetForTesting(); PlatformTest::TearDown(); } @@ -154,8 +154,8 @@ // Verifies that URLLoader receives correct load request, which also includes // variations header. TEST_F(LocationBarCoordinatorTest, LoadGoogleUrl) { - ASSERT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::SUCCESS, - VariationsHttpHeaderProvider::GetInstance()->ForceVariationIds( + ASSERT_EQ(VariationsIdsProvider::ForceIdsResult::SUCCESS, + VariationsIdsProvider::GetInstance()->ForceVariationIds( /*variation_ids=*/{"100"}, /*command_line_variation_ids=*/"")); GURL url("https://www.google.com/"); @@ -188,8 +188,8 @@ // URL. Verifies that URLLoader receives correct load request without variations // header. TEST_F(LocationBarCoordinatorTest, LoadNonGoogleUrl) { - ASSERT_EQ(VariationsHttpHeaderProvider::ForceIdsResult::SUCCESS, - VariationsHttpHeaderProvider::GetInstance()->ForceVariationIds( + ASSERT_EQ(VariationsIdsProvider::ForceIdsResult::SUCCESS, + VariationsIdsProvider::GetInstance()->ForceVariationIds( /*variation_ids=*/{"100"}, /*command_line_variation_ids=*/"")); GURL url("https://www.nongoogle.com/");
diff --git a/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@2x.png b/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@2x.png index 08af5c3..2176fcb 100644 --- a/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@2x.png +++ b/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@3x.png b/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@3x.png index 109bcb29..4d4162f67 100644 --- a/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@3x.png +++ b/ios/chrome/browser/ui/location_bar/resources/location_bar_connection_secure.imageset/location_bar_connection_secure@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/main/scene_controller.mm b/ios/chrome/browser/ui/main/scene_controller.mm index 563991f..1746089 100644 --- a/ios/chrome/browser/ui/main/scene_controller.mm +++ b/ios/chrome/browser/ui/main/scene_controller.mm
@@ -118,9 +118,6 @@ // that it can be set to |NONE| when not in use. enum class TabSwitcherDismissalMode { NONE, NORMAL, INCOGNITO }; -// Constants for deferred promo display. -const NSTimeInterval kDisplayPromoDelay = 0.1; - // Key of the UMA IOS.MultiWindow.OpenInNewWindow histogram. const char kMultiWindowOpenInNewWindowHistogram[] = "IOS.MultiWindow.OpenInNewWindow"; @@ -289,7 +286,9 @@ } if (level == SceneActivationLevelForegroundActive) { - [self presentSignInAccountsViewControllerIfNecessary]; + if (![self presentSigninUpgradePromoIfPossible]) { + [self presentSignInAccountsViewControllerIfNecessary]; + } // Mitigation for crbug.com/1092326, where a nil browser state is passed // (presumably because mainInterface is nil as well). // TODO(crbug.com/1094916): Handle this more cleanly. @@ -679,8 +678,6 @@ [self showFirstRunUI]; // Do not ever show the 'restore' infobar during first run. self.mainController.restoreHelper = nil; - } else { - [self scheduleShowPromo]; } } @@ -766,42 +763,44 @@ } } -#pragma mark - Promo support - -// Schedules presentation of the first eligible promo found, if any. -- (void)scheduleShowPromo { +// Presents the sign-in upgrade promo if is relevant and possible. +// Returns YES if the promo is shown. +- (BOOL)presentSigninUpgradePromoIfPossible { + if (!SigninShouldPresentUserSigninUpgrade( + self.mainController.mainBrowserState)) + return NO; // Don't show promos if first run is shown in any scene. (Note: This flag // is only YES while the first run UI is visible. However, as this function // is called immediately after the UI is shown, it's a safe check.) for (SceneState* sceneState in self.sceneState.appState.connectedScenes) { if (sceneState.presentingFirstRunUI) { - return; + return NO; } } - // Don't show promos in Incognito mode. + // Don't show the promo if there is a blocking task in process. + if (self.sceneState.appState.sceneShowingBlockingUI) + return NO; + // Don't show the promo in Incognito mode. if (self.currentInterface == self.incognitoInterface) - return; + return NO; // Don't show promos if the app was launched from a URL. if (self.startupParameters) - return; - - // Show the sign-in promo if needed - if (SigninShouldPresentUserSigninUpgrade( - self.mainController.mainBrowserState)) { - Browser* browser = self.mainInterface.browser; - self.signinCoordinator = [SigninCoordinator - upgradeSigninPromoCoordinatorWithBaseViewController:self.mainInterface - .viewController - browser:browser]; - - __weak SceneController* weakSelf = self; - dispatch_after( - dispatch_time(DISPATCH_TIME_NOW, - static_cast<int64_t>(kDisplayPromoDelay * NSEC_PER_SEC)), - dispatch_get_main_queue(), ^{ - [weakSelf startSigninCoordinatorWithCompletion:nil]; - }); - } + return NO; + // Don't show the promo if the window is not active. + if (self.sceneState.activationLevel < SceneActivationLevelForegroundActive) + return NO; + // Don't show the promo if already presented. + if (self.sceneState.appState.signinUpgradePromoPresentedOnce) + return NO; + self.sceneState.appState.signinUpgradePromoPresentedOnce = YES; + DCHECK(!self.signinCoordinator); + Browser* browser = self.mainInterface.browser; + self.signinCoordinator = [SigninCoordinator + upgradeSigninPromoCoordinatorWithBaseViewController:self.mainInterface + .viewController + browser:browser]; + [self startSigninCoordinatorWithCompletion:nil]; + return YES; } #pragma mark - ApplicationCommands @@ -958,6 +957,7 @@ - (void)showAdvancedSigninSettingsFromViewController: (UIViewController*)baseViewController { + DCHECK(!self.signinCoordinator); Browser* mainBrowser = self.mainInterface.browser; self.signinCoordinator = [SigninCoordinator advancedSettingsSigninCoordinatorWithBaseViewController:baseViewController @@ -971,6 +971,7 @@ retrievalTrigger: (syncer::KeyRetrievalTriggerForUMA) retrievalTrigger { + DCHECK(!self.signinCoordinator); Browser* mainBrowser = self.mainInterface.browser; self.signinCoordinator = [SigninCoordinator trustedVaultReAuthenticationCoordiantorWithBaseViewController: @@ -983,6 +984,7 @@ // TODO(crbug.com/779791) : Remove settings commands from MainController. - (void)showAddAccountFromViewController:(UIViewController*)baseViewController { + DCHECK(!self.signinCoordinator); self.signinCoordinator = [SigninCoordinator addAccountCoordinatorWithBaseViewController:baseViewController browser:self.mainInterface.browser
diff --git a/ios/chrome/browser/ui/omnibox/omnibox_app_interface.mm b/ios/chrome/browser/ui/omnibox/omnibox_app_interface.mm index 7d13db4..ec97ce8e 100644 --- a/ios/chrome/browser/ui/omnibox/omnibox_app_interface.mm +++ b/ios/chrome/browser/ui/omnibox/omnibox_app_interface.mm
@@ -6,7 +6,7 @@ #include "base/strings/string_number_conversions.h" #include "components/google/core/common/google_util.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/test/app/tab_test_util.h" #import "ios/web/public/navigation/navigation_manager.h" @@ -45,11 +45,10 @@ } + (BOOL)forceVariationID:(int)variationID { - return variations::VariationsHttpHeaderProvider::ForceIdsResult::SUCCESS == - variations::VariationsHttpHeaderProvider::GetInstance() - ->ForceVariationIds( - /*variation_ids=*/{base::NumberToString(variationID)}, - /*command_line_variation_ids=*/""); + return variations::VariationsIdsProvider::ForceIdsResult::SUCCESS == + variations::VariationsIdsProvider::GetInstance()->ForceVariationIds( + /*variation_ids=*/{base::NumberToString(variationID)}, + /*command_line_variation_ids=*/""); } @end
diff --git a/ios/chrome/browser/web/BUILD.gn b/ios/chrome/browser/web/BUILD.gn index 144ba5ac..b2ef430 100644 --- a/ios/chrome/browser/web/BUILD.gn +++ b/ios/chrome/browser/web/BUILD.gn
@@ -315,6 +315,7 @@ ":web_internal", "//base", "//base/test:test_support", + "//components/captive_portal/core", "//components/content_settings/core/browser", "//components/infobars/core", "//components/lookalikes/core", @@ -330,6 +331,7 @@ "//ios/chrome/browser/infobars:public", "//ios/chrome/browser/passwords", "//ios/chrome/browser/safe_browsing", + "//ios/chrome/browser/ssl", "//ios/chrome/browser/web", "//ios/chrome/test/fakes", "//ios/components/security_interstitials", @@ -340,6 +342,7 @@ "//ios/web/public/test/fakes", "//net", "//net:test_support", + "//services/network:test_support", "//testing/gtest", "//third_party/ocmock", "//ui/base",
diff --git a/ios/chrome/browser/web/chrome_web_client_unittest.mm b/ios/chrome/browser/web/chrome_web_client_unittest.mm index 4e01410..b4c5ee6 100644 --- a/ios/chrome/browser/web/chrome_web_client_unittest.mm +++ b/ios/chrome/browser/web/chrome_web_client_unittest.mm
@@ -15,6 +15,7 @@ #import "base/test/ios/wait_util.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" +#include "components/captive_portal/core/captive_portal_detector.h" #include "components/lookalikes/core/lookalike_url_util.h" #import "components/safe_browsing/ios/browser/safe_browsing_url_allow_list.h" #include "components/security_interstitials/core/unsafe_resource.h" @@ -25,6 +26,8 @@ #import "ios/chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #import "ios/chrome/browser/safe_browsing/safe_browsing_error.h" #import "ios/chrome/browser/safe_browsing/safe_browsing_unsafe_resource_container.h" +#import "ios/chrome/browser/ssl/captive_portal_detector_tab_helper.h" +#import "ios/chrome/browser/ssl/captive_portal_detector_tab_helper_delegate.h" #import "ios/chrome/browser/web/error_page_util.h" #include "ios/chrome/browser/web/features.h" #import "ios/components/security_interstitials/ios_blocking_page_tab_helper.h" @@ -37,9 +40,11 @@ #import "ios/web/public/test/fakes/test_web_state.h" #import "ios/web/public/test/js_test_util.h" #include "ios/web/public/test/scoped_testing_web_client.h" +#include "net/http/http_status_code.h" #include "net/ssl/ssl_info.h" #include "net/test/cert_test_util.h" #include "net/test/test_data_directory.h" +#include "services/network/test/test_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest_mac.h" #include "testing/platform_test.h" @@ -321,6 +326,19 @@ web::TestWebState test_web_state; security_interstitials::IOSBlockingPageTabHelper::CreateForWebState( &test_web_state); + + // Use a test URLLoaderFactory so that the captive portal detector doesn't + // make an actual network request. + network::TestURLLoaderFactory test_loader_factory; + test_loader_factory.AddResponse( + captive_portal::CaptivePortalDetector::kDefaultURL, "", + net::HTTP_NO_CONTENT); + id captive_portal_detector_tab_helper_delegate = [OCMockObject + mockForProtocol:@protocol(CaptivePortalDetectorTabHelperDelegate)]; + CaptivePortalDetectorTabHelper::CreateForWebState( + &test_web_state, captive_portal_detector_tab_helper_delegate, + &test_loader_factory); + test_web_state.SetBrowserState(browser_state()); web_client.PrepareErrorPage(&test_web_state, GURL(kTestUrl), error, /*is_post=*/false,
diff --git a/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm b/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm index b0f095df..808731f 100644 --- a/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm +++ b/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm
@@ -17,7 +17,7 @@ #include "components/prefs/pref_service.h" #import "components/ukm/ios/features.h" #include "components/variations/variations_associated_data.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #import "ios/chrome/app/main_controller.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/autofill/personal_data_manager_factory.h" @@ -693,16 +693,16 @@ } + (BOOL)isVariationEnabled:(int)variationID { - variations::VariationsHttpHeaderProvider* provider = - variations::VariationsHttpHeaderProvider::GetInstance(); + variations::VariationsIdsProvider* provider = + variations::VariationsIdsProvider::GetInstance(); std::vector<variations::VariationID> ids = provider->GetVariationsVector(variations::GOOGLE_WEB_PROPERTIES); return std::find(ids.begin(), ids.end(), variationID) != ids.end(); } + (BOOL)isTriggerVariationEnabled:(int)variationID { - variations::VariationsHttpHeaderProvider* provider = - variations::VariationsHttpHeaderProvider::GetInstance(); + variations::VariationsIdsProvider* provider = + variations::VariationsIdsProvider::GetInstance(); std::vector<variations::VariationID> ids = provider->GetVariationsVector(variations::GOOGLE_WEB_PROPERTIES_TRIGGER); return std::find(ids.begin(), ids.end(), variationID) != ids.end();
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 88bb096..16d4793 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -270,6 +270,7 @@ "navigation/navigation_manager_impl_unittest.mm", "navigation/navigation_manager_util_unittest.mm", "navigation/nscoder_util_unittest.mm", + "navigation/session_storage_builder_unittest.mm", "navigation/wk_back_forward_list_item_holder_unittest.mm", "navigation/wk_based_navigation_manager_impl_unittest.mm", "navigation/wk_navigation_action_policy_util_unittest.mm",
diff --git a/ios/web/navigation/session_storage_builder.mm b/ios/web/navigation/session_storage_builder.mm index 17bc8cf..d9645fa1 100644 --- a/ios/web/navigation/session_storage_builder.mm +++ b/ios/web/navigation/session_storage_builder.mm
@@ -11,6 +11,7 @@ #import "ios/web/navigation/navigation_item_impl.h" #import "ios/web/navigation/navigation_item_storage_builder.h" #include "ios/web/navigation/navigation_manager_impl.h" +#import "ios/web/navigation/wk_navigation_util.h" #import "ios/web/public/session/crw_session_storage.h" #import "ios/web/public/session/serializable_user_data_manager.h" #import "ios/web/public/web_client.h" @@ -56,9 +57,16 @@ } [item_storages addObject:item_storage_builder.BuildStorage(item)]; } + + int loc = 0; + int len = 0; + session_storage.lastCommittedItemIndex = wk_navigation_util::GetSafeItemRange( + session_storage.lastCommittedItemIndex, item_storages.count, &loc, &len); + DCHECK_LT(session_storage.lastCommittedItemIndex, - static_cast<NSInteger>(item_storages.count)); - session_storage.itemStorages = item_storages; + static_cast<NSInteger>(len)); + session_storage.itemStorages = + [item_storages subarrayWithRange:NSMakeRange(loc, len)]; SessionCertificatePolicyCacheStorageBuilder cert_builder; session_storage.certPolicyCacheStorage = cert_builder.BuildStorage( &web_state->GetSessionCertificatePolicyCacheImpl());
diff --git a/ios/web/navigation/session_storage_builder_unittest.mm b/ios/web/navigation/session_storage_builder_unittest.mm new file mode 100644 index 0000000..08d0517 --- /dev/null +++ b/ios/web/navigation/session_storage_builder_unittest.mm
@@ -0,0 +1,137 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web/navigation/session_storage_builder.h" + +#import "ios/web/navigation/wk_navigation_util.h" +#import "ios/web/public/session/crw_navigation_item_storage.h" +#import "ios/web/public/session/crw_session_storage.h" +#include "ios/web/public/test/web_test.h" +#import "ios/web/test/fakes/crw_fake_back_forward_list.h" +#import "ios/web/web_state/ui/crw_web_view_navigation_proxy.h" +#import "ios/web/web_state/web_state_impl.h" +#import "third_party/ocmock/OCMock/OCMock.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace web { + +using wk_navigation_util::kMaxSessionSize; + +// WebState that provides Mock CRWWebViewNavigationProxy object. +class WebStateWithMockProxy : public WebStateImpl { + public: + explicit WebStateWithMockProxy(const CreateParams& params) + : WebStateImpl(params), + mock_web_view_(OCMProtocolMock(@protocol(CRWWebViewNavigationProxy))), + fake_wk_list_([[CRWFakeBackForwardList alloc] init]) { + OCMStub([mock_web_view_ backForwardList]).andReturn(fake_wk_list_); + } + + id<CRWWebViewNavigationProxy> mock_web_view() { return mock_web_view_; } + + CRWFakeBackForwardList* fake_wk_list() { return fake_wk_list_; } + + private: + id<CRWWebViewNavigationProxy> GetWebViewNavigationProxy() const override { + return mock_web_view_; + } + + id mock_web_view_ = nil; + CRWFakeBackForwardList* fake_wk_list_ = nil; +}; + +using SessionStorageBuilderTest = WebTest; + +// Tests building storage for session that is longer than kMaxSessionSize with +// last committed item at the end of the session. +TEST_F(SessionStorageBuilderTest, BuildStorageForExtraLongSession) { + // Create WebState with navigation item count that exceeds kMaxSessionSize. + WebState::CreateParams params(GetBrowserState()); + WebStateWithMockProxy web_state(params); + + NSMutableArray* back_urls = [NSMutableArray array]; + for (int i = 0; i < kMaxSessionSize; i++) { + [back_urls addObject:[NSString stringWithFormat:@"http://%d.test", i]]; + } + NSString* const current_url = @"http://current.test"; + [web_state.fake_wk_list() setCurrentURL:current_url + backListURLs:back_urls + forwardListURLs:nil]; + OCMStub([web_state.mock_web_view() URL]) + .andReturn([NSURL URLWithString:current_url]); + NavigationManager* navigation_manager = web_state.GetNavigationManager(); + int original_item_count = navigation_manager->GetItemCount(); + ASSERT_EQ(kMaxSessionSize + 1, original_item_count); + + // Verify that storage item count does not exceed kMaxSessionSize. + SessionStorageBuilder builder; + CRWSessionStorage* storage = builder.BuildStorage(&web_state); + ASSERT_TRUE(storage); + int stored_item_count = storage.itemStorages.count; + ASSERT_EQ(kMaxSessionSize, stored_item_count); + + // Walk backwards and verify that URLs in the storage match original URLs. + for (int i = 0; i < kMaxSessionSize; i++) { + NavigationItem* item = + navigation_manager->GetItemAtIndex(original_item_count - i - 1); + CRWNavigationItemStorage* item_storage = + [storage.itemStorages objectAtIndex:stored_item_count - i - 1]; + EXPECT_EQ(item->GetURL(), item_storage.URL) << "index: " << i; + } +} + +// Tests building storage for session that has items with +// ShouldSkipSerialization flag. The session length after skipping the items is +// not longer than kMaxSessionSize. +TEST_F(SessionStorageBuilderTest, ShouldSkipSerializationItems) { + // Create WebState with navigation item count that exceeds kMaxSessionSize. + WebState::CreateParams params(GetBrowserState()); + WebStateWithMockProxy web_state(params); + + NSMutableArray* back_urls = [NSMutableArray array]; + for (int i = 0; i < kMaxSessionSize; i++) { + [back_urls addObject:[NSString stringWithFormat:@"http://%d.test", i]]; + } + NSString* const current_url = @"http://current.test"; + [web_state.fake_wk_list() setCurrentURL:current_url + backListURLs:back_urls + forwardListURLs:nil]; + OCMStub([web_state.mock_web_view() URL]) + .andReturn([NSURL URLWithString:current_url]); + NavigationManager* navigation_manager = web_state.GetNavigationManager(); + int original_item_count = navigation_manager->GetItemCount(); + ASSERT_EQ(kMaxSessionSize + 1, original_item_count); + + const int kSkippedItemIndex = kMaxSessionSize - 1; + web_state.GetNavigationManagerImpl() + .GetNavigationItemImplAtIndex(kSkippedItemIndex) + ->SetShouldSkipSerialization(true); + + // Verify that storage item count does not exceed kMaxSessionSize. + SessionStorageBuilder builder; + CRWSessionStorage* storage = builder.BuildStorage(&web_state); + ASSERT_TRUE(storage); + int stored_item_count = storage.itemStorages.count; + ASSERT_EQ(kMaxSessionSize, stored_item_count); + + // Verify that URLs in the storage match original URLs without skipped item. + for (int storage_index = 0, item_index = 0; + storage_index < kMaxSessionSize && + item_index < web_state.GetNavigationManagerImpl().GetItemCount(); + storage_index++, item_index++) { + if (item_index == kSkippedItemIndex) { + item_index++; + } + NavigationItem* item = navigation_manager->GetItemAtIndex(item_index); + + CRWNavigationItemStorage* item_storage = + [storage.itemStorages objectAtIndex:storage_index]; + EXPECT_EQ(item->GetURL(), item_storage.URL) << "item_index: " << item_index; + } +} + +} // namespace web
diff --git a/ios/web/navigation/wk_navigation_util.h b/ios/web/navigation/wk_navigation_util.h index 1748ce14..b09da6d8 100644 --- a/ios/web/navigation/wk_navigation_util.h +++ b/ios/web/navigation/wk_navigation_util.h
@@ -43,6 +43,15 @@ // The "Referer" [sic] HTTP header. extern NSString* const kReferrerHeaderName; +// Sets (offset, size) and returns an updated last committed index, so the final +// size is less or equal to kMaxSessionSize. If item_count is greater than +// kMaxSessionSize, then this function will trim navigation items, which are the +// furthest to |last_committed_item_index|. +int GetSafeItemRange(int last_committed_item_index, + int item_count, + int* offset, + int* size); + // Returns true if |url| is a placeholder URL or restore_session.html URL. bool IsWKInternalUrl(const GURL& url); bool IsWKInternalUrl(NSURL* url);
diff --git a/ios/web/navigation/wk_navigation_util.mm b/ios/web/navigation/wk_navigation_util.mm index 18fd37ed..8ba02269 100644 --- a/ios/web/navigation/wk_navigation_util.mm +++ b/ios/web/navigation/wk_navigation_util.mm
@@ -4,6 +4,8 @@ #import "ios/web/navigation/wk_navigation_util.h" +#include <algorithm> + #include "base/json/json_writer.h" #include "base/mac/bundle_locations.h" #include "base/strings/string_util.h" @@ -34,48 +36,15 @@ const char kOriginalUrlKey[] = "for"; NSString* const kReferrerHeaderName = @"Referer"; -namespace { -// Returns begin and end iterators and an updated last committed index for the -// given navigation items. The length of these iterators range will not exceed -// kMaxSessionSize. If |items.size()| is greater than kMaxSessionSize, then this -// function will trim navigation items, which are the furthest to -// |last_committed_item_index|. -int GetSafeItemIterators( - int last_committed_item_index, - const std::vector<std::unique_ptr<NavigationItem>>& items, - std::vector<std::unique_ptr<NavigationItem>>::const_iterator* begin, - std::vector<std::unique_ptr<NavigationItem>>::const_iterator* end) { - if (items.size() <= kMaxSessionSize) { - // No need to trim anything. - *begin = items.begin(); - *end = items.end(); - return last_committed_item_index; - } - - if (last_committed_item_index < kMaxSessionSize / 2) { - // Items which are the furthest to |last_committed_item_index| are located - // on the right side of the vector. Trim those. - *begin = items.begin(); - *end = items.begin() + kMaxSessionSize; - return last_committed_item_index; - } - - if (items.size() - last_committed_item_index <= kMaxSessionSize / 2) { - // Items which are the furthest to |last_committed_item_index| are located - // on the left side of the vector. Trim those. - *begin = items.end() - kMaxSessionSize; - *end = items.end(); - } else { - // Trim items from both sides of the vector. Keep the same number of items - // on the left and right side of |last_committed_item_index|. - *begin = items.begin() + last_committed_item_index - kMaxSessionSize / 2; - *end = items.begin() + last_committed_item_index + kMaxSessionSize / 2 + 1; - } - - // The beginning of the vector has been trimmed, so move up the last committed - // item index by whatever was trimmed from the left. - return last_committed_item_index - (*begin - items.begin()); -} +int GetSafeItemRange(int last_committed_item_index, + int item_count, + int* offset, + int* size) { + *size = std::min(kMaxSessionSize, item_count); + *offset = std::min(last_committed_item_index - kMaxSessionSize / 2, + item_count - kMaxSessionSize); + *offset = std::max(*offset, 0); + return last_committed_item_index - *offset; } bool IsWKInternalUrl(const GURL& url) { @@ -130,25 +99,26 @@ DCHECK(last_committed_item_index >= 0 && last_committed_item_index < static_cast<int>(items.size())); - std::vector<std::unique_ptr<NavigationItem>>::const_iterator begin; - std::vector<std::unique_ptr<NavigationItem>>::const_iterator end; + int first_restored_item_offset = 0; + int new_size = 0; int new_last_committed_item_index = - GetSafeItemIterators(last_committed_item_index, items, &begin, &end); - size_t new_size = end - begin; + GetSafeItemRange(last_committed_item_index, items.size(), + &first_restored_item_offset, &new_size); // The URLs and titles of the restored entries are stored in two separate // lists instead of a single list of objects to reduce the size of the JSON // string to be included in the query parameter. base::Value restored_urls(base::Value::Type::LIST); base::Value restored_titles(base::Value::Type::LIST); - for (auto it = begin; it != end; ++it) { - NavigationItem* item = (*it).get(); + for (int i = first_restored_item_offset; + i < new_size + first_restored_item_offset; i++) { + NavigationItem* item = items[i].get(); restored_urls.Append(item->GetURL().spec()); restored_titles.Append(item->GetTitle()); } base::Value session(base::Value::Type::DICTIONARY); - int offset = new_last_committed_item_index + 1 - new_size; - session.SetKey("offset", base::Value(offset)); + int committed_item_offset = new_last_committed_item_index + 1 - new_size; + session.SetKey("offset", base::Value(committed_item_offset)); session.SetKey("urls", std::move(restored_urls)); session.SetKey("titles", std::move(restored_titles)); @@ -159,7 +129,7 @@ net::EscapeQueryParamValue(session_json, false /* use_plus */); GURL::Replacements replacements; replacements.SetRefStr(ref); - *first_index = begin - items.begin(); + *first_index = first_restored_item_offset; *url = GetRestoreSessionBaseUrl().ReplaceComponents(replacements); }
diff --git a/ios/web/navigation/wk_navigation_util_unittest.mm b/ios/web/navigation/wk_navigation_util_unittest.mm index d8a6761..12a33fe 100644 --- a/ios/web/navigation/wk_navigation_util_unittest.mm +++ b/ios/web/navigation/wk_navigation_util_unittest.mm
@@ -58,6 +58,64 @@ typedef PlatformTest WKNavigationUtilTest; +// Tests various inputs for GetSafeItemRange. +TEST_F(WKNavigationUtilTest, GetSafeItemRange) { + // Session size does not exceed kMaxSessionSize and last_committed_item_index + // is in range. + for (int item_count = 0; item_count <= kMaxSessionSize; item_count++) { + for (int item_index = 0; item_index < item_count; item_index++) { + int offset = 0; + int size = 0; + EXPECT_EQ(item_index, + GetSafeItemRange(item_index, item_count, &offset, &size)) + << "item_count: " << item_count << " item_index: " << item_index; + EXPECT_EQ(0, offset) << "item_count: " << item_count + << " item_index: " << item_index; + EXPECT_EQ(item_count, size) + << "item_count: " << item_count << " item_index: " << item_index; + } + } + + // Session size is 1 item longer than kMaxSessionSize. + int offset = 0; + int size = 0; + EXPECT_EQ(0, GetSafeItemRange(0, kMaxSessionSize + 1, &offset, &size)); + EXPECT_EQ(0, offset); + EXPECT_EQ(kMaxSessionSize, size); + + offset = 0; + size = 0; + EXPECT_EQ( + kMaxSessionSize - 1, + GetSafeItemRange(kMaxSessionSize, kMaxSessionSize + 1, &offset, &size)); + EXPECT_EQ(1, offset); + EXPECT_EQ(kMaxSessionSize, size); + + offset = 0; + size = 0; + EXPECT_EQ(kMaxSessionSize / 2, + GetSafeItemRange(kMaxSessionSize / 2, kMaxSessionSize + 1, &offset, + &size)); + EXPECT_EQ(0, offset); + EXPECT_EQ(kMaxSessionSize, size); + + offset = 0; + size = 0; + EXPECT_EQ(kMaxSessionSize / 2, + GetSafeItemRange(kMaxSessionSize / 2 + 1, kMaxSessionSize + 1, + &offset, &size)); + EXPECT_EQ(1, offset); + EXPECT_EQ(kMaxSessionSize, size); + + offset = 0; + size = 0; + EXPECT_EQ(kMaxSessionSize / 2 - 1, + GetSafeItemRange(kMaxSessionSize / 2 - 1, kMaxSessionSize + 1, + &offset, &size)); + EXPECT_EQ(0, offset); + EXPECT_EQ(kMaxSessionSize, size); +} + TEST_F(WKNavigationUtilTest, CreateRestoreSessionUrl) { auto item0 = std::make_unique<NavigationItemImpl>(); item0->SetURL(GURL("http://www.0.com"));
diff --git a/ios/web/public/test/fakes/test_web_state.h b/ios/web/public/test/fakes/test_web_state.h index 99b84c58..d60a582 100644 --- a/ios/web/public/test/fakes/test_web_state.h +++ b/ios/web/public/test/fakes/test_web_state.h
@@ -91,6 +91,7 @@ void SetHasOpener(bool has_opener) override; bool CanTakeSnapshot() const override; void TakeSnapshot(const gfx::RectF& rect, SnapshotCallback callback) override; + void CreateFullPagePdf(base::OnceCallback<void(NSData*)> callback) override; // Setters for test data. void SetBrowserState(BrowserState* browser_state);
diff --git a/ios/web/public/test/fakes/test_web_state.mm b/ios/web/public/test/fakes/test_web_state.mm index e8646612..637a7be 100644 --- a/ios/web/public/test/fakes/test_web_state.mm +++ b/ios/web/public/test/fakes/test_web_state.mm
@@ -458,4 +458,9 @@ std::move(callback).Run(gfx::Image([[UIImage alloc] init])); } +void TestWebState::CreateFullPagePdf( + base::OnceCallback<void(NSData*)> callback) { + std::move(callback).Run([[NSData alloc] init]); +} + } // namespace web
diff --git a/ios/web/public/web_state.h b/ios/web/public/web_state.h index 1f9464c..18f25353 100644 --- a/ios/web/public/web_state.h +++ b/ios/web/public/web_state.h
@@ -369,6 +369,11 @@ virtual void TakeSnapshot(const gfx::RectF& rect, SnapshotCallback callback) = 0; + // Creates PDF representation of the web page and invokes the |callback| with + // the NSData of the PDF or nil if a PDF couldn't be generated. + virtual void CreateFullPagePdf( + base::OnceCallback<void(NSData*)> callback) = 0; + // Adds and removes observers for page navigation notifications. The order in // which notifications are sent to observers is undefined. Clients must be // sure to remove the observer before they go away.
diff --git a/ios/web/web_state/ui/crw_web_controller.h b/ios/web/web_state/ui/crw_web_controller.h index 708c061..34d659f 100644 --- a/ios/web/web_state/ui/crw_web_controller.h +++ b/ios/web/web_state/ui/crw_web_controller.h
@@ -178,6 +178,11 @@ - (void)takeSnapshotWithRect:(CGRect)rect completion:(void (^)(UIImage* snapshot))completion; +// Creates PDF representation of the web page and invokes the |completion| with +// the NSData of the PDF or nil if a PDF couldn't be generated. +- (void)createFullPagePDFWithCompletion: + (void (^)(NSData* PDFDocumentData))completion; + // Creates a web view if it's not yet created. Returns the web view. - (WKWebView*)ensureWebViewCreated;
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index f95c497..3897dd7 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -6,6 +6,7 @@ #import <WebKit/WebKit.h> +#include "base/bind.h" #import "base/ios/block_types.h" #include "base/ios/ios_util.h" #include "base/json/string_escape.h" @@ -860,6 +861,10 @@ }]; } +- (void)createFullPagePDFWithCompletion:(void (^)(NSData*))completionBlock { + web::CreateFullPagePdf(self.webView, base::BindOnce(completionBlock)); +} + #pragma mark - CRWTouchTrackingDelegate (Public) - (void)touched:(BOOL)touched {
diff --git a/ios/web/web_state/web_state_impl.h b/ios/web/web_state/web_state_impl.h index a704913..594da72 100644 --- a/ios/web/web_state/web_state_impl.h +++ b/ios/web/web_state/web_state_impl.h
@@ -229,6 +229,7 @@ void SetHasOpener(bool has_opener) override; bool CanTakeSnapshot() const override; void TakeSnapshot(const gfx::RectF& rect, SnapshotCallback callback) override; + void CreateFullPagePdf(base::OnceCallback<void(NSData*)> callback) override; void AddObserver(WebStateObserver* observer) override; void RemoveObserver(WebStateObserver* observer) override; void CloseWebState() override;
diff --git a/ios/web/web_state/web_state_impl.mm b/ios/web/web_state/web_state_impl.mm index a4740c1..61db0a8a 100644 --- a/ios/web/web_state/web_state_impl.mm +++ b/ios/web/web_state/web_state_impl.mm
@@ -804,6 +804,18 @@ }]; } +void WebStateImpl::CreateFullPagePdf( + base::OnceCallback<void(NSData*)> callback) { + // Move the callback to a __block pointer, which will be in scope as long + // as the callback is retained. + __block base::OnceCallback<void(NSData*)> callback_for_block = + std::move(callback); + [web_controller_ + createFullPagePDFWithCompletion:^(NSData* pdf_document_data) { + std::move(callback_for_block).Run(pdf_document_data); + }]; +} + void WebStateImpl::OnNavigationStarted(web::NavigationContextImpl* context) { // Navigation manager loads internal URLs to restore session history and // create back-forward entries for WebUI. Do not trigger external callbacks.
diff --git a/ios/web/web_state/web_state_unittest.mm b/ios/web/web_state/web_state_unittest.mm index fa62eb4..0d3dc7d 100644 --- a/ios/web/web_state/web_state_unittest.mm +++ b/ios/web/web_state/web_state_unittest.mm
@@ -217,6 +217,39 @@ }); } +// Tests that the create PDF method retuns an PDF of a rendered html page of the +// appropriate size. +TEST_F(WebStateTest, CreateFullPagePdf) { + CGFloat kSaveAreaTopInset = + UIApplication.sharedApplication.keyWindow.safeAreaInsets.top; + + ASSERT_TRUE(LoadHtml("<html><div style='background-color:#FF0000; width:50%; " + "height:100%;'></div></html>")); + [[[UIApplication sharedApplication] keyWindow] + addSubview:web_state()->GetView()]; + // The subview is added but not immediately painted, so a small delay is + // necessary. + base::test::ios::SpinRunLoopWithMinDelay(base::TimeDelta::FromSecondsD(0.2)); + + __block NSData* callback_data = nil; + web_state()->CreateFullPagePdf(base::BindOnce(^(NSData* pdf_document_data) { + callback_data = [pdf_document_data copy]; + })); + + ASSERT_TRUE(callback_data); + + CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider( + CGDataProviderCreateWithCFData((CFDataRef)callback_data)); + CGSize pdf_size = + CGPDFPageGetBoxRect(CGPDFDocumentGetPage(pdf, 1), kCGPDFMediaBox).size; + + EXPECT_EQ(pdf_size.height, + UIScreen.mainScreen.bounds.size.height - kSaveAreaTopInset); + EXPECT_EQ(pdf_size.width, [[UIScreen mainScreen] bounds].size.width); + + CGPDFDocumentRelease(pdf); +} + // Tests that message sent from main frame triggers the ScriptCommandCallback // with |is_main_frame| = true. TEST_F(WebStateTest, MessageFromMainFrame) {
diff --git a/media/learning/mojo/public/cpp/OWNERS b/media/learning/mojo/public/cpp/OWNERS index e035c95..d5fefd8 100644 --- a/media/learning/mojo/public/cpp/OWNERS +++ b/media/learning/mojo/public/cpp/OWNERS
@@ -1,4 +1,2 @@ -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS per-file *_mojom_traits*.*=set noparent per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/media/learning/mojo/public/cpp/typemaps.gni b/media/learning/mojo/public/cpp/typemaps.gni deleted file mode 100644 index 92daacc9..0000000 --- a/media/learning/mojo/public/cpp/typemaps.gni +++ /dev/null
@@ -1 +0,0 @@ -typemaps = [ "//media/learning/mojo/public/mojom/learning_types.typemap" ]
diff --git a/media/learning/mojo/public/mojom/BUILD.gn b/media/learning/mojo/public/mojom/BUILD.gn index 0790062c..22f20526 100644 --- a/media/learning/mojo/public/mojom/BUILD.gn +++ b/media/learning/mojo/public/mojom/BUILD.gn
@@ -17,4 +17,42 @@ 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" + + shared_learning_types_cpp_typemap = { + types = [ + { + mojom = "media.learning.mojom.LabelledExample" + cpp = "::media::learning::LabelledExample" + }, + { + mojom = "media.learning.mojom.FeatureValue" + cpp = "::media::learning::FeatureValue" + }, + { + mojom = "media.learning.mojom.TargetValue" + cpp = "::media::learning::TargetValue" + }, + { + mojom = "media.learning.mojom.ObservationCompletion" + cpp = "::media::learning::ObservationCompletion" + }, + { + mojom = "media.learning.mojom.TargetHistogramPair" + cpp = "::media::learning::TargetHistogramPair" + }, + { + mojom = "media.learning.mojom.TargetHistogram" + cpp = "::media::learning::TargetHistogram" + }, + ] + traits_headers = + [ "//media/learning/mojo/public/cpp/learning_mojom_traits.h" ] + traits_public_deps = [ + "//media/learning/common", + "//media/learning/mojo/public/cpp:shared_typemap_traits", + ] + } + + cpp_typemaps = [ shared_learning_types_cpp_typemap ] + blink_cpp_typemaps = [ shared_learning_types_cpp_typemap ] }
diff --git a/media/learning/mojo/public/mojom/OWNERS b/media/learning/mojo/public/mojom/OWNERS index 229dacdd..08850f4 100644 --- a/media/learning/mojo/public/mojom/OWNERS +++ b/media/learning/mojo/public/mojom/OWNERS
@@ -1,4 +1,2 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS -per-file *.typemap=set noparent -per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/media/learning/mojo/public/mojom/learning_types.typemap b/media/learning/mojo/public/mojom/learning_types.typemap deleted file mode 100644 index 93ef123de..0000000 --- a/media/learning/mojo/public/mojom/learning_types.typemap +++ /dev/null
@@ -1,19 +0,0 @@ -mojom = "//media/learning/mojo/public/mojom/learning_types.mojom" -public_headers = [ - "//media/learning/common/labelled_example.h", - "//media/learning/common/learning_task_controller.h", - "//media/learning/common/value.h", -] -traits_headers = [ "//media/learning/mojo/public/cpp/learning_mojom_traits.h" ] -public_deps = [ - "//media/learning/common", - "//media/learning/mojo/public/cpp:shared_typemap_traits", -] -type_mappings = [ - "media.learning.mojom.LabelledExample=::media::learning::LabelledExample", - "media.learning.mojom.FeatureValue=::media::learning::FeatureValue", - "media.learning.mojom.TargetValue=::media::learning::TargetValue", - "media.learning.mojom.ObservationCompletion=::media::learning::ObservationCompletion", - "media.learning.mojom.TargetHistogramPair=::media::learning::TargetHistogramPair", - "media.learning.mojom.TargetHistogram=::media::learning::TargetHistogram", -]
diff --git a/mojo/public/tools/bindings/blink_bindings_configuration.gni b/mojo/public/tools/bindings/blink_bindings_configuration.gni index a661455..d8d6cd9 100644 --- a/mojo/public/tools/bindings/blink_bindings_configuration.gni +++ b/mojo/public/tools/bindings/blink_bindings_configuration.gni
@@ -6,11 +6,8 @@ for_blink = true -_typemap_imports = [ - "//media/learning/mojo/public/cpp/typemaps.gni", - "//skia/public/mojom/typemaps.gni", - "//third_party/blink/renderer/platform/mojo/blink_typemaps.gni", -] +_typemap_imports = + [ "//third_party/blink/renderer/platform/mojo/blink_typemaps.gni" ] _typemaps = [] foreach(typemap_import, _typemap_imports) {
diff --git a/mojo/public/tools/bindings/chromium_bindings_configuration.gni b/mojo/public/tools/bindings/chromium_bindings_configuration.gni index e40fa41..4489d99 100644 --- a/mojo/public/tools/bindings/chromium_bindings_configuration.gni +++ b/mojo/public/tools/bindings/chromium_bindings_configuration.gni
@@ -23,7 +23,6 @@ "//content/public/common/typemaps.gni", "//media/capture/mojom/typemaps.gni", "//media/fuchsia/mojom/typemaps.gni", - "//media/learning/mojo/public/cpp/typemaps.gni", "//media/mojo/mojom/typemaps.gni", "//sandbox/mac/mojom/typemaps.gni", "//services/media_session/public/cpp/typemaps.gni", @@ -31,7 +30,6 @@ "//services/resource_coordinator/public/cpp/typemaps.gni", "//services/service_manager/public/cpp/typemaps.gni", "//services/tracing/public/mojom/typemaps.gni", - "//skia/public/mojom/typemaps.gni", "//third_party/blink/common/typemaps.gni", "//third_party/blink/public/public_typemaps.gni", ]
diff --git a/net/BUILD.gn b/net/BUILD.gn index 2cf8736e..5ee3df0 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1343,6 +1343,10 @@ "proxy_resolution/win/windows_system_proxy_resolution_request.h", "proxy_resolution/win/windows_system_proxy_resolution_service.cc", "proxy_resolution/win/windows_system_proxy_resolution_service.h", + "proxy_resolution/win/windows_system_proxy_resolver.cc", + "proxy_resolution/win/windows_system_proxy_resolver.h", + "proxy_resolution/win/winhttp_api_wrapper.cc", + "proxy_resolution/win/winhttp_api_wrapper.h", "socket/tcp_socket_win.cc", "socket/tcp_socket_win.h", "socket/udp_socket_win.cc", @@ -4497,6 +4501,7 @@ "proxy_resolution/win/dhcp_pac_file_fetcher_win_unittest.cc", "proxy_resolution/win/proxy_config_service_win_unittest.cc", "proxy_resolution/win/windows_system_proxy_resolution_service_unittest.cc", + "proxy_resolution/win/windows_system_proxy_resolver_unittest.cc", "ssl/client_cert_store_win_unittest.cc", "ssl/ssl_platform_key_win_unittest.cc", ]
diff --git a/net/base/filename_util.cc b/net/base/filename_util.cc index a514c48..1471fb96 100644 --- a/net/base/filename_util.cc +++ b/net/base/filename_util.cc
@@ -58,7 +58,7 @@ &url_string, 0, FILE_PATH_LITERAL("\\"), FILE_PATH_LITERAL("%5C")); #endif - return GURL(url_string); + return GURL(base::AsCrossPlatformPiece(url_string)); } bool FileURLToFilePath(const GURL& url, base::FilePath* file_path) { @@ -132,7 +132,7 @@ #if defined(OS_WIN) if (base::IsStringUTF8(path)) { - file_path_str.assign(base::UTF8ToUTF16(path)); + file_path_str.assign(base::UTF8ToWide(path)); // We used to try too hard and see if |path| made up entirely of // the 1st 256 characters in the Unicode was a zero-extended UTF-16. // If so, we converted it to 'Latin-1' and checked if the result was UTF-8. @@ -144,7 +144,7 @@ // are giving the conversion function a nonempty string, and it may fail if // the given string is not in the current encoding and give us an empty // string back. We detect this and report failure. - file_path_str = base::WideToUTF16(base::SysNativeMBToWide(path)); + file_path_str = base::SysNativeMBToWide(path); } #else // defined(OS_WIN) // Collapse multiple path slashes into a single path slash. @@ -193,7 +193,7 @@ "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "clock$"}; #if defined(OS_WIN) - std::string filename_lower = base::ToLowerASCII(base::UTF16ToUTF8(filename)); + std::string filename_lower = base::ToLowerASCII(base::WideToUTF8(filename)); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) std::string filename_lower = base::ToLowerASCII(filename); #endif
diff --git a/net/base/filename_util_internal.cc b/net/base/filename_util_internal.cc index 92db27ab..3cb42b5 100644 --- a/net/base/filename_util_internal.cc +++ b/net/base/filename_util_internal.cc
@@ -207,7 +207,7 @@ bool FilePathToString16(const base::FilePath& path, base::string16* converted) { #if defined(OS_WIN) - *converted = path.value(); + converted->assign(path.value().begin(), path.value().end()); return true; #elif defined(OS_POSIX) || defined(OS_FUCHSIA) std::string component8 = path.AsUTF8Unsafe(); @@ -266,8 +266,8 @@ base::FilePath::StringType result_str, default_name_str; #if defined(OS_WIN) replace_trailing = true; - result_str = base::UTF8ToUTF16(filename); - default_name_str = base::UTF8ToUTF16(default_name); + result_str = base::UTF8ToWide(filename); + default_name_str = base::UTF8ToWide(default_name); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) result_str = filename; default_name_str = default_name; @@ -319,7 +319,7 @@ replace_illegal_characters_function); #if defined(OS_WIN) - base::FilePath generated_name(file_name); + base::FilePath generated_name(base::AsWStringPiece(file_name)); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) base::FilePath generated_name( base::SysWideToNativeMB(base::UTF16ToWide(file_name)));
diff --git a/net/base/filename_util_unittest.cc b/net/base/filename_util_unittest.cc index 9ad798c..8e3b6602 100644 --- a/net/base/filename_util_unittest.cc +++ b/net/base/filename_util_unittest.cc
@@ -39,14 +39,14 @@ // std::u16string. std::wstring FilePathAsWString(const base::FilePath& path) { #if defined(OS_WIN) - return base::UTF16ToWide(path.value()); + return path.value(); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) return base::UTF8ToWide(path.value()); #endif } base::FilePath WStringAsFilePath(const std::wstring& str) { #if defined(OS_WIN) - return base::FilePath(base::WideToUTF16(str)); + return base::FilePath(str); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) return base::FilePath(base::WideToUTF8(str)); #endif
diff --git a/net/base/mime_util.cc b/net/base/mime_util.cc index 357006b1..1abed03 100644 --- a/net/base/mime_util.cc +++ b/net/base/mime_util.cc
@@ -245,7 +245,7 @@ static base::FilePath::StringType StringToFilePathStringType( const base::StringPiece& string_piece) { #if defined(OS_WIN) - return base::UTF8ToUTF16(string_piece); + return base::UTF8ToWide(string_piece); #else return string_piece.as_string(); #endif
diff --git a/net/base/network_interfaces_unittest.cc b/net/base/network_interfaces_unittest.cc index b5c5a19..5543169 100644 --- a/net/base/network_interfaces_unittest.cc +++ b/net/base/network_interfaces_unittest.cc
@@ -51,7 +51,7 @@ EXPECT_EQ(static_cast<DWORD>(NO_ERROR), ConvertInterfaceLuidToGuid(&luid, &guid)); auto name = base::win::String16FromGUID(guid); - EXPECT_EQ(base::as_u16cstr(base::UTF8ToWide(it->name)), name); + EXPECT_EQ(base::UTF8ToWide(it->name), name); if (it->type == NetworkChangeNotifier::CONNECTION_WIFI) { EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE, GetWifiPHYLayerProtocol());
diff --git a/net/base/platform_mime_util_win.cc b/net/base/platform_mime_util_win.cc index 47f61827..c2b843d26 100644 --- a/net/base/platform_mime_util_win.cc +++ b/net/base/platform_mime_util_win.cc
@@ -20,9 +20,9 @@ // names are not case-sensitive). base::FilePath::StringType value, key = FILE_PATH_LITERAL(".") + ext; base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) - .ReadValue(STRING16_LITERAL("Content Type"), &value); + .ReadValue(L"Content Type", &value); if (!value.empty()) { - *result = base::UTF16ToUTF8(value); + *result = base::WideToUTF8(value); return true; } return false; @@ -32,10 +32,9 @@ const std::string& mime_type, base::FilePath::StringType* ext) const { base::FilePath::StringType key = - STRING16_LITERAL("MIME\\Database\\Content Type\\") + - base::UTF8ToUTF16(mime_type); + L"MIME\\Database\\Content Type\\" + base::UTF8ToWide(mime_type); if (base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ) - .ReadValue(STRING16_LITERAL("Extension"), ext) != ERROR_SUCCESS) { + .ReadValue(L"Extension", ext) != ERROR_SUCCESS) { return false; } // Strip off the leading dot, this should always be the case.
diff --git a/net/disk_cache/backend_unittest.cc b/net/disk_cache/backend_unittest.cc index 3e98e97..ff17771 100644 --- a/net/disk_cache/backend_unittest.cc +++ b/net/disk_cache/backend_unittest.cc
@@ -3919,13 +3919,13 @@ #if defined(OS_WIN) DWORD sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; DWORD access = GENERIC_READ | GENERIC_WRITE; - base::win::ScopedHandle file2(CreateFile(base::as_wcstr(name.value()), access, + base::win::ScopedHandle file2(CreateFile(name.value().c_str(), access, sharing, nullptr, OPEN_EXISTING, 0, nullptr)); EXPECT_FALSE(file2.IsValid()); sharing |= FILE_SHARE_DELETE; - file2.Set(CreateFile(base::as_wcstr(name.value()), access, sharing, nullptr, + file2.Set(CreateFile(name.value().c_str(), access, sharing, nullptr, OPEN_EXISTING, 0, nullptr)); EXPECT_TRUE(file2.IsValid()); #endif
diff --git a/net/disk_cache/blockfile/file_win.cc b/net/disk_cache/blockfile/file_win.cc index 9dfb629..6eebc48 100644 --- a/net/disk_cache/blockfile/file_win.cc +++ b/net/disk_cache/blockfile/file_win.cc
@@ -115,9 +115,9 @@ DWORD sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; DWORD access = GENERIC_READ | GENERIC_WRITE | DELETE; - base_file_ = base::File(CreateFile(base::as_wcstr(name.value()), access, - sharing, nullptr, OPEN_EXISTING, - FILE_FLAG_OVERLAPPED, nullptr)); + base_file_ = + base::File(CreateFile(name.value().c_str(), access, sharing, nullptr, + OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr)); if (!base_file_.IsValid()) return false; @@ -126,9 +126,8 @@ CompletionHandler::Get()); init_ = true; - sync_base_file_ = - base::File(CreateFile(base::as_wcstr(name.value()), access, sharing, - nullptr, OPEN_EXISTING, 0, nullptr)); + sync_base_file_ = base::File(CreateFile(name.value().c_str(), access, sharing, + nullptr, OPEN_EXISTING, 0, nullptr)); if (!sync_base_file_.IsValid()) return false;
diff --git a/net/disk_cache/cache_util.cc b/net/disk_cache/cache_util.cc index 5512ae8f..79b260da 100644 --- a/net/disk_cache/cache_util.cc +++ b/net/disk_cache/cache_util.cc
@@ -10,6 +10,7 @@ #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/location.h" +#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" @@ -124,7 +125,7 @@ base::FilePath name = current_path.BaseName(); #if defined(OS_WIN) // We created this file so it should only contain ASCII. - std::string name_str = base::UTF16ToASCII(name.value()); + std::string name_str = base::WideToASCII(name.value()); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) std::string name_str = name.value(); #endif
diff --git a/net/disk_cache/cache_util_win.cc b/net/disk_cache/cache_util_win.cc index f38e608..8b851d4 100644 --- a/net/disk_cache/cache_util_win.cc +++ b/net/disk_cache/cache_util_win.cc
@@ -16,8 +16,7 @@ bool MoveCache(const base::FilePath& from_path, const base::FilePath& to_path) { // I don't want to use the shell version of move because if something goes // wrong, that version will attempt to move file by file and fail at the end. - if (!MoveFileEx(base::as_wcstr(from_path.value()), - base::as_wcstr(to_path.value()), 0)) { + if (!MoveFileEx(from_path.value().c_str(), to_path.value().c_str(), 0)) { PLOG(ERROR) << "Unable to move the cache"; return false; } @@ -27,16 +26,16 @@ bool DeleteCacheFile(const base::FilePath& name) { // We do a simple delete, without ever falling back to SHFileOperation, as the // version from base does. - if (!DeleteFile(base::as_wcstr(name.value()))) { + if (!DeleteFile(name.value().c_str())) { // There is an error, but we share delete access so let's see if there is a // file to open. Note that this code assumes that we have a handle to the // file at all times (even now), so nobody can have a handle that prevents // us from opening the file again (unless it was deleted). DWORD sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; DWORD access = SYNCHRONIZE; - base::win::ScopedHandle file(CreateFile(base::as_wcstr(name.value()), - access, sharing, nullptr, - OPEN_EXISTING, 0, nullptr)); + base::win::ScopedHandle file(CreateFile(name.value().c_str(), access, + sharing, nullptr, OPEN_EXISTING, 0, + nullptr)); if (file.IsValid()) return false;
diff --git a/net/disk_cache/simple/simple_util_win.cc b/net/disk_cache/simple/simple_util_win.cc index 8b6c25ed..4622b2f 100644 --- a/net/disk_cache/simple/simple_util_win.cc +++ b/net/disk_cache/simple/simple_util_win.cc
@@ -31,8 +31,8 @@ path.DirName().AppendASCII(base::StringPrintf("todelete_%016" PRIx64, base::RandUint64())); - bool rename_succeeded = !!MoveFile(base::as_wcstr(path.value()), - base::as_wcstr(rename_target.value())); + bool rename_succeeded = + !!MoveFile(path.value().c_str(), rename_target.value().c_str()); if (rename_succeeded) return DeleteCacheFile(rename_target);
diff --git a/net/dns/dns_config_service_win.cc b/net/dns/dns_config_service_win.cc index 9cd9d76..37fd844 100644 --- a/net/dns/dns_config_service_win.cc +++ b/net/dns/dns_config_service_win.cc
@@ -20,6 +20,7 @@ #include "base/metrics/histogram_macros.h" #include "base/sequence_checker.h" #include "base/single_thread_task_runner.h" +#include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -46,27 +47,27 @@ const int kRetryIntervalSeconds = 5; // Registry key paths. -const base::char16 kTcpipPath[] = - STRING16_LITERAL("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"); -const base::char16 kTcpip6Path[] = - STRING16_LITERAL("SYSTEM\\CurrentControlSet\\Services\\Tcpip6\\Parameters"); -const base::char16 kDnscachePath[] = STRING16_LITERAL( - "SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters"); -const base::char16 kPolicyPath[] = - STRING16_LITERAL("SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient"); -const base::char16 kPrimaryDnsSuffixPath[] = - STRING16_LITERAL("SOFTWARE\\Policies\\Microsoft\\System\\DNSClient"); -const base::char16 kNrptPath[] = STRING16_LITERAL( - "SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient\\DnsPolicyConfig"); -const base::char16 kControlSetNrptPath[] = STRING16_LITERAL( - "SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters" - "\\DnsPolicyConfig"); -const base::char16 kDnsConnectionsPath[] = STRING16_LITERAL( - "SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters" - "\\DnsConnections"); -const base::char16 kDnsConnectionsProxies[] = STRING16_LITERAL( - "SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters" - "\\DnsConnectionsProxies"); +const wchar_t kTcpipPath[] = + L"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"; +const wchar_t kTcpip6Path[] = + L"SYSTEM\\CurrentControlSet\\Services\\Tcpip6\\Parameters"; +const wchar_t kDnscachePath[] = + L"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters"; +const wchar_t kPolicyPath[] = + L"SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient"; +const wchar_t kPrimaryDnsSuffixPath[] = + L"SOFTWARE\\Policies\\Microsoft\\System\\DNSClient"; +const wchar_t kNrptPath[] = + L"SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient\\DnsPolicyConfig"; +const wchar_t kControlSetNrptPath[] = + L"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters\\" + L"DnsPolicyConfig"; +const wchar_t kDnsConnectionsPath[] = + L"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters\\" + L"DnsConnections"; +const wchar_t kDnsConnectionsProxies[] = + L"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters\\" + L"DnsConnectionsProxies"; enum HostsParseWinResult { HOSTS_PARSE_WIN_OK = 0, @@ -80,14 +81,14 @@ // Convenience for reading values using RegKey. class RegistryReader { public: - explicit RegistryReader(const base::char16* key) { + explicit RegistryReader(const wchar_t* key) { // Ignoring the result. |key_.Valid()| will catch failures. key_.Open(HKEY_LOCAL_MACHINE, key, KEY_QUERY_VALUE); } ~RegistryReader() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } - bool ReadString(const base::char16* name, + bool ReadString(const wchar_t* name, DnsSystemSettings::RegString* out) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); out->set = false; @@ -103,8 +104,7 @@ return (result == ERROR_FILE_NOT_FOUND); } - bool ReadDword(const base::char16* name, - DnsSystemSettings::RegDword* out) const { + bool ReadDword(const wchar_t* name, DnsSystemSettings::RegDword* out) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); out->set = false; if (!key_.Valid()) { @@ -150,10 +150,8 @@ bool ReadDevolutionSetting(const RegistryReader& reader, DnsSystemSettings::DevolutionSetting* setting) { - return reader.ReadDword(STRING16_LITERAL("UseDomainNameDevolution"), - &setting->enabled) && - reader.ReadDword(STRING16_LITERAL("DomainNameDevolutionLevel"), - &setting->level); + return reader.ReadDword(L"UseDomainNameDevolution", &setting->enabled) && + reader.ReadDword(L"DomainNameDevolutionLevel", &setting->level); } // Reads DnsSystemSettings from IpHelper and registry. @@ -173,17 +171,14 @@ RegistryReader policy_reader(kPolicyPath); RegistryReader primary_dns_suffix_reader(kPrimaryDnsSuffixPath); - if (!policy_reader.ReadString(STRING16_LITERAL("SearchList"), - &settings->policy_search_list)) { + if (!policy_reader.ReadString(L"SearchList", &settings->policy_search_list)) { return CONFIG_PARSE_WIN_READ_POLICY_SEARCHLIST; } - if (!tcpip_reader.ReadString(STRING16_LITERAL("SearchList"), - &settings->tcpip_search_list)) + if (!tcpip_reader.ReadString(L"SearchList", &settings->tcpip_search_list)) return CONFIG_PARSE_WIN_READ_TCPIP_SEARCHLIST; - if (!tcpip_reader.ReadString(STRING16_LITERAL("Domain"), - &settings->tcpip_domain)) + if (!tcpip_reader.ReadString(L"Domain", &settings->tcpip_domain)) return CONFIG_PARSE_WIN_READ_DOMAIN; if (!ReadDevolutionSetting(policy_reader, &settings->policy_devolution)) @@ -195,14 +190,13 @@ if (!ReadDevolutionSetting(tcpip_reader, &settings->tcpip_devolution)) return CONFIG_PARSE_WIN_READ_TCPIP_DEVOLUTION; - if (!policy_reader.ReadDword(STRING16_LITERAL("AppendToMultiLabelName"), + if (!policy_reader.ReadDword(L"AppendToMultiLabelName", &settings->append_to_multi_label_name)) { return CONFIG_PARSE_WIN_READ_APPEND_MULTILABEL; } - if (!primary_dns_suffix_reader.ReadString( - STRING16_LITERAL("PrimaryDnsSuffix"), - &settings->primary_dns_suffix)) { + if (!primary_dns_suffix_reader.ReadString(L"PrimaryDnsSuffix", + &settings->primary_dns_suffix)) { return CONFIG_PARSE_WIN_READ_PRIMARY_SUFFIX; } @@ -234,11 +228,10 @@ hosts->insert(std::make_pair(DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6), loopback_ipv6)); - base::char16 buffer[MAX_PATH]; + wchar_t buffer[MAX_PATH]; DWORD size = MAX_PATH; std::string localname; - if (!GetComputerNameExW(ComputerNameDnsHostname, - base::as_writable_wcstr(buffer), &size) || + if (!GetComputerNameExW(ComputerNameDnsHostname, buffer, &size) || !ParseDomainASCII(buffer, &localname)) { return HOSTS_PARSE_WIN_COMPUTER_NAME_FAILED; } @@ -296,7 +289,7 @@ ~RegistryWatcher() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } - bool Watch(const base::char16* key, const CallbackType& callback) { + bool Watch(const wchar_t* key, const CallbackType& callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!callback.is_null()); DCHECK(callback_.is_null()); @@ -342,8 +335,8 @@ // Returns the path to the HOSTS file. base::FilePath GetHostsPath() { - base::char16 buffer[MAX_PATH]; - UINT rc = GetSystemDirectory(base::as_writable_wcstr(buffer), MAX_PATH); + wchar_t buffer[MAX_PATH]; + UINT rc = GetSystemDirectory(buffer, MAX_PATH); DCHECK(0 < rc && rc < MAX_PATH); return base::FilePath(buffer).Append( FILE_PATH_LITERAL("drivers\\etc\\hosts")); @@ -462,13 +455,13 @@ DnsSystemSettings::~DnsSystemSettings() { } -bool ParseDomainASCII(base::StringPiece16 widestr, std::string* domain) { +bool ParseDomainASCII(base::WStringPiece widestr, std::string* domain) { DCHECK(domain); if (widestr.empty()) return false; // Check if already ASCII. - if (base::IsStringASCII(widestr)) { + if (base::IsStringASCII(base::AsStringPiece16(widestr))) { domain->assign(widestr.begin(), widestr.end()); return true; } @@ -476,7 +469,7 @@ // Otherwise try to convert it from IDN to punycode. const int kInitialBufferSize = 256; url::RawCanonOutputT<base::char16, kInitialBufferSize> punycode; - if (!url::IDNToASCII(widestr.data(), widestr.length(), &punycode)) + if (!url::IDNToASCII(base::as_u16cstr(widestr), widestr.length(), &punycode)) return false; // |punycode_output| should now be ASCII; convert it to a std::string. @@ -488,7 +481,7 @@ return success && !domain->empty(); } -bool ParseSearchList(const base::string16& value, +bool ParseSearchList(const std::wstring& value, std::vector<std::string>* output) { DCHECK(output); if (value.empty()) @@ -500,9 +493,8 @@ // Although nslookup and network connection property tab ignore such // fragments ("a,b,,c" becomes ["a", "b", "c"]), our reference is getaddrinfo // (which sees ["a", "b"]). WMI queries also return a matching search list. - for (const base::StringPiece16& t : - base::SplitStringPiece(value, STRING16_LITERAL(","), - base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { + for (base::WStringPiece t : base::SplitStringPiece( + value, L",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { // Convert non-ASCII to punycode, although getaddrinfo does not properly // handle such suffixes. std::string parsed; @@ -561,7 +553,7 @@ // obtained via DHCP (regkey: Tcpip\Parameters\Interfaces\{XXX}\DhcpDomain) // or specified by the user (regkey: Tcpip\Parameters\Domain). std::string dns_suffix; - if (ParseDomainASCII(base::as_u16cstr(adapter->DnsSuffix), &dns_suffix)) + if (ParseDomainASCII(adapter->DnsSuffix, &dns_suffix)) config->search.push_back(dns_suffix); }
diff --git a/net/dns/dns_config_service_win.h b/net/dns/dns_config_service_win.h index 8b64504a..6c7e3df9 100644 --- a/net/dns/dns_config_service_win.h +++ b/net/dns/dns_config_service_win.h
@@ -19,6 +19,7 @@ #include "base/memory/free_deleter.h" #include "base/memory/ref_counted.h" #include "base/strings/string16.h" +#include "base/strings/string_piece_forward.h" #include "net/base/net_export.h" #include "net/dns/dns_config_service.h" @@ -40,14 +41,14 @@ // Converts a UTF-16 domain name to ASCII, possibly using punycode. // Returns true if the conversion succeeds and output is not empty. In case of // failure, |domain| might become dirty. -bool NET_EXPORT_PRIVATE ParseDomainASCII(base::StringPiece16 widestr, +bool NET_EXPORT_PRIVATE ParseDomainASCII(base::WStringPiece widestr, std::string* domain); // Parses |value| as search list (comma-delimited list of domain names) from // a registry key and stores it in |out|. Returns true on success. Empty // entries (e.g., "chromium.org,,org") terminate the list. Non-ascii hostnames // are converted to punycode. -bool NET_EXPORT_PRIVATE ParseSearchList(const base::string16& value, +bool NET_EXPORT_PRIVATE ParseSearchList(const std::wstring& value, std::vector<std::string>* out); // All relevant settings read from registry and IP Helper. This isolates our @@ -57,7 +58,7 @@ // The |set| flag distinguishes between empty and unset values. struct RegString { bool set; - base::string16 value; + std::wstring value; }; struct RegDword {
diff --git a/net/dns/dns_config_service_win_unittest.cc b/net/dns/dns_config_service_win_unittest.cc index cd34aa1..070df338 100644 --- a/net/dns/dns_config_service_win_unittest.cc +++ b/net/dns/dns_config_service_win_unittest.cc
@@ -17,19 +17,19 @@ TEST(DnsConfigServiceWinTest, ParseSearchList) { const struct TestCase { - const base::char16* input; + const wchar_t* input; const char* output[4]; // NULL-terminated, empty if expected false } cases[] = { - {STRING16_LITERAL("chromium.org"), {"chromium.org", nullptr}}, - {STRING16_LITERAL("chromium.org,org"), {"chromium.org", "org", nullptr}}, + {L"chromium.org", {"chromium.org", nullptr}}, + {L"chromium.org,org", {"chromium.org", "org", nullptr}}, // Empty suffixes terminate the list - {STRING16_LITERAL("crbug.com,com,,org"), {"crbug.com", "com", nullptr}}, + {L"crbug.com,com,,org", {"crbug.com", "com", nullptr}}, // IDN are converted to punycode - {STRING16_LITERAL("\u017c\xf3\u0142ta.pi\u0119\u015b\u0107.pl,pl"), + {L"\u017c\xf3\u0142ta.pi\u0119\u015b\u0107.pl,pl", {"xn--ta-4ja03asj.xn--pi-wla5e0q.pl", "pl", nullptr}}, // Empty search list is invalid - {STRING16_LITERAL(""), {nullptr}}, - {STRING16_LITERAL(",,"), {nullptr}}, + {L"", {nullptr}}, + {L",,", {nullptr}}, }; for (const auto& t : cases) { @@ -219,11 +219,10 @@ { // Policy SearchList override. { - {true, - STRING16_LITERAL("policy.searchlist.a,policy.searchlist.b")}, - {true, STRING16_LITERAL("tcpip.searchlist.a,tcpip.searchlist.b")}, - {true, STRING16_LITERAL("tcpip.domain")}, - {true, STRING16_LITERAL("primary.dns.suffix")}, + {true, L"policy.searchlist.a,policy.searchlist.b"}, + {true, L"tcpip.searchlist.a,tcpip.searchlist.b"}, + {true, L"tcpip.domain"}, + {true, L"primary.dns.suffix"}, }, {"policy.searchlist.a", "policy.searchlist.b"}, }, @@ -231,18 +230,18 @@ // User-specified SearchList override. { {false}, - {true, STRING16_LITERAL("tcpip.searchlist.a,tcpip.searchlist.b")}, - {true, STRING16_LITERAL("tcpip.domain")}, - {true, STRING16_LITERAL("primary.dns.suffix")}, + {true, L"tcpip.searchlist.a,tcpip.searchlist.b"}, + {true, L"tcpip.domain"}, + {true, L"primary.dns.suffix"}, }, {"tcpip.searchlist.a", "tcpip.searchlist.b"}, }, { // Void SearchList. Using tcpip.domain { - {true, STRING16_LITERAL(",bad.searchlist,parsed.as.empty")}, - {true, STRING16_LITERAL("tcpip.searchlist,good.but.overridden")}, - {true, STRING16_LITERAL("tcpip.domain")}, + {true, L",bad.searchlist,parsed.as.empty"}, + {true, L"tcpip.searchlist,good.but.overridden"}, + {true, L"tcpip.domain"}, {false}, }, {"tcpip.domain", "connection.suffix"}, @@ -250,10 +249,10 @@ { // Void SearchList. Using primary.dns.suffix { - {true, STRING16_LITERAL(",bad.searchlist,parsed.as.empty")}, - {true, STRING16_LITERAL("tcpip.searchlist,good.but.overridden")}, - {true, STRING16_LITERAL("tcpip.domain")}, - {true, STRING16_LITERAL("primary.dns.suffix")}, + {true, L",bad.searchlist,parsed.as.empty"}, + {true, L"tcpip.searchlist,good.but.overridden"}, + {true, L"tcpip.domain"}, + {true, L"primary.dns.suffix"}, }, {"primary.dns.suffix", "connection.suffix"}, }, @@ -261,19 +260,19 @@ // Void SearchList. Using tcpip.domain when primary.dns.suffix is // empty { - {true, STRING16_LITERAL(",bad.searchlist,parsed.as.empty")}, - {true, STRING16_LITERAL("tcpip.searchlist,good.but.overridden")}, - {true, STRING16_LITERAL("tcpip.domain")}, - {true, STRING16_LITERAL("")}, + {true, L",bad.searchlist,parsed.as.empty"}, + {true, L"tcpip.searchlist,good.but.overridden"}, + {true, L"tcpip.domain"}, + {true, L""}, }, {"tcpip.domain", "connection.suffix"}, }, { // Void SearchList. Using tcpip.domain when primary.dns.suffix is NULL { - {true, STRING16_LITERAL(",bad.searchlist,parsed.as.empty")}, - {true, STRING16_LITERAL("tcpip.searchlist,good.but.overridden")}, - {true, STRING16_LITERAL("tcpip.domain")}, + {true, L",bad.searchlist,parsed.as.empty"}, + {true, L"tcpip.searchlist,good.but.overridden"}, + {true, L"tcpip.domain"}, {true}, }, {"tcpip.domain", "connection.suffix"}, @@ -294,7 +293,7 @@ { {false}, {false}, - {true, STRING16_LITERAL("a.b.c.d.e")}, + {true, L"a.b.c.d.e"}, {false}, {{true, 1}, {false}}, // policy_devolution: enabled, level {{true, 0}, {true, 3}}, // dnscache_devolution @@ -307,8 +306,8 @@ { {false}, {false}, - {true, STRING16_LITERAL("a.b.c.d.e")}, - {true, STRING16_LITERAL("f.g.i.l.j")}, + {true, L"a.b.c.d.e"}, + {true, L"f.g.i.l.j"}, {{false}, {true, 4}}, {{true, 1}, {false}}, {{true, 0}, {true, 3}}, @@ -320,7 +319,7 @@ { {false}, {false}, - {true, STRING16_LITERAL("a.b.c.d.e")}, + {true, L"a.b.c.d.e"}, {false}, {{false}, {false}}, {{false}, {true, 3}}, @@ -333,7 +332,7 @@ { {false}, {false}, - {true, STRING16_LITERAL("a.b")}, + {true, L"a.b"}, {false}, {{false}, {false}}, {{false}, {true, 2}}, @@ -346,7 +345,7 @@ { {false}, {false}, - {true, STRING16_LITERAL("a.b.c.d.e")}, + {true, L"a.b.c.d.e"}, {false}, {{true, 1}, {false}}, {{true, 1}, {false}}, @@ -359,7 +358,7 @@ { {false}, {false}, - {true, STRING16_LITERAL("a.b.c.d.e")}, + {true, L"a.b.c.d.e"}, {false}, {{false}, {true, 1}}, {{true, 1}, {true, 3}}, @@ -372,7 +371,7 @@ { {false}, {false}, - {true, STRING16_LITERAL("a.b.c.d.e")}, + {true, L"a.b.c.d.e"}, {false}, {{false}, {true, 3}}, {{false}, {true, 3}},
diff --git a/net/http/transport_security_state_static.json b/net/http/transport_security_state_static.json index 9da4b29..96984b4 100644 --- a/net/http/transport_security_state_static.json +++ b/net/http/transport_security_state_static.json
@@ -84941,7 +84941,6 @@ { "name": "mdinvest.nz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "megayachts.world", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "meikampf.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "meiobit.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "membercents.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "mentup.com.br", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "mesh.org.ua", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true },
diff --git a/net/log/net_log_event_type_list.h b/net/log/net_log_event_type_list.h index f952484..20704e9 100644 --- a/net/log/net_log_event_type_list.h +++ b/net/log/net_log_event_type_list.h
@@ -1567,6 +1567,16 @@ // } EVENT_TYPE(HTTP2_SESSION_UPDATE_STREAMS_SEND_WINDOW_SIZE) +// Sending a greased frame (a frame of reserved type) +// { +// "stream_id": <The stream ID for the window update>, +// "type" : <Frame type>, +// "flags" : <Frame flags>, +// "length" : <Frame payload length>, +// "priority" : <RequestPriority of the stream>, +// } +EVENT_TYPE(HTTP2_SESSION_SEND_GREASED_FRAME) + // ------------------------------------------------------------------------ // SpdySessionPool // ------------------------------------------------------------------------
diff --git a/net/proxy_resolution/configured_proxy_resolution_service.cc b/net/proxy_resolution/configured_proxy_resolution_service.cc index 9533773..44c1cb5 100644 --- a/net/proxy_resolution/configured_proxy_resolution_service.cc +++ b/net/proxy_resolution/configured_proxy_resolution_service.cc
@@ -25,7 +25,6 @@ #include "net/base/proxy_delegate.h" #include "net/base/url_util.h" #include "net/log/net_log.h" -#include "net/log/net_log_capture_mode.h" #include "net/log/net_log_event_type.h" #include "net/log/net_log_util.h" #include "net/log/net_log_with_source.h"
diff --git a/net/proxy_resolution/configured_proxy_resolution_service.h b/net/proxy_resolution/configured_proxy_resolution_service.h index 879d194f..d2ea1194 100644 --- a/net/proxy_resolution/configured_proxy_resolution_service.h +++ b/net/proxy_resolution/configured_proxy_resolution_service.h
@@ -362,9 +362,6 @@ base::Optional<ProxyConfigWithAnnotation> fetched_config_; base::Optional<ProxyConfigWithAnnotation> config_; - // The time when the proxy configuration was last read from the system. - base::TimeTicks config_last_update_time_; - // Map of the known bad proxies and the information about the retry time. ProxyRetryInfoMap proxy_retry_info_;
diff --git a/net/proxy_resolution/win/proxy_config_service_win.cc b/net/proxy_resolution/win/proxy_config_service_win.cc index 04dd08d5..5c7b72a 100644 --- a/net/proxy_resolution/win/proxy_config_service_win.cc +++ b/net/proxy_resolution/win/proxy_config_service_win.cc
@@ -95,21 +95,19 @@ AddKeyToWatchList( HKEY_CURRENT_USER, - STRING16_LITERAL("Software\\Microsoft\\Windows\\CurrentVersion\\") - STRING16_LITERAL("Internet Settings")); + L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); AddKeyToWatchList( HKEY_LOCAL_MACHINE, - STRING16_LITERAL("Software\\Microsoft\\Windows\\CurrentVersion\\") - STRING16_LITERAL("Internet Settings")); + L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); AddKeyToWatchList(HKEY_LOCAL_MACHINE, - STRING16_LITERAL("SOFTWARE\\Policies\\Microsoft\\Windows\\") - STRING16_LITERAL("CurrentVersion\\Internet Settings")); + L"SOFTWARE\\Policies\\Microsoft\\Windows\\CurrentVersion\\" + L"Internet Settings"); } bool ProxyConfigServiceWin::AddKeyToWatchList(HKEY rootkey, - const base::char16* subkey) { + const wchar_t* subkey) { std::unique_ptr<base::win::RegKey> key = std::make_unique<base::win::RegKey>(); if (key->Create(rootkey, subkey, KEY_NOTIFY) != ERROR_SUCCESS)
diff --git a/net/proxy_resolution/win/proxy_config_service_win.h b/net/proxy_resolution/win/proxy_config_service_win.h index 937c2028..de54457 100644 --- a/net/proxy_resolution/win/proxy_config_service_win.h +++ b/net/proxy_resolution/win/proxy_config_service_win.h
@@ -70,7 +70,7 @@ // Creates a new key and appends it to |keys_to_watch_|. If the key fails to // be created, it is not appended to the list and we return false. - bool AddKeyToWatchList(HKEY rootkey, const base::char16* subkey); + bool AddKeyToWatchList(HKEY rootkey, const wchar_t* subkey); // This is called whenever one of the registry keys we are watching change. void OnObjectSignaled(base::win::RegKey* key);
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolution_request.cc b/net/proxy_resolution/win/windows_system_proxy_resolution_request.cc index 707c427..742f153 100644 --- a/net/proxy_resolution/win/windows_system_proxy_resolution_request.cc +++ b/net/proxy_resolution/win/windows_system_proxy_resolution_request.cc
@@ -4,15 +4,167 @@ #include "net/proxy_resolution/win/windows_system_proxy_resolution_request.h" +#include <utility> + +#include "net/base/net_errors.h" +#include "net/proxy_resolution/proxy_info.h" +#include "net/proxy_resolution/proxy_list.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolution_service.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolver.h" +#include "net/traffic_annotation/network_traffic_annotation.h" + namespace net { -WindowsSystemProxyResolutionRequest::WindowsSystemProxyResolutionRequest() = - default; -WindowsSystemProxyResolutionRequest::~WindowsSystemProxyResolutionRequest() = - default; +namespace { + +constexpr net::NetworkTrafficAnnotationTag kWindowsResolverTrafficAnnotation = + net::DefineNetworkTrafficAnnotation("proxy_config_windows_resolver", R"( + semantics { + sender: "Proxy Config for Windows System Resolver" + description: + "Establishing a connection through a proxy server using system proxy " + "settings and Windows system proxy resolution code." + trigger: + "Whenever a network request is made when the system proxy settings " + "are used, the Windows system proxy resolver is enabled, and the " + "result indicates usage of a proxy server." + data: + "Proxy configuration." + destination: OTHER + destination_other: + "The proxy server specified in the configuration." + } + policy { + cookies_allowed: NO + setting: + "User cannot override system proxy settings, but can change them " + "through 'Advanced/System/Open proxy settings'." + policy_exception_justification: + "Using either of 'ProxyMode', 'ProxyServer', or 'ProxyPacUrl' " + "policies can set Chrome to use a specific proxy settings and avoid " + "system proxy." + })"); + +} // namespace + +WindowsSystemProxyResolutionRequest::WindowsSystemProxyResolutionRequest( + WindowsSystemProxyResolutionService* service, + const GURL& url, + const std::string& method, + ProxyInfo* results, + CompletionOnceCallback user_callback, + const NetLogWithSource& net_log, + scoped_refptr<WindowsSystemProxyResolver> windows_system_proxy_resolver) + : windows_system_proxy_resolver_(windows_system_proxy_resolver), + service_(service), + user_callback_(std::move(user_callback)), + results_(results), + url_(url), + method_(method), + net_log_(net_log), + creation_time_(base::TimeTicks::Now()) { + DCHECK(!user_callback_.is_null()); + DCHECK(windows_system_proxy_resolver_); +} + +WindowsSystemProxyResolutionRequest::~WindowsSystemProxyResolutionRequest() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (service_) { + service_->RemovePendingRequest(this); + net_log_.AddEvent(NetLogEventType::CANCELLED); + + if (IsStarted()) + CancelResolveJob(); + + net_log_.EndEvent(NetLogEventType::PROXY_RESOLUTION_SERVICE); + } +} LoadState WindowsSystemProxyResolutionRequest::GetLoadState() const { - return LOAD_STATE_IDLE; + // TODO(https://crbug.com/1032820): Consider adding a LoadState for "We're + // waiting on system APIs to do their thing". + return LOAD_STATE_RESOLVING_PROXY_FOR_URL; +} + +int WindowsSystemProxyResolutionRequest::Start() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!was_completed()); + DCHECK(!IsStarted()); + + // Kicks off an asynchronous call that'll eventually call back into + // AsynchronousProxyResolutionComplete() with a result. + if (!windows_system_proxy_resolver_->GetProxyForUrl(this, url_.spec())) + return ERR_FAILED; + + // Asynchronous proxy resolution has begun. + return ERR_IO_PENDING; +} + +void WindowsSystemProxyResolutionRequest::CancelResolveJob() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(IsStarted()); + // The request may already be running in the resolver. + // TODO(https://crbug.com/1032820): Cancel callback instead of just ignoring + // it. + windows_system_proxy_resolver_->RemovePendingCallbackTarget(this); + DCHECK(!IsStarted()); +} + +bool WindowsSystemProxyResolutionRequest::IsStarted() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return windows_system_proxy_resolver_->HasPendingCallbackTarget(this); +} + +int WindowsSystemProxyResolutionRequest::UpdateResultsOnProxyResolutionComplete( + const ProxyList& proxy_list, + int net_error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!was_completed()); + + results_->UseProxyList(proxy_list); + + // Make sure IsStarted() returns false while DidFinishResolvingProxy() runs. + windows_system_proxy_resolver_->RemovePendingCallbackTarget(this); + + // Note that DidFinishResolvingProxy might modify |results_|. + const int updated_result = service_->DidFinishResolvingProxy( + url_, method_, results_, net_error, net_log_); + + // Make a note in the results which configuration was in use at the + // time of the resolve. + results_->set_proxy_resolve_start_time(creation_time_); + results_->set_proxy_resolve_end_time(base::TimeTicks::Now()); + results_->set_traffic_annotation( + MutableNetworkTrafficAnnotationTag(kWindowsResolverTrafficAnnotation)); + + return updated_result; +} + +int WindowsSystemProxyResolutionRequest::SynchronousProxyResolutionComplete( + int net_error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + ProxyList proxy_list; + const int updated_result = + UpdateResultsOnProxyResolutionComplete(proxy_list, net_error); + service_ = nullptr; + return updated_result; +} + +void WindowsSystemProxyResolutionRequest::AsynchronousProxyResolutionComplete( + const ProxyList& proxy_list, + int net_error, + int windows_error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // TODO(https://crbug.com/1032820): Log Windows error |windows_error|. + + net_error = UpdateResultsOnProxyResolutionComplete(proxy_list, net_error); + + CompletionOnceCallback callback = std::move(user_callback_); + + service_->RemovePendingRequest(this); + service_ = nullptr; + user_callback_.Reset(); + std::move(callback).Run(net_error); } } // namespace net
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolution_request.h b/net/proxy_resolution/win/windows_system_proxy_resolution_request.h index 575dcff..e5af2b6 100644 --- a/net/proxy_resolution/win/windows_system_proxy_resolution_request.h +++ b/net/proxy_resolution/win/windows_system_proxy_resolution_request.h
@@ -5,17 +5,40 @@ #ifndef NET_PROXY_RESOLUTION_WIN_WINDOWS_SYSTEM_PROXY_RESOLUTION_REQUEST_H_ #define NET_PROXY_RESOLUTION_WIN_WINDOWS_SYSTEM_PROXY_RESOLUTION_REQUEST_H_ +#include <memory> +#include <string> + +#include "base/memory/ref_counted.h" +#include "base/sequence_checker.h" +#include "base/time/time.h" +#include "net/base/completion_once_callback.h" +#include "net/base/net_export.h" +#include "net/base/network_isolation_key.h" +#include "net/log/net_log_with_source.h" #include "net/proxy_resolution/proxy_resolution_request.h" +#include "url/gurl.h" namespace net { +class ProxyInfo; +class ProxyList; +class WindowsSystemProxyResolutionService; +class WindowsSystemProxyResolver; + // This is the concrete implementation of ProxyResolutionRequest used by // WindowsSystemProxyResolutionService. Manages a single asynchronous proxy // resolution request. -class WindowsSystemProxyResolutionRequest final +class NET_EXPORT WindowsSystemProxyResolutionRequest : public ProxyResolutionRequest { public: - WindowsSystemProxyResolutionRequest(); + WindowsSystemProxyResolutionRequest( + WindowsSystemProxyResolutionService* service, + const GURL& url, + const std::string& method, + ProxyInfo* results, + const CompletionOnceCallback user_callback, + const NetLogWithSource& net_log, + scoped_refptr<WindowsSystemProxyResolver> windows_system_proxy_resolver); WindowsSystemProxyResolutionRequest( const WindowsSystemProxyResolutionRequest&) = delete; @@ -24,7 +47,62 @@ ~WindowsSystemProxyResolutionRequest() override; + // ProxyResolutionRequest LoadState GetLoadState() const override; + + // Starts the resolve proxy request. + int Start(); + + // Cancels the callback from the resolver for a previously started proxy + // resolution. + void CancelResolveJob(); + + bool IsStarted(); + + // Returns true if the request has been completed. + bool was_completed() const { return user_callback_.is_null(); } + + // Helper to call after ProxyResolver completion (both synchronous and + // asynchronous). Fixes up the result that is to be returned to user. + int UpdateResultsOnProxyResolutionComplete(const ProxyList& proxy_list, + int net_error); + + // Helper to call if the request completes synchronously, since in that case + // the request will not be added to |pending_requests_| (in + // WindowsSystemProxyResolutionService). + int SynchronousProxyResolutionComplete(int net_error); + + // Callback for when the WinHttp request has completed. This is the main way + // that proxy resolutions will complete. The |proxy_list| is the list of + // proxies returned by WinHttp translated into Chromium-friendly terms. The + // |net_error| describes the status of the proxy resolution request. If + // WinHttp fails for some reason, |windows_error| contains the specific error + // returned by WinHttp. + virtual void AsynchronousProxyResolutionComplete(const ProxyList& proxy_list, + int net_error, + int windows_error); + + protected: + // The resolver will do the work of talking to system APIs and translating the + // results into something Chromium understands. + scoped_refptr<WindowsSystemProxyResolver> windows_system_proxy_resolver_; + + private: + // Note that Request holds a bare pointer to the + // WindowsSystemProxyResolutionService. Outstanding requests are cancelled + // during ~WindowsSystemProxyResolutionService, so this is guaranteed to be + // valid throughout the lifetime of this object. + WindowsSystemProxyResolutionService* service_; + CompletionOnceCallback user_callback_; + ProxyInfo* results_; + const GURL url_; + const std::string method_; + NetLogWithSource net_log_; + // Time when the request was created. Stored here rather than in |results_| + // because the time in |results_| will be cleared. + base::TimeTicks creation_time_; + + SEQUENCE_CHECKER(sequence_checker_); }; } // namespace net
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc b/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc index 080af7a..e7f9ab9 100644 --- a/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc +++ b/net/proxy_resolution/win/windows_system_proxy_resolution_service.cc
@@ -4,15 +4,37 @@ #include "net/proxy_resolution/win/windows_system_proxy_resolution_service.h" +#include <utility> + #include "base/values.h" #include "net/base/net_errors.h" +#include "net/log/net_log.h" +#include "net/log/net_log_event_type.h" +#include "net/log/net_log_with_source.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolution_request.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolver.h" namespace net { -WindowsSystemProxyResolutionService::WindowsSystemProxyResolutionService() = - default; -WindowsSystemProxyResolutionService::~WindowsSystemProxyResolutionService() = - default; +WindowsSystemProxyResolutionService::WindowsSystemProxyResolutionService( + NetLog* net_log) + : create_proxy_resolver_function_for_testing_(nullptr), net_log_(net_log) {} + +WindowsSystemProxyResolutionService::~WindowsSystemProxyResolutionService() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // Cancel any in-progress requests. + // This cancels the internal requests, but leaves the responsibility of + // canceling the high-level Request (by deleting it) to the client. + // Since |pending_requests_| might be modified in one of the requests' + // callbacks (if it deletes another request), iterating through the set in a + // for-loop will not work. + while (!pending_requests_.empty()) { + WindowsSystemProxyResolutionRequest* req = *pending_requests_.begin(); + ProxyList empty_list; + req->AsynchronousProxyResolutionComplete(empty_list, ERR_ABORTED, 0); + pending_requests_.erase(req); + } +} int WindowsSystemProxyResolutionService::ResolveProxy( const GURL& url, @@ -22,26 +44,64 @@ CompletionOnceCallback callback, std::unique_ptr<ProxyResolutionRequest>* request, const NetLogWithSource& net_log) { - return ERR_NOT_IMPLEMENTED; + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!callback.is_null()); + DCHECK(request); + + net_log.BeginEvent(NetLogEventType::PROXY_RESOLUTION_SERVICE); + + // TODO(https://crbug.com/1032820): Use a more detailed error. + if (!CreateWindowsSystemProxyResolverIfNeeded()) + return DidFinishResolvingProxy(url, method, results, ERR_FAILED, net_log); + + auto req = std::make_unique<WindowsSystemProxyResolutionRequest>( + this, url, method, results, std::move(callback), net_log, + windows_system_proxy_resolver_); + + const int net_error = req->Start(); + if (net_error != ERR_IO_PENDING) + return req->SynchronousProxyResolutionComplete(net_error); + + DCHECK(!ContainsPendingRequest(req.get())); + pending_requests_.insert(req.get()); + + // Completion will be notified through |callback|, unless the caller cancels + // the request using |request|. + *request = std::move(req); + return net_error; } void WindowsSystemProxyResolutionService::ReportSuccess( - const ProxyInfo& proxy_info) {} + const ProxyInfo& proxy_info) { + // TODO(https://crbug.com/1032820): Update proxy retry info with new proxy + // resolution data. +} void WindowsSystemProxyResolutionService::SetProxyDelegate( - ProxyDelegate* delegate) {} + ProxyDelegate* delegate) { + // TODO(https://crbug.com/1032820): Implement proxy delegates. +} -void WindowsSystemProxyResolutionService::OnShutdown() {} +void WindowsSystemProxyResolutionService::OnShutdown() { + // TODO(https://crbug.com/1032820): Add cleanup here as necessary. If cleanup + // is unnecessary, update the interface to not require an implementation for + // this so OnShutdown() can be removed. +} bool WindowsSystemProxyResolutionService::MarkProxiesAsBadUntil( const ProxyInfo& results, base::TimeDelta retry_delay, const std::vector<ProxyServer>& additional_bad_proxies, const NetLogWithSource& net_log) { + // TODO(https://crbug.com/1032820): Implement bad proxy cache. We should be + // able to share logic with the ConfiguredProxyResolutionService to accomplish + // this. return false; } -void WindowsSystemProxyResolutionService::ClearBadProxiesCache() {} +void WindowsSystemProxyResolutionService::ClearBadProxiesCache() { + proxy_retry_info_.clear(); +} const ProxyRetryInfoMap& WindowsSystemProxyResolutionService::proxy_retry_info() const { @@ -50,6 +110,7 @@ base::Value WindowsSystemProxyResolutionService::GetProxyNetLogValues( int info_sources) { + // TODO (https://crbug.com/1032820): Implement net logs. base::Value net_info_dict(base::Value::Type::DICTIONARY); return net_info_dict; } @@ -62,4 +123,66 @@ return false; } +void WindowsSystemProxyResolutionService:: + SetCreateWindowsSystemProxyResolverFunctionForTesting( + CreateWindowsSystemProxyResolverFunctionForTesting function) { + create_proxy_resolver_function_for_testing_ = function; +} + +void WindowsSystemProxyResolutionService:: + SetWindowsSystemProxyResolverForTesting( + scoped_refptr<WindowsSystemProxyResolver> + windows_system_proxy_resolver) { + windows_system_proxy_resolver_ = windows_system_proxy_resolver; +} + +bool WindowsSystemProxyResolutionService::ContainsPendingRequest( + WindowsSystemProxyResolutionRequest* req) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return pending_requests_.count(req) == 1; +} + +void WindowsSystemProxyResolutionService::RemovePendingRequest( + WindowsSystemProxyResolutionRequest* req) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(ContainsPendingRequest(req)); + pending_requests_.erase(req); +} + +bool WindowsSystemProxyResolutionService:: + CreateWindowsSystemProxyResolverIfNeeded() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (windows_system_proxy_resolver_) + return true; + + if (create_proxy_resolver_function_for_testing_) { + windows_system_proxy_resolver_ = + create_proxy_resolver_function_for_testing_(); + } else { + windows_system_proxy_resolver_ = + WindowsSystemProxyResolver::CreateWindowsSystemProxyResolver(); + } + + return !!windows_system_proxy_resolver_; +} + +int WindowsSystemProxyResolutionService::DidFinishResolvingProxy( + const GURL& url, + const std::string& method, + ProxyInfo* result, + int result_code, + const NetLogWithSource& net_log) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // TODO(https://crbug.com/1032820): Implement net logs. + // TODO(https://crbug.com/1032820): Implement proxy delegate. + // TODO(https://crbug.com/1032820): Implement proxy retry info. + + if (result_code != OK) + result->UseDirect(); + + net_log.EndEvent(NetLogEventType::PROXY_RESOLUTION_SERVICE); + return OK; +} + } // namespace net
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolution_service.h b/net/proxy_resolution/win/windows_system_proxy_resolution_service.h index 830ef9b..f90a123 100644 --- a/net/proxy_resolution/win/windows_system_proxy_resolution_service.h +++ b/net/proxy_resolution/win/windows_system_proxy_resolution_service.h
@@ -7,12 +7,24 @@ #include "net/proxy_resolution/proxy_resolution_service.h" +#include <memory> +#include <set> #include <string> +#include "base/compiler_specific.h" +#include "base/memory/ref_counted.h" +#include "base/sequence_checker.h" #include "net/base/net_export.h" namespace net { +class NetLog; +class WindowsSystemProxyResolutionRequest; +class WindowsSystemProxyResolver; + +using CreateWindowsSystemProxyResolverFunctionForTesting = + scoped_refptr<WindowsSystemProxyResolver> (*)(); + // This class decides which proxy server(s) to use for a particular URL request. // It does NOT support passing in fetched proxy configurations. Instead, it // relies entirely on WinHttp APIs to determine the proxy that should be used @@ -20,7 +32,7 @@ class NET_EXPORT WindowsSystemProxyResolutionService : public ProxyResolutionService { public: - WindowsSystemProxyResolutionService(); + explicit WindowsSystemProxyResolutionService(NetLog* net_log); WindowsSystemProxyResolutionService( const WindowsSystemProxyResolutionService&) = delete; @@ -52,9 +64,57 @@ ConfiguredProxyResolutionService** configured_proxy_resolution_service) override WARN_UNUSED_RESULT; + // Used in tests to provide a fake |windows_system_proxy_resolver_|. + void SetCreateWindowsSystemProxyResolverFunctionForTesting( + CreateWindowsSystemProxyResolverFunctionForTesting function); + void SetWindowsSystemProxyResolverForTesting( + scoped_refptr<WindowsSystemProxyResolver> windows_system_proxy_resolver); + private: + friend class WindowsSystemProxyResolutionRequest; + friend class WindowsSystemProxyResolutionServiceTest; + + typedef std::set<WindowsSystemProxyResolutionRequest*> PendingRequests; + + bool ContainsPendingRequest(WindowsSystemProxyResolutionRequest* req) + WARN_UNUSED_RESULT; + void RemovePendingRequest(WindowsSystemProxyResolutionRequest* req); + + // Lazily creates |windows_system_proxy_resolver_|. + bool CreateWindowsSystemProxyResolverIfNeeded() WARN_UNUSED_RESULT; + + size_t PendingRequestSizeForTesting() const { + return pending_requests_.size(); + } + + // Called when proxy resolution has completed (either synchronously or + // asynchronously). Handles logging the result, and cleaning out + // bad entries from the results list. + int DidFinishResolvingProxy(const GURL& url, + const std::string& method, + ProxyInfo* result, + int result_code, + const NetLogWithSource& net_log); + + CreateWindowsSystemProxyResolverFunctionForTesting + create_proxy_resolver_function_for_testing_; + // Map of the known bad proxies and the information about the retry time. ProxyRetryInfoMap proxy_retry_info_; + + // Set of pending/in-progress requests. + PendingRequests pending_requests_; + + // This is the log for any generated events. + NetLog* net_log_; + + // This object encapsulates all WinHttp logic in Chromium-friendly terms. It + // manages the lifetime of the WinHttp session (which is + // per-resolution-service). This will get handed off to individual resolution + // requests so that they can query/cancel proxy resolution as needed. + scoped_refptr<WindowsSystemProxyResolver> windows_system_proxy_resolver_; + + SEQUENCE_CHECKER(sequence_checker_); }; } // namespace net
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolution_service_unittest.cc b/net/proxy_resolution/win/windows_system_proxy_resolution_service_unittest.cc index 191cc075..b1fe13a 100644 --- a/net/proxy_resolution/win/windows_system_proxy_resolution_service_unittest.cc +++ b/net/proxy_resolution/win/windows_system_proxy_resolution_service_unittest.cc
@@ -3,23 +3,352 @@ // found in the LICENSE file. #include "net/proxy_resolution/win/windows_system_proxy_resolution_service.h" + +#include <limits> +#include <memory> +#include <string> +#include <unordered_map> + +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" +#include "base/run_loop.h" +#include "base/sequence_checker.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "net/base/network_isolation_key.h" +#include "net/base/test_completion_callback.h" #include "net/proxy_resolution/configured_proxy_resolution_service.h" +#include "net/proxy_resolution/proxy_config.h" +#include "net/proxy_resolution/proxy_info.h" +#include "net/proxy_resolution/proxy_list.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolution_request.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolver.h" +#include "net/proxy_resolution/win/winhttp_api_wrapper.h" +#include "net/test/gtest_util.h" #include "net/test/test_with_task_environment.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +using net::test::IsError; +using net::test::IsOk; namespace net { -// TaskEnvironment required to register an IP Address observer from -// ConfiguredProxyResolutionService. -using WindowsSystemProxyResolutionServiceTest = TestWithTaskEnvironment; +namespace { + +const GURL kResourceUrl("https://example.test:8080/"); + +class MockWindowsSystemProxyResolver : public WindowsSystemProxyResolver { + public: + MockWindowsSystemProxyResolver() : WindowsSystemProxyResolver(nullptr) {} + + void set_get_proxy_for_url_success(bool get_proxy_for_url_success) { + get_proxy_for_url_success_ = get_proxy_for_url_success; + } + bool GetProxyForUrl(WindowsSystemProxyResolutionRequest* callback_target, + const std::string& url) override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!get_proxy_for_url_success_) + return false; + + const int request_handle = proxy_resolver_identifier_++; + pending_callback_target_map_[callback_target] = request_handle; + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&MockWindowsSystemProxyResolver::DoQueryComplete, + base::Unretained(this), callback_target, + request_handle)); + + return get_proxy_for_url_success_; + } + + void RemovePendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target) override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + pending_callback_target_map_.erase(callback_target); + } + + bool HasPendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target) const override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return (pending_callback_target_map_.find(callback_target) != + pending_callback_target_map_.end()); + } + + void add_server_to_proxy_list(const ProxyServer& proxy_server) { + proxy_list_.AddProxyServer(proxy_server); + } + + void set_net_error(int net_error) { net_error_ = net_error; } + + void set_windows_error(int windows_error) { windows_error_ = windows_error; } + + private: + ~MockWindowsSystemProxyResolver() override { + if (!pending_callback_target_map_.empty()) + ADD_FAILURE() + << "The WindowsSystemProxyResolutionRequests must account for all " + "pending requests in the WindowsSystemProxyResolver."; + } + + void DoQueryComplete(WindowsSystemProxyResolutionRequest* callback_target, + int request_handle) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (HasPendingCallbackTarget(callback_target) && + pending_callback_target_map_[callback_target] == request_handle) + callback_target->AsynchronousProxyResolutionComplete( + proxy_list_, net_error_, windows_error_); + } + + bool get_proxy_for_url_success_ = true; + ProxyList proxy_list_; + int net_error_ = OK; + // TODO(https://crbug.com/1032820): Add tests for the |windows_error_| + // code when it is used. + int windows_error_ = 0; + + int proxy_resolver_identifier_ = 1; + std::unordered_map<WindowsSystemProxyResolutionRequest*, int> + pending_callback_target_map_; + + SEQUENCE_CHECKER(sequence_checker_); +}; + +scoped_refptr<WindowsSystemProxyResolver> +CreateWindowsSystemProxyResolverFails() { + return nullptr; +} + +} // namespace + +// These tests verify the behavior of the WindowsSystemProxyResolutionService in +// isolation by mocking out the WindowsSystemProxyResolver. +class WindowsSystemProxyResolutionServiceTest : public TestWithTaskEnvironment { + public: + void SetUp() override { + testing::Test::SetUp(); + + proxy_resolver_ = base::MakeRefCounted<MockWindowsSystemProxyResolver>(); + proxy_resolution_service_ = + std::make_unique<WindowsSystemProxyResolutionService>( + /*net_log=*/nullptr); + proxy_resolution_service_->SetWindowsSystemProxyResolverForTesting( + proxy_resolver_); + } + + WindowsSystemProxyResolutionService* service() { + return proxy_resolution_service_.get(); + } + + scoped_refptr<MockWindowsSystemProxyResolver> resolver() { + return proxy_resolver_; + } + + size_t PendingRequestSizeForTesting() { + return proxy_resolution_service_->PendingRequestSizeForTesting(); + } + + void ResetProxyResolutionService() { proxy_resolution_service_.reset(); } + + void DoResolveProxyCompletedSynchronouslyTest() { + // Make sure there would be a proxy result on success. + const ProxyServer proxy_server = + ProxyServer::FromPacString("HTTPS foopy:8443"); + resolver()->add_server_to_proxy_list(proxy_server); + + ProxyInfo info; + TestCompletionCallback callback; + NetLogWithSource log; + std::unique_ptr<ProxyResolutionRequest> request; + const int result = service()->ResolveProxy( + kResourceUrl, std::string(), NetworkIsolationKey(), &info, + callback.callback(), &request, log); + + EXPECT_THAT(result, IsOk()); + EXPECT_TRUE(info.is_direct()); + EXPECT_FALSE(callback.have_result()); + EXPECT_EQ(PendingRequestSizeForTesting(), 0u); + EXPECT_EQ(request, nullptr); + } + + void DoResolveProxyTest(const ProxyList& expected_proxy_list) { + ProxyInfo info; + TestCompletionCallback callback; + NetLogWithSource log; + std::unique_ptr<ProxyResolutionRequest> request; + int result = service()->ResolveProxy(kResourceUrl, std::string(), + NetworkIsolationKey(), &info, + callback.callback(), &request, log); + + ASSERT_THAT(result, IsError(ERR_IO_PENDING)); + ASSERT_EQ(PendingRequestSizeForTesting(), 1u); + ASSERT_NE(request, nullptr); + + // Wait for result to come back. + EXPECT_THAT(callback.GetResult(result), IsOk()); + + EXPECT_TRUE(expected_proxy_list.Equals(info.proxy_list())); + EXPECT_EQ(PendingRequestSizeForTesting(), 0u); + EXPECT_NE(request, nullptr); + } + + scoped_refptr<WindowsSystemProxyResolver> + CreateMockWindowsSystemProxyResolver() { + return proxy_resolver_; + } + + private: + std::unique_ptr<WindowsSystemProxyResolutionService> + proxy_resolution_service_; + scoped_refptr<MockWindowsSystemProxyResolver> proxy_resolver_; +}; + +TEST_F(WindowsSystemProxyResolutionServiceTest, + ResolveProxyFailedToCreateResolver) { + service()->SetWindowsSystemProxyResolverForTesting(nullptr); + service()->SetCreateWindowsSystemProxyResolverFunctionForTesting( + &CreateWindowsSystemProxyResolverFails); + DoResolveProxyCompletedSynchronouslyTest(); +} + +TEST_F(WindowsSystemProxyResolutionServiceTest, + ResolveProxyCompletedSynchronously) { + resolver()->set_get_proxy_for_url_success(false); + DoResolveProxyCompletedSynchronouslyTest(); +} + +TEST_F(WindowsSystemProxyResolutionServiceTest, + ResolveProxyFailedAsynchronously) { + resolver()->set_net_error(ERR_FAILED); + + // Make sure there would be a proxy result on success. + const ProxyServer proxy_server = + ProxyServer::FromPacString("HTTPS foopy:8443"); + resolver()->add_server_to_proxy_list(proxy_server); + + ProxyInfo info; + TestCompletionCallback callback; + NetLogWithSource log; + std::unique_ptr<ProxyResolutionRequest> request; + int result = service()->ResolveProxy(kResourceUrl, std::string(), + NetworkIsolationKey(), &info, + callback.callback(), &request, log); + + ASSERT_THAT(result, IsError(ERR_IO_PENDING)); + ASSERT_EQ(PendingRequestSizeForTesting(), 1u); + ASSERT_NE(request, nullptr); + + // Wait for result to come back. + EXPECT_THAT(callback.GetResult(result), IsOk()); + + EXPECT_TRUE(info.is_direct()); + EXPECT_EQ(PendingRequestSizeForTesting(), 0u); + EXPECT_NE(request, nullptr); +} + +TEST_F(WindowsSystemProxyResolutionServiceTest, ResolveProxyEmptyResults) { + ProxyList expected_proxy_list; + DoResolveProxyTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolutionServiceTest, ResolveProxyWithResults) { + ProxyList expected_proxy_list; + const ProxyServer proxy_server = + ProxyServer::FromPacString("HTTPS foopy:8443"); + resolver()->add_server_to_proxy_list(proxy_server); + expected_proxy_list.AddProxyServer(proxy_server); + + DoResolveProxyTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolutionServiceTest, + MultipleProxyResolutionRequests) { + ProxyList expected_proxy_list; + const ProxyServer proxy_server = + ProxyServer::FromPacString("HTTPS foopy:8443"); + resolver()->add_server_to_proxy_list(proxy_server); + expected_proxy_list.AddProxyServer(proxy_server); + NetLogWithSource log; + + ProxyInfo first_proxy_info; + TestCompletionCallback first_callback; + std::unique_ptr<ProxyResolutionRequest> first_request; + int result = service()->ResolveProxy( + kResourceUrl, std::string(), NetworkIsolationKey(), &first_proxy_info, + first_callback.callback(), &first_request, log); + ASSERT_THAT(result, IsError(ERR_IO_PENDING)); + ASSERT_EQ(PendingRequestSizeForTesting(), 1u); + ASSERT_NE(first_request, nullptr); + + ProxyInfo second_proxy_info; + TestCompletionCallback second_callback; + std::unique_ptr<ProxyResolutionRequest> second_request; + result = service()->ResolveProxy( + kResourceUrl, std::string(), NetworkIsolationKey(), &second_proxy_info, + second_callback.callback(), &second_request, log); + ASSERT_THAT(result, IsError(ERR_IO_PENDING)); + ASSERT_EQ(PendingRequestSizeForTesting(), 2u); + ASSERT_NE(second_request, nullptr); + + // Wait for results to come back. + EXPECT_THAT(first_callback.GetResult(result), IsOk()); + EXPECT_THAT(second_callback.GetResult(result), IsOk()); + + EXPECT_TRUE(expected_proxy_list.Equals(first_proxy_info.proxy_list())); + EXPECT_NE(first_request, nullptr); + EXPECT_TRUE(expected_proxy_list.Equals(second_proxy_info.proxy_list())); + EXPECT_NE(second_request, nullptr); + + EXPECT_EQ(PendingRequestSizeForTesting(), 0u); +} + +TEST_F(WindowsSystemProxyResolutionServiceTest, + ProxyResolutionServiceDestructionWithInFlightRequests) { + ProxyList expected_proxy_list; + const ProxyServer proxy_server = + ProxyServer::FromPacString("HTTPS foopy:8443"); + resolver()->add_server_to_proxy_list(proxy_server); + expected_proxy_list.AddProxyServer(proxy_server); + NetLogWithSource log; + + ProxyInfo first_proxy_info; + TestCompletionCallback first_callback; + std::unique_ptr<ProxyResolutionRequest> first_request; + int result = service()->ResolveProxy( + kResourceUrl, std::string(), NetworkIsolationKey(), &first_proxy_info, + first_callback.callback(), &first_request, log); + ASSERT_THAT(result, IsError(ERR_IO_PENDING)); + ASSERT_EQ(PendingRequestSizeForTesting(), 1u); + ASSERT_NE(first_request, nullptr); + + ProxyInfo second_proxy_info; + TestCompletionCallback second_callback; + std::unique_ptr<ProxyResolutionRequest> second_request; + result = service()->ResolveProxy( + kResourceUrl, std::string(), NetworkIsolationKey(), &second_proxy_info, + second_callback.callback(), &second_request, log); + ASSERT_THAT(result, IsError(ERR_IO_PENDING)); + ASSERT_EQ(PendingRequestSizeForTesting(), 2u); + ASSERT_NE(second_request, nullptr); + + // There are now 2 in-flight proxy resolution requests. Deleting the proxy + // resolution service should call the callbacks immediately and do any + // appropriate error handling. + ResetProxyResolutionService(); + EXPECT_TRUE(first_callback.have_result()); + EXPECT_TRUE(second_callback.have_result()); + + EXPECT_TRUE(first_proxy_info.is_direct()); + EXPECT_TRUE(second_proxy_info.is_direct()); +} TEST_F(WindowsSystemProxyResolutionServiceTest, CastToConfiguredProxyResolutionService) { - WindowsSystemProxyResolutionService service; - auto configured_service = ConfiguredProxyResolutionService::CreateDirect(); ConfiguredProxyResolutionService* casted_service = configured_service.get(); - EXPECT_FALSE(service.CastToConfiguredProxyResolutionService(&casted_service)); + EXPECT_FALSE( + service()->CastToConfiguredProxyResolutionService(&casted_service)); EXPECT_EQ(nullptr, casted_service); }
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolver.cc b/net/proxy_resolution/win/windows_system_proxy_resolver.cc new file mode 100644 index 0000000..8117b62 --- /dev/null +++ b/net/proxy_resolution/win/windows_system_proxy_resolver.cc
@@ -0,0 +1,368 @@ +// Copyright 2020 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 "net/proxy_resolution/win/windows_system_proxy_resolver.h" + +#include <cwchar> +#include <utility> + +#include "base/bind.h" +#include "base/logging.h" +#include "base/strings/string16.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "net/base/host_port_pair.h" +#include "net/base/net_errors.h" +#include "net/base/proxy_server.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolution_request.h" +#include "net/proxy_resolution/win/winhttp_api_wrapper.h" +#include "url/url_canon.h" + +namespace net { + +namespace { + +bool GetProxyServerFromWinHttpResultEntry( + const WINHTTP_PROXY_RESULT_ENTRY& result_entry, + ProxyServer* out_proxy_server) { + // TODO(https://crbug.com/1032820): Include net logs for proxy bypass + if (!result_entry.fProxy) { + *out_proxy_server = ProxyServer::Direct(); + return true; + } + + ProxyServer::Scheme scheme = ProxyServer::Scheme::SCHEME_INVALID; + switch (result_entry.ProxyScheme) { + case (INTERNET_SCHEME_HTTP): + scheme = ProxyServer::Scheme::SCHEME_HTTP; + break; + case (INTERNET_SCHEME_HTTPS): + scheme = ProxyServer::Scheme::SCHEME_HTTPS; + break; + case (INTERNET_SCHEME_SOCKS): + scheme = ProxyServer::Scheme::SCHEME_SOCKS4; + break; + default: + LOG(WARNING) << "Of the possible proxy schemes returned by WinHttp, " + "Chrome supports HTTP(S) and SOCKS4. The ProxyScheme " + "that triggered this message is: " + << result_entry.ProxyScheme; + break; + } + + if (scheme == ProxyServer::Scheme::SCHEME_INVALID) + return false; + + // Chrome expects a specific port from WinHttp. The WinHttp documentation on + // MSDN makes it unclear whether or not a specific port is guaranteed. + if (result_entry.ProxyPort == INTERNET_DEFAULT_PORT) { + LOG(WARNING) << "WinHttpGetProxyForUrlEx() returned a proxy with " + "INTERNET_PORT_DEFAULT!"; + return false; + } + + // Since there is a proxy in the result (i.e. |fProxy| is TRUE), the + // |pwszProxy| is guaranteed to be non-null and non-empty. + DCHECK(!!result_entry.pwszProxy); + DCHECK(wcslen(result_entry.pwszProxy) > 0); + + base::string16 host_wide(result_entry.pwszProxy, + wcslen(result_entry.pwszProxy)); + if (!base::IsStringASCII(host_wide)) { + const int kInitialBufferSize = 256; + url::RawCanonOutputT<base::char16, kInitialBufferSize> punycode_output; + if (!url::IDNToASCII(host_wide.data(), host_wide.length(), + &punycode_output)) + return false; + + host_wide.assign(punycode_output.data(), punycode_output.length()); + } + + // At this point the string in |host_wide| is ASCII. + std::string host; + if (!base::UTF16ToUTF8(host_wide.data(), host_wide.length(), &host)) + return false; + + HostPortPair host_and_port(host, result_entry.ProxyPort); + *out_proxy_server = ProxyServer(scheme, host_and_port); + return true; +} + +} // namespace + +// static +scoped_refptr<WindowsSystemProxyResolver> +WindowsSystemProxyResolver::CreateWindowsSystemProxyResolver() { + scoped_refptr<WindowsSystemProxyResolver> resolver = base::WrapRefCounted( + new WindowsSystemProxyResolver(std::make_unique<WinHttpAPIWrapper>())); + if (resolver->Initialize()) { + return resolver; + } + return nullptr; +} + +WindowsSystemProxyResolver::WindowsSystemProxyResolver( + std::unique_ptr<WinHttpAPIWrapper> winhttp_api_wrapper) + : winhttp_api_wrapper_(std::move(winhttp_api_wrapper)), + sequenced_task_runner_(base::SequencedTaskRunnerHandle::Get()) {} +WindowsSystemProxyResolver::~WindowsSystemProxyResolver() = default; + +bool WindowsSystemProxyResolver::Initialize() { + if (!winhttp_api_wrapper_->CallWinHttpOpen()) + return false; + + // Since this session handle will never be used for WinHTTP connections, + // these timeouts don't really mean much individually. However, WinHTTP's + // out of process PAC resolution will use a combined (sum of all timeouts) + // value to wait for an RPC reply. + if (!winhttp_api_wrapper_->CallWinHttpSetTimeouts(10000, 10000, 5000, 5000)) + return false; + + // This sets the entry point for every callback in the WinHttp session created + // above. + if (!winhttp_api_wrapper_->CallWinHttpSetStatusCallback( + &WindowsSystemProxyResolver::WinHttpStatusCallback)) + return false; + + return true; +} + +bool WindowsSystemProxyResolver::GetProxyForUrl( + WindowsSystemProxyResolutionRequest* callback_target, + const std::string& url) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // Fetch the current system proxy settings. These are per current network + // interface and per current user. + ScopedIEConfig scoped_ie_config; + if (!winhttp_api_wrapper_->CallWinHttpGetIEProxyConfigForCurrentUser( + scoped_ie_config.config())) + return false; + + // This will create a handle specifically for WinHttpGetProxyForUrlEx(). + HINTERNET resolver_handle = nullptr; + if (!winhttp_api_wrapper_->CallWinHttpCreateProxyResolver(&resolver_handle)) + return false; + + // WinHttp will do all necessary proxy resolution fallback for this request. + // If automatic settings aren't configured or fail, it'll use any manually + // configured proxies on the machine. The WINHTTP_AUTOPROXY_ALLOW_STATIC flag + // tells the APIs to pick up manually configured proxies. + // + // Separately, Windows allows different proxy settings for different network + // interfaces. The WINHTTP_AUTOPROXY_OPTIONS flag tells WinHttp to + // differentiate between these settings and to get the proxy that's most + // specific to the current interface. + WINHTTP_AUTOPROXY_OPTIONS autoproxy_options = {0}; + autoproxy_options.dwFlags = + WINHTTP_AUTOPROXY_ALLOW_STATIC | WINHTTP_AUTOPROXY_ALLOW_CM; + + // The fAutoLogonIfChallenged option has been deprecated and should always be + // set to FALSE throughout Windows 10. Even in earlier versions of the OS, + // this feature did not work particularly well. + // https://support.microsoft.com/en-us/help/3161949/ms16-077-description-of-the-security-update-for-wpad-june-14-2016 + autoproxy_options.fAutoLogonIfChallenged = FALSE; + + // Sets a specific PAC URL if there was one in the IE configs. + if (scoped_ie_config.config()->lpszAutoConfigUrl) { + autoproxy_options.dwFlags |= WINHTTP_AUTOPROXY_CONFIG_URL; + autoproxy_options.lpszAutoConfigUrl = + scoped_ie_config.config()->lpszAutoConfigUrl; + } + + // Similarly, allow WPAD if it was enabled in the IE configs. + if (!!scoped_ie_config.config()->fAutoDetect) { + autoproxy_options.dwFlags |= WINHTTP_AUTOPROXY_AUTO_DETECT; + + // Enable WPAD using both DNS and DHCP, since that is what idiomatic Windows + // applications do. + autoproxy_options.dwAutoDetectFlags |= WINHTTP_AUTO_DETECT_TYPE_DNS_A; + autoproxy_options.dwAutoDetectFlags |= WINHTTP_AUTO_DETECT_TYPE_DHCP; + } + + // Now that everything is set-up, ask WinHTTP to get the actual proxy list. + const DWORD_PTR context = reinterpret_cast<DWORD_PTR>(this); + if (!winhttp_api_wrapper_->CallWinHttpGetProxyForUrlEx( + resolver_handle, url, &autoproxy_options, context)) { + winhttp_api_wrapper_->CallWinHttpCloseHandle(resolver_handle); + return false; + } + + // Saves of the object which will receive the callback once the operation + // completes. + AddPendingCallbackTarget(callback_target, resolver_handle); + + // On a successful call to WinHttpGetProxyForUrlEx(), the callback set by + // CallWinHttpSetStatusCallback() is guaranteed to be called exactly once. + // That may happen at any time on any thread. In order to make sure this + // object does not destruct before that callback occurs, it must AddRef() + // itself. This reference will be Release()'d in the callback. + base::RefCountedThreadSafe<WindowsSystemProxyResolver>::AddRef(); + + return true; +} + +void WindowsSystemProxyResolver::AddPendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target, + HINTERNET resolver_handle) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + pending_callback_target_map_[callback_target] = resolver_handle; +} + +void WindowsSystemProxyResolver::RemovePendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + pending_callback_target_map_.erase(callback_target); +} + +bool WindowsSystemProxyResolver::HasPendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target) const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return (pending_callback_target_map_.find(callback_target) != + pending_callback_target_map_.end()); +} + +WindowsSystemProxyResolutionRequest* +WindowsSystemProxyResolver::LookupCallbackTargetFromResolverHandle( + HINTERNET resolver_handle) const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + WindowsSystemProxyResolutionRequest* pending_callback_target = nullptr; + for (auto target : pending_callback_target_map_) { + if (target.second == resolver_handle) { + pending_callback_target = target.first; + break; + } + } + return pending_callback_target; +} + +// static +void __stdcall WindowsSystemProxyResolver::WinHttpStatusCallback( + HINTERNET resolver_handle, + DWORD_PTR context, + DWORD status, + void* info, + DWORD info_len) { + DCHECK(resolver_handle); + DCHECK(context); + WindowsSystemProxyResolver* windows_system_proxy_resolver = + reinterpret_cast<WindowsSystemProxyResolver*>(context); + + // Make a copy of any error information in |info| so it can be accessed from + // the subsequently posted task. The |info| pointer's lifetime is managed by + // WinHTTP and hence is not valid once this frame returns. + int windows_error = S_OK; + if (info && status == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR) { + WINHTTP_ASYNC_RESULT* result = static_cast<WINHTTP_ASYNC_RESULT*>(info); + windows_error = result->dwError; + } + + // It is possible for PostTask() to fail (ex: during shutdown). In that case, + // the WindowsSystemProxyResolver in |context| will leak. This is expected to + // be either unusual or to occur during shutdown, where a leak doesn't matter. + // Since calling the |context| on the wrong thread may be problematic, it will + // be allowed to leak here if PostTask() fails. + windows_system_proxy_resolver->sequenced_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&WindowsSystemProxyResolver::DoWinHttpStatusCallback, + windows_system_proxy_resolver, resolver_handle, status, + windows_error)); +} + +void WindowsSystemProxyResolver::DoWinHttpStatusCallback( + HINTERNET resolver_handle, + DWORD status, + int windows_error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // The |resolver_handle| should correspond to a HINTERNET resolver_handle in + // |pending_callback_target_map_| unless the associated attempt to get a proxy + // for an URL has been cancelled. + WindowsSystemProxyResolutionRequest* pending_callback_target = + LookupCallbackTargetFromResolverHandle(resolver_handle); + + // There is no work to do if this request has been cancelled. + if (pending_callback_target) { + switch (status) { + case WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE: + GetProxyResultForCallbackTarget(pending_callback_target, + resolver_handle); + break; + case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: + HandleErrorForCallbackTarget(pending_callback_target, windows_error); + break; + default: + LOG(WARNING) << "DoWinHttpStatusCallback() expects only callbacks for " + "WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE and " + "WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, not: " + << status; + HandleErrorForCallbackTarget(pending_callback_target, E_UNEXPECTED); + break; + } + + // No matter what happened above, the |pending_callback_target| should no + // longer be in the |pending_callback_target_map_|. Either the callback was + // handled or it was cancelled. This pointer will be explicitly cleared to + // make it obvious that it can no longer be used safely. + DCHECK(!HasPendingCallbackTarget(pending_callback_target)); + pending_callback_target = nullptr; + } + + // The HINTERNET |resolver_handle| for this attempt at getting a proxy is no + // longer needed. + winhttp_api_wrapper_->CallWinHttpCloseHandle(resolver_handle); + + // The current WindowsSystemProxyResolver object may now be Release()'d on the + // correct sequence after all work is done, thus balancing out the AddRef() + // from WinHttpGetProxyForUrlEx(). + base::RefCountedThreadSafe<WindowsSystemProxyResolver>::Release(); +} + +void WindowsSystemProxyResolver::GetProxyResultForCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target, + HINTERNET resolver_handle) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(HasPendingCallbackTarget(callback_target)); + + WINHTTP_PROXY_RESULT proxy_result = {0}; + if (!winhttp_api_wrapper_->CallWinHttpGetProxyResult(resolver_handle, + &proxy_result)) { + // TODO(https://crbug.com/1032820): Use a more detailed net error. + callback_target->AsynchronousProxyResolutionComplete(ProxyList(), + ERR_FAILED, 0); + return; + } + + // Translate the results for ProxyInfo. + ProxyList proxy_list; + for (DWORD i = 0u; i < proxy_result.cEntries; ++i) { + ProxyServer proxy_server; + if (GetProxyServerFromWinHttpResultEntry(proxy_result.pEntries[i], + &proxy_server)) + proxy_list.AddProxyServer(proxy_server); + } + + // The |proxy_result| must be freed. + winhttp_api_wrapper_->CallWinHttpFreeProxyResult(&proxy_result); + + // The consumer of this proxy resolution may not understand an empty proxy + // list. Thus, this case is considered an error. + int net_error = proxy_list.IsEmpty() ? ERR_FAILED : OK; + callback_target->AsynchronousProxyResolutionComplete(proxy_list, net_error, + 0); +} + +void WindowsSystemProxyResolver::HandleErrorForCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target, + int windows_error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(HasPendingCallbackTarget(callback_target)); + + // TODO(https://crbug.com/1032820): Use a more detailed net error. + callback_target->AsynchronousProxyResolutionComplete(ProxyList(), ERR_FAILED, + windows_error); +} + +} // namespace net
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolver.h b/net/proxy_resolution/win/windows_system_proxy_resolver.h new file mode 100644 index 0000000..3596ec8f --- /dev/null +++ b/net/proxy_resolution/win/windows_system_proxy_resolver.h
@@ -0,0 +1,131 @@ +// Copyright 2020 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 NET_PROXY_RESOLUTION_WIN_WINDOWS_SYSTEM_PROXY_RESOLVER_H_ +#define NET_PROXY_RESOLUTION_WIN_WINDOWS_SYSTEM_PROXY_RESOLVER_H_ + +#include <windows.h> +#include <winhttp.h> + +#include <memory> +#include <string> +#include <unordered_map> + +#include "base/callback.h" +#include "base/compiler_specific.h" +#include "base/memory/ref_counted.h" +#include "base/sequence_checker.h" +#include "base/sequenced_task_runner.h" +#include "net/base/net_export.h" +#include "net/proxy_resolution/proxy_list.h" + +namespace net { + +class WindowsSystemProxyResolutionRequest; +class WinHttpAPIWrapper; + +// This provides a layer of abstraction between calling code Windows-specific +// code. It is shared between the WindowsSystemProxyResolutionService and +// inflight WinHttp callbacks. Internally, it takes care of all interaction with +// WinHttp. The only time this object is ever access outside of its sequence is +// during the WinHttp callback. For the sake of that callback, this must be +// RefcountedThreadSafe. +class NET_EXPORT WindowsSystemProxyResolver + : public base::RefCountedThreadSafe<WindowsSystemProxyResolver> { + public: + static scoped_refptr<WindowsSystemProxyResolver> + CreateWindowsSystemProxyResolver(); + + WindowsSystemProxyResolver(const WindowsSystemProxyResolver&) = delete; + WindowsSystemProxyResolver& operator=(const WindowsSystemProxyResolver&) = + delete; + + // This will first fetch the current system proxy settings by calling into + // WinHttpGetIEProxyConfigForCurrentUser() and then resolve the proxy using + // those settings as an input into WinHttpGetProxyForUrlEx(). + virtual bool GetProxyForUrl( + WindowsSystemProxyResolutionRequest* callback_target, + const std::string& url) WARN_UNUSED_RESULT; + + // After calling GetProxyForUrl(), a |callback_target| is saved internally for + // when proxy resolution is complete. When a + // WindowsSystemProxyResolutionRequest wants to avoid receiving a callback, + // it must remove itself from the list of pending callback targets. + virtual void RemovePendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target); + virtual bool HasPendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target) const + WARN_UNUSED_RESULT; + + protected: + explicit WindowsSystemProxyResolver( + std::unique_ptr<WinHttpAPIWrapper> winhttp_api_wrapper); + virtual ~WindowsSystemProxyResolver(); + + private: + friend class base::RefCountedThreadSafe<WindowsSystemProxyResolver>; + friend class WindowsSystemProxyResolverTest; + + // Sets up the WinHttp session that will be used throughout the lifetime of + // this object. + bool Initialize(); + + // These will interact with |pending_callback_target_map_|. + void AddPendingCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target, + HINTERNET handle); + WindowsSystemProxyResolutionRequest* LookupCallbackTargetFromResolverHandle( + HINTERNET resolver_handle) const; + + // This is the callback provided to WinHttp. Once a call to resolve a proxy + // succeeds or errors out, it'll call into here with |context| being a pointer + // to a WindowsSystemProxyResolver that has been kept alive. This callback can + // hit in any thread and will immediately post a task to the right sequence. + static void __stdcall WinHttpStatusCallback(HINTERNET resolver_handle, + DWORD_PTR context, + DWORD status, + void* info, + DWORD info_len); + + // Called from WinHttpStatusCallback on the right sequence. This will make + // decisions about what to do from the results of the proxy resolution call. + // Note that the WindowsSystemProxyResolutionRequest that asked for this proxy + // may have decided they no longer need an answer (ex: the request has gone + // away), so this function has to deal with that situation too. + void DoWinHttpStatusCallback(HINTERNET resolver_handle, + DWORD status, + int windows_error); + + // On a successful call to WinHttpGetProxyForUrlEx(), this translates WinHttp + // results into Chromium-friendly structures before notifying the right + // WindowsSystemProxyResolutionRequest. + void GetProxyResultForCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target, + HINTERNET resolver_handle); + + // On a failed call to WinHttpGetProxyForUrlEx(), this will notify the right + // WindowsSystemProxyResolutionRequest of the error. + void HandleErrorForCallbackTarget( + WindowsSystemProxyResolutionRequest* callback_target, + int windows_error); + + // This is a thin wrapper over WinHttp APIs that may be overridden for + // testing. + std::unique_ptr<WinHttpAPIWrapper> winhttp_api_wrapper_; + + // This is the mapping of WindowsSystemProxyResolutionRequest objects that + // called GetProxyForUrl() to the handle that's being used for their proxy + // resolution call. Upon receiving a callback from WinHttp (which includes an + // HINTERNET handle), a reverse lookup here will get the right + // WindowsSystemProxyResolutionRequest to use. + std::unordered_map<WindowsSystemProxyResolutionRequest*, HINTERNET> + pending_callback_target_map_; + + SEQUENCE_CHECKER(sequence_checker_); + scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_; +}; + +} // namespace net + +#endif // NET_PROXY_RESOLUTION_WIN_WINDOWS_SYSTEM_PROXY_RESOLVER_H_
diff --git a/net/proxy_resolution/win/windows_system_proxy_resolver_unittest.cc b/net/proxy_resolution/win/windows_system_proxy_resolver_unittest.cc new file mode 100644 index 0000000..5c4741be --- /dev/null +++ b/net/proxy_resolution/win/windows_system_proxy_resolver_unittest.cc
@@ -0,0 +1,859 @@ +// Copyright 2020 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 "net/proxy_resolution/win/windows_system_proxy_resolver.h" + +#include <windows.h> +#include <winhttp.h> + +#include <memory> +#include <set> +#include <string> +#include <vector> + +#include "base/bind.h" +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" +#include "base/run_loop.h" +#include "base/strings/string16.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "net/base/net_errors.h" +#include "net/base/proxy_server.h" +#include "net/base/test_completion_callback.h" +#include "net/proxy_resolution/proxy_config.h" +#include "net/proxy_resolution/proxy_list.h" +#include "net/proxy_resolution/win/windows_system_proxy_resolution_request.h" +#include "net/proxy_resolution/win/winhttp_api_wrapper.h" +#include "net/test/test_with_task_environment.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +namespace net { + +namespace { + +constexpr char kUrl[] = "https://example.test:8080/"; + +void CopySettingToIEProxyConfigString(const base::string16& setting, + LPWSTR* ie_proxy_config_string) { + *ie_proxy_config_string = static_cast<LPWSTR>( + GlobalAlloc(GPTR, sizeof(base::char16) * (setting.length() + 1))); + memcpy(*ie_proxy_config_string, setting.data(), + sizeof(wchar_t) * setting.length()); +} + +class MockProxyResolutionRequest final + : public WindowsSystemProxyResolutionRequest { + public: + MockProxyResolutionRequest( + CompletionOnceCallback user_callback, + const NetLogWithSource& net_log, + scoped_refptr<WindowsSystemProxyResolver> windows_system_proxy_resolver) + : WindowsSystemProxyResolutionRequest(/*service=*/nullptr, + GURL(), + /*method=*/std::string(), + /*results=*/nullptr, + std::move(user_callback), + net_log, + windows_system_proxy_resolver) {} + ~MockProxyResolutionRequest() override = default; + + LoadState GetLoadState() const override { + return LOAD_STATE_RESOLVING_PROXY_FOR_URL; + } + + void AsynchronousProxyResolutionComplete(const ProxyList& proxy_list, + int net_error, + int windows_error) override { + run_loop_.Quit(); + EXPECT_TRUE(windows_system_proxy_resolver_->HasPendingCallbackTarget(this)); + windows_system_proxy_resolver_->RemovePendingCallbackTarget(this); + EXPECT_FALSE( + windows_system_proxy_resolver_->HasPendingCallbackTarget(this)); + + proxy_list_ = proxy_list; + net_error_ = net_error; + windows_error_ = windows_error; + } + + void WaitForProxyResolutionComplete() { run_loop_.Run(); } + + const ProxyList& proxy_list() const { return proxy_list_; } + + int net_error() const { return net_error_; } + + int windows_error() const { return windows_error_; } + + private: + base::RunLoop run_loop_; + ProxyList proxy_list_; + int net_error_ = 0; + int windows_error_ = 0; +}; + +// This limit is arbitrary and exists only to make memory management in this +// test easier. +constexpr unsigned int kMaxProxyEntryLimit = 10u; + +// This class will internally validate behavior that MUST be present in the code +// in order to successfully use WinHttp APIs. +class MockWinHttpAPIWrapper : public WinHttpAPIWrapper { + public: + MockWinHttpAPIWrapper() {} + ~MockWinHttpAPIWrapper() override { + if (did_call_get_proxy_result_) + EXPECT_TRUE(did_call_free_proxy_result_); + EXPECT_TRUE(opened_proxy_resolvers_.empty()); + ResetWinHttpResults(); + } + + void set_call_winhttp_open_success(bool open_success) { + open_success_ = open_success; + } + bool CallWinHttpOpen() override { + did_call_open_ = true; + return open_success_; + } + + void set_call_winhttp_set_timeouts_success(bool set_timeouts_success) { + set_timeouts_success_ = set_timeouts_success; + } + bool CallWinHttpSetTimeouts(int resolve_timeout, + int connect_timeout, + int send_timeout, + int receive_timeout) override { + EXPECT_TRUE(did_call_open_); + did_call_set_timeouts_ = true; + return set_timeouts_success_; + } + + void set_call_winhttp_set_status_callback_success( + bool set_status_callback_success) { + set_status_callback_success_ = set_status_callback_success; + } + bool CallWinHttpSetStatusCallback( + WINHTTP_STATUS_CALLBACK internet_callback) override { + EXPECT_TRUE(did_call_open_); + EXPECT_NE(internet_callback, nullptr); + EXPECT_EQ(callback_, nullptr); + callback_ = internet_callback; + did_call_set_status_callback_ = true; + return set_status_callback_success_; + } + + void set_call_winhttp_get_ie_proxy_config_success( + bool get_ie_proxy_config_success) { + get_ie_proxy_config_success_ = get_ie_proxy_config_success; + } + void set_ie_proxy_config(bool is_autoproxy_enabled, + const base::string16& pac_url, + const base::string16& proxy, + const base::string16& proxy_bypass) { + is_autoproxy_enabled_ = is_autoproxy_enabled; + pac_url_ = pac_url; + proxy_ = proxy; + proxy_bypass_ = proxy_bypass; + } + bool CallWinHttpGetIEProxyConfigForCurrentUser( + WINHTTP_CURRENT_USER_IE_PROXY_CONFIG* ie_proxy_config) override { + did_call_get_ie_proxy_config_ = true; + ie_proxy_config->fAutoDetect = is_autoproxy_enabled_ ? TRUE : FALSE; + if (!pac_url_.empty()) { + CopySettingToIEProxyConfigString(pac_url_, + &ie_proxy_config->lpszAutoConfigUrl); + } + if (!proxy_.empty()) { + CopySettingToIEProxyConfigString(proxy_, &ie_proxy_config->lpszProxy); + } + if (!proxy_bypass_.empty()) { + CopySettingToIEProxyConfigString(proxy_bypass_, + &ie_proxy_config->lpszProxyBypass); + } + return get_ie_proxy_config_success_; + } + + void set_call_winhttp_create_proxy_resolver_success( + bool create_proxy_resolver_success) { + create_proxy_resolver_success_ = create_proxy_resolver_success; + } + bool CallWinHttpCreateProxyResolver(HINTERNET* out_resolver_handle) override { + EXPECT_TRUE(did_call_set_status_callback_); + EXPECT_NE(out_resolver_handle, nullptr); + if (!out_resolver_handle) + return false; + + did_call_create_proxy_resolver_ = true; + if (!create_proxy_resolver_success_) + return false; + + // The caller will be using this handle as an identifier later, so make this + // unique. + *out_resolver_handle = + reinterpret_cast<HINTERNET>(proxy_resolver_identifier_++); + EXPECT_EQ(opened_proxy_resolvers_.count(*out_resolver_handle), 0u); + opened_proxy_resolvers_.emplace(*out_resolver_handle); + + return true; + } + + void set_call_winhttp_get_proxy_for_url_success( + bool get_proxy_for_url_success) { + get_proxy_for_url_success_ = get_proxy_for_url_success; + } + bool CallWinHttpGetProxyForUrlEx(HINTERNET resolver_handle, + const std::string& url, + WINHTTP_AUTOPROXY_OPTIONS* autoproxy_options, + DWORD_PTR context) override { + // This API must be called only after the session has been correctly set up. + EXPECT_TRUE(did_call_open_); + EXPECT_TRUE(did_call_set_timeouts_); + EXPECT_TRUE(did_call_set_status_callback_); + EXPECT_NE(callback_, nullptr); + EXPECT_TRUE(did_call_get_ie_proxy_config_); + EXPECT_TRUE(did_call_create_proxy_resolver_); + EXPECT_TRUE(!did_call_get_proxy_result_); + EXPECT_TRUE(!did_call_free_proxy_result_); + + // This API must always receive valid inputs. + EXPECT_TRUE(!url.empty()); + EXPECT_TRUE(autoproxy_options); + EXPECT_FALSE(autoproxy_options->fAutoLogonIfChallenged); + EXPECT_TRUE(autoproxy_options->dwFlags & WINHTTP_AUTOPROXY_ALLOW_STATIC); + EXPECT_TRUE(autoproxy_options->dwFlags & WINHTTP_AUTOPROXY_ALLOW_CM); + if (autoproxy_options->dwFlags & WINHTTP_AUTOPROXY_CONFIG_URL) { + EXPECT_TRUE(autoproxy_options->lpszAutoConfigUrl); + } else { + EXPECT_TRUE(!autoproxy_options->lpszAutoConfigUrl); + } + if (autoproxy_options->dwFlags & WINHTTP_AUTOPROXY_AUTO_DETECT) { + EXPECT_TRUE(autoproxy_options->dwAutoDetectFlags & + WINHTTP_AUTO_DETECT_TYPE_DNS_A); + EXPECT_TRUE(autoproxy_options->dwAutoDetectFlags & + WINHTTP_AUTO_DETECT_TYPE_DHCP); + } else { + EXPECT_TRUE(!autoproxy_options->dwAutoDetectFlags); + } + + EXPECT_NE(resolver_handle, nullptr); + EXPECT_EQ(opened_proxy_resolvers_.count(resolver_handle), 1u); + EXPECT_NE(context, 0u); + if (!resolver_handle || !context || !callback_) + return false; + + did_call_get_proxy_for_url_ = true; + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&MockWinHttpAPIWrapper::RunCallback, + base::Unretained(this), resolver_handle, context)); + return get_proxy_for_url_success_; + } + + void set_call_winhttp_get_proxy_result_success( + bool get_proxy_result_success) { + get_proxy_result_success_ = get_proxy_result_success; + } + void SetCallbackStatusAndInfo(DWORD callback_status, DWORD info_error) { + callback_status_ = callback_status; + callback_info_ = std::make_unique<WINHTTP_ASYNC_RESULT>(); + callback_info_->dwError = info_error; + } + void AddToProxyResults(const ProxyServer& proxy_server, + bool bypass = false, + bool skip_port = false) { + EXPECT_LT(proxy_result_.cEntries, kMaxProxyEntryLimit - 1); + + // Assign memory as needed. + if (proxy_result_.cEntries == 0) { + proxy_result_.pEntries = + new WINHTTP_PROXY_RESULT_ENTRY[kMaxProxyEntryLimit]; + std::memset(proxy_result_.pEntries, 0, + kMaxProxyEntryLimit * sizeof(WINHTTP_PROXY_RESULT_ENTRY)); + + // The memory of the strings above will be backed by a vector of strings. + proxy_list_.reserve(kMaxProxyEntryLimit); + } + + if (bypass) { + proxy_result_.pEntries[proxy_result_.cEntries].fBypass = TRUE; + } else if (!proxy_server.is_direct()) { + // Now translate the ProxyServer into a WINHTTP_PROXY_RESULT_ENTRY and + // assign. + proxy_result_.pEntries[proxy_result_.cEntries].fProxy = TRUE; + + switch (proxy_server.scheme()) { + case ProxyServer::Scheme::SCHEME_HTTP: + proxy_result_.pEntries[proxy_result_.cEntries].ProxyScheme = + INTERNET_SCHEME_HTTP; + break; + case ProxyServer::Scheme::SCHEME_HTTPS: + proxy_result_.pEntries[proxy_result_.cEntries].ProxyScheme = + INTERNET_SCHEME_HTTPS; + break; + case ProxyServer::Scheme::SCHEME_SOCKS4: + proxy_result_.pEntries[proxy_result_.cEntries].ProxyScheme = + INTERNET_SCHEME_SOCKS; + break; + default: + ADD_FAILURE() + << "Of the possible proxy schemes returned by WinHttp, Chrome " + "supports HTTP(S) and SOCKS4. The ProxyServer::Scheme that " + "triggered this message is: " + << proxy_server.scheme(); + break; + } + + base::string16 proxy_host(proxy_server.host_port_pair().host().begin(), + proxy_server.host_port_pair().host().end()); + proxy_list_.push_back(proxy_host); + + wchar_t* proxy_host_raw = const_cast<wchar_t*>(proxy_list_.back().data()); + proxy_result_.pEntries[proxy_result_.cEntries].pwszProxy = proxy_host_raw; + + if (skip_port) + proxy_result_.pEntries[proxy_result_.cEntries].ProxyPort = + INTERNET_DEFAULT_PORT; + else + proxy_result_.pEntries[proxy_result_.cEntries].ProxyPort = + proxy_server.host_port_pair().port(); + } + + proxy_result_.cEntries++; + } + bool CallWinHttpGetProxyResult(HINTERNET resolver_handle, + WINHTTP_PROXY_RESULT* proxy_result) override { + EXPECT_TRUE(did_call_get_proxy_for_url_); + EXPECT_NE(resolver_handle, nullptr); + EXPECT_EQ(opened_proxy_resolvers_.count(resolver_handle), 1u); + if (!get_proxy_result_success_) + return false; + + EXPECT_NE(proxy_result, nullptr); + proxy_result->cEntries = proxy_result_.cEntries; + proxy_result->pEntries = proxy_result_.pEntries; + + did_call_get_proxy_result_ = true; + return get_proxy_result_success_; + } + + void CallWinHttpFreeProxyResult(WINHTTP_PROXY_RESULT* proxy_result) override { + EXPECT_TRUE(did_call_get_proxy_result_); + EXPECT_NE(proxy_result, nullptr); + did_call_free_proxy_result_ = true; + } + + void CallWinHttpCloseHandle(HINTERNET internet_handle) override { + EXPECT_EQ(opened_proxy_resolvers_.count(internet_handle), 1u); + opened_proxy_resolvers_.erase(internet_handle); + } + + void ResetWinHttpResults() { + if (proxy_result_.pEntries) { + delete[] proxy_result_.pEntries; + proxy_result_.pEntries = nullptr; + proxy_result_ = {0}; + } + proxy_list_.clear(); + } + + private: + void RunCallback(HINTERNET resolver_handle, DWORD_PTR context) { + EXPECT_NE(callback_, nullptr); + EXPECT_NE(resolver_handle, nullptr); + EXPECT_EQ(opened_proxy_resolvers_.count(resolver_handle), 1u); + EXPECT_NE(context, 0u); + callback_(resolver_handle, context, callback_status_, callback_info_.get(), + sizeof(callback_info_.get())); + + // As soon as the callback resolves, WinHttp may choose to delete the memory + // contained by |callback_info_|. This is simulated here. + callback_info_.reset(); + } + + // Data configurable by tests to simulate errors and results from WinHttp. + bool open_success_ = true; + bool set_timeouts_success_ = true; + bool set_status_callback_success_ = true; + bool get_ie_proxy_config_success_ = true; + bool create_proxy_resolver_success_ = true; + bool get_proxy_for_url_success_ = true; + bool get_proxy_result_success_ = true; + DWORD callback_status_ = WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE; + std::unique_ptr<WINHTTP_ASYNC_RESULT> callback_info_; + bool is_autoproxy_enabled_ = false; + base::string16 pac_url_; + base::string16 proxy_; + base::string16 proxy_bypass_; + WINHTTP_PROXY_RESULT proxy_result_ = {0}; + std::vector<base::string16> proxy_list_; + + // Data used internally in the mock to function and validate its own behavior. + bool did_call_open_ = false; + bool did_call_set_timeouts_ = false; + bool did_call_set_status_callback_ = false; + bool did_call_get_ie_proxy_config_ = false; + int proxy_resolver_identifier_ = 1; + std::set<HINTERNET> opened_proxy_resolvers_; + bool did_call_create_proxy_resolver_ = false; + bool did_call_get_proxy_for_url_ = false; + bool did_call_get_proxy_result_ = false; + bool did_call_free_proxy_result_ = false; + WINHTTP_STATUS_CALLBACK callback_ = nullptr; +}; + +} // namespace + +// These tests verify the behavior of the WindowsSystemProxyResolver in +// isolation by mocking out the WinHttpAPIWrapper it uses and the +// WindowsSystemProxyResolutionRequest it normally reports back to. +class WindowsSystemProxyResolverTest : public TestWithTaskEnvironment { + public: + void SetUp() override { + testing::Test::SetUp(); + + winhttp_api_wrapper_ = new MockWinHttpAPIWrapper(); + // In general, the WindowsSystemProxyResolver should be created via + // CreateWindowsSystemProxyResolver(), so the constructor is protected. Thus + // base::MakeRefCounted cannot be used here. + proxy_resolver_ = base::WrapRefCounted( + new WindowsSystemProxyResolver(base::WrapUnique(winhttp_api_wrapper_))); + } + + void TearDown() override { + EXPECT_TRUE(proxy_resolver_->HasOneRef()) << "This test has a memory leak!"; + ResetProxyResolutionService(); + + testing::Test::TearDown(); + } + + MockWinHttpAPIWrapper* winhttp_api_wrapper() { return winhttp_api_wrapper_; } + + scoped_refptr<WindowsSystemProxyResolver> proxy_resolver() { + return proxy_resolver_; + } + + bool InitializeResolver() { return proxy_resolver_->Initialize(); } + + void AddNoPortProxyToResults() { + const ProxyServer proxy_result = + ProxyServer::FromPacString("PROXY foopy:8080"); + winhttp_api_wrapper_->AddToProxyResults(proxy_result, /*bypass=*/false, + /*skip_port=*/true); + } + + void AddDirectProxyToResults(ProxyList* out_proxy_list) { + winhttp_api_wrapper_->AddToProxyResults(ProxyServer::Direct()); + out_proxy_list->AddProxyServer(ProxyServer::Direct()); + } + + void AddBypassedProxyToResults(ProxyList* out_proxy_list) { + winhttp_api_wrapper_->AddToProxyResults(ProxyServer::Direct(), + /*bypass=*/true); + out_proxy_list->AddProxyServer(ProxyServer::Direct()); + } + + void AddHTTPProxyToResults(ProxyList* out_proxy_list) { + const ProxyServer proxy_result = + ProxyServer::FromPacString("PROXY foopy:8080"); + winhttp_api_wrapper_->AddToProxyResults(proxy_result); + out_proxy_list->AddProxyServer(proxy_result); + } + + void AddHTTPSProxyToResults(ProxyList* out_proxy_list) { + const ProxyServer proxy_result = + ProxyServer::FromPacString("HTTPS foopy:8443"); + winhttp_api_wrapper_->AddToProxyResults(proxy_result); + out_proxy_list->AddProxyServer(proxy_result); + } + + void AddSOCKSProxyToResults(ProxyList* out_proxy_list) { + const ProxyServer proxy_result = + ProxyServer::FromPacString("SOCKS4 foopy:8080"); + winhttp_api_wrapper_->AddToProxyResults(proxy_result); + out_proxy_list->AddProxyServer(proxy_result); + } + + void AddIDNProxyToResults(ProxyList* out_proxy_list) { + const ProxyServer proxy_result = + ProxyServer::FromPacString("HTTPS föopy:8080"); + winhttp_api_wrapper_->AddToProxyResults(proxy_result); + + const ProxyServer expected_proxy_result = + ProxyServer::FromPacString("HTTPS xn--fopy-5jr83a:8080"); + out_proxy_list->AddProxyServer(expected_proxy_result); + } + + void PerformGetProxyForUrlAndValidateResult(const ProxyList& proxy_list, + int net_error, + int windows_error) { + ASSERT_TRUE(InitializeResolver()); + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + ASSERT_TRUE( + proxy_resolver()->GetProxyForUrl(&proxy_resolution_request, kUrl)); + ASSERT_TRUE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); + + proxy_resolution_request.WaitForProxyResolutionComplete(); + + EXPECT_TRUE(proxy_list.Equals(proxy_resolution_request.proxy_list())); + EXPECT_EQ(proxy_resolution_request.net_error(), net_error); + EXPECT_EQ(proxy_resolution_request.windows_error(), windows_error); + } + + void DoFailedGetProxyForUrlTest(int net_error, int windows_error) { + PerformGetProxyForUrlAndValidateResult(ProxyList(), net_error, + windows_error); + } + + void DoProxyConfigTest(const ProxyConfig& proxy_config) { + ProxyList proxy_list; + AddHTTPSProxyToResults(&proxy_list); + + base::string16 pac_url; + if (proxy_config.has_pac_url()) + pac_url.assign(proxy_config.pac_url().spec().begin(), + proxy_config.pac_url().spec().end()); + + base::string16 proxy; + if (!proxy_config.proxy_rules().single_proxies.IsEmpty()) + proxy.assign( + proxy_config.proxy_rules().single_proxies.ToPacString().begin(), + proxy_config.proxy_rules().single_proxies.ToPacString().end()); + + base::string16 proxy_bypass; + if (!proxy_config.proxy_rules().bypass_rules.ToString().empty()) + proxy_bypass.assign( + proxy_config.proxy_rules().bypass_rules.ToString().begin(), + proxy_config.proxy_rules().bypass_rules.ToString().end()); + + winhttp_api_wrapper_->set_ie_proxy_config(proxy_config.auto_detect(), + pac_url, proxy, proxy_bypass); + + PerformGetProxyForUrlAndValidateResult(proxy_list, OK, 0); + } + + void DoGetProxyForUrlTest(const ProxyList& proxy_list) { + PerformGetProxyForUrlAndValidateResult(proxy_list, OK, 0); + } + + void ResetProxyResolutionService() { + winhttp_api_wrapper_ = nullptr; + proxy_resolver_.reset(); + } + + private: + MockWinHttpAPIWrapper* winhttp_api_wrapper_ = nullptr; + scoped_refptr<WindowsSystemProxyResolver> proxy_resolver_; +}; + +TEST_F(WindowsSystemProxyResolverTest, InitializeFailOnOpen) { + winhttp_api_wrapper()->set_call_winhttp_open_success(false); + EXPECT_FALSE(InitializeResolver()); +} + +TEST_F(WindowsSystemProxyResolverTest, InitializeFailOnSetTimeouts) { + winhttp_api_wrapper()->set_call_winhttp_set_timeouts_success(false); + EXPECT_FALSE(InitializeResolver()); +} + +TEST_F(WindowsSystemProxyResolverTest, InitializeFailOnSetStatusCallback) { + winhttp_api_wrapper()->set_call_winhttp_set_status_callback_success(false); + EXPECT_FALSE(InitializeResolver()); +} + +TEST_F(WindowsSystemProxyResolverTest, InitializeSucceedsIfWinHttpAPIsWork) { + EXPECT_TRUE(InitializeResolver()); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlFailOnGetIEProxySettings) { + winhttp_api_wrapper()->set_call_winhttp_get_ie_proxy_config_success(false); + ASSERT_TRUE(InitializeResolver()); + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + EXPECT_FALSE( + proxy_resolver()->GetProxyForUrl(&proxy_resolution_request, kUrl)); + EXPECT_FALSE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); +} + +TEST_F(WindowsSystemProxyResolverTest, + GetProxyForUrlFailOnCreateProxyResolver) { + winhttp_api_wrapper()->set_call_winhttp_create_proxy_resolver_success(false); + ASSERT_TRUE(InitializeResolver()); + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + EXPECT_FALSE( + proxy_resolver()->GetProxyForUrl(&proxy_resolution_request, kUrl)); + EXPECT_FALSE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); +} + +TEST_F(WindowsSystemProxyResolverTest, + GetProxyForUrlFailOnWinHttpGetProxyForUrlEx) { + winhttp_api_wrapper()->set_call_winhttp_get_proxy_for_url_success(false); + ASSERT_TRUE(InitializeResolver()); + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + EXPECT_FALSE( + proxy_resolver()->GetProxyForUrl(&proxy_resolution_request, kUrl)); + EXPECT_FALSE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlFailOnFailedCallback) { + winhttp_api_wrapper()->SetCallbackStatusAndInfo( + WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, API_RECEIVE_RESPONSE); + DoFailedGetProxyForUrlTest(ERR_FAILED, API_RECEIVE_RESPONSE); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlFailOnGetProxyResult) { + winhttp_api_wrapper()->set_call_winhttp_get_proxy_result_success(false); + DoFailedGetProxyForUrlTest(ERR_FAILED, 0); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlFailOnDefaultPort) { + AddNoPortProxyToResults(); + DoFailedGetProxyForUrlTest(ERR_FAILED, 0); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlFailOnNoResults) { + DoFailedGetProxyForUrlTest(ERR_FAILED, 0); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlCancellation) { + ASSERT_TRUE(InitializeResolver()); + + // This extra scope is needed so that the MockProxyResolutionRequest destructs + // before the end of the test. This should help catch any use-after-free issue + // in the code. + { + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + ASSERT_TRUE( + proxy_resolver()->GetProxyForUrl(&proxy_resolution_request, kUrl)); + ASSERT_TRUE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); + + proxy_resolver()->RemovePendingCallbackTarget(&proxy_resolution_request); + EXPECT_FALSE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); + } + + // There must never be a callback and the resolver must not be leaked. + base::RunLoop().RunUntilIdle(); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlCancelAndRestart) { + ProxyList expected_proxy_list; + AddHTTPSProxyToResults(&expected_proxy_list); + + ASSERT_TRUE(InitializeResolver()); + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + ASSERT_TRUE( + proxy_resolver()->GetProxyForUrl(&proxy_resolution_request, kUrl)); + ASSERT_TRUE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); + + // Abandon the proxy resolution for this request. + proxy_resolver()->RemovePendingCallbackTarget(&proxy_resolution_request); + EXPECT_FALSE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); + + // Start a new proxy resolution for the request. + ASSERT_TRUE( + proxy_resolver()->GetProxyForUrl(&proxy_resolution_request, kUrl)); + ASSERT_TRUE( + proxy_resolver()->HasPendingCallbackTarget(&proxy_resolution_request)); + + // The received callback must be for the second GetProxyForUrl(). + proxy_resolution_request.WaitForProxyResolutionComplete(); + EXPECT_TRUE( + expected_proxy_list.Equals(proxy_resolution_request.proxy_list())); + EXPECT_EQ(proxy_resolution_request.net_error(), OK); + EXPECT_EQ(proxy_resolution_request.windows_error(), 0); + + // There must never be a callback for the first request and the resolver must + // not be leaked. + base::RunLoop().RunUntilIdle(); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlConfigDirect) { + DoProxyConfigTest(ProxyConfig::CreateDirect()); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlConfigAutoDetect) { + DoProxyConfigTest(ProxyConfig::CreateAutoDetect()); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlConfigPacUrl) { + const GURL pac_url("http://pac-site.test/path/to/pac-url.pac"); + DoProxyConfigTest(ProxyConfig::CreateFromCustomPacURL(pac_url)); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlConfigSingleProxy) { + ProxyConfig config; + const ProxyServer proxy_server = + ProxyServer::FromPacString("HTTPS ignored:33"); + config.proxy_rules().single_proxies.AddProxyServer(proxy_server); + DoProxyConfigTest(config); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlConfigBypass) { + ProxyConfig config; + config.proxy_rules().bypass_rules.AddRuleFromString("example.test"); + DoProxyConfigTest(config); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlConfigMultipleSettings) { + ProxyConfig config; + config.set_auto_detect(true); + + const GURL pac_url("http://pac-site.test/path/to/pac-url.pac"); + config.set_pac_url(pac_url); + + const ProxyServer proxy_server = + ProxyServer::FromPacString("HTTPS ignored:33"); + config.proxy_rules().single_proxies.AddProxyServer(proxy_server); + + DoProxyConfigTest(config); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlDirect) { + ProxyList expected_proxy_list; + AddDirectProxyToResults(&expected_proxy_list); + DoGetProxyForUrlTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlBypass) { + ProxyList expected_proxy_list; + AddBypassedProxyToResults(&expected_proxy_list); + DoGetProxyForUrlTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlHTTP) { + ProxyList expected_proxy_list; + AddHTTPProxyToResults(&expected_proxy_list); + DoGetProxyForUrlTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlHTTPS) { + ProxyList expected_proxy_list; + AddHTTPSProxyToResults(&expected_proxy_list); + DoGetProxyForUrlTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlSOCKS) { + ProxyList expected_proxy_list; + AddSOCKSProxyToResults(&expected_proxy_list); + DoGetProxyForUrlTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlIDNProxy) { + ProxyList expected_proxy_list; + AddIDNProxyToResults(&expected_proxy_list); + DoGetProxyForUrlTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolverTest, GetProxyForUrlMultipleResults) { + ProxyList expected_proxy_list; + AddHTTPSProxyToResults(&expected_proxy_list); + AddDirectProxyToResults(&expected_proxy_list); + DoGetProxyForUrlTest(expected_proxy_list); +} + +TEST_F(WindowsSystemProxyResolverTest, MultipleCallsToGetProxyForUrl) { + ProxyList expected_proxy_list; + AddHTTPSProxyToResults(&expected_proxy_list); + AddDirectProxyToResults(&expected_proxy_list); + ASSERT_TRUE(InitializeResolver()); + + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest first_proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + ASSERT_TRUE( + proxy_resolver()->GetProxyForUrl(&first_proxy_resolution_request, kUrl)); + ASSERT_TRUE(proxy_resolver()->HasPendingCallbackTarget( + &first_proxy_resolution_request)); + + MockProxyResolutionRequest second_proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + ASSERT_TRUE( + proxy_resolver()->GetProxyForUrl(&second_proxy_resolution_request, kUrl)); + ASSERT_TRUE(proxy_resolver()->HasPendingCallbackTarget( + &second_proxy_resolution_request)); + + first_proxy_resolution_request.WaitForProxyResolutionComplete(); + second_proxy_resolution_request.WaitForProxyResolutionComplete(); + + EXPECT_TRUE( + expected_proxy_list.Equals(first_proxy_resolution_request.proxy_list())); + EXPECT_EQ(first_proxy_resolution_request.net_error(), OK); + EXPECT_EQ(first_proxy_resolution_request.windows_error(), 0); + + EXPECT_TRUE( + expected_proxy_list.Equals(second_proxy_resolution_request.proxy_list())); + EXPECT_EQ(second_proxy_resolution_request.net_error(), OK); + EXPECT_EQ(second_proxy_resolution_request.windows_error(), 0); +} + +TEST_F(WindowsSystemProxyResolverTest, + MultipleCallsToGetProxyForUrlWithOneCancellation) { + ProxyList expected_proxy_list; + AddHTTPSProxyToResults(&expected_proxy_list); + AddDirectProxyToResults(&expected_proxy_list); + ASSERT_TRUE(InitializeResolver()); + + // This extra scope is needed so that the MockProxyResolutionRequests destruct + // before the end of the test. This should help catch any use-after-free issue + // in the code. + { + TestCompletionCallback unused_callback; + NetLogWithSource unused_log; + MockProxyResolutionRequest first_proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + ASSERT_TRUE(proxy_resolver()->GetProxyForUrl( + &first_proxy_resolution_request, kUrl)); + ASSERT_TRUE(proxy_resolver()->HasPendingCallbackTarget( + &first_proxy_resolution_request)); + + MockProxyResolutionRequest second_proxy_resolution_request( + unused_callback.callback(), unused_log, proxy_resolver()); + ASSERT_TRUE(proxy_resolver()->GetProxyForUrl( + &second_proxy_resolution_request, kUrl)); + ASSERT_TRUE(proxy_resolver()->HasPendingCallbackTarget( + &second_proxy_resolution_request)); + + proxy_resolver()->RemovePendingCallbackTarget( + &first_proxy_resolution_request); + EXPECT_FALSE(proxy_resolver()->HasPendingCallbackTarget( + &first_proxy_resolution_request)); + second_proxy_resolution_request.WaitForProxyResolutionComplete(); + + EXPECT_TRUE(expected_proxy_list.Equals( + second_proxy_resolution_request.proxy_list())); + EXPECT_EQ(second_proxy_resolution_request.net_error(), OK); + EXPECT_EQ(second_proxy_resolution_request.windows_error(), 0); + } + + // There must never be a callback for the first request and the resolver must + // not be leaked. + base::RunLoop().RunUntilIdle(); +} + +} // namespace net
diff --git a/net/proxy_resolution/win/winhttp_api_wrapper.cc b/net/proxy_resolution/win/winhttp_api_wrapper.cc new file mode 100644 index 0000000..7f40c5a --- /dev/null +++ b/net/proxy_resolution/win/winhttp_api_wrapper.cc
@@ -0,0 +1,113 @@ +// Copyright 2020 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 "net/proxy_resolution/win/winhttp_api_wrapper.h" + +#include <utility> + +#include "base/check_op.h" +#include "base/macros.h" +#include "base/strings/string16.h" + +namespace net { + +// TODO(https://crbug.com/1032820): Capture telemetry for WinHttp APIs if +// interesting. + +ScopedIEConfig::ScopedIEConfig() = default; +ScopedIEConfig::~ScopedIEConfig() { + if (ie_config.lpszAutoConfigUrl) + GlobalFree(ie_config.lpszAutoConfigUrl); + if (ie_config.lpszProxy) + GlobalFree(ie_config.lpszProxy); + if (ie_config.lpszProxyBypass) + GlobalFree(ie_config.lpszProxyBypass); +} + +WinHttpAPIWrapper::WinHttpAPIWrapper() = default; +WinHttpAPIWrapper::~WinHttpAPIWrapper() { + if (session_handle_) + ignore_result(CallWinHttpSetStatusCallback(nullptr)); + CloseSessionHandle(); +} + +bool WinHttpAPIWrapper::CallWinHttpOpen() { + DCHECK_EQ(nullptr, session_handle_); + session_handle_ = + WinHttpOpen(nullptr, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, + WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); + return (session_handle_ != nullptr); +} + +bool WinHttpAPIWrapper::CallWinHttpSetTimeouts(int resolve_timeout, + int connect_timeout, + int send_timeout, + int receive_timeout) { + DCHECK_NE(nullptr, session_handle_); + return (!!WinHttpSetTimeouts(session_handle_, resolve_timeout, + connect_timeout, send_timeout, receive_timeout)); +} + +bool WinHttpAPIWrapper::CallWinHttpSetStatusCallback( + WINHTTP_STATUS_CALLBACK internet_callback) { + DCHECK_NE(nullptr, session_handle_); + const WINHTTP_STATUS_CALLBACK winhttp_status_callback = + WinHttpSetStatusCallback( + session_handle_, internet_callback, + WINHTTP_CALLBACK_FLAG_REQUEST_ERROR | + WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE, + 0); + return (winhttp_status_callback != WINHTTP_INVALID_STATUS_CALLBACK); +} + +bool WinHttpAPIWrapper::CallWinHttpGetIEProxyConfigForCurrentUser( + WINHTTP_CURRENT_USER_IE_PROXY_CONFIG* ie_proxy_config) { + return !!WinHttpGetIEProxyConfigForCurrentUser(ie_proxy_config); +} + +bool WinHttpAPIWrapper::CallWinHttpCreateProxyResolver( + HINTERNET* out_resolver_handle) { + DCHECK_NE(nullptr, session_handle_); + const DWORD result = + WinHttpCreateProxyResolver(session_handle_, out_resolver_handle); + return (result == ERROR_SUCCESS); +} + +bool WinHttpAPIWrapper::CallWinHttpGetProxyForUrlEx( + HINTERNET resolver_handle, + const std::string& url, + WINHTTP_AUTOPROXY_OPTIONS* autoproxy_options, + DWORD_PTR context) { + const base::string16 wide_url(url.begin(), url.end()); + // TODO(https://crbug.com/1032820): Upgrade to WinHttpGetProxyForUrlEx2() + // if there is a clear reason to do so. + const DWORD result = WinHttpGetProxyForUrlEx(resolver_handle, wide_url.data(), + autoproxy_options, context); + return (result == ERROR_IO_PENDING); +} + +bool WinHttpAPIWrapper::CallWinHttpGetProxyResult( + HINTERNET resolver_handle, + WINHTTP_PROXY_RESULT* proxy_result) { + const DWORD result = WinHttpGetProxyResult(resolver_handle, proxy_result); + return (result == ERROR_SUCCESS); +} + +VOID WinHttpAPIWrapper::CallWinHttpFreeProxyResult( + WINHTTP_PROXY_RESULT* proxy_result) { + WinHttpFreeProxyResult(proxy_result); +} + +void WinHttpAPIWrapper::CallWinHttpCloseHandle(HINTERNET internet_handle) { + WinHttpCloseHandle(internet_handle); +} + +void WinHttpAPIWrapper::CloseSessionHandle() { + if (session_handle_) { + CallWinHttpCloseHandle(session_handle_); + session_handle_ = nullptr; + } +} + +} // namespace net
diff --git a/net/proxy_resolution/win/winhttp_api_wrapper.h b/net/proxy_resolution/win/winhttp_api_wrapper.h new file mode 100644 index 0000000..dad3e9b --- /dev/null +++ b/net/proxy_resolution/win/winhttp_api_wrapper.h
@@ -0,0 +1,129 @@ +// Copyright 2020 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 NET_PROXY_RESOLUTION_WIN_WINHTTP_API_WRAPPER_H_ +#define NET_PROXY_RESOLUTION_WIN_WINHTTP_API_WRAPPER_H_ + +#include <windows.h> +#include <winhttp.h> +#include <memory> +#include <string> + +#include "base/compiler_specific.h" +#include "net/base/net_export.h" + +namespace net { + +// This is a utility class that encapsulates the memory management necessary for +// WINHTTP_CURRENT_USER_IE_PROXY_CONFIG in RAII style. +class ScopedIEConfig final { + public: + ScopedIEConfig(); + + ScopedIEConfig(const ScopedIEConfig&) = delete; + ScopedIEConfig& operator=(const ScopedIEConfig&) = delete; + + ~ScopedIEConfig(); + + WINHTTP_CURRENT_USER_IE_PROXY_CONFIG* config() { return &ie_config; } + + private: + WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = {0}; +}; + +// This provides a layer of abstraction between calling code and WinHTTP APIs, +// allowing them to be mocked out for testing. This object is not thread safe +// and it's expected that the caller will handle using it on the same thread or +// sequence. In general, documentation for these APIs can be found here: +// https://docs.microsoft.com/en-us/windows/win32/api/winhttp/ +class NET_EXPORT WinHttpAPIWrapper { + public: + WinHttpAPIWrapper(); + + WinHttpAPIWrapper(const WinHttpAPIWrapper&) = delete; + WinHttpAPIWrapper& operator=(const WinHttpAPIWrapper&) = delete; + + virtual ~WinHttpAPIWrapper(); + + // Creates our WinHttp session handle |session_handle_|. The lifetime of that + // session handle is determined by the lifetime of this object. It'll get + // closed when this object destructs. + virtual bool CallWinHttpOpen() WARN_UNUSED_RESULT; + + // Controls the timeout for WinHttpGetProxyForUrlEx(). + virtual bool CallWinHttpSetTimeouts(int resolve_timeout, + int connect_timeout, + int send_timeout, + int receive_timeout) WARN_UNUSED_RESULT; + + // Sets the callback WinHttp will call into with the result of any + // asynchronous call. + virtual bool CallWinHttpSetStatusCallback( + WINHTTP_STATUS_CALLBACK internet_callback) WARN_UNUSED_RESULT; + + // Fetches the proxy configs for the current active network connection and + // current Windows user. The |ie_proxy_config| says whether or not + // AutoProxy (WPAD) is enabled and if there's a PAC URL configured for this + // connection/user. + virtual bool CallWinHttpGetIEProxyConfigForCurrentUser( + WINHTTP_CURRENT_USER_IE_PROXY_CONFIG* ie_proxy_config) WARN_UNUSED_RESULT; + + // Creates a handle |resolver_handle| that should be used for the call to + // WinHttpGetProxyForUrlEx(). + virtual bool CallWinHttpCreateProxyResolver(HINTERNET* out_resolver_handle) + WARN_UNUSED_RESULT; + + // Using the specific |resolver_handle| handle from + // CallWinHttpCreateProxyResolver(), resolve a proxy for a specific |url| with + // the aid of some |autoproxy_options|. When WinHttpGetProxyForUrlEx() + // finishes its work or hits an error, it'll call into the callback set by + // CallWinHttpSetStatusCallback() above exactly once and supply the provided + // |context|. + // + // WinHttpGetProxyForUrlEx() will go async to do all necessary logic. As long + // as it receives good inputs (valid handle, valid combination of flags, + // non-null PAC URL if needed), this API will almost always return + // ERROR_IO_PENDING. It'll only fail for reasons like running out of memory. + // When it returns ERROR_IO_PENDING, CallWinHttpGetProxyForUrlEx() will return + // true. + // + // WinHttpGetProxyForUrlEx() will do proxy fallback internally and return to + // a proxy result. It will first check WPAD (if enabled). If that fails, it'll + // attempt to download and run any provided PAC script. If the PAC script was + // not provided or if it fails, it'll use the right per-interface static + // proxy. If all else fails or isn't configured, it'll simply return DIRECT. + // WinHttpGetProxyForUrlEx() supports commonly used enterprise proxy features + // such as DirectAccess/NRPT. + virtual bool CallWinHttpGetProxyForUrlEx( + HINTERNET resolver_handle, + const std::string& url, + WINHTTP_AUTOPROXY_OPTIONS* autoproxy_options, + DWORD_PTR context) WARN_UNUSED_RESULT; + + // As long as CallWinHttpGetProxyForUrlEx() doesn't hit any errors, there will + // be a proxy result to examine. This function retrieves that proxy resolution + // result |proxy_result| using the resolver's handle |resolver_handle|. The + // result must be freed with CallWinHttpFreeProxyResult(). + virtual bool CallWinHttpGetProxyResult(HINTERNET resolver_handle, + WINHTTP_PROXY_RESULT* proxy_result) + WARN_UNUSED_RESULT; + + // Frees the |proxy_result| retrieved by CallWinHttpGetProxyResult(). + virtual void CallWinHttpFreeProxyResult(WINHTTP_PROXY_RESULT* proxy_result); + + // Every opened HINTERNET handle must be closed. This closes handle + // |internet_handle|. After being closed, WinHttp calls cannot be made using + // that handle. + virtual void CallWinHttpCloseHandle(HINTERNET internet_handle); + + private: + // Closes |session_handle_|. + void CloseSessionHandle(); + + HINTERNET session_handle_ = nullptr; +}; + +} // namespace net + +#endif // NET_PROXY_RESOLUTION_WIN_WINHTTP_API_WRAPPER_H_
diff --git a/net/quic/platform/impl/quic_default_proof_providers_impl.cc b/net/quic/platform/impl/quic_default_proof_providers_impl.cc index 66817850..abae462 100644 --- a/net/quic/platform/impl/quic_default_proof_providers_impl.cc +++ b/net/quic/platform/impl/quic_default_proof_providers_impl.cc
@@ -93,8 +93,8 @@ std::make_unique<SimpleTicketCrypter>(QuicChromiumClock::GetInstance())); CHECK(proof_source->Initialize( #if defined(OS_WIN) - base::FilePath(base::UTF8ToUTF16(GetQuicFlag(FLAGS_certificate_file))), - base::FilePath(base::UTF8ToUTF16(GetQuicFlag(FLAGS_key_file))), + base::FilePath(base::UTF8ToWide(GetQuicFlag(FLAGS_certificate_file))), + base::FilePath(base::UTF8ToWide(GetQuicFlag(FLAGS_key_file))), base::FilePath())); #else base::FilePath(GetQuicFlag(FLAGS_certificate_file)),
diff --git a/net/quic/platform/impl/quic_flags_impl.cc b/net/quic/platform/impl/quic_flags_impl.cc index ab50b42..f2c1542 100644 --- a/net/quic/platform/impl/quic_flags_impl.cc +++ b/net/quic/platform/impl/quic_flags_impl.cc
@@ -18,6 +18,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" #define QUIC_FLAG(type, flag, value) type flag = value; @@ -34,19 +35,21 @@ return v; } -// Overload for platforms where base::CommandLine::StringType == base::string16. +#if defined(WCHAR_T_IS_UTF16) +// Overload for platforms where base::CommandLine::StringType == std::wstring. std::vector<std::string> __attribute__((unused)) -ToQuicStringVector(const std::vector<base::string16>& v) { +ToQuicStringVector(const std::vector<std::wstring>& v) { std::vector<std::string> qsv; for (const auto& s : v) { if (!base::IsStringASCII(s)) { QUIC_LOG(ERROR) << "Unable to convert to ASCII: " << s; continue; } - qsv.push_back(base::UTF16ToASCII(s)); + qsv.push_back(base::WideToASCII(s)); } return qsv; } +#endif // defined(WCHAR_T_IS_UTF16) size_t FindLineWrapPosition(const std::string& s, size_t desired_len) { if (s.length() <= desired_len) {
diff --git a/net/spdy/spdy_session.cc b/net/spdy/spdy_session.cc index ba4d006..f7b2b6e 100644 --- a/net/spdy/spdy_session.cc +++ b/net/spdy/spdy_session.cc
@@ -429,6 +429,20 @@ return dict; } +base::Value NetLogSpdyGreasedFrameParams(spdy::SpdyStreamId stream_id, + uint8_t type, + uint8_t flags, + size_t length, + RequestPriority priority) { + base::Value dict(base::Value::Type::DICTIONARY); + dict.SetIntKey("stream_id", stream_id); + dict.SetIntKey("type", type); + dict.SetIntKey("flags", flags); + dict.SetIntKey("length", length); + dict.SetStringKey("priority", RequestPriorityToString(priority)); + return dict; +} + // Helper function to return the total size of an array of objects // with .size() member functions. template <typename T, size_t N> @@ -1125,6 +1139,13 @@ if (availability_state_ == STATE_DRAINING) return; + net_log_.AddEvent(NetLogEventType::HTTP2_SESSION_SEND_GREASED_FRAME, [&] { + return NetLogSpdyGreasedFrameParams( + stream->stream_id(), greased_http2_frame_.value().type, + greased_http2_frame_.value().flags, + greased_http2_frame_.value().payload.length(), stream->priority()); + }); + EnqueueWrite( stream->priority(), static_cast<spdy::SpdyFrameType>(greased_http2_frame_.value().type), @@ -1196,7 +1217,9 @@ spdy::SpdyStreamId stream_id, IOBuffer* data, int len, - spdy::SpdyDataFlags flags) { + spdy::SpdyDataFlags flags, + int* effective_len, + bool* end_stream) { if (availability_state_ == STATE_DRAINING) { return std::unique_ptr<SpdyBuffer>(); } @@ -1211,7 +1234,7 @@ return std::unique_ptr<SpdyBuffer>(); } - int effective_len = std::min(len, kMaxSpdyFrameChunkSize); + *effective_len = std::min(len, kMaxSpdyFrameChunkSize); bool send_stalled_by_stream = (stream->send_window_size() <= 0); bool send_stalled_by_session = IsSendStalled(); @@ -1251,7 +1274,7 @@ return std::unique_ptr<SpdyBuffer>(); } - effective_len = std::min(effective_len, stream->send_window_size()); + *effective_len = std::min(*effective_len, stream->send_window_size()); // Obey send window size of the session. if (send_stalled_by_session) { @@ -1263,42 +1286,39 @@ return std::unique_ptr<SpdyBuffer>(); } - effective_len = std::min(effective_len, session_send_window_size_); + *effective_len = std::min(*effective_len, session_send_window_size_); - DCHECK_GE(effective_len, 0); + DCHECK_GE(*effective_len, 0); // Clear FIN flag if only some of the data will be in the data // frame. - if (effective_len < len) + if (*effective_len < len) flags = static_cast<spdy::SpdyDataFlags>(flags & ~spdy::DATA_FLAG_FIN); - net_log_.AddEvent(NetLogEventType::HTTP2_SESSION_SEND_DATA, [&] { - return NetLogSpdyDataParams(stream_id, effective_len, - (flags & spdy::DATA_FLAG_FIN) != 0); - }); // Send PrefacePing for DATA_FRAMEs with nonzero payload size. - if (effective_len > 0) + if (*effective_len > 0) MaybeSendPrefacePing(); // TODO(mbelshe): reduce memory copies here. DCHECK(buffered_spdy_framer_.get()); std::unique_ptr<spdy::SpdySerializedFrame> frame( buffered_spdy_framer_->CreateDataFrame( - stream_id, data->data(), static_cast<uint32_t>(effective_len), + stream_id, data->data(), static_cast<uint32_t>(*effective_len), flags)); auto data_buffer = std::make_unique<SpdyBuffer>(std::move(frame)); // Send window size is based on payload size, so nothing to do if this is // just a FIN with no payload. - if (effective_len != 0) { - DecreaseSendWindowSize(static_cast<int32_t>(effective_len)); + if (*effective_len != 0) { + DecreaseSendWindowSize(static_cast<int32_t>(*effective_len)); data_buffer->AddConsumeCallback(base::BindRepeating( &SpdySession::OnWriteBufferConsumed, weak_factory_.GetWeakPtr(), - static_cast<size_t>(effective_len))); + static_cast<size_t>(*effective_len))); } + *end_stream = (flags & spdy::DATA_FLAG_FIN) == spdy::DATA_FLAG_FIN; return data_buffer; } @@ -2790,6 +2810,13 @@ base::WeakPtr<SpdyStream>(), kSpdySessionCommandsTrafficAnnotation); if (greased_http2_frame_ && frame_type == spdy::SpdyFrameType::SETTINGS) { + net_log_.AddEvent(NetLogEventType::HTTP2_SESSION_SEND_GREASED_FRAME, [&] { + return NetLogSpdyGreasedFrameParams( + /* stream_id = */ 0, greased_http2_frame_.value().type, + greased_http2_frame_.value().flags, + greased_http2_frame_.value().payload.length(), priority); + }); + EnqueueWrite( priority, static_cast<spdy::SpdyFrameType>(greased_http2_frame_.value().type),
diff --git a/net/spdy/spdy_session.h b/net/spdy/spdy_session.h index 201a504e..7946b7b 100644 --- a/net/spdy/spdy_session.h +++ b/net/spdy/spdy_session.h
@@ -456,12 +456,16 @@ spdy::SpdyHeaderBlock headers, NetLogSource source_dependency); - // Creates and returns a SpdyBuffer holding a data frame with the - // given data. May return NULL if stalled by flow control. + // Creates and returns a SpdyBuffer holding a data frame with the given data. + // Sets |*effective_len| to number of bytes sent, and |*end_stream| to the + // value of the END_STREAM (also known as fin) flag. Returns nullptr if + // session is draining or if session or stream is stalled by flow control. std::unique_ptr<SpdyBuffer> CreateDataBuffer(spdy::SpdyStreamId stream_id, IOBuffer* data, int len, - spdy::SpdyDataFlags flags); + spdy::SpdyDataFlags flags, + int* effective_len, + bool* end_stream); // Send PRIORITY frames according to the new priority of an existing stream. void UpdateStreamPriority(SpdyStream* stream,
diff --git a/net/spdy/spdy_stream.cc b/net/spdy/spdy_stream.cc index 0c28112f..1c23165 100644 --- a/net/spdy/spdy_stream.cc +++ b/net/spdy/spdy_stream.cc
@@ -53,6 +53,16 @@ return dict; } +base::Value NetLogSpdyDataParams(spdy::SpdyStreamId stream_id, + int size, + bool fin) { + base::Value dict(base::Value::Type::DICTIONARY); + dict.SetIntKey("stream_id", static_cast<int>(stream_id)); + dict.SetIntKey("size", size); + dict.SetBoolKey("fin", fin); + return dict; +} + } // namespace // A wrapper around a stream that calls into ProduceHeadersFrame(). @@ -850,9 +860,12 @@ spdy::SpdyDataFlags flags = (pending_send_status_ == NO_MORE_DATA_TO_SEND) ? spdy::DATA_FLAG_FIN : spdy::DATA_FLAG_NONE; + int effective_len; + bool end_stream; std::unique_ptr<SpdyBuffer> data_buffer( session_->CreateDataBuffer(stream_id_, pending_send_data_.get(), - pending_send_data_->BytesRemaining(), flags)); + pending_send_data_->BytesRemaining(), flags, + &effective_len, &end_stream)); // We'll get called again by PossiblyResumeIfSendStalled(). if (!data_buffer) return; @@ -878,6 +891,10 @@ session_->EnqueueGreasedFrame(GetWeakPtr()); } + net_log_.AddEvent(NetLogEventType::HTTP2_SESSION_SEND_DATA, [&] { + return NetLogSpdyDataParams(stream_id_, effective_len, end_stream); + }); + session_->EnqueueStreamWrite( GetWeakPtr(), spdy::SpdyFrameType::DATA, std::make_unique<SimpleBufferProducer>(std::move(data_buffer)));
diff --git a/net/test/embedded_test_server/request_handler_util.cc b/net/test/embedded_test_server/request_handler_util.cc index 2e20ab5..f779b33 100644 --- a/net/test/embedded_test_server/request_handler_util.cc +++ b/net/test/embedded_test_server/request_handler_util.cc
@@ -11,6 +11,7 @@ #include <utility> #include "base/base64.h" +#include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/format_macros.h" #include "base/strings/string_util.h" @@ -27,7 +28,8 @@ namespace net { namespace test_server { -const char kMockHttpHeadersExtension[] = "mock-http-headers"; +constexpr base::FilePath::CharType kMockHttpHeadersExtension[] = + FILE_PATH_LITERAL("mock-http-headers"); std::string GetContentType(const base::FilePath& path) { if (path.MatchesExtension(FILE_PATH_LITERAL(".crx"))) @@ -209,15 +211,8 @@ if (!UpdateReplacedText(query, &file_contents)) return failed_response; - base::FilePath::StringPieceType mock_headers_extension; -#if defined(OS_WIN) - base::string16 temp = base::ASCIIToUTF16(kMockHttpHeadersExtension); - mock_headers_extension = temp; -#else - mock_headers_extension = kMockHttpHeadersExtension; -#endif - - base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); + base::FilePath headers_path( + file_path.AddExtension(kMockHttpHeadersExtension)); if (base::PathExists(headers_path)) { std::string headers_contents;
diff --git a/net/test/embedded_test_server/request_handler_util.h b/net/test/embedded_test_server/request_handler_util.h index 8e8370f..f81ac3b 100644 --- a/net/test/embedded_test_server/request_handler_util.h +++ b/net/test/embedded_test_server/request_handler_util.h
@@ -30,7 +30,7 @@ // foo.html.mock-http-headers // When the test server serves foo.html, if it finds foo.html.mock-http-headers // it will use the contents of that file for the headers. -extern const char kMockHttpHeadersExtension[]; +extern const base::FilePath::CharType kMockHttpHeadersExtension[]; // Returns the Content-Type header value for a path based on its extension. std::string GetContentType(const base::FilePath& path);
diff --git a/net/test/spawned_test_server/base_test_server.cc b/net/test/spawned_test_server/base_test_server.cc index 8330ccda5..9bda291 100644 --- a/net/test/spawned_test_server/base_test_server.cc +++ b/net/test/spawned_test_server/base_test_server.cc
@@ -15,6 +15,7 @@ #include "base/json/json_reader.h" #include "base/logging.h" #include "base/path_service.h" +#include "base/strings/string_util.h" #include "base/values.h" #include "net/base/address_list.h" #include "net/base/host_port_pair.h" @@ -419,7 +420,8 @@ arguments->SetString("host", host_port_pair_.host()); arguments->SetInteger("port", host_port_pair_.port()); - arguments->SetString("data-dir", document_root_.value()); + arguments->SetStringKey("data-dir", + base::AsCrossPlatformPiece(document_root_.value())); if (VLOG_IS_ON(1) || log_to_console_) arguments->Set("log-to-console", std::make_unique<base::Value>()); @@ -452,7 +454,9 @@ << " doesn't exist. Can't launch https server."; return false; } - arguments->SetString("cert-and-key-file", certificate_path.value()); + arguments->SetStringKey( + "cert-and-key-file", + base::AsCrossPlatformPiece(certificate_path.value())); } // Check the client certificate related arguments. @@ -468,7 +472,7 @@ << " doesn't exist. Can't launch https server."; return false; } - ssl_client_certs->AppendString(it->value()); + ssl_client_certs->Append(base::AsCrossPlatformPiece(it->value())); } if (ssl_client_certs->GetSize())
diff --git a/sandbox/win/src/sandbox_policy_diagnostic.cc b/sandbox/win/src/sandbox_policy_diagnostic.cc index d0c6c67..ddaccf7 100644 --- a/sandbox/win/src/sandbox_policy_diagnostic.cc +++ b/sandbox/win/src/sandbox_policy_diagnostic.cc
@@ -15,7 +15,9 @@ #include "base/check.h" #include "base/json/json_string_value_serializer.h" #include "base/numerics/safe_conversions.h" +#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/policy_engine_opcodes.h" @@ -98,8 +100,8 @@ } } -base::string16 GetSidAsString(const Sid* sid) { - base::string16 result; +std::wstring GetSidAsString(const Sid* sid) { + std::wstring result; if (!sid->ToSddlString(&result)) DCHECK(false) << "Failed to make sddl string"; return result; @@ -432,11 +434,14 @@ base::Value(GetPlatformMitigationsAsHex(desired_mitigations_))); if (app_container_sid_) - value.SetKey(kAppContainerSid, - base::Value(GetSidAsString(app_container_sid_.get()))); + value.SetStringKey( + kAppContainerSid, + base::AsStringPiece16(GetSidAsString(app_container_sid_.get()))); - if (lowbox_sid_) - value.SetKey(kLowboxSid, base::Value(GetSidAsString(lowbox_sid_.get()))); + if (lowbox_sid_) { + value.SetStringKey( + kLowboxSid, base::AsStringPiece16(GetSidAsString(lowbox_sid_.get()))); + } if (policy_rules_) value.SetKey(kPolicyRules, GetPolicyRules(policy_rules_.get()));
diff --git a/skia/BUILD.gn b/skia/BUILD.gn index 9aa49e5..e8f6caad 100644 --- a/skia/BUILD.gn +++ b/skia/BUILD.gn
@@ -311,6 +311,15 @@ ] } + # The *_public variables should be added to 'public' not 'sources'. + # However, Skia does not export enough *_public variables to make Chromium + # 'gn check' clean. Until that can be done add the *_public variables to + # 'sources' so that the buildbot 'analyze' step is aware of their existence. + sources += skia_core_public + sources += skia_utils_public + sources += skia_effects_public + sources += skia_effects_imagefilter_public + # The imported Skia gni source paths are made absolute by gn. defines = skia_core_defines sources += skia_sksl_sources
diff --git a/skia/public/mojom/BUILD.gn b/skia/public/mojom/BUILD.gn index 37be67e..31cc78d 100644 --- a/skia/public/mojom/BUILD.gn +++ b/skia/public/mojom/BUILD.gn
@@ -37,6 +37,64 @@ ] public_deps = [ "//mojo/public/mojom/base" ] + + shared_skia_cpp_typemaps = [ + { + types = [ + { + mojom = "skia.mojom.BlurTileMode" + cpp = "::SkBlurImageFilter::TileMode" + }, + ] + traits_headers = [ "blur_image_filter_tile_mode_mojom_traits.h" ] + traits_public_deps = [ "//skia" ] + }, + { + types = [ + { + mojom = "skia.mojom.Bitmap" + cpp = "::SkBitmap" + nullable_is_same_type = true + }, + { + mojom = "skia.mojom.InlineBitmap" + cpp = "::SkBitmap" + nullable_is_same_type = true + }, + ] + traits_headers = [ "bitmap_skbitmap_mojom_traits.h" ] + traits_public_deps = [ + ":shared_typemap_traits", + "//skia", + ] + }, + { + types = [ + { + mojom = "skia.mojom.SkColor" + cpp = "::SkColor" + }, + ] + traits_headers = [ "skcolor_mojom_traits.h" ] + traits_public_deps = [ "//skia" ] + }, + { + types = [ + { + mojom = "skia.mojom.ImageInfo" + cpp = "::SkImageInfo" + }, + ] + traits_headers = [ "image_info_mojom_traits.h" ] + traits_public_deps = [ + ":shared_typemap_traits", + "//skia", + ] + }, + ] + + cpp_typemaps = shared_skia_cpp_typemaps + blink_cpp_typemaps = shared_skia_cpp_typemaps } mojom("test_interfaces") {
diff --git a/skia/public/mojom/OWNERS b/skia/public/mojom/OWNERS index 7ed4e44..a534d61 100644 --- a/skia/public/mojom/OWNERS +++ b/skia/public/mojom/OWNERS
@@ -3,6 +3,3 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS - -per-file *.typemap=set noparent -per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/skia/public/mojom/blur_image_filter_tile_mode.typemap b/skia/public/mojom/blur_image_filter_tile_mode.typemap deleted file mode 100644 index 7ac7c79..0000000 --- a/skia/public/mojom/blur_image_filter_tile_mode.typemap +++ /dev/null
@@ -1,9 +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. - -mojom = "//skia/public/mojom/blur_image_filter_tile_mode.mojom" -public_headers = [ "//third_party/skia/include/effects/SkBlurImageFilter.h" ] -traits_headers = - [ "//skia/public/mojom/blur_image_filter_tile_mode_mojom_traits.h" ] -type_mappings = [ "skia.mojom.BlurTileMode=::SkBlurImageFilter::TileMode" ]
diff --git a/skia/public/mojom/skbitmap.typemap b/skia/public/mojom/skbitmap.typemap deleted file mode 100644 index 56b7e94..0000000 --- a/skia/public/mojom/skbitmap.typemap +++ /dev/null
@@ -1,18 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -mojom = "//skia/public/mojom/bitmap.mojom" -public_headers = [ "//third_party/skia/include/core/SkBitmap.h" ] -traits_headers = [ "//skia/public/mojom/bitmap_skbitmap_mojom_traits.h" ] -deps = [ - "//mojo/public/cpp/bindings", -] -public_deps = [ - "//skia", - "//skia/public/mojom:shared_typemap_traits", -] -type_mappings = [ - "skia.mojom.Bitmap=::SkBitmap[nullable_is_same_type]", - "skia.mojom.InlineBitmap=::SkBitmap[nullable_is_same_type]", -]
diff --git a/skia/public/mojom/skcolor.typemap b/skia/public/mojom/skcolor.typemap deleted file mode 100644 index 8528029..0000000 --- a/skia/public/mojom/skcolor.typemap +++ /dev/null
@@ -1,11 +0,0 @@ -# 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. - -mojom = "//skia/public/mojom/skcolor.mojom" -public_headers = [ "//third_party/skia/include/core/SkColor.h" ] -traits_headers = [ "//skia/public/mojom/skcolor_mojom_traits.h" ] -sources = [ - "//skia/public/mojom/skcolor_mojom_traits.h", -] -type_mappings = [ "skia.mojom.SkColor=::SkColor" ]
diff --git a/skia/public/mojom/skimageinfo.typemap b/skia/public/mojom/skimageinfo.typemap deleted file mode 100644 index a821d95..0000000 --- a/skia/public/mojom/skimageinfo.typemap +++ /dev/null
@@ -1,15 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -mojom = "//skia/public/mojom/image_info.mojom" -public_headers = [ "//third_party/skia/include/core/SkImageInfo.h" ] -traits_headers = [ "//skia/public/mojom/image_info_mojom_traits.h" ] -deps = [ - "//mojo/public/cpp/bindings", -] -public_deps = [ - "//skia", - "//skia/public/mojom:shared_typemap_traits", -] -type_mappings = [ "skia.mojom.ImageInfo=::SkImageInfo" ]
diff --git a/skia/public/mojom/typemaps.gni b/skia/public/mojom/typemaps.gni deleted file mode 100644 index ca48cec5..0000000 --- a/skia/public/mojom/typemaps.gni +++ /dev/null
@@ -1,10 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -typemaps = [ - "//skia/public/mojom/blur_image_filter_tile_mode.typemap", - "//skia/public/mojom/skbitmap.typemap", - "//skia/public/mojom/skcolor.typemap", - "//skia/public/mojom/skimageinfo.typemap", -]
diff --git a/sql/database.cc b/sql/database.cc index 64c7e9ce..05831c9 100644 --- a/sql/database.cc +++ b/sql/database.cc
@@ -148,7 +148,7 @@ std::string AsUTF8ForSQL(const base::FilePath& path) { #if defined(OS_WIN) - return base::UTF16ToUTF8(path.value()); + return base::WideToUTF8(path.value()); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) return path.value(); #endif @@ -459,7 +459,7 @@ const char* path = sqlite3_db_filename(db_, "main"); const base::StringPiece db_path(path); #if defined(OS_WIN) - return base::FilePath(base::UTF8ToUTF16(db_path)); + return base::FilePath(base::UTF8ToWide(db_path)); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) return base::FilePath(db_path); #else @@ -1117,7 +1117,7 @@ Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?")); #if OS_WIN - s.BindString16(0, other_db_path.value()); + s.BindString16(0, base::AsStringPiece16(other_db_path.value())); #elif defined(OS_POSIX) || defined(OS_FUCHSIA) s.BindString(0, other_db_path.value()); #else
diff --git a/sql/statement.cc b/sql/statement.cc index b49e47b..aba466d 100644 --- a/sql/statement.cc +++ b/sql/statement.cc
@@ -9,6 +9,7 @@ #include "base/logging.h" #include "base/numerics/safe_conversions.h" +#include "base/strings/string_piece_forward.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "third_party/sqlite/sqlite3.h" @@ -145,7 +146,7 @@ SQLITE_TRANSIENT)); } -bool Statement::BindString16(int col, const base::string16& value) { +bool Statement::BindString16(int col, base::StringPiece16 value) { return BindString(col, base::UTF16ToUTF8(value)); }
diff --git a/sql/statement.h b/sql/statement.h index 6983e21..ba31163 100644 --- a/sql/statement.h +++ b/sql/statement.h
@@ -14,6 +14,7 @@ #include "base/memory/ref_counted.h" #include "base/sequence_checker.h" #include "base/strings/string16.h" +#include "base/strings/string_piece_forward.h" #include "sql/database.h" namespace sql { @@ -111,7 +112,7 @@ bool BindDouble(int col, double val); bool BindCString(int col, const char* val); bool BindString(int col, const std::string& val); - bool BindString16(int col, const base::string16& value); + bool BindString16(int col, base::StringPiece16 value); bool BindBlob(int col, const void* value, int value_len); // Retrieving ----------------------------------------------------------------
diff --git a/testing/buildbot/chromium.ci.json b/testing/buildbot/chromium.ci.json index 6c4797f3..f9e6fb4 100644 --- a/testing/buildbot/chromium.ci.json +++ b/testing/buildbot/chromium.ci.json
@@ -248142,6 +248142,7 @@ "test_id_prefix": "ninja://third_party/angle/src/tests:angle_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248160,6 +248161,7 @@ "test_id_prefix": "ninja://extensions/shell:app_shell_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248341,6 +248343,7 @@ "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248453,6 +248456,7 @@ "test_id_prefix": "ninja://chrome/test/chromedriver:chromedriver_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248471,6 +248475,7 @@ "test_id_prefix": "ninja://components:components_browsertests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248489,6 +248494,7 @@ "test_id_prefix": "ninja://components:components_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248507,6 +248513,7 @@ "test_id_prefix": "ninja://ui/compositor:compositor_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248529,6 +248536,7 @@ "args": [ "--enable-features=StorageServiceOutOfProcess" ], + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248549,6 +248557,7 @@ "test_id_prefix": "ninja://content/test:content_browsertests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248657,6 +248666,7 @@ "test_id_prefix": "ninja://ui/events:events_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248678,6 +248688,7 @@ "args": [ "--enable-features=StorageServiceOutOfProcess" ], + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248697,6 +248708,7 @@ "test_id_prefix": "ninja://extensions:extensions_browsertests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -248949,6 +248961,7 @@ "test_id_prefix": "ninja://media:media_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -249273,6 +249286,7 @@ "test_id_prefix": "ninja://skia:skia_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -249327,6 +249341,7 @@ "test_id_prefix": "ninja://storage:storage_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -249399,6 +249414,7 @@ "test_id_prefix": "ninja://ui/touch_selection:ui_touch_selection_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -249417,6 +249433,7 @@ "test_id_prefix": "ninja://chrome/test:unit_tests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -249435,6 +249452,7 @@ "test_id_prefix": "ninja://url:url_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -249471,6 +249489,7 @@ "test_id_prefix": "ninja://components/viz:viz_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py"
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index e008bc6..ca270fe4 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -57099,6 +57099,7 @@ "test_id_prefix": "ninja://third_party/angle/src/tests:angle_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57117,6 +57118,7 @@ "test_id_prefix": "ninja://extensions/shell:app_shell_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57298,6 +57300,7 @@ "test_id_prefix": "ninja://third_party/boringssl:boringssl_ssl_tests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57410,6 +57413,7 @@ "test_id_prefix": "ninja://chrome/test/chromedriver:chromedriver_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57428,6 +57432,7 @@ "test_id_prefix": "ninja://components:components_browsertests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57446,6 +57451,7 @@ "test_id_prefix": "ninja://components:components_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57464,6 +57470,7 @@ "test_id_prefix": "ninja://ui/compositor:compositor_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57486,6 +57493,7 @@ "args": [ "--enable-features=StorageServiceOutOfProcess" ], + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57506,6 +57514,7 @@ "test_id_prefix": "ninja://content/test:content_browsertests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57614,6 +57623,7 @@ "test_id_prefix": "ninja://ui/events:events_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57635,6 +57645,7 @@ "args": [ "--enable-features=StorageServiceOutOfProcess" ], + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57654,6 +57665,7 @@ "test_id_prefix": "ninja://extensions:extensions_browsertests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -57906,6 +57918,7 @@ "test_id_prefix": "ninja://media:media_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -58230,6 +58243,7 @@ "test_id_prefix": "ninja://skia:skia_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -58284,6 +58298,7 @@ "test_id_prefix": "ninja://storage:storage_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -58356,6 +58371,7 @@ "test_id_prefix": "ninja://ui/touch_selection:ui_touch_selection_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -58374,6 +58390,7 @@ "test_id_prefix": "ninja://chrome/test:unit_tests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -58392,6 +58409,7 @@ "test_id_prefix": "ninja://url:url_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -58428,6 +58446,7 @@ "test_id_prefix": "ninja://components/viz:viz_unittests/" }, { + "experiment_percentage": 100, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py"
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 8a375c5..b428292 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -3211,6 +3211,166 @@ 'ui_base_unittests': {}, }, + # This suite is the combination of several test suites with + # some experimental enabled. + # TODO(crbug.com/1104291): Remove this when all tests can + # pass on CI/CQ. + 'lacros_gtests': { + 'absl_hardening_tests': {}, + 'accessibility_unittests': {}, + 'angle_unittests': {}, + 'app_shell_unittests': { + 'experiment_percentage': 100, + }, + 'aura_unittests': { + 'experiment_percentage': 100, + }, + 'base_unittests': {}, + 'base_util_unittests': {}, + 'blink_common_unittests': {}, + 'blink_fuzzer_unittests': {}, + 'blink_heap_unittests': {}, + 'blink_platform_unittests': {}, + 'boringssl_crypto_tests': {}, + 'boringssl_ssl_tests': {}, + 'browser_tests': { + 'swarming': { + 'shards': 10, + }, + 'experiment_percentage': 100, + }, + 'capture_unittests': { + 'args': [ + '--gtest_filter=-*UsingRealWebcam*', + ], + }, + 'cast_unittests': {}, + 'cc_unittests': {}, + 'chrome_app_unittests': {}, + 'chromedriver_unittests': {}, + 'components_browsertests': { + 'experiment_percentage': 100, + }, + 'components_unittests': { + 'experiment_percentage': 100, + }, + 'compositor_unittests': { + 'experiment_percentage': 100, + }, + 'content_browsertests': { + 'android_swarming': { + 'shards': 9, + }, + 'swarming': { + 'shards': 6, + }, + 'experiment_percentage': 100, + }, + 'content_unittests': { + 'experiment_percentage': 100, + }, + 'crypto_unittests': {}, + 'device_unittests': {}, + 'display_unittests': {}, + 'events_unittests': {}, + 'extensions_browsertests': { + 'experiment_percentage': 100, + }, + 'extensions_unittests': { + 'experiment_percentage': 100, + }, + 'filesystem_service_unittests': {}, + 'gcm_unit_tests': {}, + 'gfx_unittests': {}, + 'gin_unittests': {}, + 'google_apis_unittests': {}, + 'gpu_unittests': {}, + 'gwp_asan_unittests': {}, + 'ipc_tests': {}, + 'jingle_unittests': {}, + 'latency_unittests': {}, + 'libjingle_xmpp_unittests': {}, + 'media_blink_unittests': {}, + 'media_unittests': {}, + 'message_center_unittests': { + 'experiment_percentage': 100, + }, + 'midi_unittests': {}, + 'mojo_unittests': {}, + 'nacl_loader_unittests': {}, + 'native_theme_unittests': {}, + 'net_unittests': {}, + 'pdf_unittests': {}, + 'perfetto_unittests': {}, + 'ppapi_unittests': {}, + 'printing_unittests': {}, + 'remoting_unittests': {}, + 'service_manager_unittests': {}, + 'services_unittests': {}, + 'shell_dialogs_unittests': {}, + 'skia_unittests': {}, + 'snapshot_unittests': { + 'experiment_percentage': 100, + }, + 'sql_unittests': {}, + 'storage_service_unsandboxed_content_browsertests': { + 'args': [ + '--enable-features=StorageServiceOutOfProcess', + ], + 'swarming': { + 'shards': 2, + }, + 'test': 'content_browsertests', + 'experiment_percentage': 100, + }, + 'storage_service_unsandboxed_extensions_browsertests': { + 'args': [ + '--enable-features=StorageServiceOutOfProcess', + ], + 'test': 'extensions_browsertests', + 'experiment_percentage': 100, + }, + # TODO(crbug.com/1104291): Re-enable this. + # 'storage_service_unsandboxed_interactive_ui_tests': { + # 'args': [ + # '--enable-features=StorageServiceOutOfProcess' + # ], + # 'swarming': { + # 'shards': 3, + # }, + # 'test': 'interactive_ui_tests', + # }, + 'storage_unittests': {}, + 'sync_integration_tests': { + 'experiment_percentage': 100, + }, + 'ui_base_unittests': {}, + 'ui_touch_selection_unittests': {}, + 'unit_tests': { + 'experiment_percentage': 100, + }, + 'url_unittests': { + 'experiment_percentage': 100, + }, + 'views_unittests': { + 'experiment_percentage': 100, + }, + 'viz_unittests': {}, + 'webkit_unit_tests': { + 'test': 'blink_unittests', + }, + 'wm_unittests': { + 'experiment_percentage': 100, + }, + 'wtf_unittests': {}, + # TODO(crbug.com/1104291): Re-enable this. + # 'interactive_ui_tests': { + # 'swarming': { + # 'shards': 3, + # }, + # }, + }, + # END tests which run on the GPU bots 'layout_ng_gtests': { 'webkit_unit_tests_ng': { @@ -5390,14 +5550,18 @@ # This is: # linux_chromeos_gtests # - linux_chromeos_specific_gtests - 'aura_gtests', - 'chromium_gtests', - 'chromium_gtests_for_devices_with_graphical_output', + # TODO(crbug.com/1104291): Following test suites should be + # added and delete lacros_gtests. + # - chromium_gtests + # - chromium_gtests_for_devices_with_graphical_output + # - non_android_chromium_gtests + # - aura_gtests + # - storage_service_gtests + # - aura_gtests 'chromium_gtests_for_linux_and_chromeos_only', 'chromium_gtests_for_win_and_linux_only', + 'lacros_gtests', 'linux_flavor_specific_chromium_gtests', - 'non_android_chromium_gtests', - 'storage_service_gtests', ], 'linux_viz_gtests': [
diff --git a/third_party/abseil-cpp/absl.gni b/third_party/abseil-cpp/absl.gni index 823fc4b..88ce3aa 100644 --- a/third_party/abseil-cpp/absl.gni +++ b/third_party/abseil-cpp/absl.gni
@@ -34,6 +34,7 @@ } _chromium_absl_clients = [ + "//chrome/services/sharing/nearby/platform_v2/*", "//third_party/blink/renderer/modules/peerconnection", "//third_party/blink/renderer/platform", "//third_party/googletest:gtest",
diff --git a/third_party/android_system_sdk/README.chromium b/third_party/android_system_sdk/README.chromium index dd7daef..e0184177 100644 --- a/third_party/android_system_sdk/README.chromium +++ b/third_party/android_system_sdk/README.chromium
@@ -12,7 +12,7 @@ Revision is the BUILD ID of the Android release build. Because prebuilt system SDKs are not distributed publicly, Googlers will need to -follow http://go/clank-webview/next-layers to update this. +follow http://go/clank-webview/rolling_the_android_sdk.md to update this. Local Modifications: None
diff --git a/third_party/blink/common/BUILD.gn b/third_party/blink/common/BUILD.gn index 5a35d2b..fd09857 100644 --- a/third_party/blink/common/BUILD.gn +++ b/third_party/blink/common/BUILD.gn
@@ -151,6 +151,7 @@ "user_agent/user_agent_metadata.cc", "web_package/signed_exchange_consts.cc", "web_package/web_package_request_matcher.cc", + "widget/device_emulation_params_mojom_traits.cc", "widget/screen_info_mojom_traits.cc", "widget/visual_properties_mojom_traits.cc", ]
diff --git a/third_party/blink/common/widget/device_emulation_params_mojom_traits.cc b/third_party/blink/common/widget/device_emulation_params_mojom_traits.cc new file mode 100644 index 0000000..a28542a --- /dev/null +++ b/third_party/blink/common/widget/device_emulation_params_mojom_traits.cc
@@ -0,0 +1,30 @@ +// Copyright 2020 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 "third_party/blink/public/common/widget/device_emulation_params_mojom_traits.h" + +#include "ui/gfx/geometry/mojom/geometry.mojom.h" + +namespace mojo { + +bool StructTraits<blink::mojom::DeviceEmulationParamsDataView, + blink::DeviceEmulationParams>:: + Read(blink::mojom::DeviceEmulationParamsDataView data, + blink::DeviceEmulationParams* out) { + if (!data.ReadScreenSize(&out->screen_size) || + !data.ReadViewPosition(&out->view_position) || + !data.ReadViewSize(&out->view_size) || + !data.ReadViewportOffset(&out->viewport_offset) || + !data.ReadWindowSegments(&out->window_segments)) + return false; + out->screen_type = data.screen_type(); + out->device_scale_factor = data.device_scale_factor(); + out->scale = data.scale(); + out->viewport_scale = data.viewport_scale(); + out->screen_orientation_type = data.screen_orientation_type(); + out->screen_orientation_angle = data.screen_orientation_angle(); + return true; +} + +} // namespace mojo
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index d8e150b3..9e19f60 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -305,7 +305,6 @@ "web/web_context_menu_data.h", "web/web_crypto_normalize.h", "web/web_custom_element.h", - "web/web_device_emulation_params.h", "web/web_document.h", "web/web_document_loader.h", "web/web_dom_activity_logger.h",
diff --git a/third_party/blink/public/common/BUILD.gn b/third_party/blink/public/common/BUILD.gn index 1839fc3..ae028cf 100644 --- a/third_party/blink/public/common/BUILD.gn +++ b/third_party/blink/public/common/BUILD.gn
@@ -172,6 +172,7 @@ "web_cache/web_cache_resource_type_stats.h", "web_package/signed_exchange_consts.h", "web_package/web_package_request_matcher.h", + "widget/device_emulation_params.h", "widget/screen_info.h", "widget/visual_properties.h", ]
diff --git a/third_party/blink/public/web/web_device_emulation_params.h b/third_party/blink/public/common/widget/device_emulation_params.h similarity index 72% rename from third_party/blink/public/web/web_device_emulation_params.h rename to third_party/blink/public/common/widget/device_emulation_params.h index e38f2d0d..c876cc3f 100644 --- a/third_party/blink/public/web/web_device_emulation_params.h +++ b/third_party/blink/public/common/widget/device_emulation_params.h
@@ -2,28 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_DEVICE_EMULATION_PARAMS_H_ -#define THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_DEVICE_EMULATION_PARAMS_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_WIDGET_DEVICE_EMULATION_PARAMS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_WIDGET_DEVICE_EMULATION_PARAMS_H_ #include "base/optional.h" +#include "third_party/blink/public/mojom/widget/device_emulation_params.mojom-shared.h" #include "third_party/blink/public/mojom/widget/screen_orientation.mojom-shared.h" -#include "third_party/blink/public/platform/web_rect.h" -#include "third_party/blink/public/platform/web_size.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" namespace blink { // All sizes are measured in device independent pixels. -struct WebDeviceEmulationParams { - enum ScreenPosition { kDesktop, kMobile, kScreenPositionLast = kMobile }; - - ScreenPosition screen_position = kDesktop; +struct DeviceEmulationParams { + mojom::EmulatedScreenType screen_type = mojom::EmulatedScreenType::kDesktop; // Emulated screen size. Typically full / physical size of the device screen // in DIP. Empty size means using default value: original one for kDesktop // screen position, equal to |view_size| for kMobile. - WebSize screen_size; + gfx::Size screen_size; // Position of view on the screen. Missing position means using default value: // original one for kDesktop screen position, (0, 0) for kMobile. @@ -32,7 +31,7 @@ // Emulated view size. A width or height of 0 means no override in that // dimension, but the other can still be applied. When both are 0, then the // |scale| will be applied to the view instead. - WebSize view_size; + gfx::Size view_size; // If zero, the original device scale factor is preserved. float device_scale_factor = 0; @@ -54,18 +53,18 @@ mojom::ScreenOrientation::kUndefined; // Screen orientation angle, used together with screenOrientationType. - int screen_orientation_angle = 0; + uint32_t screen_orientation_angle = 0; // Screen window segments dimensions. std::vector<gfx::Rect> window_segments; - WebDeviceEmulationParams() = default; + DeviceEmulationParams() = default; }; -inline bool operator==(const WebDeviceEmulationParams& a, - const WebDeviceEmulationParams& b) { - return a.screen_position == b.screen_position && - a.screen_size == b.screen_size && a.view_position == b.view_position && +inline bool operator==(const DeviceEmulationParams& a, + const DeviceEmulationParams& b) { + return a.screen_type == b.screen_type && a.screen_size == b.screen_size && + a.view_position == b.view_position && a.device_scale_factor == b.device_scale_factor && a.view_size == b.view_size && a.scale == b.scale && a.screen_orientation_type == b.screen_orientation_type && @@ -75,8 +74,8 @@ a.window_segments == b.window_segments; } -inline bool operator!=(const WebDeviceEmulationParams& a, - const WebDeviceEmulationParams& b) { +inline bool operator!=(const DeviceEmulationParams& a, + const DeviceEmulationParams& b) { return !(a == b); }
diff --git a/third_party/blink/public/common/widget/device_emulation_params_mojom_traits.h b/third_party/blink/public/common/widget/device_emulation_params_mojom_traits.h new file mode 100644 index 0000000..abcf659a --- /dev/null +++ b/third_party/blink/public/common/widget/device_emulation_params_mojom_traits.h
@@ -0,0 +1,72 @@ +// Copyright 2020 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 THIRD_PARTY_BLINK_PUBLIC_COMMON_WIDGET_DEVICE_EMULATION_PARAMS_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_WIDGET_DEVICE_EMULATION_PARAMS_MOJOM_TRAITS_H_ + +#include "third_party/blink/public/common/common_export.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" +#include "third_party/blink/public/mojom/widget/device_emulation_params.mojom-shared.h" + +namespace mojo { + +template <> +struct BLINK_COMMON_EXPORT + StructTraits<blink::mojom::DeviceEmulationParamsDataView, + blink::DeviceEmulationParams> { + static blink::mojom::EmulatedScreenType screen_type( + const blink::DeviceEmulationParams& r) { + return r.screen_type; + } + + static const gfx::Size& screen_size(const blink::DeviceEmulationParams& r) { + return r.screen_size; + } + + static base::Optional<gfx::Point> view_position( + const blink::DeviceEmulationParams& r) { + return r.view_position; + } + + static const gfx::Size& view_size(const blink::DeviceEmulationParams& r) { + return r.view_size; + } + + static float device_scale_factor(const blink::DeviceEmulationParams& r) { + return r.device_scale_factor; + } + + static float scale(const blink::DeviceEmulationParams& r) { return r.scale; } + + static const gfx::PointF& viewport_offset( + const blink::DeviceEmulationParams& r) { + return r.viewport_offset; + } + + static float viewport_scale(const blink::DeviceEmulationParams& r) { + return r.viewport_scale; + } + + static blink::mojom::ScreenOrientation screen_orientation_type( + const blink::DeviceEmulationParams& r) { + return r.screen_orientation_type; + } + + static uint32_t screen_orientation_angle( + const blink::DeviceEmulationParams& r) { + return r.screen_orientation_angle; + } + + static const std::vector<gfx::Rect>& window_segments( + const blink::DeviceEmulationParams& r) { + return r.window_segments; + } + + static bool Read(blink::mojom::DeviceEmulationParamsDataView r, + blink::DeviceEmulationParams* out); +}; + +} // namespace mojo + +#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_WIDGET_DEVICE_EMULATION_PARAMS_MOJOM_TRAITS_H_
diff --git a/third_party/blink/public/devtools_protocol/browser_protocol.pdl b/third_party/blink/public/devtools_protocol/browser_protocol.pdl index 5792b5d..86970ce 100644 --- a/third_party/blink/public/devtools_protocol/browser_protocol.pdl +++ b/third_party/blink/public/devtools_protocol/browser_protocol.pdl
@@ -4260,6 +4260,11 @@ High VeryHigh + # Post data entry for HTTP request + type PostDataEntry extends object + properties + optional binary bytes + # HTTP request data. type Request extends object properties @@ -4275,6 +4280,8 @@ optional string postData # True when the request has POST data. Note that postData might still be omitted when this flag is true when the data is too long. optional boolean hasPostData + # Request body elements. This will be converted from base64 to binary + experimental optional array of PostDataEntry postDataEntries # The mixed content type of the request. optional Security.MixedContentType mixedContentType # Priority of the resource request at the time request is sent.
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index 18c6e2f..97fa120 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -158,6 +158,7 @@ "speech/speech_recognition_result.mojom", "speech/speech_recognizer.mojom", "speech/speech_synthesis.mojom", + "storage_access/storage_access_automation.mojom", "timing/performance_mark_or_measure.mojom", "timing/resource_timing.mojom", "timing/worker_timing_container.mojom", @@ -171,6 +172,7 @@ "webdatabase/web_database.mojom", "websockets/websocket_connector.mojom", "webtransport/quic_transport_connector.mojom", + "widget/device_emulation_params.mojom", "widget/screen_info.mojom", "widget/screen_orientation.mojom", "widget/visual_properties.mojom", @@ -305,6 +307,15 @@ ] traits_headers = [ "//third_party/blink/public/common/widget/visual_properties_mojom_traits.h" ] }, + { + types = [ + { + mojom = "blink.mojom.DeviceEmulationParams" + cpp = "::blink::DeviceEmulationParams" + }, + ] + traits_headers = [ "//third_party/blink/public/common/widget/device_emulation_params_mojom_traits.h" ] + }, ] cpp_typemaps = [ {
diff --git a/third_party/blink/public/mojom/loader/previews_resource_loading_hints.mojom b/third_party/blink/public/mojom/loader/previews_resource_loading_hints.mojom index 9500ba8..3a3d8b26 100644 --- a/third_party/blink/public/mojom/loader/previews_resource_loading_hints.mojom +++ b/third_party/blink/public/mojom/loader/previews_resource_loading_hints.mojom
@@ -4,34 +4,57 @@ module blink.mojom; +import "mojo/public/mojom/base/time.mojom"; + // Resource loading hints passed by the browser to renderers. Send at most once // per page load from browser to renderer as part of a preview treatment. The // hints are provided to the renderer and aid in optimizing the loading of // resources. struct PreviewsResourceLoadingHints { - // SourceId to use when recording UKM for the resource loading hints. This - // is based on the browser NavigationHandle's navigation id. - int64 ukm_source_id; - // List of subresources to block. The list contains the URL patterns of - // subresources to block. - // TODO(tbansal): https://crbug.com/856243. Update the mojom message below - // to match the updated resource loading hints proto. - array<string> subresources_to_block; + // SourceId to use when recording UKM for the resource loading hints. This + // is based on the browser NavigationHandle's navigation id. + int64 ukm_source_id; + // List of subresources to block. The list contains the URL patterns of + // subresources to block. + // TODO(tbansal): https://crbug.com/856243. Update the mojom message below + // to match the updated resource loading hints proto. + array<string> subresources_to_block; }; // Image loading hints passed by the browser to renderers. Send at most once // per page load from browser to renderer. The hints are provided to the // renderer and aid in redirecting these public images to compressed versions. struct CompressPublicImagesHints { - array<string> image_urls; + array<string> image_urls; +}; + +// LiteVideo hints passed by the browser to renderers. Send at most once +// per render frame from browser to renderer. The hints are provided to the +// renderer and aid in optimizing media data use. +struct LiteVideoHint { + // The number of kilobytes for media to be observed before starting to + // throttle requests. + int64 kilobytes_to_buffer_before_throttle; + // The network downlink bandwidth target in kilobytes per second used to + // calculate the throttling delay on media requests. + int64 target_downlink_bandwidth_kbps; + // The network downlink rtt target in milliseconds used to calculate the + // throttling delay on media requests. + mojo_base.mojom.TimeDelta target_downlink_rtt_latency; + // The maximum delay a throttle can introduce for a media request. + mojo_base.mojom.TimeDelta max_throttling_delay; }; // Render process implemented interface that receives hints from the browser // about how to load resources. interface PreviewsResourceLoadingHintsReceiver { - // Sends the resource loading hints from the browser to renderers. - SetResourceLoadingHints(PreviewsResourceLoadingHints previews_resource_loading_hints); + // Sends the resource loading hints from the browser to renderers. + SetResourceLoadingHints(PreviewsResourceLoadingHints previews_resource_loading_hints); - // Sends the public image URL hints from the browser to renderers. - SetCompressPublicImagesHints(CompressPublicImagesHints images_hints); + // Sends the public image URL hints from the browser to renderers. + SetCompressPublicImagesHints(CompressPublicImagesHints images_hints); + + // Sends the hints for reducing the data-costs of streaming + // media/videos from the browser to renderers. + SetLiteVideoHint(LiteVideoHint lite_video_hint); };
diff --git a/third_party/blink/public/mojom/storage_access/OWNERS b/third_party/blink/public/mojom/storage_access/OWNERS new file mode 100644 index 0000000..d370d11 --- /dev/null +++ b/third_party/blink/public/mojom/storage_access/OWNERS
@@ -0,0 +1,4 @@ +file://chrome/browser/storage_access_api/OWNERS + +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/mojom/storage_access/storage_access_automation.mojom b/third_party/blink/public/mojom/storage_access/storage_access_automation.mojom new file mode 100644 index 0000000..4ce5315 --- /dev/null +++ b/third_party/blink/public/mojom/storage_access/storage_access_automation.mojom
@@ -0,0 +1,14 @@ +// Copyright 2020 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. + +module blink.test.mojom; + +// Provides a way for tests to change the storage access policy. +// See https://privacycg.github.io/storage-access/#automation +interface StorageAccessAutomation { + // Sets whether |origin| has access to cookies from |embedding_origin|. + SetStorageAccess(string origin, + string embedding_origin, + bool allowed) => (bool success); +};
diff --git a/third_party/blink/public/mojom/widget/device_emulation_params.mojom b/third_party/blink/public/mojom/widget/device_emulation_params.mojom new file mode 100644 index 0000000..8f21199 --- /dev/null +++ b/third_party/blink/public/mojom/widget/device_emulation_params.mojom
@@ -0,0 +1,52 @@ +// Copyright 2020 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. + +module blink.mojom; + +import "ui/gfx/geometry/mojom/geometry.mojom"; +import "third_party/blink/public/mojom/widget/screen_orientation.mojom"; + +enum EmulatedScreenType { kDesktop, kMobile }; + +struct DeviceEmulationParams { + EmulatedScreenType screen_type; + + // Emulated screen size. Typically full / physical size of the device screen + // in DIP. Empty size means using default value: original one for kDesktop + // screen position, equal to |view_size| for kMobile. + gfx.mojom.Size screen_size; + + // Position of view on the screen. Missing position means using default value: + // original one for kDesktop screen position, (0, 0) for kMobile. + gfx.mojom.Point? view_position; + + // Emulated view size. A width or height of 0 means no override in that + // dimension, but the other can still be applied. When both are 0, then the + // |scale| will be applied to the view instead. + gfx.mojom.Size view_size; + + // If zero, the original device scale factor is preserved. + float device_scale_factor; + + // Scale the contents of the main frame. The view's size will be scaled by + // this number when they are not specified in |view_size|. + float scale; + + // Forced viewport offset for screenshots during emulation, (-1, -1) for + // disabled. + gfx.mojom.PointF viewport_offset; + + // Viewport scale for screenshots during emulation, 0 for current. + float viewport_scale; + + // Optional screen orientation type, with ScreenOrientation::Undefined + // value meaning no emulation necessary. + ScreenOrientation screen_orientation_type; + + // Screen orientation angle, used together with screen_orientation_type. + uint32 screen_orientation_angle; + + // Screen window segments dimensions. + array<gfx.mojom.Rect> window_segments; +};
diff --git a/third_party/blink/public/web/web_view.h b/third_party/blink/public/web/web_view.h index b5562d3..bed7381 100644 --- a/third_party/blink/public/web/web_view.h +++ b/third_party/blink/public/web/web_view.h
@@ -67,7 +67,7 @@ class WebString; class WebViewClient; class WebWidget; -struct WebDeviceEmulationParams; +struct DeviceEmulationParams; struct WebRect; struct WebSize; struct WebTextAutosizerPageInfo; @@ -341,7 +341,7 @@ // Developer tools ----------------------------------------------------- // Enables device emulation as specified in params. - virtual void EnableDeviceEmulation(const WebDeviceEmulationParams&) = 0; + virtual void EnableDeviceEmulation(const DeviceEmulationParams&) = 0; // Cancel emulation started via |enableDeviceEmulation| call. virtual void DisableDeviceEmulation() = 0;
diff --git a/third_party/blink/public/web/web_widget_client.h b/third_party/blink/public/web/web_widget_client.h index 3a38525..1f5777e 100644 --- a/third_party/blink/public/web/web_widget_client.h +++ b/third_party/blink/public/web/web_widget_client.h
@@ -299,6 +299,11 @@ // Indicate composition is complete to pepper. virtual void ImeFinishComposingTextForPepper(bool keep_selection) {} + // Called only for main frame widgets; updates the widget client about + // whether it is currently nested inside a frame tree. Main frames can be + // nested in cases like Portals or GuestViews. + virtual void SetIsNestedMainFrameWidget(bool is_nested) {} + // Called to indicate a syntehtic event was queued. virtual void WillQueueSyntheticEvent(const WebCoalescedInputEvent& event) {}
diff --git a/third_party/blink/renderer/bindings/idl_in_core.gni b/third_party/blink/renderer/bindings/idl_in_core.gni index 225dcfd..06751b5 100644 --- a/third_party/blink/renderer/bindings/idl_in_core.gni +++ b/third_party/blink/renderer/bindings/idl_in_core.gni
@@ -670,6 +670,7 @@ # These IDL definitions are used only for testing. static_idl_files_in_core_for_testing = get_path_info( [ + "//third_party/blink/renderer/core/dom/testing/internals_storage_access.idl", "//third_party/blink/renderer/core/fetch/testing/internals_fetch.idl", "//third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.idl", "//third_party/blink/renderer/core/testing/callback_function_test.idl",
diff --git a/third_party/blink/renderer/bindings/idl_in_modules.gni b/third_party/blink/renderer/bindings/idl_in_modules.gni index 04011912..3e7a61e6 100644 --- a/third_party/blink/renderer/bindings/idl_in_modules.gni +++ b/third_party/blink/renderer/bindings/idl_in_modules.gni
@@ -381,7 +381,6 @@ "//third_party/blink/renderer/modules/native_file_system/file_system_writable_file_stream.idl", "//third_party/blink/renderer/modules/native_file_system/get_system_directory_options.idl", "//third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.idl", - "//third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator_entry.idl", "//third_party/blink/renderer/modules/native_file_system/open_file_picker_options.idl", "//third_party/blink/renderer/modules/native_file_system/save_file_picker_options.idl", "//third_party/blink/renderer/modules/native_file_system/window_native_file_system.idl",
diff --git a/third_party/blink/renderer/bindings/templates/interface_base.cc.tmpl b/third_party/blink/renderer/bindings/templates/interface_base.cc.tmpl index 0dff254..8473ac9 100644 --- a/third_party/blink/renderer/bindings/templates/interface_base.cc.tmpl +++ b/third_party/blink/renderer/bindings/templates/interface_base.cc.tmpl
@@ -529,6 +529,26 @@ {% endfilter %} {% endif %} + {% if interface_name == 'FileSystemDirectoryHandle' %} + // Temporary @@asyncIterator support for FileSystemDirectoryHandle + // TODO(https://crbug.com/1087157): Replace with proper bindings support. + static const V8DOMConfiguration::SymbolKeyedMethodConfiguration + kSymbolKeyedIteratorConfiguration = { + v8::Symbol::GetAsyncIterator, + "entries", + V8FileSystemDirectoryHandle::EntriesMethodCallback, + 0, + v8::DontEnum, + V8DOMConfiguration::kOnPrototype, + V8DOMConfiguration::kCheckHolder, + V8DOMConfiguration::kDoNotCheckAccess, + V8DOMConfiguration::kHasSideEffect + }; + V8DOMConfiguration::InstallMethod( + isolate, world, prototype_template, signature, + kSymbolKeyedIteratorConfiguration); + {% endif %} + {% if interface_name == 'Iterator' %} // The WebIDL spec says when an interface has pair iterators the iterators it // returns must be instances of the "default iterator object" whose @@ -566,6 +586,17 @@ interface_template->Inherit(intrinsic_iterator_prototype_interface_template); {% endif %} + {% if interface_name == 'NativeFileSystemDirectoryIterator' %} + // Temporary @@asyncIterator support for FileSystemDirectoryHandle + // TODO(https://crbug.com/1087157): Replace with proper bindings support. + v8::Local<v8::FunctionTemplate> intrinsic_iterator_prototype_interface_template = + v8::FunctionTemplate::New(isolate); + intrinsic_iterator_prototype_interface_template->RemovePrototype(); + intrinsic_iterator_prototype_interface_template->SetIntrinsicDataProperty( + V8AtomicString(isolate, "prototype"), v8::kAsyncIteratorPrototype); + interface_template->Inherit(intrinsic_iterator_prototype_interface_template); + {% endif %} + {% if interface_name == 'DOMException' %} // The WebIDL spec states that DOMException objects have a few peculiarities. // One of them is similar to what it mandates for Iterator objects when it
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn index 8eca046..0328e98 100644 --- a/third_party/blink/renderer/core/BUILD.gn +++ b/third_party/blink/renderer/core/BUILD.gn
@@ -229,6 +229,8 @@ sources = [ "$blink_core_output_dir/testing/internal_settings_generated.cc", "$blink_core_output_dir/testing/internal_settings_generated.h", + "dom/testing/internals_storage_access.cc", + "dom/testing/internals_storage_access.h", "fetch/testing/internals_fetch.cc", "fetch/testing/internals_fetch.h", "fetch/testing/worker_internals_fetch.cc",
diff --git a/third_party/blink/renderer/core/animation/css/css_animations.cc b/third_party/blink/renderer/core/animation/css/css_animations.cc index 34cad42..667467d 100644 --- a/third_party/blink/renderer/core/animation/css/css_animations.cc +++ b/third_party/blink/renderer/core/animation/css/css_animations.cc
@@ -1795,6 +1795,7 @@ case CSSPropertyID::kWebkitWritingMode: case CSSPropertyID::kWillChange: case CSSPropertyID::kWritingMode: + case CSSPropertyID::kTextCombineUpright: return true; default: return false;
diff --git a/third_party/blink/renderer/core/core_idl_files.gni b/third_party/blink/renderer/core/core_idl_files.gni index de597dd..ca28a4236 100644 --- a/third_party/blink/renderer/core/core_idl_files.gni +++ b/third_party/blink/renderer/core/core_idl_files.gni
@@ -787,6 +787,7 @@ webcore_testing_dependency_idl_files = get_path_info([ + "dom/testing/internals_storage_access.idl", "fetch/testing/internals_fetch.idl", "fetch/testing/worker_internals_fetch.idl", "testing/origin_trials_test_partial.idl",
diff --git a/third_party/blink/renderer/core/dom/testing/internals_storage_access.cc b/third_party/blink/renderer/core/dom/testing/internals_storage_access.cc new file mode 100644 index 0000000..5140e78 --- /dev/null +++ b/third_party/blink/renderer/core/dom/testing/internals_storage_access.cc
@@ -0,0 +1,50 @@ +// Copyright 2020 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 "third_party/blink/renderer/core/dom/testing/internals_storage_access.h" +#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h" +#include "third_party/blink/public/mojom/storage_access/storage_access_automation.mojom-blink.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" + +namespace blink { + +// static +ScriptPromise InternalsStorageAccess::setStorageAccess( + ScriptState* script_state, + Internals&, + const String& origin, + const String& embedding_origin, + const bool blocked, + ExceptionState& exception_state) { + mojo::Remote<test::mojom::blink::StorageAccessAutomation> + storage_access_automation; + Platform::Current()->GetBrowserInterfaceBroker()->GetInterface( + storage_access_automation.BindNewPipeAndPassReceiver()); + DCHECK(storage_access_automation.is_bound()); + + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + ScriptPromise promise = resolver->Promise(); + auto* raw_storage_access_automation = storage_access_automation.get(); + raw_storage_access_automation->SetStorageAccess( + origin, embedding_origin, blocked, + WTF::Bind( + // While we only really need |resolver|, we also take the + // mojo::Remote<> so that it remains alive after this function exits. + [](ScriptPromiseResolver* resolver, + mojo::Remote<test::mojom::blink::StorageAccessAutomation>, + bool success) { + if (success) + resolver->Resolve(); + else + resolver->Reject(); + }, + WrapPersistent(resolver), std::move(storage_access_automation))); + + return promise; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/dom/testing/internals_storage_access.h b/third_party/blink/renderer/core/dom/testing/internals_storage_access.h new file mode 100644 index 0000000..693336d --- /dev/null +++ b/third_party/blink/renderer/core/dom/testing/internals_storage_access.h
@@ -0,0 +1,32 @@ +// Copyright 2020 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 THIRD_PARTY_BLINK_RENDERER_CORE_DOM_TESTING_INTERNALS_STORAGE_ACCESS_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_TESTING_INTERNALS_STORAGE_ACCESS_H_ + +#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" +#include "third_party/blink/renderer/platform/wtf/forward.h" + +namespace blink { + +class ExceptionState; +class Internals; +class ScriptPromise; +class ScriptState; + +class InternalsStorageAccess { + STATIC_ONLY(InternalsStorageAccess); + + public: + static ScriptPromise setStorageAccess(ScriptState*, + Internals&, + const String& origin, + const String& embedding_origin, + const bool blocked, + ExceptionState&); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_TESTING_INTERNALS_STORAGE_ACCESS_H_
diff --git a/third_party/blink/renderer/core/dom/testing/internals_storage_access.idl b/third_party/blink/renderer/core/dom/testing/internals_storage_access.idl new file mode 100644 index 0000000..d2c13df5 --- /dev/null +++ b/third_party/blink/renderer/core/dom/testing/internals_storage_access.idl
@@ -0,0 +1,9 @@ +// Copyright 2020 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. + +[ + ImplementedAs=InternalsStorageAccess +] partial interface Internals { + [CallWith=ScriptState, RaisesException] Promise<void> setStorageAccess(USVString origin, USVString embeddingOrigin, boolean blocked); +};
diff --git a/third_party/blink/renderer/core/events/wheel_event.cc b/third_party/blink/renderer/core/events/wheel_event.cc index 6e331ec..04fe796 100644 --- a/third_party/blink/renderer/core/events/wheel_event.cc +++ b/third_party/blink/renderer/core/events/wheel_event.cc
@@ -46,13 +46,6 @@ : WheelEvent::kDomDeltaPixel; } -// Negate a long value without integer overflow. -int32_t NegateIfPossible(int32_t value) { - if (value == std::numeric_limits<int32_t>::min()) - return value; - return -value; -} - MouseEventInit* GetMouseEventInitForWheel(const WebMouseWheelEvent& event, AbstractView* view) { MouseEventInit* initializer = MouseEventInit::Create(); @@ -98,16 +91,16 @@ : MouseEvent(type, initializer), wheel_delta_(initializer->wheelDeltaX() ? initializer->wheelDeltaX() - : NegateIfPossible(-initializer->deltaX()), + : static_cast<int32_t>(initializer->deltaX()), initializer->wheelDeltaY() ? initializer->wheelDeltaY() - : NegateIfPossible(-initializer->deltaY())), + : static_cast<int32_t>(initializer->deltaY())), delta_x_(initializer->deltaX() ? initializer->deltaX() - : NegateIfPossible(initializer->wheelDeltaX())), + : -static_cast<int32_t>(initializer->wheelDeltaX())), delta_y_(initializer->deltaY() ? initializer->deltaY() - : NegateIfPossible(initializer->wheelDeltaY())), + : -static_cast<int32_t>(initializer->wheelDeltaY())), delta_z_(initializer->deltaZ()), delta_mode_(initializer->deltaMode()) {}
diff --git a/third_party/blink/renderer/core/exported/web_frame_test.cc b/third_party/blink/renderer/core/exported/web_frame_test.cc index 9a7ee4e..95b568e 100644 --- a/third_party/blink/renderer/core/exported/web_frame_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -58,6 +58,7 @@ #include "third_party/blink/public/common/input/web_keyboard_event.h" #include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/common/page/launching_process_state.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/mojom/blob/blob.mojom-blink.h" #include "third_party/blink/public/mojom/blob/data_element.mojom-blink.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" @@ -73,7 +74,6 @@ #include "third_party/blink/public/platform/web_url_response.h" #include "third_party/blink/public/web/web_console_message.h" #include "third_party/blink/public/web/web_context_menu_data.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_document_loader.h" #include "third_party/blink/public/web/web_form_element.h" @@ -9849,8 +9849,8 @@ }; TEST_F(DeviceEmulationTest, DeviceSizeInvalidatedOnResize) { - WebDeviceEmulationParams params; - params.screen_position = WebDeviceEmulationParams::kMobile; + DeviceEmulationParams params; + params.screen_type = mojom::EmulatedScreenType::kMobile; web_view_helper_.GetWebView()->EnableDeviceEmulation(params); TestResize(WebSize(700, 500), "300x300");
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index fc961dd..76632fa 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -2889,8 +2889,7 @@ return device_emulation_transform_; } -void WebViewImpl::EnableDeviceEmulation( - const WebDeviceEmulationParams& params) { +void WebViewImpl::EnableDeviceEmulation(const DeviceEmulationParams& params) { TransformationMatrix device_emulation_transform = dev_tools_emulator_->EnableDeviceEmulation(params); SetDeviceEmulationTransform(device_emulation_transform); @@ -3003,6 +3002,12 @@ void WebViewImpl::SetInsidePortal(bool inside_portal) { GetPage()->SetInsidePortal(inside_portal); + + // We may not have created the frame widget yet but that's ok because it'll + // be created with this value correctly initialized. This can also be null if + // the main frame is remote. + if (web_widget_) + web_widget_->SetIsNestedMainFrameWidget(inside_portal); } void WebViewImpl::SetIsActive(bool active) {
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.h b/third_party/blink/renderer/core/exported/web_view_impl.h index 395899d9..c9baaad 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.h +++ b/third_party/blink/renderer/core/exported/web_view_impl.h
@@ -190,7 +190,7 @@ WebHitTestResult HitTestResultForTap(const gfx::Point&, const WebSize&) override; uint64_t CreateUniqueIdentifierForRequest() override; - void EnableDeviceEmulation(const WebDeviceEmulationParams&) override; + void EnableDeviceEmulation(const DeviceEmulationParams&) override; void DisableDeviceEmulation() override; void PerformCustomContextMenuAction(unsigned action) override; void DidCloseContextMenu() override; @@ -701,7 +701,7 @@ WeakPersistent<WebLocalFrameImpl> local_root_with_empty_mouse_wheel_listener_; // The WebWidget for the main frame. This is expected to be unset when the - // WebWidget destroys itself. + // WebWidget destroys itself. This will be null if the main frame is remote. WeakPersistent<WebFrameWidgetBase> web_widget_; // We defer commits when transitioning to a new page. ChromeClientImpl calls
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index 2a2ff42..4e948c9 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -56,6 +56,7 @@ #include "third_party/blink/public/common/input/web_keyboard_event.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/common/page/web_drag_operation.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/mojom/frame/frame_owner_element_type.mojom-blink.h" #include "third_party/blink/public/mojom/frame/tree_scope_type.mojom-blink.h" #include "third_party/blink/public/mojom/input/focus_type.mojom-blink.h" @@ -66,7 +67,6 @@ #include "third_party/blink/public/public_buildflags.h" #include "third_party/blink/public/web/web_autofill_client.h" #include "third_party/blink/public/web/web_console_message.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_element.h" #include "third_party/blink/public/web/web_frame.h" @@ -690,8 +690,8 @@ base_url); UpdateAllLifecyclePhases(); - WebDeviceEmulationParams params; - params.screen_position = WebDeviceEmulationParams::kMobile; + DeviceEmulationParams params; + params.screen_type = mojom::EmulatedScreenType::kMobile; Document& document = *web_view_impl->MainFrameImpl()->GetFrame()->GetDocument(); @@ -2405,8 +2405,8 @@ float page_scale_expected = web_view_impl->PageScaleFactor(); - WebDeviceEmulationParams params; - params.screen_position = WebDeviceEmulationParams::kDesktop; + DeviceEmulationParams params; + params.screen_type = mojom::EmulatedScreenType::kDesktop; params.device_scale_factor = 0; params.scale = 1; @@ -5042,7 +5042,7 @@ expected_matrix.MakeIdentity(); EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform()); - WebDeviceEmulationParams emulation_params; + DeviceEmulationParams emulation_params; emulation_params.scale = 2.f; web_view_impl->EnableDeviceEmulation(emulation_params); expected_matrix.MakeIdentity().Scale(2.f); @@ -5080,7 +5080,7 @@ ScrollOffset(100, 150), mojom::blink::ScrollType::kProgrammatic, mojom::blink::ScrollBehavior::kInstant); - WebDeviceEmulationParams emulation_params; + DeviceEmulationParams emulation_params; emulation_params.viewport_offset = gfx::PointF(50, 55); emulation_params.viewport_scale = 2.f; web_view_impl->EnableDeviceEmulation(emulation_params); @@ -5267,8 +5267,8 @@ EXPECT_FALSE(frame_view->VisualViewportSuppliesScrollbars()); EXPECT_NE(nullptr, frame_view->LayoutViewport()->VerticalScrollbar()); - WebDeviceEmulationParams params; - params.screen_position = WebDeviceEmulationParams::kMobile; + DeviceEmulationParams params; + params.screen_type = mojom::EmulatedScreenType::kMobile; params.device_scale_factor = 0; params.scale = 1;
diff --git a/third_party/blink/renderer/core/frame/frame_overlay_test.cc b/third_party/blink/renderer/core/frame/frame_overlay_test.cc index 497c732a..c40df182 100644 --- a/third_party/blink/renderer/core/frame/frame_overlay_test.cc +++ b/third_party/blink/renderer/core/frame/frame_overlay_test.cc
@@ -8,7 +8,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/renderer/core/exported/web_view_impl.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" @@ -117,7 +117,7 @@ } TEST_P(FrameOverlayTest, DeviceEmulationScale) { - WebDeviceEmulationParams params; + DeviceEmulationParams params; params.scale = 1.5; GetWebView()->EnableDeviceEmulation(params); GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
diff --git a/third_party/blink/renderer/core/frame/visual_viewport_test.cc b/third_party/blink/renderer/core/frame/visual_viewport_test.cc index 47eb471..e400bed 100644 --- a/third_party/blink/renderer/core/frame/visual_viewport_test.cc +++ b/third_party/blink/renderer/core/frame/visual_viewport_test.cc
@@ -15,11 +15,11 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/input/web_coalesced_input_event.h" #include "third_party/blink/public/common/input/web_input_event.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_ax_context.h" #include "third_party/blink/public/web/web_context_menu_data.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame_client.h" #include "third_party/blink/public/web/web_script_source.h" @@ -2538,7 +2538,7 @@ EXPECT_FALSE(visual_viewport.GetDeviceEmulationTransformNode()); EXPECT_FALSE(GetFrame()->View()->VisualViewportNeedsRepaint()); - WebDeviceEmulationParams params; + DeviceEmulationParams params; params.viewport_offset = gfx::PointF(); params.viewport_scale = 1.f; WebView()->EnableDeviceEmulation(params); @@ -2577,7 +2577,7 @@ // Set an identity device emulation transform and ensure the transform // paint property node is cleared and repaint visual viewport. - WebView()->EnableDeviceEmulation(WebDeviceEmulationParams()); + WebView()->EnableDeviceEmulation(DeviceEmulationParams()); UpdateAllLifecyclePhasesExceptPaint(); EXPECT_TRUE(GetFrame()->View()->VisualViewportNeedsRepaint()); EXPECT_FALSE(visual_viewport.GetDeviceEmulationTransformNode()); @@ -2630,7 +2630,7 @@ check_scrollbar(scrollbar, 1.f); // Apply device emulation scale. - WebDeviceEmulationParams params; + DeviceEmulationParams params; params.viewport_offset = gfx::PointF(); params.viewport_scale = 1.5f; WebView()->EnableDeviceEmulation(params);
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_base.cc b/third_party/blink/renderer/core/frame/web_frame_widget_base.cc index e76085af..7e32b58 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_base.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_base.cc
@@ -1486,6 +1486,11 @@ } } +void WebFrameWidgetBase::SetIsNestedMainFrameWidget(bool is_nested) { + if (client_) + client_->SetIsNestedMainFrameWidget(is_nested); +} + gfx::Range WebFrameWidgetBase::CompositionRange() { WebLocalFrame* focused_frame = FocusedWebLocalFrameInWidget(); if (!focused_frame)
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_base.h b/third_party/blink/renderer/core/frame/web_frame_widget_base.h index be7e3d7..fd29eb3 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_base.h +++ b/third_party/blink/renderer/core/frame/web_frame_widget_base.h
@@ -476,6 +476,10 @@ // Called when the widget should get targeting input. void SetMouseCapture(bool capture); + // Called when a main frame widget is promoted or demoted from being the top + // level widget in a tab/window. E.g. a portal is activated or deactivated. + void SetIsNestedMainFrameWidget(bool is_nested); + protected: enum DragAction { kDragEnter, kDragOver };
diff --git a/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc b/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc index 320cace..4f257e5 100644 --- a/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc +++ b/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc
@@ -6,6 +6,7 @@ #include <algorithm> +#include "third_party/blink/public/mojom/widget/device_emulation_params.mojom-blink.h" #include "third_party/blink/public/web/web_settings.h" #include "third_party/blink/renderer/core/events/web_input_event_conversion.h" #include "third_party/blink/renderer/core/exported/web_view_impl.h" @@ -217,10 +218,10 @@ } TransformationMatrix DevToolsEmulator::EnableDeviceEmulation( - const WebDeviceEmulationParams& params) { + const DeviceEmulationParams& params) { if (device_metrics_enabled_ && emulation_params_.view_size == params.view_size && - emulation_params_.screen_position == params.screen_position && + emulation_params_.screen_type == params.screen_type && emulation_params_.device_scale_factor == params.device_scale_factor && emulation_params_.scale == params.scale && emulation_params_.viewport_offset == params.viewport_offset && @@ -235,11 +236,11 @@ device_metrics_enabled_ = true; web_view_->GetPage()->GetSettings().SetDeviceScaleAdjustment( - calculateDeviceScaleAdjustment(params.view_size.width, - params.view_size.height, + calculateDeviceScaleAdjustment(params.view_size.width(), + params.view_size.height(), params.device_scale_factor)); - if (params.screen_position == WebDeviceEmulationParams::kMobile) + if (params.screen_type == mojom::blink::EmulatedScreenType::kMobile) EnableMobileEmulation(); else DisableMobileEmulation();
diff --git a/third_party/blink/renderer/core/inspector/dev_tools_emulator.h b/third_party/blink/renderer/core/inspector/dev_tools_emulator.h index e208016..2f2e555 100644 --- a/third_party/blink/renderer/core/inspector/dev_tools_emulator.h +++ b/third_party/blink/renderer/core/inspector/dev_tools_emulator.h
@@ -7,9 +7,9 @@ #include <memory> #include "base/optional.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/platform/pointer_properties.h" #include "third_party/blink/public/platform/web_viewport_style.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/transforms/transformation_matrix.h" @@ -49,7 +49,7 @@ // Enables and/or sets the parameters for emulation. Returns the emulation // transform to be used as a result. - TransformationMatrix EnableDeviceEmulation(const WebDeviceEmulationParams&); + TransformationMatrix EnableDeviceEmulation(const DeviceEmulationParams&); // Disables emulation. void DisableDeviceEmulation(); @@ -106,7 +106,7 @@ bool device_metrics_enabled_; bool emulate_mobile_enabled_; - WebDeviceEmulationParams emulation_params_; + DeviceEmulationParams emulation_params_; struct ViewportOverride { FloatPoint position;
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc index b00c8d5..6f9fe7e 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -523,9 +523,11 @@ .build(); } -static bool FormDataToString(scoped_refptr<EncodedFormData> body, - size_t max_body_size, - String* content) { +static bool FormDataToString( + scoped_refptr<EncodedFormData> body, + size_t max_body_size, + protocol::Array<protocol::Network::PostDataEntry>* data_entries, + String* content) { *content = ""; if (!body || body->IsEmpty()) return false; @@ -540,6 +542,15 @@ if (max_body_size != 0 && body->SizeInBytes() > max_body_size) return true; + for (const auto& element : body->Elements()) { + auto data_entry = protocol::Network::PostDataEntry::create().build(); + auto bytes = protocol::Binary::fromSpan( + reinterpret_cast<const uint8_t*>(element.data_.data()), + element.data_.size()); + data_entry->setBytes(std::move(bytes)); + data_entries->push_back(std::move(data_entry)); + } + Vector<char> bytes; body->Flatten(bytes); *content = String::FromUTF8WithLatin1Fallback(bytes.data(), bytes.size()); @@ -550,8 +561,11 @@ BuildObjectForResourceRequest(const ResourceRequest& request, scoped_refptr<EncodedFormData> post_data, size_t max_body_size) { - String postData; - bool hasPostData = FormDataToString(post_data, max_body_size, &postData); + String data_string; + auto data_entries = + std::make_unique<protocol::Array<protocol::Network::PostDataEntry>>(); + bool has_post_data = FormDataToString(post_data, max_body_size, + data_entries.get(), &data_string); KURL url = request.Url(); // protocol::Network::Request doesn't have a separate referrer string member // like blink::ResourceRequest, so here we add ResourceRequest's referrer @@ -572,9 +586,11 @@ .build(); if (url.FragmentIdentifier()) result->setUrlFragment("#" + url.FragmentIdentifier()); - if (!postData.IsEmpty()) - result->setPostData(postData); - if (hasPostData) + if (!data_string.IsEmpty()) + result->setPostData(data_string); + if (data_entries->size()) + result->setPostDataEntries(std::move(data_entries)); + if (has_post_data) result->setHasPostData(true); return result; }
diff --git a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc index 30f63d4..cd29e15 100644 --- a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc
@@ -14,6 +14,7 @@ #include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h" #include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h" #include "third_party/blink/renderer/core/layout/ng/ng_fragment.h" +#include "third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h" #include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" @@ -570,8 +571,11 @@ // is not exactly correct. // TODO(dgrogan): Replace with a variant of ComputeReplacedSize that // ignores min-width, width, max-width. + MinMaxSizesInput input(child_percentage_size_.block_size, + MinMaxSizesType::kContent); flex_base_border_box = - child.GetLayoutBox()->PreferredLogicalWidths().max_size; + ComputeMinAndMaxContentContribution(Style(), child, input) + .sizes.max_size; } else { flex_base_border_box = MinMaxSizesFunc(MinMaxSizesType::kContent).sizes.max_size;
diff --git a/third_party/blink/renderer/core/layout/scrollbars_test.cc b/third_party/blink/renderer/core/layout/scrollbars_test.cc index e573778..f6158f1 100644 --- a/third_party/blink/renderer/core/layout/scrollbars_test.cc +++ b/third_party/blink/renderer/core/layout/scrollbars_test.cc
@@ -1398,8 +1398,8 @@ DCHECK(!div_scrollable->VerticalScrollbar()->GetTheme().IsMockTheme()); // Turn on mobile emulator. - WebDeviceEmulationParams params; - params.screen_position = WebDeviceEmulationParams::kMobile; + DeviceEmulationParams params; + params.screen_type = mojom::EmulatedScreenType::kMobile; WebView().EnableDeviceEmulation(params); // For root Scrollbar, mobile emulator will change them to page VisualViewport @@ -1652,8 +1652,8 @@ DCHECK(!div_scrollable->VerticalScrollbar()->GetTheme().IsMockTheme()); // Turn on mobile emulator. - WebDeviceEmulationParams params; - params.screen_position = WebDeviceEmulationParams::kMobile; + DeviceEmulationParams params; + params.screen_type = mojom::EmulatedScreenType::kMobile; WebView().EnableDeviceEmulation(params); // For root Scrollbar, mobile emulator will change them to page VisualViewport
diff --git a/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc b/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc index cb23d50..b27e7bd 100644 --- a/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc +++ b/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc
@@ -27,10 +27,10 @@ WebFeature::kClientHintsUA, WebFeature::kClientHintsUAArch, WebFeature::kClientHintsUAPlatform, - WebFeature::kClientHintsUAPlatformVersion, WebFeature::kClientHintsUAModel, WebFeature::kClientHintsUAMobile, WebFeature::kClientHintsUAFullVersion, + WebFeature::kClientHintsUAPlatformVersion, }; static_assert(static_cast<int>(network::mojom::WebClientHintsType::kMaxValue) +
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc b/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc index cdbe271b..4e47cec 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc
@@ -28,6 +28,7 @@ #include "third_party/blink/renderer/core/animation/scroll_timeline.h" #include "third_party/blink/renderer/core/animation/worklet_animation_controller.h" +#include "third_party/blink/renderer/core/layout/layout_embedded_content.h" #include "third_party/blink/renderer/core/layout/layout_video.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/page/page.h" @@ -386,6 +387,16 @@ true; } } + + // If this is an iframe whose content document is composited, then we can't + // squash layers painted after the iframe with layers painted before it. + if (layer->GetLayoutObject().IsLayoutEmbeddedContent() && + ToLayoutEmbeddedContent(layer->GetLayoutObject()) + .ContentDocumentIsCompositing()) { + squashing_state.have_assigned_backings_to_entire_squashing_layer_subtree = + false; + } + layer->ClearNeedsCompositingLayerAssignment(); }
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc b/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc index dc276dd..97e640c 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc
@@ -11,6 +11,10 @@ namespace blink { class CompositedLayerAssignerTest : public RenderingTest { + public: + CompositedLayerAssignerTest() + : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {} + private: void SetUp() override { EnableCompositing(); @@ -97,4 +101,23 @@ EXPECT_EQ(kPaintsIntoOwnBacking, squashed->GetCompositingState()); } +TEST_F(CompositedLayerAssignerTest, + SquashingAcrossCompositedInnerDocumentDisallowed) { + SetBodyInnerHTML(R"HTML( + <div id="bottom" style="position: absolute; will-change: transform">Bottom</div> + <div id="middle" style="position: absolute"> + <iframe style="border: 10px solid magenta"></iframe> + </div> + <div id="top" style="position: absolute; width: 200px; height: 200px; background: green;">Top</div> + )HTML"); + SetChildFrameHTML(R"HTML( + <style>body {will-change: transform; background: blue}</style> + )HTML"); + LocalFrameView* frame_view = GetDocument().View(); + frame_view->UpdateAllLifecyclePhases(DocumentUpdateReason::kTest); + PaintLayer* top = + ToLayoutBoxModelObject(GetLayoutObjectByElementId("top"))->Layer(); + EXPECT_EQ(kPaintsIntoOwnBacking, top->GetCompositingState()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc b/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc index 160768ef..faf4b89 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc
@@ -603,8 +603,14 @@ // Layer assignment is needed for allocating or removing composited // layers related to this PaintLayer; hence the below conditions. if (reasons_to_composite || layer->GetCompositingState() != kNotComposited || - layer->LostGroupedMapping()) + layer->LostGroupedMapping()) { layer->SetNeedsCompositingLayerAssignment(); + } else if (contains_composited_layer) { + // If this is an iframe whose content document is composited, then we need + // CompositedLayerAssigner to process this layer, to ensure that we don't + // squash layers painted before the iframe with layers painted after it. + layer->PropagateDescendantNeedsCompositingLayerAssignment(); + } // At this point we have finished collecting all reasons to composite this // layer.
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index 6c1cf2e..0e0b2e0 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -2360,7 +2360,10 @@ void PaintLayer::SetNeedsCompositingLayerAssignment() { needs_compositing_layer_assignment_ = true; + PropagateDescendantNeedsCompositingLayerAssignment(); +} +void PaintLayer::PropagateDescendantNeedsCompositingLayerAssignment() { for (PaintLayer* curr = CompositingContainer(); curr && !curr->StackingDescendantNeedsCompositingLayerAssignment(); curr = curr->CompositingContainer()) {
diff --git a/third_party/blink/renderer/core/paint/paint_layer.h b/third_party/blink/renderer/core/paint/paint_layer.h index 3e11f92..b54ce2a 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.h +++ b/third_party/blink/renderer/core/paint/paint_layer.h
@@ -1106,6 +1106,7 @@ void SetNeedsCompositingLayerAssignment(); void ClearNeedsCompositingLayerAssignment(); + void PropagateDescendantNeedsCompositingLayerAssignment(); bool NeedsCompositingLayerAssignment() const { return needs_compositing_layer_assignment_;
diff --git a/third_party/blink/renderer/core/testing/internals.cc b/third_party/blink/renderer/core/testing/internals.cc index e6d423d8..10b1b47b 100644 --- a/third_party/blink/renderer/core/testing/internals.cc +++ b/third_party/blink/renderer/core/testing/internals.cc
@@ -32,12 +32,12 @@ #include "base/optional.h" #include "cc/layers/picture_layer.h" #include "gpu/command_buffer/client/gles2_interface.h" +#include "third_party/blink/public/common/widget/device_emulation_params.h" #include "third_party/blink/public/mojom/devtools/inspector_issue.mojom-blink.h" #include "third_party/blink/public/mojom/favicon/favicon_url.mojom-blink.h" #include "third_party/blink/public/mojom/input/focus_type.mojom-blink.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_graphics_context_3d_provider.h" -#include "third_party/blink/public/web/web_device_emulation_params.h" #include "third_party/blink/renderer/bindings/core/v8/script_function.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" @@ -3447,7 +3447,7 @@ "The document's page cannot be retrieved."); return; } - WebDeviceEmulationParams params; + DeviceEmulationParams params; params.scale = scale; page->GetChromeClient().GetWebView()->EnableDeviceEmulation(params); }
diff --git a/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl b/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl index ff5939b6..505b2a85 100644 --- a/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl +++ b/third_party/blink/renderer/modules/native_file_system/file_system_directory_handle.idl
@@ -10,6 +10,14 @@ RuntimeEnabled=NativeFileSystem, ImplementedAs=NativeFileSystemDirectoryHandle ] interface FileSystemDirectoryHandle : FileSystemHandle { + // TODO(https://crbug.com/1087157): This interface defines an async + // iterable, however that isn't supported yet by the bindings. So for now + // just explicitly define what an async iterable definition implies. + //async iterable<USVString, FileSystemHandle>; + NativeFileSystemDirectoryIterator entries(); + NativeFileSystemDirectoryIterator keys(); + NativeFileSystemDirectoryIterator values(); + [CallWith=ScriptState, RuntimeEnabled=LegacyNativeFileSystem, ImplementedAs=getFileHandle] Promise<FileSystemFileHandle> getFile(USVString name, optional FileSystemGetFileOptions options = {}); [CallWith=ScriptState, RuntimeEnabled=LegacyNativeFileSystem, ImplementedAs=getDirectoryHandle] @@ -18,7 +26,7 @@ [CallWith=ScriptState] Promise<FileSystemFileHandle> getFileHandle(USVString name, optional FileSystemGetFileOptions options = {}); [CallWith=ScriptState] Promise<FileSystemDirectoryHandle> getDirectoryHandle(USVString name, optional FileSystemGetDirectoryOptions options = {}); - [CallWith=ScriptState] object getEntries(); + [CallWith=ScriptState, RuntimeEnabled=LegacyNativeFileSystem] object getEntries(); [CallWith=ScriptState] Promise<void> removeEntry(USVString name, optional FileSystemRemoveOptions options = {});
diff --git a/third_party/blink/renderer/modules/native_file_system/idls.gni b/third_party/blink/renderer/modules/native_file_system/idls.gni index c2d514a..6832fcfb 100644 --- a/third_party/blink/renderer/modules/native_file_system/idls.gni +++ b/third_party/blink/renderer/modules/native_file_system/idls.gni
@@ -23,7 +23,6 @@ "file_system_remove_options.idl", "get_system_directory_options.idl", "open_file_picker_options.idl", - "native_file_system_directory_iterator_entry.idl", "save_file_picker_options.idl", "write_params.idl", ]
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc index 9c6ef20..1bebd1f 100644 --- a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc +++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc
@@ -12,6 +12,7 @@ #include "third_party/blink/public/mojom/native_file_system/native_file_system_manager.mojom-blink.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_file_system_directory_handle.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_file_system_get_directory_options.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_file_system_get_file_options.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_file_system_remove_options.h" @@ -43,6 +44,24 @@ DCHECK(mojo_ptr_.is_bound()); } +NativeFileSystemDirectoryIterator* NativeFileSystemDirectoryHandle::entries() { + return MakeGarbageCollected<NativeFileSystemDirectoryIterator>( + this, NativeFileSystemDirectoryIterator::Mode::kKeyValue, + GetExecutionContext()); +} + +NativeFileSystemDirectoryIterator* NativeFileSystemDirectoryHandle::keys() { + return MakeGarbageCollected<NativeFileSystemDirectoryIterator>( + this, NativeFileSystemDirectoryIterator::Mode::kKey, + GetExecutionContext()); +} + +NativeFileSystemDirectoryIterator* NativeFileSystemDirectoryHandle::values() { + return MakeGarbageCollected<NativeFileSystemDirectoryIterator>( + this, NativeFileSystemDirectoryIterator::Mode::kValue, + GetExecutionContext()); +} + ScriptPromise NativeFileSystemDirectoryHandle::getFileHandle( ScriptState* script_state, const String& name, @@ -119,7 +138,8 @@ ScriptValue NativeFileSystemDirectoryHandle::getEntries( ScriptState* script_state) { auto* iterator = MakeGarbageCollected<NativeFileSystemDirectoryIterator>( - this, ExecutionContext::From(script_state)); + this, NativeFileSystemDirectoryIterator::Mode::kValue, + ExecutionContext::From(script_state)); auto* isolate = script_state->GetIsolate(); auto context = script_state->GetContext(); v8::Local<v8::Object> result = v8::Object::New(isolate);
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h index ffddfc8..6e60c09 100644 --- a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h +++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h
@@ -15,6 +15,7 @@ class FileSystemGetFileOptions; class FileSystemRemoveOptions; class GetSystemDirectoryOptions; +class NativeFileSystemDirectoryIterator; class NativeFileSystemDirectoryHandle final : public NativeFileSystemHandle { DEFINE_WRAPPERTYPEINFO(); @@ -25,6 +26,11 @@ const String& name, mojo::PendingRemote<mojom::blink::NativeFileSystemDirectoryHandle>); + // FileSystemDirectoryHandle IDL interface: + NativeFileSystemDirectoryIterator* entries(); + NativeFileSystemDirectoryIterator* keys(); + NativeFileSystemDirectoryIterator* values(); + bool isDirectory() const override { return true; } ScriptPromise getFileHandle(ScriptState*,
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.cc b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.cc index b665fa8e..ad8ccda 100644 --- a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.cc +++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.cc
@@ -4,8 +4,9 @@ #include "third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.h" +#include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_native_file_system_directory_iterator_entry.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/fileapi/file_error.h" #include "third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h" @@ -17,8 +18,10 @@ NativeFileSystemDirectoryIterator::NativeFileSystemDirectoryIterator( NativeFileSystemDirectoryHandle* directory, + Mode mode, ExecutionContext* execution_context) : ExecutionContextClient(execution_context), + mode_(mode), directory_(directory), receiver_(this, execution_context) { directory_->MojoHandle()->GetEntries(receiver_.BindNewPipeAndPassRemote( @@ -35,10 +38,25 @@ } if (!entries_.IsEmpty()) { - NativeFileSystemDirectoryIteratorEntry* result = - NativeFileSystemDirectoryIteratorEntry::Create(); - result->setValue(entries_.TakeFirst()); - return ScriptPromise::Cast(script_state, ToV8(result, script_state)); + NativeFileSystemHandle* handle = entries_.TakeFirst(); + ScriptValue result; + switch (mode_) { + case Mode::kKey: + result = V8IteratorResult(script_state, handle->name()); + break; + case Mode::kValue: + result = V8IteratorResult(script_state, handle); + break; + case Mode::kKeyValue: + HeapVector<ScriptValue, 2> keyvalue; + keyvalue.push_back(ScriptValue(script_state->GetIsolate(), + ToV8(handle->name(), script_state))); + keyvalue.push_back(ScriptValue(script_state->GetIsolate(), + ToV8(handle, script_state))); + result = V8IteratorResult(script_state, keyvalue); + break; + } + return ScriptPromise::Cast(script_state, result); } if (waiting_for_more_entries_) { @@ -47,10 +65,7 @@ return pending_next_->Promise(); } - NativeFileSystemDirectoryIteratorEntry* result = - NativeFileSystemDirectoryIteratorEntry::Create(); - result->setDone(true); - return ScriptPromise::Cast(script_state, ToV8(result, script_state)); + return ScriptPromise::Cast(script_state, V8IteratorResultDone(script_state)); } void NativeFileSystemDirectoryIterator::Trace(Visitor* visitor) const {
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.h b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.h index b265f53..adbbb2b 100644 --- a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.h +++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.h
@@ -28,7 +28,11 @@ USING_GARBAGE_COLLECTED_MIXIN(NativeFileSystemDirectoryIterator); public: + // Should this iterator returns keys, values or both? + enum Mode { kKey, kValue, kKeyValue }; + NativeFileSystemDirectoryIterator(NativeFileSystemDirectoryHandle* directory, + Mode mode, ExecutionContext* execution_context); ScriptPromise next(ScriptState*); @@ -40,6 +44,7 @@ Vector<mojom::blink::NativeFileSystemEntryPtr> entries, bool has_more_entries) override; + Mode mode_; mojom::blink::NativeFileSystemErrorPtr error_; bool waiting_for_more_entries_ = true; HeapDeque<Member<NativeFileSystemHandle>> entries_;
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator_entry.idl b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator_entry.idl deleted file mode 100644 index 833cd94..0000000 --- a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator_entry.idl +++ /dev/null
@@ -1,11 +0,0 @@ -// 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. - -// Used by NativeFileSystemDirectoryIterator to represents results of next() calls. -// https://github.com/WICG/writable-files/blob/master/EXPLAINER.md -// https://www.ecma-international.org/ecma-262/9.0/index.html#sec-iteratorresult-interface -dictionary NativeFileSystemDirectoryIteratorEntry { - FileSystemHandle value; - boolean done = false; -};
diff --git a/third_party/blink/renderer/modules/nfc/ndef_reader.cc b/third_party/blink/renderer/modules/nfc/ndef_reader.cc index b83d27aa7..df9dfaa 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_reader.cc +++ b/third_party/blink/renderer/modules/nfc/ndef_reader.cc
@@ -37,6 +37,7 @@ constexpr char kNotSupportedOrPermissionDenied[] = "WebNFC feature is unavailable or permission denied."; +constexpr char kInvalidStateErrorMessage[] = "A scan() operation is ongoing."; } // namespace // static @@ -93,21 +94,27 @@ return ScriptPromise(); } - // With the note in - // https://w3c.github.io/web-nfc/#the-ndefreader-and-ndefwriter-objects, - // successive invocations of NDEFReader.scan() with new options should replace - // existing filters. So stop current reading for this case. + if (has_pending_scan_request_) { + exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, + kInvalidStateErrorMessage); + return ScriptPromise(); + } + has_pending_scan_request_ = true; + + // https://github.com/w3c/web-nfc/issues/592 + // reject scan promise when there's already an ongoing scan. if (GetNfcProxy()->IsReading(this)) { - Abort(signal_.Get()); + exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, + kInvalidStateErrorMessage); + return ScriptPromise(); } resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state); - // 8. If reader.[[Signal]] is not null, then add the following abort steps to - // reader.[[Signal]]: + // 8. If reader.[[Signal]] is not null, then add the following abort steps + // to reader.[[Signal]]: if (options->hasSignal()) { - signal_ = options->signal(); - signal_->AddAlgorithm(WTF::Bind(&NDEFReader::Abort, WrapPersistent(this), - WrapPersistent(options->signal()))); + options->signal()->AddAlgorithm( + WTF::Bind(&NDEFReader::Abort, WrapPersistent(this))); } GetPermissionService()->RequestPermission( @@ -130,16 +137,20 @@ void NDEFReader::OnRequestPermission(const NDEFScanOptions* options, PermissionStatus status) { - if (!resolver_) + if (!resolver_) { + has_pending_scan_request_ = false; return; + } if (status != PermissionStatus::GRANTED) { + has_pending_scan_request_ = false; resolver_->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kNotAllowedError, "NFC permission request denied.")); resolver_.Clear(); return; } if (options->hasSignal() && options->signal()->aborted()) { + has_pending_scan_request_ = false; resolver_->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kAbortError, "The NFC operation was cancelled.")); resolver_.Clear(); @@ -157,6 +168,7 @@ void NDEFReader::OnScanRequestCompleted( device::mojom::blink::NDEFErrorPtr error) { + has_pending_scan_request_ = false; if (!resolver_) return; @@ -173,7 +185,6 @@ void NDEFReader::Trace(Visitor* visitor) const { visitor->Trace(permission_service_); visitor->Trace(resolver_); - visitor->Trace(signal_); EventTargetWithInlineData::Trace(visitor); ActiveScriptWrappable::Trace(visitor); ExecutionContextLifecycleObserver::Trace(visitor); @@ -217,14 +228,7 @@ GetNfcProxy()->StopReading(this); } -void NDEFReader::Abort(AbortSignal* signal) { - // In the case of successive invocations of NDEFReader.scan() with - // different signals, we should make sure aborting on previous signal - // won't abort current reading. - // If this is not triggered by the current signal, just ignore it. - if (signal && signal != signal_) - return; - +void NDEFReader::Abort() { if (resolver_) { resolver_->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kAbortError, "The NFC operation was cancelled."));
diff --git a/third_party/blink/renderer/modules/nfc/ndef_reader.h b/third_party/blink/renderer/modules/nfc/ndef_reader.h index cfb0aa6d..c7608481 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_reader.h +++ b/third_party/blink/renderer/modules/nfc/ndef_reader.h
@@ -18,7 +18,6 @@ namespace blink { -class AbortSignal; class ExecutionContext; class NFCProxy; class NDEFScanOptions; @@ -61,7 +60,7 @@ // ExecutionContextLifecycleObserver overrides. void ContextDestroyed() override; - void Abort(AbortSignal* signal); + void Abort(); NFCProxy* GetNfcProxy() const; @@ -79,11 +78,8 @@ // case the callback passed to Watch() won't be called and // mojo::WrapCallbackWithDefaultInvokeIfNotRun() is forbidden in Blink. Member<ScriptPromiseResolver> resolver_; - - // Currently AbortSignal has no method to remove an algorithm so this - // field tracks the most recently configured AbortSignal so that others - // can be ignored. - Member<AbortSignal> signal_; + // To reject if there is already an ongoing scan. + bool has_pending_scan_request_ = false; }; } // namespace blink
diff --git a/third_party/blink/tools/blinkpy/w3c/android_wpt_expectations_updater_unittest.py b/third_party/blink/tools/blinkpy/w3c/android_wpt_expectations_updater_unittest.py index 9a7eeceec..5fc3016 100644 --- a/third_party/blink/tools/blinkpy/w3c/android_wpt_expectations_updater_unittest.py +++ b/third_party/blink/tools/blinkpy/w3c/android_wpt_expectations_updater_unittest.py
@@ -37,6 +37,7 @@ 'crbug.com/1050754 external/wpt/cat.html [ Failure ]\n' 'external/wpt/dog.html [ Crash Timeout ]\n' 'crbug.com/6789043 external/wpt/van.html [ Failure ]\n' + 'external/wpt/unexpected_pass.html [ Failure ]\n' '\n' '# This comment will not be deleted\n' 'crbug.com/111111 external/wpt/hello_world.html [ Crash ]\n') @@ -105,6 +106,11 @@ 'actual': 'CRASH CRASH TIMEOUT', 'is_unexpected': True, }, + 'unexpected_pass.html': { + 'expected': 'FAIL', + 'actual': 'PASS', + 'is_unexpected': True + }, 'dog.html': { 'expected': 'SKIP', 'actual': 'SKIP', @@ -116,7 +122,8 @@ updater = AndroidWPTExpectationsUpdater( host, ['-vvv', '--android-product', ANDROID_WEBVIEW, '--clean-up-test-expectations', - '--clean-up-affected-tests-only']) + '--clean-up-affected-tests-only', + '--include-unexpected-pass']) updater.git_cl = MockGitCL(host, { Build('MOCK Android Pie', 123): TryJobStatus('COMPLETED', 'FAILURE')}) @@ -137,6 +144,7 @@ 'crbug.com/1050754 external/wpt/ghi.html [ Timeout ]\n' 'crbug.com/1111111 crbug.com/1050754' ' external/wpt/jkl.html [ Failure ]\n' + 'crbug.com/1050754 external/wpt/unexpected_pass.html [ Failure Pass ]\n' 'crbug.com/6789043 external/wpt/van.html [ Failure ]\n' 'external/wpt/www.html [ Crash Failure ]\n' '\n' @@ -194,6 +202,11 @@ 'actual': 'CRASH CRASH TIMEOUT', 'is_unexpected': True, }, + 'unexpected_pass.html': { + 'expected': 'FAIL', + 'actual': 'PASS', + 'is_unexpected': True, + }, 'new.html': { 'expected': 'PASS', 'actual': 'CRASH CRASH FAIL', @@ -205,7 +218,8 @@ updater = AndroidWPTExpectationsUpdater( host, ['-vvv', '--android-product', ANDROID_WEBLAYER, '--clean-up-test-expectations', - '--clean-up-affected-tests-only']) + '--clean-up-affected-tests-only', + '--include-unexpected-pass']) updater.git_cl = MockGitCL(host, { Build('MOCK Android Weblayer - Pie', 123): TryJobStatus('COMPLETED', 'FAILURE')}) @@ -227,6 +241,7 @@ 'crbug.com/1111111 crbug.com/1050754' ' external/wpt/jkl.html [ Failure ]\n' 'crbug.com/1050754 external/wpt/new.html [ Failure Crash ]\n' + 'crbug.com/1050754 external/wpt/unexpected_pass.html [ Failure Pass ]\n' 'crbug.com/6789043 external/wpt/van.html [ Failure ]\n' 'external/wpt/www.html [ Crash Failure ]\n' '\n' @@ -273,6 +288,11 @@ 'actual': 'SKIP', 'is_unexpected': True, }, + 'unexpected_pass.html': { + 'expected': 'FAIL', + 'actual': 'PASS', + 'is_unexpected': True + }, }, }, step_name=WEBLAYER_WPT_STEP + ' (with patch)'), step_name=WEBLAYER_WPT_STEP + ' (with patch)') @@ -295,6 +315,11 @@ 'expected': 'SKIP', 'actual': 'SKIP', }, + 'unexpected_pass.html': { + 'expected': 'FAIL', + 'actual': 'PASS', + 'is_unexpected': True + }, }, }, step_name=WEBVIEW_WPT_STEP + ' (with patch)'), step_name=WEBVIEW_WPT_STEP + ' (with patch)') @@ -318,6 +343,11 @@ 'actual': 'SKIP', 'is_unexpected': True, }, + 'unexpected_pass.html': { + 'expected': 'FAIL', + 'actual': 'PASS', + 'is_unexpected': True + }, }, }, step_name=CHROME_ANDROID_WPT_STEP + ' (with patch)'), step_name=CHROME_ANDROID_WPT_STEP + ' (with patch)') @@ -325,6 +355,7 @@ host, ['-vvv', '--clean-up-test-expectations', '--clean-up-affected-tests-only', + '--include-unexpected-pass', '--android-product', ANDROID_WEBLAYER, '--android-product', CHROME_ANDROID, '--android-product', ANDROID_WEBVIEW]) @@ -360,6 +391,7 @@ 'crbug.com/1050754 external/wpt/def.html [ Crash ]\n' 'external/wpt/dog.html [ Crash Timeout ]\n' 'crbug.com/1111111 external/wpt/jkl.html [ Failure ]\n' + 'crbug.com/1050754 external/wpt/unexpected_pass.html [ Failure Pass ]\n' 'crbug.com/6789043 external/wpt/wagon.html [ Failure ]\n' 'crbug.com/1050754 external/wpt/weblayer_only.html [ Failure Crash ]\n' 'external/wpt/www.html [ Crash Failure ]\n' @@ -379,6 +411,7 @@ 'crbug.com/1050754 external/wpt/def.html [ Crash ]\n' 'external/wpt/dog.html [ Crash Timeout ]\n' 'crbug.com/1111111 external/wpt/jkl.html [ Failure ]\n' + 'crbug.com/1050754 external/wpt/unexpected_pass.html [ Failure Pass ]\n' 'crbug.com/6789043 external/wpt/wagon.html [ Failure ]\n' 'crbug.com/1050754 external/wpt/webview_only.html [ Timeout ]\n' 'external/wpt/www.html [ Crash Failure ]\n' @@ -400,6 +433,7 @@ 'external/wpt/dog.html [ Crash Timeout ]\n' 'crbug.com/1111111 crbug.com/1050754' ' external/wpt/jkl.html [ Failure ]\n' + 'crbug.com/1050754 external/wpt/unexpected_pass.html [ Failure Pass ]\n' 'crbug.com/6789043 external/wpt/wagon.html [ Failure ]\n' 'external/wpt/www.html [ Crash Failure ]\n' '\n'
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py index b5807674..91efdea 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py
@@ -44,7 +44,6 @@ self.git_cl = GitCL(host) self.git = self.host.git(self.finder.chromium_base()) self.configs_with_no_results = [] - self.configs_with_all_pass = [] self.patchset = None # Get options from command line arguments. @@ -83,6 +82,11 @@ log_level = logging.DEBUG if self.options.verbose else logging.INFO configure_logging(logging_level=log_level, include_time=True) + if not(self.options.android_product or + self.options.update_android_expectations_only): + assert not self.options.include_unexpected_pass, ( + 'Command line argument --include-unexpected-pass is not ' + 'supported in desktop mode.') self.patchset = self.options.patchset if (self.options.clean_up_test_expectations or @@ -132,6 +136,12 @@ '--android-product', action='append', default=[], help='Android products whose baselines will be updated.', choices=PRODUCTS) + parser.add_argument( + '--include-unexpected-pass', + action='store_true', + help='Adds Pass to tests with failure expectations. ' + 'This command line argument can be used to mark tests ' + 'as flaky.') def update_expectations(self): """Downloads text new baselines and adds test expectations lines. @@ -153,9 +163,8 @@ # Here we build up a dict of failing test results for all platforms. test_expectations = {} for build, job_status in build_to_status.iteritems(): - if job_status.result == 'SUCCESS': - self.configs_with_all_pass.extend( - self.get_builder_configs(build)) + if (job_status.result == 'SUCCESS' and + not self.options.include_unexpected_pass): continue result_dicts = self.get_failing_results_dicts(build) for result_dict in result_dicts: @@ -236,13 +245,13 @@ self.configs_with_no_results.extend(self.get_builder_configs(build)) return [] - failing_test_results = [] + unexpected_test_results = [] for results_set in test_results_list: results_dict = self.generate_failing_results_dict( build, results_set) if results_dict: - failing_test_results.append(results_dict) - return failing_test_results + unexpected_test_results.append(results_dict) + return unexpected_test_results def _get_web_test_results(self, build): """Gets web tests results for a builder. @@ -291,9 +300,6 @@ raise ScriptError('No configuration was found for builder and web test' ' step combination ') config = configs[0] - if config in self.configs_with_all_pass: - return {} - for result in web_test_results.didnt_run_as_expected_results(): # TODO(rmhasan) If a test fails unexpectedly then it runs multiple # times until, it passes or a retry limit is reached. Even though @@ -301,7 +307,11 @@ # creating test expectations for. Maybe we should add a mode # which creates expectations for tests that are flaky but still # pass in a web test step. - if result.did_pass(): + + # Create flaky expectations for flaky tests on Android. In order to + # do this we should add 'Pass' to all tests with failing + # expectations that pass in the patchset's try job. + if result.did_pass() and not self.options.include_unexpected_pass: continue test_name = result.test_name()
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py index eb14d26..fa8964d 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py
@@ -157,6 +157,17 @@ 'crbug.com/626703 [ Mac10.10 ] external/wpt/test/path.html [ Timeout ]\n' ) + def test_cmd_arg_include_unexpected_pass_raieses_exception(self): + host = self.mock_host() + expectations_path = \ + host.port_factory.get().path_to_generic_test_expectations_file() + host.filesystem.write_text_file(expectations_path, + WPTExpectationsUpdater.MARKER_COMMENT + '\n') + updater = WPTExpectationsUpdater(host, args=['--include-unexpected-pass']) + with self.assertRaises(AssertionError) as ctx: + updater.run() + self.assertIn('--include-unexpected-pass', str(ctx.exception)) + def test_get_failing_results_dict_only_passing_results(self): host = self.mock_host() host.results_fetcher.set_results( @@ -1039,8 +1050,6 @@ } } tests_to_rebaseline, _ = updater.get_tests_to_rebaseline(two) - # external/wpt/test/zzzz.html is another possible candidate, but it - # is not listed in the results dict, so it shall not be rebaselined. self.assertEqual(tests_to_rebaseline, ['external/wpt/test/path.html']) def test_get_test_to_rebaseline_does_not_return_ref_tests(self):
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 3304e881..19efbc50 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -6941,3 +6941,7 @@ crbug.com/1107634 [ Mac10.10 ] virtual/text-antialias/selection/select-ligature-vertical-1.html [ Pass Failure ] crbug.com/1107634 [ Mac10.10 ] virtual/text-antialias/selection/select-ligature-vertical-2.html [ Pass Failure ] crbug.com/1107634 [ Mac10.10 ] virtual/text-antialias/selection/select-ligature-vertical-3.html [ Pass Failure ] + +# Sheriff 2020-07-21 +crbug.com/1107923 [ Mac10.15 ] inspector-protocol/debugger/wasm-streaming-url.js [ Pass Failure ] +
diff --git a/third_party/blink/web_tests/external/wpt/css/css-flexbox/percentage-max-height-003.html b/third_party/blink/web_tests/external/wpt/css/css-flexbox/percentage-max-height-003.html new file mode 100644 index 0000000..eaab8a3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-flexbox/percentage-max-height-003.html
@@ -0,0 +1,57 @@ +<!doctype html> +<link rel="author" title="David Grogan" href="mailto:dgrogan@chromium.org"> +<link rel="help" href="https://drafts.csswg.org/css-flexbox/#definite-sizes"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<link rel="bookmark" href="https://crbug.com/1107604"> +<meta name="assert" content="Replaced children with % max-height are sized correctly when they are deeply nested flex items with imposed definite heights." /> + +<style> +#reference-overlapped-red { + position: absolute; + background-color: red; + width: 100px; + height: 100px; + z-index: -1; +} + +#outer-flexbox { + display: flex; + width: 200px; + height: 200px; + flex-direction: column; + align-items: flex-start; +} + +#middle-flexbox { + display: flex; + height: 50%; + /* This needs to be stretched for repro */ + align-items: stretch; + min-height: 0px; +} + +#inner-flexbox { + display: flex; + align-items: flex-start; + min-width: 0px; +} + +img { + max-height: 100%; + min-width: 0px; +} +</style> + +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div id="reference-overlapped-red"></div> + +<div id=outer-flexbox> + <div id=middle-flexbox> + <div id=inner-flexbox> + <!-- This is a 400x400 green square. It's inline so that there is no + raciness when an image resource loads, which affects chrome's behavior + on this test. --> + <img src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 400' width='400' height='400'><rect width='400' height='400' fill='green'/></svg>"> + </div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-pseudo/parsing/marker-supported-properties-in-animation-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-pseudo/parsing/marker-supported-properties-in-animation-expected.txt index be3a6bf..8926c19 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-pseudo/parsing/marker-supported-properties-in-animation-expected.txt +++ b/third_party/blink/web_tests/external/wpt/css/css-pseudo/parsing/marker-supported-properties-in-animation-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 60 tests; 53 PASS, 7 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 60 tests; 54 PASS, 6 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Animation of font in ::marker PASS Animation of font-family in ::marker PASS Animation of font-feature-settings in ::marker @@ -18,7 +18,7 @@ PASS Animation of font-weight in ::marker FAIL Animation of white-space in ::marker assert_equals: expected "nowrap" but got "pre" PASS Animation of color in ::marker -FAIL Animation of text-combine-upright in ::marker assert_equals: expected "none" but got "all" +PASS Animation of text-combine-upright in ::marker PASS Animation of unicode-bidi in ::marker PASS Animation of direction in ::marker PASS Animation of content in ::marker
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any-expected.txt b/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any-expected.txt index 48bb1aab..fd08a2bb 100644 --- a/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any-expected.txt +++ b/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any-expected.txt
@@ -39,7 +39,7 @@ PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object's "constructor" property PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object's @@unscopables property -FAIL FileSystemDirectoryHandle interface: async iterable<USVString, FileSystemHandle> Cannot read property 'writable' of undefined +FAIL FileSystemDirectoryHandle interface: async iterable<USVString, FileSystemHandle> assert_equals: entries method should be the same as @@asyncIterator method expected function "function entries() { [native code] }" but got function "function entries() { [native code] }" PASS FileSystemDirectoryHandle interface: operation getFileHandle(USVString, optional FileSystemGetFileOptions) PASS FileSystemDirectoryHandle interface: operation getDirectoryHandle(USVString, optional FileSystemGetDirectoryOptions) PASS FileSystemDirectoryHandle interface: operation removeEntry(USVString, optional FileSystemRemoveOptions)
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any.worker-expected.txt index 78b28e0..0b3ae0d 100644 --- a/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any.worker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/native-file-system/idlharness.https.any.worker-expected.txt
@@ -39,7 +39,7 @@ PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object's "constructor" property PASS FileSystemDirectoryHandle interface: existence and properties of interface prototype object's @@unscopables property -FAIL FileSystemDirectoryHandle interface: async iterable<USVString, FileSystemHandle> Cannot read property 'writable' of undefined +FAIL FileSystemDirectoryHandle interface: async iterable<USVString, FileSystemHandle> assert_equals: entries method should be the same as @@asyncIterator method expected function "function entries() { [native code] }" but got function "function entries() { [native code] }" PASS FileSystemDirectoryHandle interface: operation getFileHandle(USVString, optional FileSystemGetFileOptions) PASS FileSystemDirectoryHandle interface: operation getDirectoryHandle(USVString, optional FileSystemGetDirectoryOptions) PASS FileSystemDirectoryHandle interface: operation removeEntry(USVString, optional FileSystemRemoveOptions)
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/native_FileSystemDirectoryHandle-getEntries-manual.https.html b/third_party/blink/web_tests/external/wpt/native-file-system/native_FileSystemDirectoryHandle-iteration-manual.https.html similarity index 82% rename from third_party/blink/web_tests/external/wpt/native-file-system/native_FileSystemDirectoryHandle-getEntries-manual.https.html rename to third_party/blink/web_tests/external/wpt/native-file-system/native_FileSystemDirectoryHandle-iteration-manual.https.html index 858bf02..10d89109 100644 --- a/third_party/blink/web_tests/external/wpt/native-file-system/native_FileSystemDirectoryHandle-getEntries-manual.https.html +++ b/third_party/blink/web_tests/external/wpt/native-file-system/native_FileSystemDirectoryHandle-iteration-manual.https.html
@@ -7,4 +7,4 @@ <script src="/resources/testdriver-vendor.js"></script> <script src="resources/test-helpers.js"></script> <script src="resources/native-fs-test-helpers.js"></script> -<script src="script-tests/FileSystemDirectoryHandle-getEntries.js"></script> +<script src="script-tests/FileSystemDirectoryHandle-iteration.js"></script>
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/resources/messaging-serialize-helpers.js b/third_party/blink/web_tests/external/wpt/native-file-system/resources/messaging-serialize-helpers.js index b4d41aa..3ef347f 100644 --- a/third_party/blink/web_tests/external/wpt/native-file-system/resources/messaging-serialize-helpers.js +++ b/third_party/blink/web_tests/external/wpt/native-file-system/resources/messaging-serialize-helpers.js
@@ -77,7 +77,7 @@ // Serialize the contents of the directory. const serialized_files = []; const serialized_directories = []; - for await (const child_handle of directory_handle.getEntries()) { + for await (const child_handle of directory_handle.values()) { const serialized_child_handle = await serialize_handle(child_handle); if (child_handle.kind === "directory") { serialized_directories.push(serialized_child_handle);
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/resources/native-fs-test-helpers.js b/third_party/blink/web_tests/external/wpt/native-file-system/resources/native-fs-test-helpers.js index 231bc067..cd1613ea 100644 --- a/third_party/blink/web_tests/external/wpt/native-file-system/resources/native-fs-test-helpers.js +++ b/third_party/blink/web_tests/external/wpt/native-file-system/resources/native-fs-test-helpers.js
@@ -21,7 +21,7 @@ const entries = await self.showDirectoryPicker(); assert_true(entries instanceof FileSystemHandle); assert_true(entries instanceof FileSystemDirectoryHandle); - for await (const entry of entries.getEntries()) { + for await (const entry of entries) { assert_unreached('Selected directory is not empty'); } return entries; @@ -32,7 +32,7 @@ const directory = await directory_promise; // To be resilient against tests not cleaning up properly, cleanup before // every test. - for await (let entry of directory.getEntries()) { + for await (let entry of directory.values()) { await directory.removeEntry( entry.name, {recursive: entry.kind === 'directory'}); }
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/resources/sandboxed-fs-test-helpers.js b/third_party/blink/web_tests/external/wpt/native-file-system/resources/sandboxed-fs-test-helpers.js index 1b27445..e3c18db 100644 --- a/third_party/blink/web_tests/external/wpt/native-file-system/resources/sandboxed-fs-test-helpers.js +++ b/third_party/blink/web_tests/external/wpt/native-file-system/resources/sandboxed-fs-test-helpers.js
@@ -9,7 +9,7 @@ async function cleanupSandboxedFileSystem() { const dir = await self.getOriginPrivateDirectory(); - for await (let entry of dir.getEntries()) + for await (let entry of dir.values()) await dir.removeEntry(entry.name, {recursive: entry.kind === 'directory'}); }
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/resources/test-helpers.js b/third_party/blink/web_tests/external/wpt/native-file-system/resources/test-helpers.js index 0d8bdfd..2746934 100644 --- a/third_party/blink/web_tests/external/wpt/native-file-system/resources/test-helpers.js +++ b/third_party/blink/web_tests/external/wpt/native-file-system/resources/test-helpers.js
@@ -25,7 +25,7 @@ async function getDirectoryEntryCount(handle) { let result = 0; - for await (let entry of handle.getEntries()) { + for await (let entry of handle) { result++; } return result; @@ -33,7 +33,7 @@ async function getSortedDirectoryEntries(handle) { let result = []; - for await (let entry of handle.getEntries()) { + for await (let entry of handle.values()) { if (entry.kind === 'directory') result.push(entry.name + '/'); else
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/sandboxed_FileSystemDirectoryHandle-getEntries.https.any.js b/third_party/blink/web_tests/external/wpt/native-file-system/sandboxed_FileSystemDirectoryHandle-getEntries.https.any.js deleted file mode 100644 index da620e2a..0000000 --- a/third_party/blink/web_tests/external/wpt/native-file-system/sandboxed_FileSystemDirectoryHandle-getEntries.https.any.js +++ /dev/null
@@ -1,3 +0,0 @@ -// META: script=resources/test-helpers.js -// META: script=resources/sandboxed-fs-test-helpers.js -// META: script=script-tests/FileSystemDirectoryHandle-getEntries.js
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/sandboxed_FileSystemDirectoryHandle-iteration.https.any.js b/third_party/blink/web_tests/external/wpt/native-file-system/sandboxed_FileSystemDirectoryHandle-iteration.https.any.js new file mode 100644 index 0000000..3961ea3e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/native-file-system/sandboxed_FileSystemDirectoryHandle-iteration.https.any.js
@@ -0,0 +1,3 @@ +// META: script=resources/test-helpers.js +// META: script=resources/sandboxed-fs-test-helpers.js +// META: script=script-tests/FileSystemDirectoryHandle-iteration.js
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/script-tests/FileSystemDirectoryHandle-getEntries.js b/third_party/blink/web_tests/external/wpt/native-file-system/script-tests/FileSystemDirectoryHandle-getEntries.js deleted file mode 100644 index 571683c..0000000 --- a/third_party/blink/web_tests/external/wpt/native-file-system/script-tests/FileSystemDirectoryHandle-getEntries.js +++ /dev/null
@@ -1,41 +0,0 @@ -directory_test(async (t, root) => { - const file_name1 = 'foo1.txt'; - const file_name2 = 'foo2.txt'; - await createFileWithContents(t, file_name1, 'contents', /*parent=*/ root); - await createFileWithContents(t, file_name2, 'contents', /*parent=*/ root); - - let abortIter = async (dir) => { - for await (let entry of dir.getEntries()) { - return entry.name; - } - }; - - try { - await abortIter(root); - } catch(e) { - assert_unreached('Error thrown on iteration abort.'); - } - -}, 'getEntries(): returning early from an iteration works'); - -directory_test(async (t, root) => { - const file_name1 = 'foo1.txt'; - const file_name2 = 'foo2.txt'; - await createFileWithContents(t, file_name1, 'contents', /*parent=*/ root); - await createFileWithContents(t, file_name2, 'contents', /*parent=*/ root); - - let fullIter = async (dir) => { - let name; - for await (let entry of dir.getEntries()) { - name = entry.name; - } - return name; - }; - - try { - await fullIter(root); - } catch(e) { - assert_unreached('Error thrown on iteration.'); - } - -}, 'getEntries(): full iteration works');
diff --git a/third_party/blink/web_tests/external/wpt/native-file-system/script-tests/FileSystemDirectoryHandle-iteration.js b/third_party/blink/web_tests/external/wpt/native-file-system/script-tests/FileSystemDirectoryHandle-iteration.js new file mode 100644 index 0000000..200f5af6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/native-file-system/script-tests/FileSystemDirectoryHandle-iteration.js
@@ -0,0 +1,80 @@ +directory_test(async (t, root) => { + const file_name1 = 'foo1.txt'; + const file_name2 = 'foo2.txt'; + await createFileWithContents(t, file_name1, 'contents', /*parent=*/ root); + await createFileWithContents(t, file_name2, 'contents', /*parent=*/ root); + + for await (let entry of root) { + break; + } + +}, 'returning early from an iteration doesn\'t crash'); + +directory_test(async (t, root) => { + const file_name1 = 'foo1.txt'; + const file_name2 = 'foo2.txt'; + await createFileWithContents(t, file_name1, 'contents', /*parent=*/ root); + await createFileWithContents(t, file_name2, 'contents', /*parent=*/ root); + + let names = []; + for await (let entry of root) { + assert_true(Array.isArray(entry)); + assert_equals(entry.length, 2); + assert_equals(typeof entry[0], 'string'); + assert_true(entry[1] instanceof FileSystemFileHandle); + assert_equals(entry[0], entry[1].name); + names.push(entry[0]); + } + names.sort(); + assert_array_equals(names, [file_name1, file_name2]); + +}, '@@asyncIterator: full iteration works'); + +directory_test(async (t, root) => { + const file_name1 = 'foo1.txt'; + const file_name2 = 'foo2.txt'; + await createFileWithContents(t, file_name1, 'contents', /*parent=*/ root); + await createFileWithContents(t, file_name2, 'contents', /*parent=*/ root); + + let names = []; + for await (let entry of root.entries()) { + assert_true(Array.isArray(entry)); + assert_equals(entry.length, 2); + assert_equals(typeof entry[0], 'string'); + assert_true(entry[1] instanceof FileSystemFileHandle); + assert_equals(entry[0], entry[1].name); + names.push(entry[0]); + } + names.sort(); + assert_array_equals(names, [file_name1, file_name2]); +}, 'entries: full iteration works'); + +directory_test(async (t, root) => { + const file_name1 = 'foo1.txt'; + const file_name2 = 'foo2.txt'; + await createFileWithContents(t, file_name1, 'contents', /*parent=*/ root); + await createFileWithContents(t, file_name2, 'contents', /*parent=*/ root); + + let names = []; + for await (let entry of root.values()) { + assert_true(entry instanceof FileSystemFileHandle); + names.push(entry.name); + } + names.sort(); + assert_array_equals(names, [file_name1, file_name2]); +}, 'values: full iteration works'); + +directory_test(async (t, root) => { + const file_name1 = 'foo1.txt'; + const file_name2 = 'foo2.txt'; + await createFileWithContents(t, file_name1, 'contents', /*parent=*/ root); + await createFileWithContents(t, file_name2, 'contents', /*parent=*/ root); + + let names = []; + for await (let entry of root.keys()) { + assert_equals(typeof entry, 'string'); + names.push(entry); + } + names.sort(); + assert_array_equals(names, [file_name1, file_name2]); +}, 'keys: full iteration works');
diff --git a/third_party/blink/web_tests/external/wpt/resources/testdriver.js b/third_party/blink/web_tests/external/wpt/resources/testdriver.js index a8588b44..4d373c9 100644 --- a/third_party/blink/web_tests/external/wpt/resources/testdriver.js +++ b/third_party/blink/web_tests/external/wpt/resources/testdriver.js
@@ -355,6 +355,32 @@ set_user_verified: function(authenticator_id, uv) { return window.test_driver_internal.set_user_verified(authenticator_id, uv); }, + + /** + * Sets the storage access rule for an origin when embedded + * in a third-party context. + * + * {@link https://privacycg.github.io/storage-access/#set-storage-access-command} + * + * @param {String} origin - A third-party origin to block or allow. + * May be "*" to indicate all origins. + * @param {String} embedding_origin - an embedding (first-party) origin + * on which {origin}'s access should + * be blocked or allowed. + * May be "*" to indicate all origins. + * @param {String} state - The storage access setting. + * Must be either "allowed" or "blocked". + * + * @returns {Promise} Fulfilled after the storage access rule has been + * set, or rejected if setting the rule fails. + */ + set_storage_access: function(origin, embedding_origin, state) { + if (state !== "allowed" && state !== "blocked") { + throw new Error("storage access status must be 'allowed' or 'blocked'"); + } + const blocked = state === "blocked"; + return window.test_driver_internal.set_storage_access(origin, embedding_origin, blocked); + }, }; window.test_driver_internal = { @@ -569,5 +595,13 @@ set_user_verified: function(authenticator_id, uv) { return Promise.reject(new Error("unimplemented")); }, + + /** + * Sets the storage access policy for a third-party origin when loaded + * in the current first party context + */ + set_storage_access: function(origin, embedding_origin, blocked) { + return Promise.reject(new Error("unimplemented")); + }, }; })();
diff --git a/third_party/blink/web_tests/external/wpt/storage-access-api/resources/set-cookie.py b/third_party/blink/web_tests/external/wpt/storage-access-api/resources/set-cookie.py new file mode 100644 index 0000000..019697a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/storage-access-api/resources/set-cookie.py
@@ -0,0 +1,27 @@ +def main(request, response): + name = request.GET.first(b"name") + value = request.GET.first(b"value") + testcase = request.GET.first(b"testcase") + response_headers = [(b"Set-Cookie", name + b"=" + value)] + + body = b""" + <!DOCTYPE html> + <meta charset="utf-8"> + <title>Set Storage Access Subframe</title> + <script src="/resources/testharness.js"></script> + + <script> + let querystring = window.location.search.substring(1).split("&"); + const allowed = querystring.some(param => param.toLowerCase() === "allowed=true"); + + test(() => { + if (allowed) { + assert_equals(document.cookie, "%s=%s"); + } else { + assert_equals(document.cookie, ""); + } + }, "[%s] Cookie access is allowed: " + allowed); + </script> + """ % (name, value, testcase) + + return (200, response_headers, body)
diff --git a/third_party/blink/web_tests/external/wpt/storage-access-api/storageAccess.testdriver.sub.html b/third_party/blink/web_tests/external/wpt/storage-access-api/storageAccess.testdriver.sub.html new file mode 100644 index 0000000..59f925f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/storage-access-api/storageAccess.testdriver.sub.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<head> + <title>TestDriver - Set Storage Access Command Tests</title> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + <script src="/resources/testdriver.js"></script> + <script src="/resources/testdriver-vendor.js"></script> + <script src="helpers.js"></script> +</head> +<body> + <script> + "use strict"; + + promise_test(async t => { + // Allow a third-party site embedded in this first-party site. + await window.test_driver.set_storage_access("http://{{domains[www]}}:{{ports[http][0]}}/", "http://{{domains[]}}:{{ports[http][0]}}/", "allowed"); + // Block a third-party site embedded in this first-party site. + await window.test_driver.set_storage_access("http://{{domains[www1]}}:{{ports[http][0]}}/", "http://{{domains[]}}:{{ports[http][0]}}/", "blocked"); + // Block a third-party site on all first-party sites. + await window.test_driver.set_storage_access("http://{{domains[www2]}}:{{ports[http][0]}}/", "*", "blocked"); + }, "Set up storage access rules"); + + RunTestsInIFrame("http://{{domains[]}}:{{ports[http][0]}}/storage-access-api/resources/set-cookie.py?name=hello0&value=world0&allowed=true&testcase=same-site"); + + RunTestsInIFrame("http://{{domains[www]}}:{{ports[http][0]}}/storage-access-api/resources/set-cookie.py?name=hello&value=world&allowed=true&testcase=third-party-allowed-on-first-party-site"); + + RunTestsInIFrame("http://{{domains[www1]}}:{{ports[http][0]}}/storage-access-api/resources/set-cookie.py?name=hello1&value=world1&allowed=false&testcase=third-party-blocked-on-first-party-site"); + + RunTestsInIFrame("http://{{domains[www2]}}:{{ports[http][0]}}/storage-access-api/resources/set-cookie.py?name=hello2&value=world2&allowed=false&testcase=third-party-blocked-all"); + </script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-002-expected.txt b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-002-expected.txt index 2e2cd8c..bf24d1a 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-002-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-002-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 263 tests; 250 PASS, 13 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 260 tests; 247 PASS, 13 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Setup PASS isolation (type: discrete) has testAccumulation function PASS isolation: "isolate" onto "auto" @@ -173,9 +173,6 @@ PASS text-anchor (type: discrete) has testAccumulation function PASS text-anchor: "end" onto "middle" PASS text-anchor: "middle" onto "end" -PASS text-combine-upright (type: discrete) has testAccumulation function -PASS text-combine-upright: "none" onto "all" -PASS text-combine-upright: "all" onto "none" PASS text-decoration-color (type: color) has testAccumulation function PASS text-decoration-color supports animating as color of rgb() with overflowed from and to values PASS text-decoration-color supports animating as color of #RGB
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-002-expected.txt b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-002-expected.txt index b825451..0128b40 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-002-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-002-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 259 tests; 249 PASS, 10 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 256 tests; 246 PASS, 10 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Setup PASS isolation (type: discrete) has testAddition function PASS isolation: "isolate" onto "auto" @@ -173,9 +173,6 @@ PASS text-anchor (type: discrete) has testAddition function PASS text-anchor: "end" onto "middle" PASS text-anchor: "middle" onto "end" -PASS text-combine-upright (type: discrete) has testAddition function -PASS text-combine-upright: "none" onto "all" -PASS text-combine-upright: "all" onto "none" PASS text-decoration-color (type: color) has testAddition function PASS text-decoration-color supports animating as color of rgb() with overflowed from and to values PASS text-decoration-color supports animating as color of #RGB
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-002-expected.txt b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-002-expected.txt index 0c4134b..d26b6ea 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-002-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/interpolation-per-property-002-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 318 tests; 305 PASS, 13 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 314 tests; 301 PASS, 13 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Setup PASS isolation (type: discrete) has testInterpolation function PASS isolation uses discrete animation when animating between "auto" and "isolate" with linear easing @@ -208,10 +208,6 @@ PASS text-anchor uses discrete animation when animating between "middle" and "end" with linear easing PASS text-anchor uses discrete animation when animating between "middle" and "end" with effect easing PASS text-anchor uses discrete animation when animating between "middle" and "end" with keyframe easing -PASS text-combine-upright (type: discrete) has testInterpolation function -PASS text-combine-upright uses discrete animation when animating between "all" and "none" with linear easing -PASS text-combine-upright uses discrete animation when animating between "all" and "none" with effect easing -PASS text-combine-upright uses discrete animation when animating between "all" and "none" with keyframe easing PASS text-decoration-color (type: color) has testInterpolation function PASS text-decoration-color supports animating as color of rgb() PASS text-decoration-color supports animating as color of #RGB
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/property-list.js b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/property-list.js index 3c3bf5d..e9b7c52 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/property-list.js +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/property-list.js
@@ -1261,12 +1261,6 @@ { type: 'discrete', options: [ [ 'middle', 'end' ] ] } ] }, - 'text-combine-upright': { - // https://drafts.csswg.org/css-writing-modes-3/#propdef-text-combine-upright - types: [ - { type: 'discrete', options: [ [ 'all', 'none' ] ] } - ] - }, 'text-decoration-color': { // https://drafts.csswg.org/css-text-decor-3/#propdef-text-decoration-color types: [ 'color' ]
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan.https.html index db50b66..46f2871 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan.https.html
@@ -284,4 +284,19 @@ await promise; }, "Test that reading message with multiple records should succeed."); +nfc_test(async (t, mockNFC) => { + const reader = new NDEFReader(); + const promise1 = reader.scan(); + const promise2 = promise_rejects_dom(t, 'InvalidStateError', reader.scan()); + await promise1; + await promise2; +}, "Test that NDEFReader.scan rejects if there is already an ongoing scan."); + +nfc_test(async (t, mockNFC) => { + const reader = new NDEFReader(); + const controller = new AbortController(); + await reader.scan({signal : controller.signal}); + controller.abort(); + await reader.scan(); +}, "Test that NDEFReader.scan can be started after the previous scan is aborted."); </script>
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan_filter.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan_filter.https.html index ddb25b87..1fea243 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan_filter.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan_filter.https.html
@@ -162,79 +162,4 @@ ); } -nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); - const controller = new AbortController(); - const signal = controller.signal; - const textMsg = createMessage([createTextRecord(test_text_data)]); - const urlMsg = createMessage([createUrlRecord(test_url_data)]); - const mimeMsg = createMessage([createMimeRecord(test_buffer_data)]); - - const readerWatcher = new EventWatcher(t, reader, ["reading", "error"]); - const promise = readerWatcher.wait_for("reading").then(event => { - controller.abort(); - assertWebNDEFMessagesEqual(event.message, new NDEFMessage(mimeMsg)); - }); - - const scanOptions1 = {recordType: "text", signal: signal}; - const scanOptions2 = {recordType: "url", signal: signal}; - const scanOptions3 = {recordType: "mime", signal: signal}; - - await reader.scan(scanOptions1); - await reader.scan(scanOptions2); - // There is maximum one filter for an NDEFReader object, - // last filter will replace all previous ones. - await reader.scan(scanOptions3); - - mockNFC.setReadingMessage(textMsg); - mockNFC.setReadingMessage(urlMsg); - mockNFC.setReadingMessage(mimeMsg); - await promise; -}, "Multiple scan() from the same NDEFReader object with new options should \ -replace existing filters."); - -nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); - const controller1 = new AbortController(); - const controller2 = new AbortController(); - const urlMsg = createMessage([createUrlRecord(test_url_data)]); - const mimeMsg = createMessage([createMimeRecord(test_buffer_data)]); - - const readerWatcher = new EventWatcher(t, reader, ["reading", "error"]); - const promise = readerWatcher.wait_for("reading").then(event => { - assertWebNDEFMessagesEqual(event.message, new NDEFMessage(mimeMsg)); - controller2.abort(); - }); - - const scanOptions1 = {recordType: "url", signal: controller1.signal}; - const scanOptions2 = {recordType: "mime", signal: controller2.signal}; - - // There is maximum one filter for an NDEFReader object, - // last filter will replace all previous ones. - await reader.scan(scanOptions1); - await reader.scan(scanOptions2); - - mockNFC.setReadingMessage(urlMsg); - - controller1.abort(); - - mockNFC.setReadingMessage(mimeMsg); - await promise; -}, "Aborting on previous signal should not stop current reading for multiple \ -scan() with different signals."); - -nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); - const controller = new AbortController(); - const scanOptions1 = {recordType: "url", signal: controller.signal }; - const scanOptions2 = {recordType: "mime"}; - - await reader.scan(scanOptions1); - const promise = reader.scan(scanOptions2); - controller.abort(); - - await promise_rejects_dom(t, 'AbortError', promise); -}, "Aborting on previous signal can stop current reading if no new signals \ -passed to successive scan()."); - </script>
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-post-data-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-post-data-expected.txt new file mode 100644 index 0000000..987dcdc --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-post-data-expected.txt
@@ -0,0 +1,12 @@ +Test post data interception +[ + [0] : { + bytes : AQIDBAU= + } +] +[ + [0] : { + bytes : AQIDBAU= + } +] +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-post-data.js b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-post-data.js new file mode 100644 index 0000000..cf8faee --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-post-data.js
@@ -0,0 +1,19 @@ +(async function(testRunner) { + const {page, session, dp} = await testRunner.startBlank( + `Test post data interception`); + + await dp.Network.enable(); + await dp.Fetch.enable(); + + const [requestWillBeSent, requestPaused] = await Promise.all([ + dp.Network.onceRequestWillBeSent(), + dp.Fetch.onceRequestPaused(), + session.evaluate(`fetch('${testRunner.url('./resources/hello-world.txt')}', { + method: 'post', + body: new Uint8Array([1, 2, 3, 4, 5]) + })`) + ]); + testRunner.log(requestWillBeSent.params.request.postDataEntries); + testRunner.log(requestPaused.params.request.postDataEntries); + testRunner.completeTest(); +})
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/native-file-system-origin-trial-interfaces.html b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/native-file-system-origin-trial-interfaces.html index 81c93db..38be8934 100644 --- a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/native-file-system-origin-trial-interfaces.html +++ b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/native-file-system-origin-trial-interfaces.html
@@ -13,7 +13,7 @@ OriginTrialsHelper.check_properties_exist(this, { 'FileSystemHandle': ['kind', 'name', 'queryPermission', 'requestPermission'], 'FileSystemFileHandle': ['getFile', 'createWritable'], - 'FileSystemDirectoryHandle': ['getFileHandle', 'getDirectoryHandle', 'getEntries', 'removeEntry'], + 'FileSystemDirectoryHandle': ['getFileHandle', 'getDirectoryHandle', 'entries', 'removeEntry'], 'FileSystemWritableFileStream': ['write', 'truncate', 'close', 'seek'], 'global': ['showOpenFilePicker', 'showSaveFilePicker', 'showDirectoryPicker', 'getOriginPrivateDirectory'], });
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index c0e5f5a..dcb1409 100644 --- a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -559,12 +559,15 @@ setter onprogress interface FileSystemDirectoryHandle : FileSystemHandle attribute @@toStringTag + method @@asyncIterator method constructor + method entries method getDirectoryHandle - method getEntries method getFileHandle + method keys method removeEntry method resolve + method values interface FileSystemFileHandle : FileSystemHandle attribute @@toStringTag method constructor
diff --git a/third_party/blink/web_tests/resources/global-interface-listing.js b/third_party/blink/web_tests/resources/global-interface-listing.js index 9d371d25..4146891d 100644 --- a/third_party/blink/web_tests/resources/global-interface-listing.js +++ b/third_party/blink/web_tests/resources/global-interface-listing.js
@@ -87,6 +87,7 @@ } var wellKnownSymbols = new Map([ + [Symbol.asyncIterator, "@@asyncIterator"], [Symbol.hasInstance, "@@hasInstance"], [Symbol.isConcatSpreadable, "@@isConcatSpreadable"], [Symbol.iterator, "@@iterator"],
diff --git a/third_party/blink/web_tests/resources/testdriver-vendor.js b/third_party/blink/web_tests/resources/testdriver-vendor.js index 6d4602cd..2c38446 100644 --- a/third_party/blink/web_tests/resources/testdriver-vendor.js +++ b/third_party/blink/web_tests/resources/testdriver-vendor.js
@@ -410,6 +410,10 @@ permission_params.state); } + window.test_driver_internal.set_storage_access = function(origin, embedding_origin, blocked) { + return internals.setStorageAccess(origin, embedding_origin, blocked); + } + // Enable automation so we don't wait for user input on unimplemented APIs window.test_driver_internal.in_automation = true;
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt index fbc41fa..80775d2 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -494,12 +494,15 @@ [Worker] method readAsText [Worker] interface FileSystemDirectoryHandle : FileSystemHandle [Worker] attribute @@toStringTag +[Worker] method @@asyncIterator [Worker] method constructor +[Worker] method entries [Worker] method getDirectoryHandle -[Worker] method getEntries [Worker] method getFileHandle +[Worker] method keys [Worker] method removeEntry [Worker] method resolve +[Worker] method values [Worker] interface FileSystemFileHandle : FileSystemHandle [Worker] attribute @@toStringTag [Worker] method constructor
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index bcf9e21..fd9f7b9b 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -2445,12 +2445,15 @@ setter onprogress interface FileSystemDirectoryHandle : FileSystemHandle attribute @@toStringTag + method @@asyncIterator method constructor + method entries method getDirectoryHandle - method getEntries method getFileHandle + method keys method removeEntry method resolve + method values interface FileSystemFileHandle : FileSystemHandle attribute @@toStringTag method constructor
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt index 8b1f6dd2..3abb4ade 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -489,12 +489,15 @@ [Worker] method readAsText [Worker] interface FileSystemDirectoryHandle : FileSystemHandle [Worker] attribute @@toStringTag +[Worker] method @@asyncIterator [Worker] method constructor +[Worker] method entries [Worker] method getDirectoryHandle -[Worker] method getEntries [Worker] method getFileHandle +[Worker] method keys [Worker] method removeEntry [Worker] method resolve +[Worker] method values [Worker] interface FileSystemFileHandle : FileSystemHandle [Worker] attribute @@toStringTag [Worker] method constructor
diff --git a/third_party/closure_compiler/externs/networking_private.js b/third_party/closure_compiler/externs/networking_private.js index 349618e..0ad4183 100644 --- a/third_party/closure_compiler/externs/networking_private.js +++ b/third_party/closure_compiler/externs/networking_private.js
@@ -788,7 +788,6 @@ * EAP: (!chrome.networkingPrivate.EAPProperties|undefined), * Frequency: (number|undefined), * FrequencyList: (!Array<number>|undefined), - * FTEnabled: (boolean|undefined), * HexSSID: (string|undefined), * HiddenSSID: (boolean|undefined), * Passphrase: (string|undefined), @@ -808,7 +807,6 @@ * EAP: (!chrome.networkingPrivate.ManagedEAPProperties|undefined), * Frequency: (number|undefined), * FrequencyList: (!Array<number>|undefined), - * FTEnabled: (!chrome.networkingPrivate.ManagedBoolean|undefined), * HexSSID: (!chrome.networkingPrivate.ManagedDOMString|undefined), * HiddenSSID: (!chrome.networkingPrivate.ManagedBoolean|undefined), * Passphrase: (!chrome.networkingPrivate.ManagedDOMString|undefined),
diff --git a/third_party/dom_distiller_js/update_domdistiller_js.sh b/third_party/dom_distiller_js/update_domdistiller_js.sh index 640982c..e3f7d70 100755 --- a/third_party/dom_distiller_js/update_domdistiller_js.sh +++ b/third_party/dom_distiller_js/update_domdistiller_js.sh
@@ -5,10 +5,13 @@ # found in the LICENSE file. # -# Clones the dom-distiller repo, compiles and extracts its javascript Then -# copies that js into the Chromium tree. +# Clones the dom-distiller repo, compiles and extracts its JavaScript. The +# artifact would be uploaded as a CL in dom-distiller/dist repo, and then +# generates a rolling commit to be uploaded. # This script requires that ant is installed. It takes an optional parameter -# for which SHA1 to roll to. If left unspecified the script rolls to HEAD. +# for which SHA1 in dom-distiller repo to roll to. If left unspecified the +# script rolls to HEAD. The second optional parameter is the Gerrit URL of +# the CL in dom-distiller/dist repo to be validated. ( set -e @@ -27,11 +30,17 @@ mkdir $tmpdir pushd $tmpdir + function finish { + rm -rf $tmpdir + } + trap finish EXIT + git clone $repo_host/dom-distiller pushd dom-distiller # The new git SHA1 is HEAD or the first command line parameter. [[ -z "$1" ]] && gitsha_target="HEAD" || gitsha_target="$1" + gerrit_url="$2" new_gitsha=$(git rev-parse --short=10 ${gitsha_target}) git reset --hard ${new_gitsha} git log --oneline ${curr_gitsha}..${new_gitsha} > $changes @@ -43,12 +52,13 @@ # rejoin. Finally, remove the trailing ',' and concat to $bugs. git log ${curr_gitsha}..${new_gitsha} \ | grep -E 'BUG=|Bug:' \ - | sed -e 's/.*\(BUG=\|Bug:\)\(.*\)/\2/' -e 's/\s*//g' -e '/^$/d' \ + | sed -e 's/.*\(BUG=\|Bug:\)\(.*\)/\2/' -e 's/\s*//g' -e '/^$/d' -e '/None/d' \ | tr ',' '\n' \ | sort \ | uniq \ | tr '\n' ',' \ - | head --bytes=-1 \ + | sed -e 's/,/, /g' \ + | head --bytes=-2 \ >> $bugs echo >> $bugs # add a newline @@ -57,8 +67,13 @@ popd # dom-distiller git clone $repo_host/dom-distiller/dist $tmpdir/dom-distiller-dist - rm -rf $tmpdir/dom-distiller-dist/* pushd dom-distiller-dist + if [[ -n "$gerrit_url" ]]; then + echo "Validating $gerrit_url" + git cl patch --force $gerrit_url + fi + rm -rf $tmpdir/dom-distiller-dist/* + cp -r $tmpdir/dom-distiller/out/package/* . # Stop rolling python/plugin_pb2.py for protobuf backward compatibility. @@ -67,10 +82,35 @@ git add . if [[ $(git status --short | wc -l) -ne 0 ]]; then - git commit -a -m "Package for ${new_gitsha}" - git push origin master + if [[ -n "$gerrit_url" ]]; then + echo "FAIL. The output is different from $gerrit_url." + exit 1 + fi + # For Change-Id footer. + curl -Lo $(git rev-parse --git-dir)/hooks/commit-msg https://gerrit-review.googlesource.com/tools/hooks/commit-msg + chmod +x $(git rev-parse --git-dir)/hooks/commit-msg + + gen_message () { + echo "Package for ${new_gitsha}" + echo + echo "This is generated from:" + echo "${repo_host}/dom-distiller/+/${new_gitsha}." + echo + echo "To validate, run the following command in chromium/src:" + echo "third_party/dom_distiller_js/update_domdistiller_js.sh ${new_gitsha} <Gerrit-URL>" + } + + message=$tmpdir/message + gen_message > $message + + git commit -a -F $message + git push origin master:refs/for/master else # No changes to external repo, but need to check if DEPS refers to same SHA1. + if [[ -n "$gerrit_url" ]]; then + echo "PASS. The output is the same as $gerrit_url." + exit 0 + fi echo "WARNING: There were no changes to the distribution package." fi new_dist_gitsha=$(git rev-parse HEAD) @@ -80,7 +120,6 @@ curr_dist_gitsha=$(grep -e "/chromium\/dom-distiller\/dist.git" $src_path/DEPS | sed -e "s/.*'\([A-Za-z0-9]\{40\}\)'.*/\1/g") if [[ "${new_dist_gitsha}" == "${curr_dist_gitsha}" ]]; then echo "The roll does not include any changes to the dist package. Exiting." - rm -rf $tmpdir exit 1 fi @@ -109,6 +148,4 @@ $src_path/tools/checklicenses/checklicenses.py third_party/dom_distiller_js > $tmpdir/checklicenses.out || cat $tmpdir/checklicenses.out git commit -a -F $message - - rm -rf $tmpdir )
diff --git a/third_party/weston/BUILD.gn b/third_party/weston/BUILD.gn index 8f23d2b..a6c9fa4 100644 --- a/third_party/weston/BUILD.gn +++ b/third_party/weston/BUILD.gn
@@ -176,6 +176,7 @@ ":weston_touch_calibration_protocol", "//third_party/libdrm", "//third_party/wayland:wayland_server", + "//third_party/wayland:wayland_util", "//third_party/wayland-protocols:input_method_protocol", "//third_party/wayland-protocols:input_timestamps_protocol", "//third_party/wayland-protocols:linux_dmabuf_protocol",
diff --git a/tools/ipc_fuzzer/fuzzer/fuzzer.cc b/tools/ipc_fuzzer/fuzzer/fuzzer.cc index f424b99..57d2d07 100644 --- a/tools/ipc_fuzzer/fuzzer/fuzzer.cc +++ b/tools/ipc_fuzzer/fuzzer/fuzzer.cc
@@ -663,14 +663,11 @@ }; template <> -struct FuzzTraits<blink::WebDeviceEmulationParams::ScreenPosition> { - static bool Fuzz(blink::WebDeviceEmulationParams::ScreenPosition* p, - Fuzzer* fuzzer) { - int screen_position = RandInRange( - blink::WebDeviceEmulationParams::ScreenPosition::kScreenPositionLast + - 1); - *p = static_cast<blink::WebDeviceEmulationParams::ScreenPosition>( - screen_position); +struct FuzzTraits<blink::mojom::EmulatedScreenType> { + static bool Fuzz(blink::mojom::EmulatedScreenType* p, Fuzzer* fuzzer) { + int screen_type = RandInRange( + static_cast<int>(blink::mojom::EmulatedScreenType::kMaxValue) + 1); + *p = static_cast<blink::mojom::EmulatedScreenType>(screen_type); return true; } };
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 1bccb00f..76e410fd 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -58,7 +58,7 @@ 'fuchsia-official': 'fuchsia_official_optimize_goma', 'linux-archive-rel': 'release_bot', 'linux-archive-dbg': 'debug_bot', - 'linux-official': 'official_optimize_goma', + 'linux-official': 'linux_official_optimize_goma', 'mac-archive-rel': 'release_bot_mac_strip_minimal_symbols', 'mac-archive-dbg': 'debug_bot', 'win32-official': 'x86_official_optimize_goma', @@ -2067,6 +2067,10 @@ 'libfuzzer', 'asan', 'release_trybot', 'chrome_with_codecs', 'pdf_xfa', 'disable_nacl', 'mojo_fuzzer', ], + 'linux_official_optimize_goma': [ + 'official_optimize_goma', 'linux_official_link_jobs', + ], + 'mac_arm64_release_bot': [ 'release_bot', 'arm64', ], @@ -2755,6 +2759,14 @@ 'gn_args': 'max_jobs_per_link=32', }, + # Without this, linux-official uses too many concurrent links with the + # available RAM. We want to adjust this number to mitigate possible memory + # issues related to linking. + # See https://bugs.chromium.org/p/chromium/issues/detail?id=1103490 + 'linux_official_link_jobs': { + 'gn_args': 'concurrent_links=6', + }, + 'lsan': { 'gn_args': 'is_lsan=true', },
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 5e315b8..2ec67a8 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -21262,6 +21262,7 @@ <int value="740" label="ExtensionInstallBlocklist"/> <int value="741" label="ReportDeviceSystemInfo"/> <int value="742" label="AutoplayAllowlist"/> + <int value="743" label="DevicePrinters"/> </enum> <enum name="EnterprisePolicyDeviceIdValidity"> @@ -40463,6 +40464,7 @@ label="AutofillSaveCreditCardUsesImprovedMessaging:enabled"/> <int value="-1309066678" label="ServiceWorkerOnUI:enabled"/> <int value="-1308600417" label="NewNetErrorPageUI:disabled"/> + <int value="-1308184869" label="MediaFeedsBackgroundFetching:enabled"/> <int value="-1304957199" label="OfflinePagesShowAlternateDinoPage:enabled"/> <int value="-1304758527" label="SyncSendTabToSelf:disabled"/> <int value="-1302904242" label="enable-navigation-tracing"/> @@ -43212,6 +43214,7 @@ <int value="1698089268" label="WebXRMultiGpu:disabled"/> <int value="1699180023" label="PaymentRequestOptionalTotal:disabled"/> <int value="1699182601" label="DockedMagnifier:disabled"/> + <int value="1700117535" label="MediaFeedsBackgroundFetching:disabled"/> <int value="1700394127" label="OverlayScrollbar:disabled"/> <int value="1701972870" label="NTPSnippetsIncreasedVisibility:enabled"/> <int value="1702090999" label="ClearOldBrowsingData:disabled"/> @@ -46335,6 +46338,19 @@ <int value="6" label="XHTML-MP document type"/> </enum> +<enum name="MetricKitExitData"> + <int value="0" label="App exited normally"/> + <int value="1" label="App exited abnormally"/> + <int value="2" label="Watchdog terminated the app"/> + <int value="3" label="App used too much CPU time"/> + <int value="4" label="App used too much memory"/> + <int value="5" label="Terminated to free up memory"/> + <int value="6" label="Suspended while having file locks"/> + <int value="7" label="Invalid memory access"/> + <int value="8" label="Illegal or undefined instruction"/> + <int value="9" label="Exceeded allocated time for background task"/> +</enum> + <enum name="MetricsReportingChange"> <int value="0" label="Error"> Error occurred while updating MetricsReporting
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 0616c4f0..63735ba 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -3529,8 +3529,9 @@ </histogram> <histogram name="Android.InstantApps.ApiCallDurationWithoutApp" units="ms" - expires_after="M85"> + expires_after="2022-01-31"> <owner>sbirch@google.com</owner> + <owner>tedchoc@chromium.org</owner> <summary> Measures the amount of time spent in the getInstantAppIntent() API call when the API was not able to find an Instant App for the URL. This is recorded @@ -3541,8 +3542,9 @@ </histogram> <histogram name="Android.InstantApps.CallSource" enum="InstantAppsCallSource" - expires_after="M85"> + expires_after="2022-01-31"> <owner>sbirch@google.com</owner> + <owner>tedchoc@chromium.org</owner> <summary> For intents to load a web page in browser from Instant Apps, records where the request to load came from. @@ -3561,8 +3563,9 @@ </histogram> <histogram name="Android.InstantApps.EligiblePageLoaded" enum="Boolean" - expires_after="M85"> + expires_after="2022-01-31"> <owner>sbirch@google.com</owner> + <owner>tedchoc@chromium.org</owner> <summary> Records whether any given successful page load (for http and https schemes only) could have been handled by an Instant App. @@ -3570,8 +3573,9 @@ </histogram> <histogram name="Android.InstantApps.FallbackDuration" units="ms" - expires_after="M85"> + expires_after="2022-01-31"> <owner>sbirch@google.com</owner> + <owner>tedchoc@chromium.org</owner> <summary> Measures the time from when we first received an eligible intent for Instant Apps to the time we processed it in the case where the Instant Apps activity @@ -3592,8 +3596,9 @@ </histogram> <histogram name="Android.InstantApps.ShouldShowBanner" enum="InstantAppsBanner" - expires_after="M85"> + expires_after="2022-01-31"> <owner>sbirch@google.com</owner> + <owner>tedchoc@chromium.org</owner> <summary> Logs the reasons the banner is shown or hidden on an instant apps eligible pages. Triggered every time asynchronous Instant Apps API indicates the @@ -8917,7 +8922,7 @@ </histogram> <histogram name="Arc.OptInCancel" enum="ArcOptInCancel" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>elijahtaylor@google.com</owner> <owner>shihuis@google.com</owner> <summary>Arc OptIn cancelation reason.</summary> @@ -10503,7 +10508,7 @@ </histogram> <histogram name="Ash.Shelf.NumberOfItems" units="Icons" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>anasalazar@google.com</owner> <owner>mmourgos@google.com</owner> <summary> @@ -10523,7 +10528,7 @@ </histogram> <histogram name="Ash.Shelf.NumberOfUnpinnedItems" units="Icons" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>anasalazar@google.com</owner> <owner>mmourgos@google.com</owner> <summary> @@ -12643,7 +12648,7 @@ </summary> </histogram> -<histogram name="AsyncDNS.ServerCount" units="units" expires_after="2020-11-15"> +<histogram name="AsyncDNS.ServerCount" units="units" expires_after="2021-01-17"> <owner>pauljensen@chromium.org</owner> <owner>mef@chromium.org</owner> <summary> @@ -13106,7 +13111,7 @@ </histogram> <histogram name="AuthPolicy.ErrorTypeOfRefreshDevicePolicy" - enum="AuthPolicyErrorType" expires_after="2020-10-25"> + enum="AuthPolicyErrorType" expires_after="2021-01-17"> <owner>fsandrade@chromium.org</owner> <owner>tomdobro@chromium.org</owner> <summary> @@ -21502,7 +21507,7 @@ </histogram> <histogram name="Blink.VisibleBeforeLoaded.LazyLoadImages.AboveTheFold" - enum="NQEEffectiveConnectionType" expires_after="2020-11-15"> + enum="NQEEffectiveConnectionType" expires_after="2021-01-17"> <owner>sclittle@chromium.org</owner> <owner>rajendrant@chromium.org</owner> <summary> @@ -26000,7 +26005,7 @@ </histogram> <histogram name="ChromeOS.Apps.IntentPickerDestinationPlatform" - enum="ArcIntentHandlerDestinationPlatform" expires_after="2020-11-15"> + enum="ArcIntentHandlerDestinationPlatform" expires_after="2021-01-17"> <owner>elijahtaylor@google.com</owner> <owner>dominickn@chromium.org</owner> <owner>shihuis@google.com</owner> @@ -31787,7 +31792,7 @@ </summary> </histogram> -<histogram name="Cookie.Count" units="units" expires_after="2020-11-15"> +<histogram name="Cookie.Count" units="units" expires_after="2021-01-17"> <owner>battre@chromium.org</owner> <summary> Number of cookies in the store (recorded every 10 minutes of active browsing @@ -35519,7 +35524,7 @@ </histogram> <histogram name="Cryptohome.MigrationUI.MigrationResult" - enum="MigrationUIMigrationResult" expires_after="2020-11-15"> + enum="MigrationUIMigrationResult" expires_after="2021-01-17"> <owner>fukino@chromium.org</owner> <summary> The result of encryption migration from eCryptfs to Ext4 dircrypto. The @@ -46058,7 +46063,7 @@ </histogram> <histogram name="Download.Service.Files.FreeDiskSpace" units="%" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>xingliu@chromium.org</owner> <summary> The percentage of free disk space to total disk space. Recorded during @@ -52777,7 +52782,7 @@ </histogram> <histogram name="Event.Latency.ScrollUpdate.Wheel.TimeToHandled2" - units="microseconds" expires_after="2020-11-15"> + units="microseconds" expires_after="2021-01-17"> <owner>tdresser@chromium.org</owner> <summary> Time between initial creation of a wheel event and the generated @@ -54033,7 +54038,7 @@ </histogram> <histogram name="ExploreSites.RequestStatus" enum="ExploreSitesRequestStatus" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>dimich@chromium.org</owner> <owner>freedjm@chromium.org</owner> <summary> @@ -62373,7 +62378,7 @@ </histogram> <histogram name="FirstRun.NewUserExperience.NtpBackgroundInteraction" - enum="NuxNtpBackgroundInteractions" expires_after="2020-11-15"> + enum="NuxNtpBackgroundInteractions" expires_after="2021-01-17"> <owner>hcarmona@chromium.org</owner> <owner>johntlee@chromium.org</owner> <summary> @@ -64548,7 +64553,7 @@ </histogram> <histogram name="GPU.BlacklistFeatureTestResults" - enum="GPUBlacklistFeatureTestResults" expires_after="2020-11-15"> + enum="GPUBlacklistFeatureTestResults" expires_after="2021-01-17"> <owner>vmiura@chromium.org</owner> <summary> Counts number of browser invocations for which a GPU feature is @@ -66099,7 +66104,7 @@ </histogram> <histogram name="GPU.SharedImage.ContentConsumed" enum="BooleanMatched" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>penghuang@chromium.org</owner> <owner>backer@chromium.org</owner> <summary> @@ -66199,7 +66204,7 @@ </histogram> <histogram name="GPU.SwapTimeUs" units="microseconds" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>vasilyt@chromium.org</owner> <owner>backer@chromium.org</owner> <summary> @@ -72596,6 +72601,99 @@ </summary> </histogram> +<histogram name="IOS.MetricKit.ApplicationHangTime" units="ms" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The durations of time in which the app is too busy to handle user + interaction responsively. Logged when a MXMetricPayload is received (one per + day). + </summary> +</histogram> + +<histogram name="IOS.MetricKit.ApplicationResumeTime" units="ms" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The amount of time taken to resume the app from the background. Logged when + a MXMetricPayload is received (one per day). + </summary> +</histogram> + +<histogram name="IOS.MetricKit.AverageSuspendedMemory" units="MB" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The average amount of memory in use by the app when it's suspended. Logged + when a MXMetricPayload is received (one per day). + </summary> +</histogram> + +<histogram name="IOS.MetricKit.BackgroundExitData" enum="MetricKitExitData" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The reason for the application termination in background. Logged when a + MXMetricPayload is received (one per day). + </summary> +</histogram> + +<histogram name="IOS.MetricKit.BackgroundTimePerDay" units="ms" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The total time the app is in the background. Logged when a MXMetricPayload + is received (one per day). Note: The date the data is reported is later than + the day it account for. + </summary> +</histogram> + +<histogram name="IOS.MetricKit.ForegroundExitData" enum="MetricKitExitData" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The reason for the application termination in background. Logged when a + MXMetricPayload is received (one per day). + </summary> +</histogram> + +<histogram name="IOS.MetricKit.ForegroundTimePerDay" units="ms" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The total time the app is in the foreground. Logged when a MXMetricPayload + is received (one per day). Note: The date the data is reported is later than + the day it account for. + </summary> +</histogram> + +<histogram name="IOS.MetricKit.PeakMemoryUsage" units="MB" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The largest amount of memory used by the app. Logged when a MXMetricPayload + is received (one per day). + </summary> +</histogram> + +<histogram name="IOS.MetricKit.TimeToFirstDraw" units="ms" + expires_after="2021-01-06"> + <owner>eugenebut@chromium.org</owner> + <owner>olivierrobin@chromium.org</owner> + <summary> + The amount of time taken to launch the app. Logged when a MXMetricPayload is + received (one per day). + </summary> +</histogram> + <histogram name="IOS.MultiWindow.OpenInNewWindow" enum="WindowActivityOrigin" expires_after="2021-06-30"> <owner>marq@chromium.org</owner> @@ -73595,7 +73693,7 @@ </histogram> <histogram name="KeyboardAccessory.AccessorySheetSuggestionsSelected" - enum="AccessorySuggestionType" expires_after="2020-11-08"> + enum="AccessorySuggestionType" expires_after="2021-01-17"> <owner>fhorschig@chromium.org</owner> <summary> Android only. Records which type of suggestion was selected from an open @@ -73625,7 +73723,7 @@ </histogram> <histogram name="KeyboardAccessory.AccessorySheetTriggered" - enum="AccessorySheetTrigger" expires_after="2020-11-08"> + enum="AccessorySheetTrigger" expires_after="2021-01-17"> <owner>fhorschig@chromium.org</owner> <summary> Android only. Records how often the bottom sheet was opened or closed by a @@ -110319,9 +110417,11 @@ </summary> </histogram> -<histogram name="NewTabPage.URLState" enum="NewTabURLState" expires_after="M85"> - <owner>dbeam@chromium.org</owner> +<histogram name="NewTabPage.URLState" enum="NewTabURLState" + expires_after="2021-01-01"> + <owner>tiborg@chromium.org</owner> <owner>yyushkina@chromium.org</owner> + <owner>chrome-desktop-ntp@google.com</owner> <summary> Records the status of the New Tab page URL when an NTP is opened. </summary> @@ -127744,7 +127844,7 @@ <summary>The size of PDF documents opened in the PDF viewer.</summary> </histogram> -<histogram name="PDF.FormType" enum="PDFFormTypes" expires_after="2020-10-11"> +<histogram name="PDF.FormType" enum="PDFFormTypes" expires_after="2021-01-17"> <owner>rharrison@chromium.org</owner> <owner>thestig@chromium.org</owner> <summary> @@ -137965,7 +138065,7 @@ </histogram> <histogram name="PrintPreview.PrintDocumentType" - enum="PrintPreviewPrintDocumentTypeBuckets" expires_after="2020-10-04"> + enum="PrintPreviewPrintDocumentTypeBuckets" expires_after="2021-01-17"> <owner>rbpotter@chromium.org</owner> <summary> Track type of documents printed (HTML vs PDF). Recorded immediately after a @@ -139451,7 +139551,7 @@ <histogram name="ProximityAuth.BluetoothGattNotifySessionResult" enum="ProximityAuth_BluetoothGattServiceOperationResult" - expires_after="2020-10-04"> + expires_after="2021-01-17"> <owner>hansberry@chromium.org</owner> <summary> Provides a breakdown of how many times each possible Bluetooth GATT @@ -139465,7 +139565,7 @@ <histogram name="ProximityAuth.BluetoothGattWriteCharacteristicResult" enum="ProximityAuth_BluetoothGattServiceOperationResult" - expires_after="2020-10-04"> + expires_after="2021-01-17"> <owner>hansberry@chromium.org</owner> <summary> Provides a breakdown of how many times each possible Bluetooth GATT @@ -171746,7 +171846,7 @@ </histogram> <histogram name="Sync.BackendInitializeFirstTime" units="ms" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>mastiz@chromium.org</owner> <owner>treib@chromium.org</owner> <summary> @@ -173245,7 +173345,7 @@ </histogram> <histogram name="Sync.LocalSyncTransportDataStartupState" - enum="LocalSyncTransportDataStartupState" expires_after="2020-11-08"> + enum="LocalSyncTransportDataStartupState" expires_after="2021-01-17"> <owner>rushans@google.com</owner> <owner>mastiz@chromium.org</owner> <summary> @@ -179734,7 +179834,7 @@ </histogram> <histogram name="Tracing.Background.FinalizationDisallowedReason" - enum="TracingFinalizationDisallowedReason" expires_after="2020-11-15"> + enum="TracingFinalizationDisallowedReason" expires_after="2021-01-17"> <owner>ssid@chromium.org</owner> <summary> Reason why background tracing finalization was not allowed. Also see @@ -179744,7 +179844,7 @@ </histogram> <histogram name="Tracing.Background.FinalizingTraceSizeInKB" units="KB" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>oysteine@chromium.org</owner> <summary> The size, in kilobytes, of a finalized trace ready to be uploaded. @@ -182462,7 +182562,7 @@ </histogram> <histogram name="UMA.TruncatedEvents.UserAction" units="events" - expires_after="2021-01-10"> + expires_after="2021-01-17"> <owner>rkaplow@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner> <summary> @@ -184147,8 +184247,9 @@ </histogram> <histogram name="V8.CompileScript.CacheBehaviour" enum="V8CacheBehaviour" - expires_after="M85"> + expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> The cache behaviour of compiling a V8 script, including whether we produced or consumed a code cache, whether we hit V8's isolate's cache, and if we @@ -184157,8 +184258,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds" units="microseconds" - expires_after="M85"> - <owner>yangguo@chromium.org</owner> + expires_after="2021-02-01"> + <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing/caching). @@ -184171,8 +184273,10 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.BackgroundThread" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> + <owner>leszeks@chromium.org</owner> <owner>rmcilroy@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing) on a background thread. @@ -184186,8 +184290,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.ConsumeCache" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script when the 'compilation' is deserializing it from the code cache. @@ -184201,8 +184306,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.ConsumeCache.Failed" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing/caching) when the compilation tried to deserialize it from the code cache, but failed. @@ -184216,8 +184322,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.IsolateCacheHit" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing/caching) in the case where the V8 isolate's compilation cache is hit. @@ -184231,8 +184338,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.NoCache.CacheTooCold" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing) when the cache is too cold to use. @@ -184246,8 +184354,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.NoCache.InlineScript" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing) when the script is an inline script. @@ -184261,8 +184370,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.NoCache.Other" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing) when we do not want to cache it. @@ -184276,8 +184386,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.NoCache.ScriptTooSmall" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing) when the script is too small to be cached. @@ -184291,8 +184402,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.ProduceCache" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in compiling a script (incl. parsing) and serializing it for the code cache. @@ -184306,8 +184418,9 @@ </histogram> <histogram name="V8.CompileScriptMicroSeconds.StreamingFinalization" - units="microseconds" expires_after="M85"> + units="microseconds" expires_after="2021-02-01"> <owner>leszeks@chromium.org</owner> + <owner>v8-runtime@google.com</owner> <summary> Total time spent in finalizing a script that was streaming compiled. @@ -192983,7 +193096,7 @@ </histogram> <histogram name="WebRTC.PeerConnection.ThermalState" enum="ThermalState" - expires_after="2020-10-01"> + expires_after="2021-01-17"> <owner>eshr@google.com</owner> <owner>hbos@chromium.com</owner> <summary> @@ -193023,7 +193136,7 @@ </histogram> <histogram name="WebRTC.ReceivedAudioTrackDuration" units="ms" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>perkj@chromium.org</owner> <summary> Durations of audio tracks received over a PeerConnection. The stopwatch @@ -193033,7 +193146,7 @@ </histogram> <histogram name="WebRTC.ReceivedVideoTrackDuration" units="ms" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>perkj@chromium.org</owner> <summary> Durations of video tracks received over a PeerConnection. The stopwatch @@ -193043,7 +193156,7 @@ </histogram> <histogram name="WebRTC.ReliableDataChannelMessageSize" units="bytes" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>perkj@chromium.org</owner> <summary> Sizes of messages sent over reliable data channels. The size of an @@ -193059,7 +193172,7 @@ </histogram> <histogram name="WebRTC.SentAudioTrackDuration" units="ms" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>perkj@chromium.org</owner> <summary> Durations of audio tracks sent over a PeerConnection. The stopwatch starts @@ -195039,7 +195152,7 @@ </histogram> <histogram name="WebUITabStrip.CloseAction" enum="WebUITabStripCloseActions" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>collinbaker@chromium.org</owner> <owner>dfried@chromium.org</owner> <summary> @@ -195050,7 +195163,7 @@ </histogram> <histogram name="WebUITabStrip.CloseTabAction" - enum="WebUITabStripCloseTabActions" expires_after="2020-11-15"> + enum="WebUITabStripCloseTabActions" expires_after="2021-01-17"> <owner>johntlee@chromium.org</owner> <owner>dpapad@chromium.org</owner> <summary> @@ -195061,7 +195174,7 @@ </histogram> <histogram name="WebUITabStrip.OpenAction" enum="WebUITabStripOpenActions" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>collinbaker@chromium.org</owner> <owner>dfried@chromium.org</owner> <summary> @@ -195072,7 +195185,7 @@ </histogram> <histogram name="WebUITabStrip.OpenDuration" units="ms" - expires_after="2020-11-15"> + expires_after="2021-01-17"> <owner>collinbaker@chromium.org</owner> <owner>dfried@chromium.org</owner> <summary>
diff --git a/tools/traffic_annotation/summary/annotations.xml b/tools/traffic_annotation/summary/annotations.xml index 1c31722..a6ad4d3b 100644 --- a/tools/traffic_annotation/summary/annotations.xml +++ b/tools/traffic_annotation/summary/annotations.xml
@@ -238,6 +238,7 @@ <item id="proxy_config_headless" hash_code="133221587" type="0" content_hash_code="77459277" os_list="linux,windows" file_path="headless/lib/browser/headless_request_context_manager.cc"/> <item id="proxy_config_settings" hash_code="136468456" type="0" content_hash_code="19527377" os_list="linux,windows" file_path="components/proxy_config/pref_proxy_config_tracker_impl.cc"/> <item id="proxy_config_system" hash_code="11258689" type="0" content_hash_code="77057929" os_list="linux,windows" file_path="net/proxy_resolution/configured_proxy_resolution_service.cc"/> + <item id="proxy_config_windows_resolver" hash_code="13924805" type="0" content_hash_code="123023599" os_list="windows" file_path="net/proxy_resolution/win/windows_system_proxy_resolution_request.cc"/> <item id="proxy_script_fetcher" hash_code="37531401" type="0" deprecated="2018-03-16" content_hash_code="31866133" file_path=""/> <item id="puch_client_channel" hash_code="34459548" type="0" deprecated="2020-01-23" content_hash_code="92475475" file_path=""/> <item id="qr_code_save" hash_code="87963126" type="0" content_hash_code="72717245" os_list="linux,windows" file_path="chrome/browser/ui/views/qrcode_generator/qrcode_generator_bubble.cc"/>
diff --git a/ui/base/cocoa/command_dispatcher.h b/ui/base/cocoa/command_dispatcher.h index 08811a94..1203c0a4 100644 --- a/ui/base/cocoa/command_dispatcher.h +++ b/ui/base/cocoa/command_dispatcher.h
@@ -58,9 +58,6 @@ - (void)dispatchUsingKeyModifiers:(id)sender forHandler:(id<UserInterfaceItemCommandHandler>)handler; -// TODO(bokan): Temporary to help debug https://crbug.com/1039833. -- (BOOL)isRedispatchingKeyEvent; - @end // If the NSWindow's firstResponder implements CommandDispatcherTarget, then
diff --git a/ui/base/cocoa/command_dispatcher.mm b/ui/base/cocoa/command_dispatcher.mm index ffc8ebd..1ae7b17 100644 --- a/ui/base/cocoa/command_dispatcher.mm +++ b/ui/base/cocoa/command_dispatcher.mm
@@ -267,10 +267,6 @@ [[self bubbleParent] commandDispatchUsingKeyModifiers:sender]; } -- (BOOL)isRedispatchingKeyEvent { - return _isRedispatchingKeyEvent; -} - - (NSWindow<CommandDispatchingWindow>*)bubbleParent { NSWindow* parent = [_owner parentWindow]; if (parent && [parent hasKeyAppearance] &&
diff --git a/ui/views/view_targeter_delegate.cc b/ui/views/view_targeter_delegate.cc index 82f1424..c64e6ea 100644 --- a/ui/views/view_targeter_delegate.cc +++ b/ui/views/view_targeter_delegate.cc
@@ -89,17 +89,6 @@ if (views::UsePointBasedTargeting(rect) || (!rect_view && !point_view)) return root; - // If |root| is a suitable candidate for rect-based targeting, check to - // see if it is closer than the current best suitable candidate so far. - gfx::Rect local_bounds(root->GetLocalBounds()); - if (views::PercentCoveredBy(local_bounds, rect) >= kRectTargetOverlap) { - gfx::Point touch_center(rect.CenterPoint()); - int cur_dist = - views::DistanceSquaredFromCenterToPoint(touch_center, local_bounds); - if (!rect_view || cur_dist < rect_view_distance) - rect_view = root; - } - return rect_view ? rect_view : point_view; }
diff --git a/ui/views/view_targeter_unittest.cc b/ui/views/view_targeter_unittest.cc index f2994f9a..a14e363 100644 --- a/ui/views/view_targeter_unittest.cc +++ b/ui/views/view_targeter_unittest.cc
@@ -4,6 +4,7 @@ #include "ui/views/view_targeter.h" +#include <memory> #include <utility> #include "base/macros.h" @@ -651,5 +652,29 @@ widget->CloseNow(); } +TEST_F(ViewTargeterTest, FavorChildContainingHitBounds) { + Widget widget; + Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); + init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + init_params.bounds = gfx::Rect(0, 0, 200, 200); + widget.Init(std::move(init_params)); + + View* content = widget.SetContentsView(std::make_unique<View>()); + content->SetBounds(0, 0, 50, 50); + View* child = content->AddChildView(std::make_unique<View>()); + child->SetBounds(2, 2, 50, 50); + + internal::RootView* root_view = + static_cast<internal::RootView*>(widget.GetRootView()); + ui::EventTargeter* targeter = root_view->targeter(); + + gfx::RectF bounding_box(gfx::PointF(4.f, 4.f), gfx::SizeF(42.f, 42.f)); + ui::GestureEventDetails details(ui::ET_GESTURE_TAP); + details.set_bounding_box(bounding_box); + GestureEventForTest tap(details); + + EXPECT_EQ(child, targeter->FindTargetForEvent(root_view, &tap)); +} + } // namespace test } // namespace views
diff --git a/ui/views/view_unittest.cc b/ui/views/view_unittest.cc index fc05e41..64a19f80 100644 --- a/ui/views/view_unittest.cc +++ b/ui/views/view_unittest.cc
@@ -1532,7 +1532,8 @@ // the center points of |v4| and |v41|. touch_rect.SetRect(310, 210, 80, 80); result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v41, result_view); + // |v411| is the deepest view that is completely contained by |touch_rect|. + EXPECT_EQ(v411, result_view); result_view = nullptr; // Intersects all of |v4|, |v41|, and |v411| but only covers @@ -1603,21 +1604,19 @@ // Intersects all of |v2|, |v3|, |v32|, |v4|, |v41|, and |v411|. // Covers |v2|, |v32|, |v4|, |v41|, and |v411| by at least 60%. - // The center point of |touch_rect| is closest to the center - // point of |root_view|. touch_rect.SetRect(110, 15, 375, 450); result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(root_view, result_view); + // Target is |v411| as it is the deepest view touched by at least 60% of the + // rect. + EXPECT_EQ(v411, result_view); result_view = nullptr; // Covers all views (except |v5| and |v51|) by at least 60%. The // center point of |touch_rect| is equally close to the center - // points of |v2| and |v32|. One is not a descendant of the other, - // so in this case the view selected is arbitrary (i.e., - // it depends only on the ordering of nodes in the views - // hierarchy). + // points of |v2| and |v32|. touch_rect.SetRect(0, 0, 400, 300); result_view = root_view->GetEventHandlerForRect(touch_rect); + // |v32| is the deepest view that is contained by the rest. EXPECT_EQ(v32, result_view); result_view = nullptr;
diff --git a/weblayer/browser/browser_context_impl.cc b/weblayer/browser/browser_context_impl.cc index 582cdba..d22bc27 100644 --- a/weblayer/browser/browser_context_impl.cc +++ b/weblayer/browser/browser_context_impl.cc
@@ -26,7 +26,7 @@ #include "components/translate/core/browser/translate_prefs.h" #include "components/user_prefs/user_prefs.h" #include "components/variations/variations_client.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "content/public/browser/device_service.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/resource_context.h" @@ -285,7 +285,7 @@ } std::string GetVariationsHeader() const override { - return variations::VariationsHttpHeaderProvider::GetInstance() + return variations::VariationsIdsProvider::GetInstance() ->GetClientDataHeader(IsSignedIn()); }
diff --git a/weblayer/browser/navigation_browsertest.cc b/weblayer/browser/navigation_browsertest.cc index 4d3c4ae..0d024d8 100644 --- a/weblayer/browser/navigation_browsertest.cc +++ b/weblayer/browser/navigation_browsertest.cc
@@ -8,7 +8,7 @@ #include "base/files/file_path.h" #include "base/test/bind_test_util.h" #include "components/variations/net/variations_http_headers.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "content/public/test/url_loader_interceptor.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/controllable_http_response.h" @@ -616,7 +616,7 @@ // Forces variations code to set the header. auto* variations_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); + variations::VariationsIdsProvider::GetInstance(); variations_provider->ForceVariationIds({"12", "456", "t789"}, ""); }
diff --git a/weblayer/browser/weblayer_variations_http_browsertest.cc b/weblayer/browser/weblayer_variations_http_browsertest.cc index f55317da..5b6ea6d 100644 --- a/weblayer/browser/weblayer_variations_http_browsertest.cc +++ b/weblayer/browser/weblayer_variations_http_browsertest.cc
@@ -4,7 +4,7 @@ #include "weblayer/test/weblayer_browser_test.h" -#include "components/variations/variations_http_header_provider.h" +#include "components/variations/variations_ids_provider.h" #include "content/public/test/network_connection_change_simulator.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" @@ -87,7 +87,7 @@ void SetUpOnMainThread() override { auto* variations_provider = - variations::VariationsHttpHeaderProvider::GetInstance(); + variations::VariationsIdsProvider::GetInstance(); variations_provider->ForceVariationIds({"12", "456", "t789"}, ""); // The test makes requests to google.com which we want to redirect to the