diff --git a/.clang-tidy b/.clang-tidy index c7515c8..9e666cd2 100644 --- a/.clang-tidy +++ b/.clang-tidy
@@ -1,5 +1,6 @@ --- Checks: '-*, + bugprone-argument-comment, bugprone-string-integer-assignment, bugprone-unused-raii, bugprone-use-after-move, @@ -32,4 +33,3 @@ - key: modernize-use-emplace.IgnoreImplicitConstructors value: 1 ... -
diff --git a/DEPS b/DEPS index 8321df55..c82608a 100644 --- a/DEPS +++ b/DEPS
@@ -200,11 +200,11 @@ # 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': '416fe32ce119762b58289e38d5d5149bd1ce724a', + 'skia_revision': 'a1ebb44f6150ee5492580c2d570a6fb2dcd7c7a9', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': 'f1e2bbd80f2e2eacf7e043e18ee55f0b8cf22171', + 'v8_revision': '4f7b9247f5edfccbe90dfa8ced02893e7fd38d23', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -212,7 +212,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '3f564fc76ea8a556d628517b055af85c27a60bc3', + 'angle_revision': 'df873e5fa6d33d5d402cf90dc6106e6812bc71f7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -275,7 +275,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': '25c0c4f6128cce306ea3d99a47f333ba49371862', + 'devtools_frontend_revision': '9cfe927efca2515dd556acc8a2e482ee0662dbeb', # 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. @@ -327,7 +327,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '6a7095d8c75373e363d52faed3c74f517ca7311f', + 'dawn_revision': 'a6a7e46e54518bd730caf47ef4d4a01ff81f9123', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -919,7 +919,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1af7968d686d4492359a695eb57636f9d355f488', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '6d2a0fef93155cb26724fbc0430f7a6f1d1aaed1', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1291,7 +1291,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '42433abb9596f1f471251070f7fd7d135c3e9df0', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '05e6cccec4351c20459256bab83bd8f79fa7ff55', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1369,7 +1369,7 @@ 'packages': [ { 'package': 'fuchsia/third_party/aemu/linux-amd64', - 'version': 'uQdbvtcP840HCVMjrZtUTrYeUgSD_J2rxG1WcyDUbvMC' + 'version': 'jfuzh1KU9b_qTmPrfQ2v7GW8FB2tUz0uUUjeyB_2LdQC' }, ], 'condition': 'host_os == "linux" and checkout_fuchsia', @@ -1623,7 +1623,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@d96af00c928618697579b3829f6806ebc8ad0882', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@8f303e8141bca8377cc2c848e5a92c93aebeee3e', 'condition': 'checkout_src_internal', },
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index f93669b..29be6ce 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -1429,6 +1429,8 @@ "tray_action/tray_action.cc", "tray_action/tray_action.h", "tray_action/tray_action_observer.h", + "utility/layer_util.cc", + "utility/layer_util.h", "utility/screenshot_controller.cc", "utility/screenshot_controller.h", "utility/transformer_util.cc",
diff --git a/ash/login/login_screen_controller.cc b/ash/login/login_screen_controller.cc index 95bbb145..ec1d56b 100644 --- a/ash/login/login_screen_controller.cc +++ b/ash/login/login_screen_controller.cc
@@ -326,6 +326,13 @@ ->SetShutdownButtonEnabled(enable); } +void LoginScreenController::EnableShelfButtons(bool enable) { + Shelf::ForWindow(Shell::Get()->GetPrimaryRootWindow()) + ->shelf_widget() + ->login_shelf_view() + ->SetButtonEnabled(enable); +} + void LoginScreenController::SetIsFirstSigninStep(bool is_first) { Shelf::ForWindow(Shell::Get()->GetPrimaryRootWindow()) ->shelf_widget()
diff --git a/ash/login/login_screen_controller.h b/ash/login/login_screen_controller.h index c79a983..a3cc00c 100644 --- a/ash/login/login_screen_controller.h +++ b/ash/login/login_screen_controller.h
@@ -112,6 +112,7 @@ bool IsReadyForPassword() override; void EnableAddUserButton(bool enable) override; void EnableShutdownButton(bool enable) override; + void EnableShelfButtons(bool enable) override; void SetIsFirstSigninStep(bool is_first) override; void ShowParentAccessButton(bool show) override; void SetAllowLoginAsGuest(bool allow_guest) override;
diff --git a/ash/login/ui/README.md b/ash/login/ui/README.md new file mode 100644 index 0000000..b52e786 --- /dev/null +++ b/ash/login/ui/README.md
@@ -0,0 +1,71 @@ +General hierarchy of UI elements in authentication UI: + +`LockScreen` is the root element, that owns `LockContentsView` (potentially +wrapped in `LockDebugView`). It resides in kShellWindowId_LockScreenContainer +layer of the primary display. + +`LoginDataDispatcher` implements `LoginScreenModel` and redirects calls to its +observers, main of which is `LockContentView`. + +`LockContentView` is a full-screen view that owns and displays all other +authentication UI elements: + * When only one user is in the list it is displayed using `LoginBigUserView`; + * When two users are on the list, they are displayed using two + `LoginBigUserView`s; + * When 3+ users are in the list, one `LoginBigUserView` is used to display + selected user, and rest of the users are displayed using + `ScrollableUsersListView`; + * `LoginExpandedPublicAccountView` when the user tries to sign in to public + account. + * Allows selection of language/keyboard for Public session + * Displays monitoring warning indicator and triggers + `PublicAccountWarningDialog` + * Allows to actually sign in to the public account + * Also owns/refers to following optional UI elements: + * `LockScreenMediaControlsView` + * `NoteActionLaunchButton` + * UI that shows information about system. + * Various bubbles and indicators + * `UserAddingScreenIndicator` displayed when screen is used for + multiprofile login + * `BottomStatusIndicator` for indicating management/ADB sideloading + info + * `ManagementBubble` for management disclosure + * `AuthErrorBubble` for displaying auth errors + * `LoginErrorBubble` for displaying: + * security warnings when detachable keyboard does not match one + used on previous login + * ext4 migration warning + * supervised user deprecation notice + * `LoginTooltipView` for easy unlock tooltips + +`LoginBigUserView` contains one of: + * `LoginPublicAccountUserView` that consists of: + * `LoginUserView` (see below) + * Arrow button to proceed to showing `LoginExpandedPublicAccountView` + (see above) + * `LoginAuthUserView` that represents user information and provides UI + for authentication. It consists of: + * `LoginUserView` + * (Animated) user image + * Name label + * Drop-down info with an option to remove user + * `LoginPasswordView` that shows: + * Password input field + * "Show Password" button + * CAPS LOCK indicator + * Submit button + * Quick unlock indicator + * or pair of `LoginPinView` (that provides digital keyboard) along with + `LoginPinInputView` (that provides positional input field) + * Password/PIN toggle button + * Button to trigger online sign-in + * `FingerprintView` + * `ChallengeResponseView` + * `DisabledAuthMessageView` (e.g. when child user has an associated + time limit) + * `LockedTpmMessageView` + +`PinRequestWidget` works as a standalone UI. It contains a `PinRequestView` +that consists of `LoginPinKeyboard` and one of either `FixedLengthCodeInput` or +`FlexCodeInput`, both of which are subclasses of `AccessCodeInput`.
diff --git a/ash/public/cpp/login_screen.h b/ash/public/cpp/login_screen.h index 4dd111a..a3ed9fd 100644 --- a/ash/public/cpp/login_screen.h +++ b/ash/public/cpp/login_screen.h
@@ -51,6 +51,9 @@ // Sets whether shutdown button is enabled in the login screen. virtual void EnableShutdownButton(bool enable) = 0; + // Sets whether shelf buttons are enabled. + virtual void EnableShelfButtons(bool enable) = 0; + // Used to show or hide apps the guest and buttons on the login shelf during // OOBE. virtual void SetIsFirstSigninStep(bool is_first) = 0;
diff --git a/ash/rotator/screen_rotation_animator.cc b/ash/rotator/screen_rotation_animator.cc index 4436400..13f2cef0 100644 --- a/ash/rotator/screen_rotation_animator.cc +++ b/ash/rotator/screen_rotation_animator.cc
@@ -13,6 +13,7 @@ #include "ash/rotator/screen_rotation_animation.h" #include "ash/rotator/screen_rotation_animator_observer.h" #include "ash/shell.h" +#include "ash/utility/layer_util.h" #include "ash/utility/transformer_util.h" #include "base/bind.h" #include "base/command_line.h" @@ -21,7 +22,6 @@ #include "base/time/time.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_result.h" -#include "third_party/khronos/GLES2/gl2.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" #include "ui/compositor/animation_throughput_reporter.h" @@ -360,23 +360,14 @@ std::unique_ptr<ui::LayerTreeOwner> ScreenRotationAnimator::CopyLayerTree( std::unique_ptr<viz::CopyOutputResult> result) { - DCHECK(!result->IsEmpty()); - DCHECK_EQ(result->format(), viz::CopyOutputResult::Format::RGBA_TEXTURE); - auto transfer_resource = viz::TransferableResource::MakeGL( - result->GetTextureResult()->mailbox, GL_LINEAR, GL_TEXTURE_2D, - result->GetTextureResult()->sync_token, result->size(), - false /* is_overlay_candidate */); - std::unique_ptr<viz::SingleReleaseCallback> release_callback = - result->TakeTextureOwnership(); + std::unique_ptr<ui::Layer> copy_layer = + CreateLayerFromCopyOutputResult(std::move(result)); const gfx::Rect rect( GetScreenRotationContainer(root_window_)->layer()->size()); - std::unique_ptr<ui::Layer> copy_layer = std::make_unique<ui::Layer>(); copy_layer->SetBounds(rect); // TODO(crbug.com/1040279): This is a workaround and should be removed once // the issue is fixed. copy_layer->SetFillsBoundsOpaquely(false); - copy_layer->SetTransferableResource(transfer_resource, - std::move(release_callback), rect.size()); return std::make_unique<ui::LayerTreeOwner>(std::move(copy_layer)); }
diff --git a/ash/shelf/login_shelf_view.cc b/ash/shelf/login_shelf_view.cc index a8a796e..60abde8e 100644 --- a/ash/shelf/login_shelf_view.cc +++ b/ash/shelf/login_shelf_view.cc
@@ -31,6 +31,7 @@ #include "ash/system/status_area_widget.h" #include "ash/system/status_area_widget_delegate.h" #include "ash/system/tray/system_tray_notifier.h" +#include "ash/system/tray/tray_background_view.h" #include "ash/system/tray/tray_popup_utils.h" #include "ash/wm/lock_state_controller.h" #include "base/bind.h" @@ -77,6 +78,18 @@ const char* kLoginShelfButtonClassName = "LoginShelfButton"; +constexpr LoginShelfView::ButtonId kButtonIds[] = { + LoginShelfView::kShutdown, + LoginShelfView::kRestart, + LoginShelfView::kSignOut, + LoginShelfView::kCloseNote, + LoginShelfView::kCancel, + LoginShelfView::kParentAccess, + LoginShelfView::kBrowseAsGuest, + LoginShelfView::kAddUser, + LoginShelfView::kEnterpriseEnrollment, +}; + SkColor GetButtonTextColor() { return DeprecatedGetContentLayerColor( AshColorProvider::ContentLayerType::kButtonLabelColor, @@ -655,18 +668,42 @@ void LoginShelfView::SetShutdownButtonEnabled(bool enable_shutdown_button) { GetViewByID(kShutdown)->SetEnabled(enable_shutdown_button); } + +void LoginShelfView::SetButtonEnabled(bool enabled) { + // Only allow enabling shelf buttons when shelf is temporarily disabled and + // only allow temporarily disabling shelf buttons when shelf is not already + // disabled. + if (enabled != is_shelf_temp_disabled_) + return; + is_shelf_temp_disabled_ = !enabled; + + for (const auto& button_id : kButtonIds) { + GetViewByID(button_id)->SetEnabled(enabled); + } + + StatusAreaWidget* status_area_widget = + Shelf::ForWindow(GetWidget()->GetNativeWindow())->GetStatusAreaWidget(); + if (enabled) { + for (TrayBackgroundView* tray_button : status_area_widget->tray_buttons()) { + // Do not enable the button if it is already in disabled state before we + // temporarily disable it. + if (disabled_tray_buttons_.count(tray_button)) + continue; + tray_button->SetEnabled(true); + } + disabled_tray_buttons_.clear(); + } else { + for (TrayBackgroundView* tray_button : status_area_widget->tray_buttons()) { + // Record the tray button if it is already in disabled state before we + // temporarily disable it. + if (!tray_button->GetEnabled()) + disabled_tray_buttons_.insert(tray_button); + tray_button->SetEnabled(false); + } + } +} + void LoginShelfView::SetButtonOpacity(float target_opacity) { - static constexpr ButtonId kButtonIds[] = { - kShutdown, - kRestart, - kSignOut, - kCloseNote, - kCancel, - kParentAccess, - kBrowseAsGuest, - kAddUser, - kEnterpriseEnrollment - }; for (const auto& button_id : kButtonIds) { AnimateButtonOpacity(GetViewByID(button_id)->layer(), target_opacity, ShelfConfig::Get()->DimAnimationDuration(),
diff --git a/ash/shelf/login_shelf_view.h b/ash/shelf/login_shelf_view.h index 3384808..3cfb31e 100644 --- a/ash/shelf/login_shelf_view.h +++ b/ash/shelf/login_shelf_view.h
@@ -37,6 +37,7 @@ enum class LockScreenActionBackgroundState; class KioskAppsButton; +class TrayBackgroundView; // LoginShelfView contains the shelf buttons visible outside of an active user // session. ShelfView and LoginShelfView should never be shown together. @@ -102,6 +103,10 @@ // Sets whether shutdown button is enabled in the login screen. void SetShutdownButtonEnabled(bool enable_shutdown_button); + // Disable shelf buttons and tray buttons temporarily and enable them back + // later. It could be used for temporary disable due to opened modal dialog. + void SetButtonEnabled(bool enabled); + // Sets and animates the opacity of login shelf buttons. void SetButtonOpacity(float target_opacity); @@ -208,6 +213,14 @@ // Number of active scoped Guest button blockers. int scoped_guest_button_blockers_ = 0; + // Whether shelf buttons are temporarily disabled due to opened modal dialog. + bool is_shelf_temp_disabled_ = false; + + // Set of the tray buttons which are in disabled state. It is used to record + // and recover the states of tray buttons after temporarily disable of the + // buttons. + std::set<TrayBackgroundView*> disabled_tray_buttons_; + base::WeakPtrFactory<LoginShelfView> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LoginShelfView);
diff --git a/ash/system/power/power_button_controller.cc b/ash/system/power/power_button_controller.cc index 9e142aa..e592db51 100644 --- a/ash/system/power/power_button_controller.cc +++ b/ash/system/power/power_button_controller.cc
@@ -113,7 +113,12 @@ power_manager_client->AddObserver(this); power_manager_client->GetSwitchStates(base::BindOnce( &PowerButtonController::OnGetSwitchStates, weak_factory_.GetWeakPtr())); - AccelerometerReader::GetInstance()->AddObserver(this); + + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kAshEnableTabletMode)) { + AccelerometerReader::GetInstance()->AddObserver(this); + } + auto* shell = Shell::Get(); shell->display_configurator()->AddObserver(this); backlights_forced_off_observer_.Add(backlights_forced_off_setter); @@ -380,28 +385,20 @@ if (result->tablet_mode != chromeos::PowerManagerClient::TabletMode::UNSUPPORTED) { - has_tablet_mode_switch_ = true; + AccelerometerReader::GetInstance()->RemoveObserver(this); InitTabletPowerButtonMembers(); } } void PowerButtonController::OnAccelerometerUpdated( scoped_refptr<const AccelerometerUpdate> update) { - if (ec_lid_angle_driver_status_ == ECLidAngleDriverStatus::UNKNOWN) { - ec_lid_angle_driver_status_ = - AccelerometerReader::GetInstance()->GetECLidAngleDriverStatus(); - } + DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kAshEnableTabletMode)); - // When ChromeOS EC lid angle driver is supported, there's always tablet mode - // switch in device, so PowerButtonController doesn't need to listens to - // accelerometer events. - if (ec_lid_angle_driver_status_ == ECLidAngleDriverStatus::SUPPORTED) { - AccelerometerReader::GetInstance()->RemoveObserver(this); - return; - } - - if (!has_tablet_mode_switch_ && observe_accelerometer_events_) - InitTabletPowerButtonMembers(); + // This device has at least an accelerometer, therefore it is a tablet or + // convertible. + AccelerometerReader::GetInstance()->RemoveObserver(this); + InitTabletPowerButtonMembers(); } void PowerButtonController::OnBacklightsForcedOffChanged(bool forced_off) { @@ -479,7 +476,6 @@ button_type_ = cl->HasSwitch(switches::kAuraLegacyPowerButton) ? ButtonType::LEGACY : ButtonType::NORMAL; - observe_accelerometer_events_ = cl->HasSwitch(switches::kAshEnableTabletMode); force_tablet_power_button_ = cl->HasSwitch(switches::kForceTabletPowerButton); ParsePowerButtonPositionSwitch();
diff --git a/ash/system/power/power_button_controller.h b/ash/system/power/power_button_controller.h index 27ee782..2fac951 100644 --- a/ash/system/power/power_button_controller.h +++ b/ash/system/power/power_button_controller.h
@@ -217,23 +217,10 @@ // Saves the button type for this power button. ButtonType button_type_ = ButtonType::NORMAL; - // True if the device should observe accelerometer events to enter tablet - // mode. - bool observe_accelerometer_events_ = false; - // True if the kForceTabletPowerButton flag is set. This forces tablet power // button behavior even while in laptop mode. bool force_tablet_power_button_ = false; - // True if the device has tablet mode switch. - bool has_tablet_mode_switch_ = false; - - // When ChromeOS EC lid angle driver is supported, there's always tablet mode - // switch in device, so PowerButtonController doesn't need to listens to - // accelerometer events. - ECLidAngleDriverStatus ec_lid_angle_driver_status_ = - ECLidAngleDriverStatus::UNKNOWN; - // True if the screen was off when the power button was pressed. bool screen_off_when_power_button_down_ = false;
diff --git a/ash/system/status_area_widget.h b/ash/system/status_area_widget.h index 0414e34b..c7465507 100644 --- a/ash/system/status_area_widget.h +++ b/ash/system/status_area_widget.h
@@ -136,6 +136,10 @@ Shelf* shelf() { return shelf_; } + const std::vector<TrayBackgroundView*>& tray_buttons() const { + return tray_buttons_; + } + LoginStatus login_status() const { return login_status_; } // Returns true if the shelf should be visible. This is used when the
diff --git a/ash/utility/layer_util.cc b/ash/utility/layer_util.cc new file mode 100644 index 0000000..0fd907c --- /dev/null +++ b/ash/utility/layer_util.cc
@@ -0,0 +1,67 @@ +// 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 "ash/utility/layer_util.h" + +#include "components/viz/common/frame_sinks/copy_output_request.h" +#include "components/viz/common/frame_sinks/copy_output_result.h" +#include "third_party/khronos/GLES2/gl2.h" +#include "ui/compositor/layer.h" +#include "ui/gfx/geometry/size.h" + +namespace ash { +namespace { + +void CopyCopyOutputResultToLayer( + std::unique_ptr<viz::CopyOutputResult> copy_result, + ui::Layer* target_layer) { + DCHECK(!copy_result->IsEmpty()); + DCHECK_EQ(copy_result->format(), viz::CopyOutputResult::Format::RGBA_TEXTURE); + + const gfx::Size layer_size = copy_result->size(); + viz::TransferableResource transferable_resource = + viz::TransferableResource::MakeGL( + copy_result->GetTextureResult()->mailbox, GL_LINEAR, GL_TEXTURE_2D, + copy_result->GetTextureResult()->sync_token, layer_size, + /*is_overlay_candidate=*/false); + std::unique_ptr<viz::SingleReleaseCallback> release_callback = + copy_result->TakeTextureOwnership(); + target_layer->SetTransferableResource( + transferable_resource, std::move(release_callback), layer_size); +} + +void CopyToNewLayerOnCopyRequestFinished( + LayerCopyCallback layer_copy_callback, + std::unique_ptr<viz::CopyOutputResult> copy_result) { + if (!copy_result || copy_result->IsEmpty()) { + std::move(layer_copy_callback).Run(nullptr); + return; + } + + auto copy_layer = CreateLayerFromCopyOutputResult(std::move(copy_result)); + std::move(layer_copy_callback).Run(std::move(copy_layer)); +} + +} // namespace + +std::unique_ptr<ui::Layer> CreateLayerFromCopyOutputResult( + std::unique_ptr<viz::CopyOutputResult> copy_result) { + auto copy_layer = std::make_unique<ui::Layer>(); + CopyCopyOutputResultToLayer(std::move(copy_result), copy_layer.get()); + return copy_layer; +} + +void CopyLayerContentToNewLayer(ui::Layer* layer, LayerCopyCallback callback) { + auto new_callback = + base::BindOnce(&CopyToNewLayerOnCopyRequestFinished, std::move(callback)); + auto copy_request = std::make_unique<viz::CopyOutputRequest>( + viz::CopyOutputRequest::ResultFormat::RGBA_TEXTURE, + std::move(new_callback)); + gfx::Rect bounds(layer->size()); + copy_request->set_area(bounds); + copy_request->set_result_selection(bounds); + layer->RequestCopyOfOutput(std::move(copy_request)); +} + +} // namespace ash
diff --git a/ash/utility/layer_util.h b/ash/utility/layer_util.h new file mode 100644 index 0000000..ff175de --- /dev/null +++ b/ash/utility/layer_util.h
@@ -0,0 +1,34 @@ +// 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 ASH_UTILITY_LAYER_UTIL_H_ +#define ASH_UTILITY_LAYER_UTIL_H_ + +#include <memory> + +#include "base/callback.h" + +namespace ui { +class Layer; +} + +namespace viz { +class CopyOutputResult; +} + +namespace ash { +using LayerCopyCallback = + base::OnceCallback<void(std::unique_ptr<ui::Layer> new_layer)>; + +// Creates the new layer using the image in |copy_result|. +std::unique_ptr<ui::Layer> CreateLayerFromCopyOutputResult( + std::unique_ptr<viz::CopyOutputResult> copy_result); + +// Creates a new layer that has a copy of the |layer|'s content. This is an +// async API and a new layer will be passed to the |callback| when copy is done. +void CopyLayerContentToNewLayer(ui::Layer* layer, LayerCopyCallback callback); + +} // namespace ash + +#endif // ASH_UTILITY_LAYER_UTIL_H_
diff --git a/ash/wm/tablet_mode/tablet_mode_controller.cc b/ash/wm/tablet_mode/tablet_mode_controller.cc index 88849e5..93623ac 100644 --- a/ash/wm/tablet_mode/tablet_mode_controller.cc +++ b/ash/wm/tablet_mode/tablet_mode_controller.cc
@@ -20,6 +20,7 @@ #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/strings/grit/ash_strings.h" +#include "ash/utility/layer_util.h" #include "ash/wm/overview/overview_controller.h" #include "ash/wm/splitview/split_view_utils.h" #include "ash/wm/tablet_mode/internal_input_devices_event_blocker.h" @@ -38,9 +39,6 @@ #include "base/time/tick_clock.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/system/devicemode.h" -#include "components/viz/common/frame_sinks/copy_output_request.h" -#include "components/viz/common/frame_sinks/copy_output_result.h" -#include "third_party/khronos/GLES2/gl2.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window_observer.h" #include "ui/base/accelerators/accelerator.h" @@ -161,26 +159,6 @@ TabletModeController::GetObservedTabletTransitionProperty(); } -std::unique_ptr<ui::Layer> CreateLayerFromScreenshotResult( - std::unique_ptr<viz::CopyOutputResult> copy_result) { - DCHECK(!copy_result->IsEmpty()); - DCHECK_EQ(copy_result->format(), viz::CopyOutputResult::Format::RGBA_TEXTURE); - - const gfx::Size layer_size = copy_result->size(); - viz::TransferableResource transferable_resource = - viz::TransferableResource::MakeGL( - copy_result->GetTextureResult()->mailbox, GL_LINEAR, GL_TEXTURE_2D, - copy_result->GetTextureResult()->sync_token, layer_size, - /*is_overlay_candidate=*/false); - std::unique_ptr<viz::SingleReleaseCallback> release_callback = - copy_result->TakeTextureOwnership(); - auto screenshot_layer = std::make_unique<ui::Layer>(); - screenshot_layer->SetTransferableResource( - transferable_resource, std::move(release_callback), layer_size); - - return screenshot_layer; -} - // Check if there is any external and internal pointing device in // |input_devices|. void CheckHasPointingDevices( @@ -1199,25 +1177,19 @@ // Request a screenshot. screenshot_taken_callback_.Reset(base::BindOnce( - &TabletModeController::OnScreenshotTaken, weak_factory_.GetWeakPtr(), + &TabletModeController::OnLayerCopyed, weak_factory_.GetWeakPtr(), std::move(callback), root_window)); - const gfx::Rect request_bounds(screenshot_window->layer()->size()); - auto screenshot_request = std::make_unique<viz::CopyOutputRequest>( - viz::CopyOutputRequest::ResultFormat::RGBA_TEXTURE, - screenshot_taken_callback_.callback()); - screenshot_request->set_area(request_bounds); - screenshot_request->set_result_selection(request_bounds); - screenshot_window->layer()->RequestCopyOfOutput( - std::move(screenshot_request)); + CopyLayerContentToNewLayer(screenshot_window->layer(), + screenshot_taken_callback_.callback()); VLOG(1) << "Tablet screenshot requested."; } -void TabletModeController::OnScreenshotTaken( +void TabletModeController::OnLayerCopyed( base::OnceClosure on_screenshot_taken, aura::Window* root_window, - std::unique_ptr<viz::CopyOutputResult> copy_result) { + std::unique_ptr<ui::Layer> copy_layer) { aura::Window* top_window = destroy_observer_ ? destroy_observer_->window() : nullptr; ResetDestroyObserver(); @@ -1228,14 +1200,14 @@ if (!base::Contains(Shell::GetAllRootWindows(), root_window)) return; - if (!copy_result || copy_result->IsEmpty() || !top_window) { + if (!copy_layer || !top_window) { std::move(on_screenshot_taken).Run(); return; } // Stack the screenshot under |top_window|, to fully occlude all windows // except |top_window| for the duration of the enter tablet mode animation. - screenshot_layer_ = CreateLayerFromScreenshotResult(std::move(copy_result)); + screenshot_layer_ = std::move(copy_layer); top_window->parent()->layer()->Add(screenshot_layer_.get()); screenshot_layer_->SetBounds(top_window->GetRootWindow()->bounds()); top_window->parent()->layer()->StackBelow(screenshot_layer_.get(),
diff --git a/ash/wm/tablet_mode/tablet_mode_controller.h b/ash/wm/tablet_mode/tablet_mode_controller.h index daac01d..4bf22b5 100644 --- a/ash/wm/tablet_mode/tablet_mode_controller.h +++ b/ash/wm/tablet_mode/tablet_mode_controller.h
@@ -53,10 +53,6 @@ class Widget; } -namespace viz { -class CopyOutputResult; -} - namespace ash { class InternalInputDevicesEventBlocker; @@ -312,9 +308,9 @@ // Called when a screenshot is taken. Creates |screenshot_widget_| which holds // the screenshot results and stacks it under top window. |root_window| // specifies on which root window the screen shot is taken. - void OnScreenshotTaken(base::OnceClosure on_screenshot_taken, - aura::Window* root_window, - std::unique_ptr<viz::CopyOutputResult> copy_result); + void OnLayerCopyed(base::OnceClosure on_screenshot_taken, + aura::Window* root_window, + std::unique_ptr<ui::Layer> copy_layer); // Calculates whether the device is currently in a physical tablet state, // using the most recent seen device events such as lid angle changes. @@ -464,7 +460,7 @@ // Tracks and record transition smoothness. base::Optional<ui::ThroughputTracker> transition_tracker_; - base::CancelableOnceCallback<void(std::unique_ptr<viz::CopyOutputResult>)> + base::CancelableOnceCallback<void(std::unique_ptr<ui::Layer>)> screenshot_taken_callback_; base::CancelableOnceClosure screenshot_set_callback_;
diff --git a/base/allocator/partition_allocator/partition_bucket.cc b/base/allocator/partition_allocator/partition_bucket.cc index be169dac..9a4a7a7 100644 --- a/base/allocator/partition_allocator/partition_bucket.cc +++ b/base/allocator/partition_allocator/partition_bucket.cc
@@ -569,7 +569,7 @@ void* addr = SlotSpanMetadata<thread_safe>::ToPointer(new_slot_span); root->RecommitSystemPagesForData( addr, new_slot_span->bucket->get_bytes_per_span(), - PageKeepPermissionsIfPossible); + PageUpdatePermissions); new_slot_span->Reset(); *is_already_zeroed = kDecommittedPagesAreAlwaysZeroed; }
diff --git a/base/allocator/partition_allocator/partition_page.cc b/base/allocator/partition_allocator/partition_page.cc index aafb7ba0..ebd83974 100644 --- a/base/allocator/partition_allocator/partition_page.cc +++ b/base/allocator/partition_allocator/partition_page.cc
@@ -168,7 +168,7 @@ PA_DCHECK(!bucket->is_direct_mapped()); void* addr = SlotSpanMetadata::ToPointer(this); root->DecommitSystemPagesForData(addr, bucket->get_bytes_per_span(), - PageKeepPermissionsIfPossible); + PageUpdatePermissions); // We actually leave the decommitted slot span in the active list. We'll sweep // it on to the decommitted list when we next walk the active list.
diff --git a/base/allocator/partition_allocator/partition_root.cc b/base/allocator/partition_allocator/partition_root.cc index fb63b42a..d4c850b 100644 --- a/base/allocator/partition_allocator/partition_root.cc +++ b/base/allocator/partition_allocator/partition_root.cc
@@ -596,6 +596,16 @@ template <bool thread_safe> void PartitionRoot<thread_safe>::PurgeMemory(int flags) { + // PCScan quarantines freed slots. Trigger the scan first to let it call + // FreeNoHooksImmediate on slots that pass the quarantine. + // + // In turn, FreeNoHooksImmediate may add slots to thread cache. Purge it next + // so that the slots are actually freed. (This is done synchronously only for + // the current thread.) + // + // Lastly decommit empty slot spans and lastly try to discard unused pages at + // the end of the remaining active slots. + // TODO(chromium:1129751): Change to LIKELY once PCScan is enabled by default. if (UNLIKELY(IsScanEnabled())) { if (flags & PartitionPurgeForceAllFreed) @@ -603,6 +613,10 @@ else PCScan::Instance().PerformScanIfNeeded(PCScan::InvocationMode::kBlocking); } + + if (with_thread_cache) + internal::ThreadCacheRegistry::Instance().PurgeAll(); + { ScopedGuard guard{lock_}; if (flags & PartitionPurgeDecommitEmptySlotSpans) @@ -615,9 +629,6 @@ } } } - - if (with_thread_cache) - internal::ThreadCacheRegistry::Instance().PurgeAll(); } template <bool thread_safe>
diff --git a/base/allocator/partition_allocator/thread_cache.cc b/base/allocator/partition_allocator/thread_cache.cc index ebe3d58..5bdaf5c 100644 --- a/base/allocator/partition_allocator/thread_cache.cc +++ b/base/allocator/partition_allocator/thread_cache.cc
@@ -227,6 +227,11 @@ } void ThreadCache::Purge() { + PA_REENTRANCY_GUARD(is_in_thread_cache_); + PurgeInternal(); +} + +void ThreadCache::PurgeInternal() { for (auto& bucket : buckets_) ClearBucket(bucket, 0);
diff --git a/base/allocator/partition_allocator/thread_cache.h b/base/allocator/partition_allocator/thread_cache.h index 3d4f3ffd..23670aa 100644 --- a/base/allocator/partition_allocator/thread_cache.h +++ b/base/allocator/partition_allocator/thread_cache.h
@@ -16,6 +16,7 @@ #include "base/allocator/partition_allocator/partition_tls.h" #include "base/base_export.h" #include "base/gtest_prod_util.h" +#include "base/macros.h" #include "base/no_destructor.h" #include "base/partition_alloc_buildflags.h" #include "base/synchronization/lock.h" @@ -92,6 +93,31 @@ return n < 1 ? -1 : (n < 2 ? 0 : (1 + ConstexprLog2(n >> 1))); } +#if DCHECK_IS_ON() +class ReentrancyGuard { + public: + explicit ReentrancyGuard(bool& flag) : flag_(flag) { + PA_CHECK(!flag_); + flag_ = true; + } + + ~ReentrancyGuard() { flag_ = false; } + + private: + bool& flag_; +}; + +#define PA_REENTRANCY_GUARD(x) \ + ReentrancyGuard guard { x } + +#else + +#define PA_REENTRANCY_GUARD(x) \ + do { \ + } while (0) + +#endif // DCHECK_IS_ON() + // Per-thread cache. *Not* threadsafe, must only be accessed from a single // thread. // @@ -168,6 +194,7 @@ explicit ThreadCache(PartitionRoot<ThreadSafe>* root); static void Delete(void* thread_cache_ptr); + void PurgeInternal(); // Empties the |bucket| until there are at most |limit| objects in it. void ClearBucket(Bucket& bucket, size_t limit); @@ -185,6 +212,9 @@ Bucket buckets_[kBucketCount]; ThreadCacheStats stats_; PartitionRoot<ThreadSafe>* const root_; +#if DCHECK_IS_ON() + bool is_in_thread_cache_ = false; +#endif // Intrusive list since ThreadCacheRegistry::RegisterThreadCache() cannot // allocate. @@ -201,8 +231,9 @@ ALWAYS_INLINE bool ThreadCache::MaybePutInCache(void* address, size_t bucket_index) { + PA_REENTRANCY_GUARD(is_in_thread_cache_); if (UNLIKELY(should_purge_.load(std::memory_order_relaxed))) - Purge(); + PurgeInternal(); INCREMENT_COUNTER(stats_.cache_fill_count); @@ -231,6 +262,7 @@ } ALWAYS_INLINE void* ThreadCache::GetFromCache(size_t bucket_index) { + PA_REENTRANCY_GUARD(is_in_thread_cache_); INCREMENT_COUNTER(stats_.alloc_count); // Only handle "small" allocations. if (UNLIKELY(bucket_index >= kBucketCount)) {
diff --git a/base/win/.clang-tidy b/base/win/.clang-tidy index 7a75762..d0f8c61 100644 --- a/base/win/.clang-tidy +++ b/base/win/.clang-tidy
@@ -1,5 +1,6 @@ --- Checks: '-*, + bugprone-argument-comment, google-build-namespaces, google-readability-namespace-comments, modernize-avoid-bind,
diff --git a/build/find_isolated_tests.py b/build/find_isolated_tests.py deleted file mode 100755 index c5b3ab77..0000000 --- a/build/find_isolated_tests.py +++ /dev/null
@@ -1,78 +0,0 @@ -#!/usr/bin/env python -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Scans build output directory for .isolated files, calculates their SHA1 -hashes, stores final list in JSON document and then removes *.isolated files -found (to ensure no stale *.isolated stay around on the next build). - -Used to figure out what tests were build in isolated mode to trigger these -tests to run on swarming. - -For more info see: -https://sites.google.com/a/chromium.org/dev/developers/testing/isolated-testing -""" - -import glob -import hashlib -import json -import optparse -import os -import re -import sys - - -def hash_file(filepath): - """Calculates the hash of a file without reading it all in memory at once.""" - digest = hashlib.sha1() - with open(filepath, 'rb') as f: - while True: - chunk = f.read(1024*1024) - if not chunk: - break - digest.update(chunk) - return digest.hexdigest() - - -def main(): - parser = optparse.OptionParser( - usage='%prog --build-dir <path> --output-json <path>', - description=sys.modules[__name__].__doc__) - parser.add_option( - '--build-dir', - help='Path to a directory to search for *.isolated files.') - parser.add_option( - '--output-json', - help='File to dump JSON results into.') - - options, _ = parser.parse_args() - if not options.build_dir: - parser.error('--build-dir option is required') - if not options.output_json: - parser.error('--output-json option is required') - - result = {} - - # Get the file hash values and output the pair. - pattern = os.path.join(options.build_dir, '*.isolated') - for filepath in sorted(glob.glob(pattern)): - test_name = os.path.splitext(os.path.basename(filepath))[0] - if re.match(r'^.+?\.\d$', test_name): - # It's a split .isolated file, e.g. foo.0.isolated. Ignore these. - continue - - # TODO(csharp): Remove deletion once the isolate tracked dependencies are - # inputs for the isolated files. - sha1_hash = hash_file(filepath) - os.remove(filepath) - result[test_name] = sha1_hash - - with open(options.output_json, 'wb') as f: - json.dump(result, f) - - return 0 - - -if __name__ == '__main__': - sys.exit(main())
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index d1df4db7..8ad5cf81 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -0.20201130.2.1 +0.20201201.0.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index d1df4db7..8ad5cf81 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -0.20201130.2.1 +0.20201201.0.1
diff --git a/chrome/VERSION b/chrome/VERSION index 9c0dda2..8123308 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=89 MINOR=0 -BUILD=4342 +BUILD=4343 PATCH=0
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index b6619eb..645bb3f 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -828,6 +828,7 @@ "//chrome/browser/signin/services/android:java", "//chrome/browser/signin/services/android:junit", "//chrome/browser/tab:java", + "//chrome/browser/tab:junit", "//chrome/browser/tabmodel:factory_java", "//chrome/browser/tabmodel:java", "//chrome/browser/tabmodel/internal:java", @@ -3210,10 +3211,8 @@ "java/src/org/chromium/chrome/browser/compositor/LayerTitleCache.java", "java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelContent.java", "java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java", - "java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/resources/ResourceFactory.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java", - "java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/StaticTabSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java", @@ -3393,6 +3392,8 @@ "java/src/org/chromium/chrome/browser/tabmodel/TabModelJniBridge.java", "java/src/org/chromium/chrome/browser/tabmodel/TabModelObserverJniBridge.java", "java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java", + "java/src/org/chromium/chrome/browser/toolbar/bottom/ScrollingBottomViewSceneLayer.java", + "java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarSceneLayer.java", "java/src/org/chromium/chrome/browser/translate/TranslateBridge.java", "java/src/org/chromium/chrome/browser/usage_stats/NotificationSuspender.java", "java/src/org/chromium/chrome/browser/usage_stats/UsageStatsBridge.java",
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index 0af3887..33dfe68b 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -336,14 +336,9 @@ "java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java", "java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripStacker.java", "java/src/org/chromium/chrome/browser/compositor/overlays/strip/TabLoadTracker.java", - "java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayCoordinator.java", - "java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediator.java", - "java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayProperties.java", - "java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/resources/ResourceFactory.java", "java/src/org/chromium/chrome/browser/compositor/resources/StaticResourcePreloads.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java", - "java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/StaticTabSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/TabListSceneLayer.java", "java/src/org/chromium/chrome/browser/compositor/scene_layer/TabStripSceneLayer.java", @@ -1288,6 +1283,7 @@ "java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerCoordinator.java", "java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerDelegate.java", "java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerDelegateImpl.java", + "java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerFeatureUtils.java", "java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerMediator.java", "java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerProperties.java", "java/src/org/chromium/chrome/browser/signin/account_picker/AddAccountRowViewBinder.java", @@ -1451,6 +1447,7 @@ "java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsProperties.java", "java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsViewBinder.java", "java/src/org/chromium/chrome/browser/toolbar/bottom/ScrollingBottomViewResourceFrameLayout.java", + "java/src/org/chromium/chrome/browser/toolbar/bottom/ScrollingBottomViewSceneLayer.java", "java/src/org/chromium/chrome/browser/toolbar/load_progress/LoadProgressCoordinator.java", "java/src/org/chromium/chrome/browser/toolbar/load_progress/LoadProgressMediator.java", "java/src/org/chromium/chrome/browser/toolbar/load_progress/LoadProgressProperties.java", @@ -1484,6 +1481,10 @@ "java/src/org/chromium/chrome/browser/toolbar/top/ToolbarPhone.java", "java/src/org/chromium/chrome/browser/toolbar/top/ToolbarTablet.java", "java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarCoordinator.java", + "java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayCoordinator.java", + "java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediator.java", + "java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayProperties.java", + "java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarSceneLayer.java", "java/src/org/chromium/chrome/browser/toolbar/top/ViewShiftingActionBarDelegate.java", "java/src/org/chromium/chrome/browser/tracing/TracingController.java", "java/src/org/chromium/chrome/browser/tracing/TracingNotificationManager.java",
diff --git a/chrome/android/chrome_junit_test_java_sources.gni b/chrome/android/chrome_junit_test_java_sources.gni index 6813f01..263d10c 100644 --- a/chrome/android/chrome_junit_test_java_sources.gni +++ b/chrome/android/chrome_junit_test_java_sources.gni
@@ -46,7 +46,6 @@ "junit/src/org/chromium/chrome/browser/compositor/layouts/SceneOverlayTest.java", "junit/src/org/chromium/chrome/browser/compositor/layouts/StaticLayoutUnitTest.java", "junit/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperTest.java", - "junit/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediatorTest.java", "junit/src/org/chromium/chrome/browser/content_capture/ContentCaptureHistoryDeletionObserverTest.java", "junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java", "junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuHeaderMediatorTest.java", @@ -240,6 +239,7 @@ "junit/src/org/chromium/chrome/browser/toolbar/top/StartSurfaceToolbarMediatorUnitTest.java", "junit/src/org/chromium/chrome/browser/toolbar/top/ToggleTabStackButtonCoordinatorTest.java", "junit/src/org/chromium/chrome/browser/toolbar/top/ToggleTabStackButtonTest.java", + "junit/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediatorTest.java", "junit/src/org/chromium/chrome/browser/usage_stats/EventTrackerTest.java", "junit/src/org/chromium/chrome/browser/usage_stats/PageViewObserverTest.java", "junit/src/org/chromium/chrome/browser/webapps/MockWebappDataStorageClockRule.java",
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInputActionIntegrationTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInputActionIntegrationTest.java index 03a1924..f57875f 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInputActionIntegrationTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantInputActionIntegrationTest.java
@@ -49,9 +49,10 @@ import org.chromium.chrome.browser.autofill_assistant.proto.SelectOptionProto; import org.chromium.chrome.browser.autofill_assistant.proto.SelectorProto; import org.chromium.chrome.browser.autofill_assistant.proto.SelectorProto.Filter; +import org.chromium.chrome.browser.autofill_assistant.proto.SendChangeEventProto; import org.chromium.chrome.browser.autofill_assistant.proto.SendClickEventProto; import org.chromium.chrome.browser.autofill_assistant.proto.SendKeystrokeEventsProto; -import org.chromium.chrome.browser.autofill_assistant.proto.SetFieldValueProto; +import org.chromium.chrome.browser.autofill_assistant.proto.SetElementAttributeProto; import org.chromium.chrome.browser.autofill_assistant.proto.SetFormFieldValueProto; import org.chromium.chrome.browser.autofill_assistant.proto.SetFormFieldValueProto.KeyPress; import org.chromium.chrome.browser.autofill_assistant.proto.SupportedScriptProto; @@ -521,10 +522,16 @@ CheckElementIsOnTopProto.newBuilder().setClientId(clientId)) .build()); list.add((ActionProto) ActionProto.newBuilder() - .setSetFieldValue( - SetFieldValueProto.newBuilder().setClientId(clientId).setValue( - TextValue.newBuilder().setText(""))) + .setSetElementAttribute( + SetElementAttributeProto.newBuilder() + .setClientId(clientId) + .addAttribute("value") + .setValue(TextValue.newBuilder().setText(""))) .build()); + list.add( + (ActionProto) ActionProto.newBuilder() + .setSendChangeEvent(SendChangeEventProto.newBuilder().setClientId(clientId)) + .build()); list.add((ActionProto) ActionProto.newBuilder() .setSendClickEvent(SendClickEventProto.newBuilder().setClientId(clientId)) .build());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerImpl.java index 2bfab6c6..3008835 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerImpl.java
@@ -32,8 +32,6 @@ import org.chromium.chrome.browser.compositor.layouts.components.LayoutTab; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; import org.chromium.chrome.browser.compositor.overlays.strip.StripLayoutHelperManager; -import org.chromium.chrome.browser.compositor.overlays.toolbar.TopToolbarOverlayCoordinator; -import org.chromium.chrome.browser.compositor.scene_layer.ScrollingBottomViewSceneLayer; import org.chromium.chrome.browser.fullscreen.BrowserControlsManager; import org.chromium.chrome.browser.gesturenav.HistoryNavigationCoordinator; import org.chromium.chrome.browser.layouts.CompositorModelChangeProcessor; @@ -65,6 +63,8 @@ import org.chromium.chrome.browser.tabmodel.TabModelUtils; import org.chromium.chrome.browser.toolbar.ControlContainer; import org.chromium.chrome.browser.toolbar.ToolbarColors; +import org.chromium.chrome.browser.toolbar.bottom.ScrollingBottomViewSceneLayer; +import org.chromium.chrome.browser.toolbar.top.TopToolbarOverlayCoordinator; import org.chromium.components.browser_ui.widget.gesture.SwipeGestureListener.SwipeHandler; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.ui.base.LocalizationUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetView.java index 1e164e74..989d95c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetView.java
@@ -73,6 +73,9 @@ .findViewById(R.id.account_picker_selected_account); mDismissButton = mViewFlipper.getChildAt(ViewState.COLLAPSED_ACCOUNT_LIST) .findViewById(R.id.account_picker_dismiss_button); + if (AccountPickerFeatureUtils.shouldShowNoThanksOnDismissButton()) { + mDismissButton.setText(R.string.no_thanks); + } // TODO(https://crbug.com/1146990): Use different continue buttons for different view // states.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerFeatureUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerFeatureUtils.java new file mode 100644 index 0000000..2f6dc9c --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerFeatureUtils.java
@@ -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. + +package org.chromium.chrome.browser.signin.account_picker; + +import org.chromium.chrome.browser.flags.ChromeFeatureList; + +/** + * This class is used to handle state of feature flags in the project + * MobileIdentityConsistency. + */ +public class AccountPickerFeatureUtils { + private static final String DISMISS_BUTTON_PARAM = "dismiss_button"; + private static final String DISMISS_BUTTON_NO_THANKS = "no_thanks"; + + static boolean shouldShowNoThanksOnDismissButton() { + return DISMISS_BUTTON_NO_THANKS.equals(ChromeFeatureList.getFieldTrialParamByFeature( + ChromeFeatureList.MOBILE_IDENTITY_CONSISTENCY_VAR, DISMISS_BUTTON_PARAM)); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java index c93b689b..f98936d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java
@@ -55,7 +55,6 @@ import org.chromium.chrome.browser.status_indicator.StatusIndicatorCoordinator; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabModelSelector; -import org.chromium.chrome.browser.tasks.tab_management.TabUiFeatureUtilities; import org.chromium.chrome.browser.toolbar.ToolbarButtonInProductHelpController; import org.chromium.chrome.browser.ui.RootUiCoordinator; import org.chromium.chrome.browser.ui.appmenu.AppMenuHandler; @@ -272,16 +271,6 @@ } @Override - protected void initializeToolbar() { - super.initializeToolbar(); - if (!mActivity.isTablet() - && (TabUiFeatureUtilities.isTabGroupsAndroidEnabled() - || TabUiFeatureUtilities.isConditionalTabStripEnabled())) { - getToolbarManager().enableBottomControls(); - } - } - - @Override protected boolean shouldShowMenuUpdateBadge() { return true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java index 3c65b9ad..1ced8c0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java
@@ -44,12 +44,11 @@ import org.chromium.chrome.browser.browser_controls.BrowserStateBrowserControlsVisibilityDelegate; import org.chromium.chrome.browser.compositor.CompositorViewHolder; import org.chromium.chrome.browser.compositor.Invalidator; +import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelManager.OverlayPanelManagerObserver; import org.chromium.chrome.browser.compositor.layouts.Layout; import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl; import org.chromium.chrome.browser.compositor.layouts.SceneChangeObserver; -import org.chromium.chrome.browser.compositor.overlays.toolbar.TopToolbarOverlayCoordinator; import org.chromium.chrome.browser.customtabs.features.toolbar.CustomTabToolbar; -import org.chromium.chrome.browser.device.DeviceClassManager; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.findinpage.FindToolbarManager; import org.chromium.chrome.browser.findinpage.FindToolbarObserver; @@ -89,6 +88,7 @@ import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelSelectorObserver; import org.chromium.chrome.browser.tasks.ReturnToChromeExperimentsUtil; +import org.chromium.chrome.browser.tasks.tab_management.TabUiFeatureUtilities; import org.chromium.chrome.browser.toolbar.ThemeColorProvider.ThemeColorObserver; import org.chromium.chrome.browser.toolbar.ThemeColorProvider.TintObserver; import org.chromium.chrome.browser.toolbar.bottom.BottomControlsCoordinator; @@ -165,7 +165,6 @@ private ObservableSupplierImpl<BottomControlsCoordinator> mBottomControlsCoordinatorSupplier = new ObservableSupplierImpl<>(); private final ObservableSupplierImpl<Tab> mActivityTabSupplier = new ObservableSupplierImpl<>(); - private TopToolbarOverlayCoordinator mOverlayCoordinator; private TabModelSelector mTabModelSelector; private TabModelSelectorObserver mTabModelSelectorObserver; private ObservableSupplier<TabModelSelector> mTabModelSelectorSupplier; @@ -245,6 +244,9 @@ private OneshotSupplier<IntentMetadata> mIntentMetadataOneshotSupplier; private OneshotSupplier<Boolean> mPromoShownOneshotSupplier; + private OverlayPanelManagerObserver mOverlayPanelManagerObserver; + private ObservableSupplierImpl<Boolean> mOverlayPanelVisibilitySupplier = + new ObservableSupplierImpl<>(); private static class TabObscuringCallback implements Callback<Boolean> { private final TabObscuringHandler mTabObscuringHandler; @@ -396,12 +398,10 @@ mCustomTabThemeColorProvider = new SettableThemeColorProvider(/* context= */ mActivity); mActivityTabProvider = tabProvider; - // clang-format off mToolbarTabController = new ToolbarTabControllerImpl(mLocationBarModel::getTab, () -> mShowStartSurfaceSupplier != null && mShowStartSurfaceSupplier.get(), profileSupplier, mBottomControlsCoordinatorSupplier, ToolbarManager::homepageUrl, this::updateButtonStatus); - // clang-format on BrowserStateBrowserControlsVisibilityDelegate controlsVisibilityDelegate = mBrowserControlsSizer.getBrowserVisibilityDelegate(); @@ -743,6 +743,18 @@ } }; + mOverlayPanelManagerObserver = new OverlayPanelManagerObserver() { + @Override + public void onOverlayPanelShown() { + mOverlayPanelVisibilitySupplier.set(true); + } + + @Override + public void onOverlayPanelHidden() { + mOverlayPanelVisibilitySupplier.set(false); + } + }; + mToolbar.setTabCountProvider(mTabCountProvider); mToolbar.setIncognitoStateProvider(mIncognitoStateProvider); @@ -793,8 +805,7 @@ client.run(); } }, () -> identityDiscController.getForStartSurface(mStartSurfaceState), - startSurfaceSupplier, - () -> mLayoutManager.getResourceManager()); + startSurfaceSupplier, mCompositorViewHolder::getResourceManager); // clang-format on mHomepageStateListener = () -> { mHomeButtonVisibilitySupplier.set(HomepageManager.isHomepageEnabled()); @@ -965,16 +976,13 @@ /** * Enable the bottom controls. */ - public void enableBottomControls() { - // clang-format off - mBottomControlsCoordinatorSupplier.set(new BottomControlsCoordinator(mBrowserControlsSizer, - mFullscreenManager, mActivity.findViewById(R.id.bottom_controls_stub), - mAppThemeColorProvider, mShareDelegateSupplier, - mMenuButtonCoordinator.getMenuButtonHelperSupplier(), - mToolbarTabController::openHomepage, - mCallbackController.makeCancelable((reason) -> setUrlBarFocus(true, reason)), - mScrimCoordinator, mOmniboxFocusStateSupplier)); - // clang-format on + private void enableBottomControls() { + mBottomControlsCoordinatorSupplier.set( + new BottomControlsCoordinator(mActivity, mWindowAndroid, mLayoutManager, + mCompositorViewHolder.getResourceManager(), mBrowserControlsSizer, + mFullscreenManager, mActivity.findViewById(R.id.bottom_controls_stub), + mAppThemeColorProvider, mShareDelegateSupplier, mScrimCoordinator, + mOmniboxFocusStateSupplier, mOverlayPanelVisibilitySupplier)); } /** @@ -1015,18 +1023,8 @@ mToolbar.initializeWithNative(layoutManager::requestUpdate, tabSwitcherClickHandler, tabSwitcherLongClickHandler, newTabClickHandler, bookmarkClickHandler, - customTabsBackClickHandler, mBrowserControlsSizer); - // If fullscreen is disabled, don't bother creating this overlay; only the android view will - // ever be shown. - if (DeviceClassManager.enableFullscreen()) { - mOverlayCoordinator = new TopToolbarOverlayCoordinator(mActivity, layoutManager, - mControlContainer::getProgressBarDrawingInfo, mActivityTabProvider, - mBrowserControlsSizer, layoutManager::getResourceManager); - layoutManager.addSceneOverlay(mOverlayCoordinator); - ToolbarLayout toolbarLayout = mActivity.findViewById(R.id.toolbar); - toolbarLayout.setOverlayVisibilityCallback(mCallbackController.makeCancelable( - mOverlayCoordinator::setIsAndroidViewVisible)); - } + customTabsBackClickHandler, layoutManager, mActivityTabSupplier, + mBrowserControlsSizer); mToolbar.addOnAttachStateChangeListener(new OnAttachStateChangeListener() { @Override @@ -1046,22 +1044,17 @@ if (layoutManager != null) { mLayoutManager = layoutManager; mLayoutManager.addSceneChangeObserver(mSceneChangeObserver); + mLayoutManager.getOverlayPanelManager().addObserver(mOverlayPanelManagerObserver); } // TODO(https://crbug.com/1086676, pnoland): Remove this by having MBC listen for native // init directly. mMenuButtonCoordinator.onNativeInitialized(); - BottomControlsCoordinator bcc = mBottomControlsCoordinatorSupplier.get(); - if (bcc != null) { - Runnable closeAllTabsAction = () -> { - mTabModelSelector.getModel(mIncognitoStateProvider.isIncognitoSelected()) - .closeAllTabs(); - }; - bcc.initializeWithNative(mActivity, mCompositorViewHolder.getResourceManager(), - mCompositorViewHolder.getLayoutManager(), tabSwitcherClickHandler, - newTabClickHandler, mWindowAndroid, mTabCountProvider, mIncognitoStateProvider, - mActivity.findViewById(R.id.control_container), closeAllTabsAction); + if (!DeviceFormFactor.isNonMultiDisplayContextOnTablet(mActivity) + && (TabUiFeatureUtilities.isTabGroupsAndroidEnabled() + || TabUiFeatureUtilities.isConditionalTabStripEnabled())) { + enableBottomControls(); } TemplateUrlServiceFactory.get().runWhenLoaded(this::registerTemplateUrlObserver); @@ -1187,6 +1180,7 @@ if (mLayoutManager != null) { mLayoutManager.removeSceneChangeObserver(mSceneChangeObserver); + mLayoutManager.getOverlayPanelManager().removeObserver(mOverlayPanelManagerObserver); mLayoutManager = null; } @@ -1197,11 +1191,6 @@ mBottomControlsCoordinatorSupplier = null; } - if (mOverlayCoordinator != null) { - mOverlayCoordinator.destroy(); - mOverlayCoordinator = null; - } - mToolbar.removeUrlExpansionObserver(mStatusBarColorController); mToolbar.destroy(); @@ -1626,6 +1615,9 @@ mLayoutStateProvider.addObserver(mLayoutStateObserver); mAppThemeColorProvider.setLayoutStateProvider(mLayoutStateProvider); mLocationBarModel.setLayoutStateProvider(mLayoutStateProvider); + if (mBottomControlsCoordinatorSupplier.get() != null) { + mBottomControlsCoordinatorSupplier.get().setLayoutStateProvider(mLayoutStateProvider); + } } private void updateCurrentTabDisplayStatus() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsCoordinator.java index dd58bc81..10d8506 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsCoordinator.java
@@ -7,28 +7,24 @@ import android.annotation.SuppressLint; import android.app.Activity; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewStub; import androidx.annotation.Nullable; -import org.chromium.base.Callback; import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.browser_controls.BrowserControlsSizer; -import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl; import org.chromium.chrome.browser.fullscreen.FullscreenManager; +import org.chromium.chrome.browser.layouts.LayoutManager; +import org.chromium.chrome.browser.layouts.LayoutStateProvider; import org.chromium.chrome.browser.share.ShareDelegate; -import org.chromium.chrome.browser.tabmodel.IncognitoStateProvider; import org.chromium.chrome.browser.tasks.tab_management.TabGroupUi; import org.chromium.chrome.browser.tasks.tab_management.TabManagementModuleProvider; import org.chromium.chrome.browser.tasks.tab_management.TabUiFeatureUtilities; -import org.chromium.chrome.browser.toolbar.TabCountProvider; import org.chromium.chrome.browser.toolbar.ThemeColorProvider; import org.chromium.chrome.browser.toolbar.bottom.BottomControlsViewBinder.ViewHolder; -import org.chromium.chrome.browser.ui.appmenu.AppMenuButtonHelper; import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.modelutil.PropertyModel; @@ -59,6 +55,8 @@ /** * Build the coordinator that manages the bottom controls. + * @param activity Activity instance to use. + * @param windowAndroid A {@link WindowAndroid} for watching keyboard visibility events. * @param controlsSizer A {@link BrowserControlsSizer} to update the bottom controls * height for the renderer. * @param fullscreenManager A {@link FullscreenManager} to listen for fullscreen changes. @@ -66,36 +64,44 @@ * @param themeColorProvider The {@link ThemeColorProvider} for the bottom toolbar. * @param shareDelegateSupplier The supplier for the {@link ShareDelegate} the bottom controls * should use to share content. - * @param openHomepageAction The action that opens the homepage. - * @param setUrlBarFocusAction The function that sets Url bar focus. The first argument is - * whether the bar should be focused, and the second is the OmniboxFocusReason. * @param scrimCoordinator The {@link ScrimCoordinator} to control scrim view. * @param omniboxFocusStateSupplier Supplier to access the focus state of the omnibox. + * @param overlayPanelVisibilitySupplier Notifies overlay panel visibility event. + * @param resourceManager A {@link ResourceManager} for loading textures into the compositor. + * @param layoutManager A {@link LayoutManagerImpl} to attach overlays to. */ @SuppressLint("CutPasteId") // Not actually cut and paste since it's View vs ViewGroup. - public BottomControlsCoordinator(BrowserControlsSizer controlsSizer, - FullscreenManager fullscreenManager, ViewStub stub, + public BottomControlsCoordinator(Activity activity, WindowAndroid windowAndroid, + LayoutManager layoutManager, ResourceManager resourceManager, + BrowserControlsSizer controlsSizer, FullscreenManager fullscreenManager, ViewStub stub, ThemeColorProvider themeColorProvider, ObservableSupplier<ShareDelegate> shareDelegateSupplier, - ObservableSupplier<AppMenuButtonHelper> menuButtonHelperSupplier, - Runnable openHomepageAction, Callback<Integer> setUrlBarFocusAction, ScrimCoordinator scrimCoordinator, - ObservableSupplier<Boolean> omniboxFocusStateSupplier) { + ObservableSupplier<Boolean> omniboxFocusStateSupplier, + ObservableSupplier<Boolean> overlayPanelVisibilitySupplier) { final ScrollingBottomViewResourceFrameLayout root = (ScrollingBottomViewResourceFrameLayout) stub.inflate(); PropertyModel model = new PropertyModel(BottomControlsProperties.ALL_KEYS); + ScrollingBottomViewSceneLayer sceneLayer = + new ScrollingBottomViewSceneLayer(root, root.getTopShadowHeight()); PropertyModelChangeProcessor.create( - model, new ViewHolder(root), BottomControlsViewBinder::bind); - + model, new ViewHolder(root, sceneLayer), BottomControlsViewBinder::bind); + layoutManager.createCompositorMCP( + model, sceneLayer, BottomControlsViewBinder::bindCompositorMCP); int bottomControlsHeightId = R.dimen.bottom_controls_height; View container = root.findViewById(R.id.bottom_container_slot); ViewGroup.LayoutParams params = container.getLayoutParams(); params.height = root.getResources().getDimensionPixelOffset(bottomControlsHeightId); - mMediator = new BottomControlsMediator(model, controlsSizer, fullscreenManager, - root.getResources().getDimensionPixelOffset(bottomControlsHeightId)); + mMediator = + new BottomControlsMediator(windowAndroid, model, controlsSizer, fullscreenManager, + root.getResources().getDimensionPixelOffset(bottomControlsHeightId), + overlayPanelVisibilitySupplier); + + resourceManager.getDynamicResourceLoader().registerResource( + root.getId(), root.getResourceAdapter()); if (TabUiFeatureUtilities.isTabGroupsAndroidEnabled() || TabUiFeatureUtilities.isConditionalTabStripEnabled()) { @@ -108,36 +114,10 @@ // Set the visibility of BottomControls to false by default. Components within // BottomControls should update the visibility explicitly if needed. - mMediator.setBottomControlsVisible(false); - } + setBottomControlsVisible(false); - /** - * Initialize the bottom controls with the components that had native initialization - * dependencies. - * <p> - * Calling this must occur after the native library have completely loaded. - * @param activity Activity instance to use. - * @param resourceManager A {@link ResourceManager} for loading textures into the compositor. - * @param layoutManager A {@link LayoutManagerImpl} to attach overlays to. - * @param tabSwitcherListener An {@link OnClickListener} that is triggered when the - * bottom toolbar's tab switcher button is clicked. - * @param newTabClickListener An {@link OnClickListener} that is triggered when the - * bottom toolbar's new tab button is clicked. - * @param windowAndroid A {@link WindowAndroid} for watching keyboard visibility events. - * @param tabCountProvider Updates the tab count number in the tab switcher button and in the - * incognito toggle tab layout. - * @param incognitoStateProvider Notifies components when incognito mode is entered or exited. - * @param topToolbarRoot The root {@link ViewGroup} of the top toolbar. - * @param closeAllTabsAction The runnable that closes all tabs in the current tab model. - */ - public void initializeWithNative(Activity activity, ResourceManager resourceManager, - LayoutManagerImpl layoutManager, OnClickListener tabSwitcherListener, - OnClickListener newTabClickListener, WindowAndroid windowAndroid, - TabCountProvider tabCountProvider, IncognitoStateProvider incognitoStateProvider, - ViewGroup topToolbarRoot, Runnable closeAllTabsAction) { - mMediator.setLayoutManager(layoutManager); - mMediator.setResourceManager(resourceManager); - mMediator.setWindowAndroid(windowAndroid); + sceneLayer.setIsVisible(mMediator.isCompositedViewVisible()); + layoutManager.addSceneOverlay(sceneLayer); if (mTabGroupUi != null) { mTabGroupUi.initializeWithNative(activity, mMediator::setBottomControlsVisible); @@ -145,6 +125,13 @@ } /** + * @param layoutStateProvider {@link LayoutStateProvider} object. + */ + public void setLayoutStateProvider(LayoutStateProvider layoutStateProvider) { + mMediator.setLayoutStateProvider(layoutStateProvider); + } + + /** * @param isVisible Whether the bottom control is visible. */ public void setBottomControlsVisible(boolean isVisible) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsMediator.java index e052af5..f305a6a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsMediator.java
@@ -4,18 +4,17 @@ package org.chromium.chrome.browser.toolbar.bottom; +import org.chromium.base.CallbackController; +import org.chromium.base.supplier.ObservableSupplier; import org.chromium.chrome.browser.browser_controls.BrowserControlsSizer; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider; -import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelManager; -import org.chromium.chrome.browser.compositor.layouts.Layout; -import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl; -import org.chromium.chrome.browser.compositor.layouts.SceneChangeObserver; -import org.chromium.chrome.browser.compositor.layouts.ToolbarSwipeLayout; import org.chromium.chrome.browser.fullscreen.FullscreenManager; +import org.chromium.chrome.browser.layouts.LayoutStateProvider; +import org.chromium.chrome.browser.layouts.LayoutStateProvider.LayoutStateObserver; +import org.chromium.chrome.browser.layouts.LayoutType; import org.chromium.ui.KeyboardVisibilityDelegate; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.modelutil.PropertyModel; -import org.chromium.ui.resources.ResourceManager; /** * This class is responsible for reacting to events from the outside world, interacting with other @@ -24,8 +23,7 @@ */ class BottomControlsMediator implements BrowserControlsStateProvider.Observer, KeyboardVisibilityDelegate.KeyboardVisibilityListener, - SceneChangeObserver, - OverlayPanelManager.OverlayPanelManagerObserver { + LayoutStateObserver { /** The model for the bottom controls component that holds all of its view state. */ private final PropertyModel mModel; @@ -35,13 +33,15 @@ /** The browser controls sizer/manager to observe browser controls events. */ private final BrowserControlsSizer mBrowserControlsSizer; + private final CallbackController mCallbackController; + /** * The height of the bottom bar in pixels, not including the top shadow. */ private int mBottomControlsHeight; /** A {@link WindowAndroid} for watching keyboard visibility events. */ - private WindowAndroid mWindowAndroid; + private final WindowAndroid mWindowAndroid; /** The bottom controls visibility. */ private boolean mIsBottomControlsVisible; @@ -55,17 +55,22 @@ /** Whether the soft keyboard is visible. */ private boolean mIsKeyboardVisible; + private LayoutStateProvider mLayoutStateProvider; + /** * Build a new mediator that handles events from outside the bottom controls component. + * @param windowAndroid A {@link WindowAndroid} for watching keyboard visibility events. * @param model The {@link BottomControlsProperties} that holds all the view state for the * bottom controls component. - @param controlsSizer The {@link BrowserControlsSizer} to manipulate browser controls. + * @param controlsSizer The {@link BrowserControlsSizer} to manipulate browser controls. * @param fullscreenManager A {@link FullscreenManager} for events related to the browser * controls. * @param bottomControlsHeight The height of the bottom bar in pixels. + * @param overlayPanelVisibilitySupplier Notifies overlay panel visibility event. */ - BottomControlsMediator(PropertyModel model, BrowserControlsSizer controlsSizer, - FullscreenManager fullscreenManager, int bottomControlsHeight) { + BottomControlsMediator(WindowAndroid windowAndroid, PropertyModel model, + BrowserControlsSizer controlsSizer, FullscreenManager fullscreenManager, + int bottomControlsHeight, ObservableSupplier<Boolean> overlayPanelVisibilitySupplier) { mModel = model; mFullscreenManager = fullscreenManager; @@ -73,23 +78,20 @@ mBrowserControlsSizer.addObserver(this); mBottomControlsHeight = bottomControlsHeight; - } + mCallbackController = new CallbackController(); + overlayPanelVisibilitySupplier.addObserver(mCallbackController.makeCancelable((showing) -> { + mIsOverlayPanelShowing = showing; + updateAndroidViewVisibility(); + })); - void setResourceManager(ResourceManager resourceManager) { - mModel.set(BottomControlsProperties.RESOURCE_MANAGER, resourceManager); - } - - void setWindowAndroid(WindowAndroid windowAndroid) { - assert mWindowAndroid == null : "#setWindowAndroid should only be called once per toolbar."; // Watch for keyboard events so we can hide the bottom toolbar when the keyboard is showing. mWindowAndroid = windowAndroid; mWindowAndroid.getKeyboardDelegate().addKeyboardVisibilityListener(this); } - void setLayoutManager(LayoutManagerImpl layoutManager) { - mModel.set(BottomControlsProperties.LAYOUT_MANAGER, layoutManager); - layoutManager.addSceneChangeObserver(this); - layoutManager.getOverlayPanelManager().addObserver(this); + void setLayoutStateProvider(LayoutStateProvider layoutStateProvider) { + mLayoutStateProvider = layoutStateProvider; + layoutStateProvider.addObserver(this); } void setBottomControlsVisible(boolean visible) { @@ -102,15 +104,12 @@ * Clean up anything that needs to be when the bottom controls component is destroyed. */ void destroy() { + mCallbackController.destroy(); mBrowserControlsSizer.removeObserver(this); - if (mWindowAndroid != null) { - mWindowAndroid.getKeyboardDelegate().removeKeyboardVisibilityListener(this); - mWindowAndroid = null; - } - if (mModel.get(BottomControlsProperties.LAYOUT_MANAGER) != null) { - LayoutManagerImpl manager = mModel.get(BottomControlsProperties.LAYOUT_MANAGER); - manager.getOverlayPanelManager().removeObserver(this); - manager.removeSceneChangeObserver(this); + mWindowAndroid.getKeyboardDelegate().removeKeyboardVisibilityListener(this); + if (mLayoutStateProvider != null) { + mLayoutStateProvider.removeObserver(this); + mLayoutStateProvider = null; } } @@ -122,30 +121,17 @@ } @Override - public void onOverlayPanelShown() { - mIsOverlayPanelShowing = true; - updateAndroidViewVisibility(); - } - - @Override - public void onOverlayPanelHidden() { - mIsOverlayPanelShowing = false; - updateAndroidViewVisibility(); - } - - @Override public void keyboardVisibilityChanged(boolean isShowing) { mIsKeyboardVisible = isShowing; updateCompositedViewVisibility(); updateAndroidViewVisibility(); } - @Override - public void onTabSelectionHinted(int tabId) {} + // LayoutStateObserver @Override - public void onSceneChange(Layout layout) { - mIsInSwipeLayout = layout instanceof ToolbarSwipeLayout; + public void onStartedShowing(@LayoutType int layoutType, boolean showToolbar) { + mIsInSwipeLayout = layoutType == LayoutType.TOOLBAR_SWIPE; updateAndroidViewVisibility(); } @@ -164,14 +150,17 @@ * visibility changes. */ private void updateCompositedViewVisibility() { - final boolean isCompositedViewVisible = - mIsBottomControlsVisible && !mIsKeyboardVisible && !isInFullscreenMode(); + final boolean isCompositedViewVisible = isCompositedViewVisible(); mModel.set(BottomControlsProperties.COMPOSITED_VIEW_VISIBLE, isCompositedViewVisible); mBrowserControlsSizer.setBottomControlsHeight( isCompositedViewVisible ? mBottomControlsHeight : 0, mBrowserControlsSizer.getBottomControlsMinHeight()); } + boolean isCompositedViewVisible() { + return mIsBottomControlsVisible && !mIsKeyboardVisible && !isInFullscreenMode(); + } + /** * The Android View is the interactive view. The composited view should always be behind the * Android view which means we hide the Android view whenever the composited view is hidden. @@ -181,8 +170,7 @@ */ private void updateAndroidViewVisibility() { mModel.set(BottomControlsProperties.ANDROID_VIEW_VISIBLE, - mIsBottomControlsVisible && !mIsKeyboardVisible && !mIsOverlayPanelShowing - && !mIsInSwipeLayout && mBrowserControlsSizer.getBottomControlOffset() == 0 - && !isInFullscreenMode()); + isCompositedViewVisible() && !mIsOverlayPanelShowing && !mIsInSwipeLayout + && mBrowserControlsSizer.getBottomControlOffset() == 0); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsProperties.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsProperties.java index 8193cfb..4c5201f2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsProperties.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsProperties.java
@@ -4,12 +4,9 @@ package org.chromium.chrome.browser.toolbar.bottom; -import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel.WritableBooleanPropertyKey; import org.chromium.ui.modelutil.PropertyModel.WritableIntPropertyKey; -import org.chromium.ui.modelutil.PropertyModel.WritableObjectPropertyKey; -import org.chromium.ui.resources.ResourceManager; class BottomControlsProperties { /** The height of the bottom control container (view which includes the top shadow) in px. */ @@ -26,15 +23,6 @@ static final WritableBooleanPropertyKey COMPOSITED_VIEW_VISIBLE = new WritableBooleanPropertyKey(); - /** A {@link LayoutManagerImpl} to attach overlays to. */ - static final WritableObjectPropertyKey<LayoutManagerImpl> LAYOUT_MANAGER = - new WritableObjectPropertyKey<>(); - - /** A {@link ResourceManager} for loading textures into the compositor. */ - static final WritableObjectPropertyKey<ResourceManager> RESOURCE_MANAGER = - new WritableObjectPropertyKey<>(); - - static final PropertyKey[] ALL_KEYS = - new PropertyKey[] {BOTTOM_CONTROLS_CONTAINER_HEIGHT_PX, Y_OFFSET, ANDROID_VIEW_VISIBLE, - COMPOSITED_VIEW_VISIBLE, LAYOUT_MANAGER, RESOURCE_MANAGER}; + static final PropertyKey[] ALL_KEYS = new PropertyKey[] {BOTTOM_CONTROLS_CONTAINER_HEIGHT_PX, + Y_OFFSET, ANDROID_VIEW_VISIBLE, COMPOSITED_VIEW_VISIBLE}; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsViewBinder.java index 3810ec5..4a27d7e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomControlsViewBinder.java
@@ -7,7 +7,6 @@ import android.view.View; import org.chromium.chrome.R; -import org.chromium.chrome.browser.compositor.scene_layer.ScrollingBottomViewSceneLayer; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -26,8 +25,10 @@ /** * @param bottomControlsRootView The Android View based bottom controls. */ - public ViewHolder(ScrollingBottomViewResourceFrameLayout bottomControlsRootView) { + public ViewHolder(ScrollingBottomViewResourceFrameLayout bottomControlsRootView, + ScrollingBottomViewSceneLayer layer) { root = bottomControlsRootView; + sceneLayer = layer; } } @@ -37,32 +38,22 @@ bottomControlsWrapper.getLayoutParams().height = model.get(BottomControlsProperties.BOTTOM_CONTROLS_CONTAINER_HEIGHT_PX); } else if (BottomControlsProperties.Y_OFFSET == propertyKey) { - // Native may not have completely initialized by the time this is set. - if (view.sceneLayer == null) return; view.sceneLayer.setYOffset(model.get(BottomControlsProperties.Y_OFFSET)); } else if (BottomControlsProperties.ANDROID_VIEW_VISIBLE == propertyKey) { view.root.setVisibility(model.get(BottomControlsProperties.ANDROID_VIEW_VISIBLE) ? View.VISIBLE : View.INVISIBLE); } else if (BottomControlsProperties.COMPOSITED_VIEW_VISIBLE == propertyKey) { - if (view.sceneLayer == null) return; final boolean showCompositedView = model.get(BottomControlsProperties.COMPOSITED_VIEW_VISIBLE); view.sceneLayer.setIsVisible(showCompositedView); - model.get(BottomControlsProperties.LAYOUT_MANAGER).requestUpdate(); - } else if (BottomControlsProperties.LAYOUT_MANAGER == propertyKey) { - assert view.sceneLayer == null; - view.sceneLayer = - new ScrollingBottomViewSceneLayer(view.root, view.root.getTopShadowHeight()); - view.sceneLayer.setIsVisible( - model.get(BottomControlsProperties.COMPOSITED_VIEW_VISIBLE)); - model.get(BottomControlsProperties.LAYOUT_MANAGER).addSceneOverlay(view.sceneLayer); - } else if (BottomControlsProperties.RESOURCE_MANAGER == propertyKey) { - model.get(BottomControlsProperties.RESOURCE_MANAGER) - .getDynamicResourceLoader() - .registerResource(view.root.getId(), view.root.getResourceAdapter()); } else { assert false : "Unhandled property detected in BottomControlsViewBinder!"; } } + + static void bindCompositorMCP(PropertyModel model, ScrollingBottomViewSceneLayer sceneLayer, + PropertyKey propertyKey) { + assert propertyKey == null; + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/ScrollingBottomViewSceneLayer.java similarity index 98% rename from chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java rename to chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/ScrollingBottomViewSceneLayer.java index 5870ec0f..b31c1cd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ScrollingBottomViewSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/ScrollingBottomViewSceneLayer.java
@@ -2,7 +2,7 @@ // 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.compositor.scene_layer; +package org.chromium.chrome.browser.toolbar.bottom; import android.graphics.RectF; import android.view.View;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java index 2825fbd..2262693 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/ToolbarLayout.java
@@ -83,7 +83,7 @@ private MenuButtonCoordinator mMenuButtonCoordinator; private AppMenuButtonHelper mAppMenuButtonHelper; - private Callback<Boolean> mOverlayVisibilityCallback; + private TopToolbarOverlayCoordinator mOverlayCoordinator; /** * Basic constructor for {@link ToolbarLayout}. @@ -121,20 +121,17 @@ mMenuButtonCoordinator = menuButtonCoordinator; } - /** - * @param callback Callback to invoke on visibility change of the texture version - * of the top toolbar. - */ - public void setOverlayVisibilityCallback(Callback<Boolean> callback) { - mOverlayVisibilityCallback = callback; - mOverlayVisibilityCallback.onResult(getVisibility() == View.VISIBLE); + /** @param overlay The coordinator for the texture version of the top toolbar. */ + void setOverlayCoordinator(TopToolbarOverlayCoordinator overlay) { + mOverlayCoordinator = overlay; + mOverlayCoordinator.setIsAndroidViewVisible(getVisibility() == View.VISIBLE); } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); - if (mOverlayVisibilityCallback != null) { - mOverlayVisibilityCallback.onResult(visibility == View.VISIBLE); + if (mOverlayCoordinator != null) { + mOverlayCoordinator.setIsAndroidViewVisible(visibility == View.VISIBLE); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarCoordinator.java index 8b0609c..1790cacc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarCoordinator.java
@@ -20,8 +20,11 @@ import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider; +import org.chromium.chrome.browser.device.DeviceClassManager; +import org.chromium.chrome.browser.layouts.LayoutManager; import org.chromium.chrome.browser.layouts.LayoutStateProvider; import org.chromium.chrome.browser.omnibox.LocationBar; +import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.IncognitoStateProvider; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.toolbar.ButtonData; @@ -38,7 +41,6 @@ import org.chromium.chrome.features.start_surface.StartSurface; import org.chromium.chrome.features.start_surface.StartSurfaceConfiguration; import org.chromium.chrome.features.start_surface.StartSurfaceState; -import org.chromium.components.browser_ui.widget.ClipDrawableProgressBar; import org.chromium.ui.resources.ResourceManager; import java.util.List; @@ -83,9 +85,9 @@ private ObservableSupplier<AppMenuButtonHelper> mAppMenuButtonHelperSupplier; private ObservableSupplier<TabModelSelector> mTabModelSelectorSupplier; - private Callback<ClipDrawableProgressBar.DrawingInfo> mProgressDrawInfoCallback; private ToolbarControlContainer mControlContainer; private Supplier<ResourceManager> mResourceManagerSupplier; + private TopToolbarOverlayCoordinator mOverlayCoordinator; /** * Creates a new {@link TopToolbarCoordinator}. @@ -129,10 +131,6 @@ mOptionalButtonController = new OptionalBrowsingModeButtonController(buttonDataProviders, userEducationHelper, mToolbarLayout, () -> toolbarDataProvider.getTab()); mResourceManagerSupplier = resourceManagerSupplier; - mProgressDrawInfoCallback = (info) -> { - if (controlContainer == null) return; - controlContainer.getProgressBarDrawingInfo(info); - }; mTabModelSelectorSupplier = tabModelSelectorSupplier; @@ -177,12 +175,16 @@ * @param newTabClickHandler The click handler for the new tab button. * @param bookmarkClickHandler The click handler for the bookmarks button. * @param customTabsBackClickHandler The click handler for the custom tabs back button. - * @param browserControlsStateProvider Access to the state of the browser controls. + * @param layoutManager A {@link LayoutManager} used to watch for scene changes. + * @param tabSupplier Supplier of the activity tab. + * @param browserControlsStateProvider {@link BrowserControlsStateProvider} to access browser + * controls offsets. */ public void initializeWithNative(Runnable layoutUpdater, OnClickListener tabSwitcherClickHandler, OnLongClickListener tabSwitcherLongClickHandler, OnClickListener newTabClickHandler, OnClickListener bookmarkClickHandler, OnClickListener customTabsBackClickHandler, + LayoutManager layoutManager, ObservableSupplier<Tab> tabSupplier, BrowserControlsStateProvider browserControlsStateProvider) { assert mTabModelSelectorSupplier.get() != null; if (mTabSwitcherModeCoordinatorPhone != null) { @@ -207,6 +209,16 @@ mToolbarLayout.setLayoutUpdater(layoutUpdater); mToolbarLayout.onNativeLibraryReady(); + + // If fullscreen is disabled, don't bother creating this overlay; only the android view will + // ever be shown. + if (DeviceClassManager.enableFullscreen()) { + mOverlayCoordinator = new TopToolbarOverlayCoordinator(mToolbarLayout.getContext(), + layoutManager, mControlContainer::getProgressBarDrawingInfo, tabSupplier, + browserControlsStateProvider, mResourceManagerSupplier); + layoutManager.addSceneOverlay(mOverlayCoordinator); + mToolbarLayout.setOverlayCoordinator(mOverlayCoordinator); + } } /** @@ -234,6 +246,10 @@ * Cleans up any code as necessary. */ public void destroy() { + if (mOverlayCoordinator != null) { + mOverlayCoordinator.destroy(); + mOverlayCoordinator = null; + } mToolbarLayout.destroy(); if (mTabSwitcherModeCoordinatorPhone != null) { mTabSwitcherModeCoordinatorPhone.destroy();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayCoordinator.java similarity index 95% rename from chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayCoordinator.java rename to chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayCoordinator.java index 7705bfb..87f590a9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayCoordinator.java
@@ -2,15 +2,15 @@ // 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.compositor.overlays.toolbar; +package org.chromium.chrome.browser.toolbar.top; import android.content.Context; import android.graphics.RectF; import org.chromium.base.Callback; +import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider; import org.chromium.chrome.browser.layouts.CompositorModelChangeProcessor; import org.chromium.chrome.browser.layouts.EventFilter; @@ -18,6 +18,7 @@ import org.chromium.chrome.browser.layouts.SceneOverlay; import org.chromium.chrome.browser.layouts.components.VirtualView; import org.chromium.chrome.browser.layouts.scene_layer.SceneOverlayLayer; +import org.chromium.chrome.browser.tab.Tab; import org.chromium.components.browser_ui.widget.ClipDrawableProgressBar; import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.resources.ResourceManager; @@ -40,7 +41,7 @@ public TopToolbarOverlayCoordinator(Context context, LayoutManager layoutManager, Callback<ClipDrawableProgressBar.DrawingInfo> progressInfoCallback, - ActivityTabProvider tabSupplier, + ObservableSupplier<Tab> tabSupplier, BrowserControlsStateProvider browserControlsStateProvider, Supplier<ResourceManager> resourceManagerSupplier) { mModel = new PropertyModel.Builder(TopToolbarOverlayProperties.ALL_KEYS)
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediator.java similarity index 88% rename from chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediator.java rename to chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediator.java index 0123c47..7154af1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediator.java
@@ -2,7 +2,7 @@ // 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.compositor.overlays.toolbar; +package org.chromium.chrome.browser.toolbar.top; import android.content.Context; @@ -10,15 +10,16 @@ import androidx.annotation.VisibleForTesting; import org.chromium.base.Callback; -import org.chromium.chrome.browser.ActivityTabProvider; +import org.chromium.base.CallbackController; +import org.chromium.base.supplier.ObservableSupplier; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider; import org.chromium.chrome.browser.browser_controls.BrowserControlsUtils; import org.chromium.chrome.browser.layouts.LayoutStateProvider; import org.chromium.chrome.browser.layouts.LayoutStateProvider.LayoutStateObserver; import org.chromium.chrome.browser.layouts.LayoutType; +import org.chromium.chrome.browser.tab.CurrentTabObserver; 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.tasks.tab_management.TabUiFeatureUtilities; import org.chromium.chrome.browser.toolbar.ToolbarColors; import org.chromium.components.browser_ui.widget.ClipDrawableProgressBar; @@ -45,10 +46,13 @@ private final Callback<ClipDrawableProgressBar.DrawingInfo> mProgressInfoCallback; /** Provides current tab. */ - private final ActivityTabProvider mTabSupplier; + private final ObservableSupplier<Tab> mTabSupplier; /** An observer that watches for changes in the active tab. */ - private final ActivityTabProvider.ActivityTabObserver mTabSupplierObserver; + private final CurrentTabObserver mTabObserver; + + /** A callback to invoke upon activity tab switching. */ + private final Callback<Tab> mActivityTabCallback; /** Access to the current state of the browser controls. */ private final BrowserControlsStateProvider mBrowserControlsStateProvider; @@ -59,8 +63,8 @@ /** The view state for this overlay. */ private final PropertyModel mModel; - /** The last non-null tab. */ - private Tab mLastActiveTab; + /** Callback controller for cancelable callbacks. */ + private final CallbackController mCallbackController; /** Whether the active layout has its own toolbar to display instead of this one. */ private boolean mLayoutHasOwnToolbar; @@ -71,7 +75,7 @@ TopToolbarOverlayMediator(PropertyModel model, Context context, LayoutStateProvider layoutStateProvider, Callback<ClipDrawableProgressBar.DrawingInfo> progressInfoCallback, - ActivityTabProvider tabSupplier, + ObservableSupplier<Tab> tabSupplier, BrowserControlsStateProvider browserControlsStateProvider) { mContext = context; mLayoutStateProvider = layoutStateProvider; @@ -79,6 +83,7 @@ mTabSupplier = tabSupplier; mBrowserControlsStateProvider = browserControlsStateProvider; mModel = model; + mCallbackController = new CallbackController(); mSceneChangeObserver = new LayoutStateObserver() { @Override @@ -93,7 +98,7 @@ }; mLayoutStateProvider.addObserver(mSceneChangeObserver); - final TabObserver currentTabObserver = new EmptyTabObserver() { + mTabObserver = new CurrentTabObserver(mTabSupplier, new EmptyTabObserver() { @Override public void onDidChangeThemeColor(Tab tab, int color) { updateThemeColor(tab); @@ -109,21 +114,20 @@ updateVisibility(); updateThemeColor(tab); } - }; + }); // Keep an observer attached to the visible tab (and only the visible tab) to update // properties including theme color. - mTabSupplierObserver = (tab, hint) -> { - if (mLastActiveTab != null) mLastActiveTab.removeObserver(currentTabObserver); + mActivityTabCallback = mCallbackController.makeCancelable(tab -> { if (tab == null) return; - - mLastActiveTab = tab; - mLastActiveTab.addObserver(currentTabObserver); updateVisibility(); - updateThemeColor(mLastActiveTab); + updateThemeColor(tab); updateProgress(); - }; - mTabSupplier.addObserverAndTrigger(mTabSupplierObserver); + }); + + mTabSupplier.addObserver(mActivityTabCallback); + mActivityTabCallback.onResult(mTabSupplier.get()); + mTabObserver.triggerWithCurrentTab(); mBrowserControlsObserver = new BrowserControlsStateProvider.Observer() { @Override @@ -223,9 +227,10 @@ /** Clean up any state and observers. */ void destroy() { - mTabSupplier.removeObserver(mTabSupplierObserver); - mTabSupplierObserver.onActivityTabChanged(null, false); - mLastActiveTab = null; + mCallbackController.destroy(); + mTabObserver.destroy(); + mActivityTabCallback.onResult(null); + mTabSupplier.removeObserver(mActivityTabCallback); mLayoutStateProvider.removeObserver(mSceneChangeObserver); mBrowserControlsStateProvider.removeObserver(mBrowserControlsObserver);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayProperties.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayProperties.java similarity index 96% rename from chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayProperties.java rename to chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayProperties.java index 4b3514b..f920f48 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayProperties.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayProperties.java
@@ -2,7 +2,7 @@ // 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.compositor.overlays.toolbar; +package org.chromium.chrome.browser.toolbar.top; import org.chromium.components.browser_ui.widget.ClipDrawableProgressBar.DrawingInfo; import org.chromium.ui.modelutil.PropertyKey;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarSceneLayer.java similarity index 98% rename from chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarSceneLayer.java rename to chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarSceneLayer.java index d92096c..9a7d765b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarSceneLayer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/TopToolbarSceneLayer.java
@@ -2,7 +2,7 @@ // 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.compositor.overlays.toolbar; +package org.chromium.chrome.browser.toolbar.top; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java index 8159e5d..d3e58030 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java
@@ -386,7 +386,7 @@ @Test @LargeTest @Feature({"Navigation"}) - public void testNoNewTabForSameApp() throws Exception { + public void testNoNewTabForSameApp() { mActivityTestRule.startMainActivityOnBlankPage(); String url1 = mTestServer.getURL("/chrome/test/data/android/google.html"); @@ -418,7 +418,6 @@ TestThreadUtils.runOnUiThreadBlocking( () -> mActivityTestRule.getActivity().onBackPressed()); CriteriaHelper.pollUiThread(() -> !mActivityTestRule.getActivity().hasWindowFocus()); - mActivityTestRule.resumeMainActivityFromLauncher(); } /** @@ -428,7 +427,7 @@ @Test @LargeTest @Feature({"Navigation"}) - public void testNewTabForUnknownApp() throws Exception { + public void testNewTabForUnknownApp() { mActivityTestRule.startMainActivityOnBlankPage(); String url1 = mTestServer.getURL("/chrome/test/data/android/google.html"); @@ -466,7 +465,6 @@ TestThreadUtils.runOnUiThreadBlocking( () -> mActivityTestRule.getActivity().onBackPressed()); CriteriaHelper.pollUiThread(() -> !mActivityTestRule.getActivity().hasWindowFocus()); - mActivityTestRule.resumeMainActivityFromLauncher(); } /** @@ -476,7 +474,7 @@ @Test @LargeTest @Feature({"Navigation"}) - public void testNewTabWithNewTabExtra() throws Exception { + public void testNewTabWithNewTabExtra() { mActivityTestRule.startMainActivityOnBlankPage(); String url1 = mTestServer.getURL("/chrome/test/data/android/google.html"); @@ -508,7 +506,6 @@ TestThreadUtils.runOnUiThreadBlocking( () -> mActivityTestRule.getActivity().onBackPressed()); CriteriaHelper.pollUiThread(() -> !mActivityTestRule.getActivity().hasWindowFocus()); - mActivityTestRule.resumeMainActivityFromLauncher(); } /** @@ -518,7 +515,7 @@ @Test @LargeTest @Feature({"Navigation", "Main"}) - public void testNoNewTabForSameAppOnStart() throws Exception { + public void testNoNewTabForSameAppOnStart() { String url1 = mTestServer.getURL("/chrome/test/data/android/google.html"); String url2 = mTestServer.getURL("/chrome/test/data/android/about.html"); @@ -543,7 +540,6 @@ TestThreadUtils.runOnUiThreadBlocking( () -> mActivityTestRule.getActivity().onBackPressed()); CriteriaHelper.pollUiThread(() -> !mActivityTestRule.getActivity().hasWindowFocus()); - mActivityTestRule.resumeMainActivityFromLauncher(); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java index e54957f..5133f22 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestMetricsTest.java
@@ -346,8 +346,8 @@ "PaymentRequest.TransactionAmount.Completed")); // Make sure the events were logged correctly. - int expectedSample = - Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_GOOGLE | Event.COULD_NOT_SHOW; + int expectedSample = Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_GOOGLE + | Event.COULD_NOT_SHOW | Event.NEEDS_COMPLETION_PAYMENT; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample)); @@ -386,8 +386,8 @@ "PaymentRequest.TransactionAmount.Completed")); // Make sure the events were logged correctly. - int expectedSample = - Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_OTHER | Event.COULD_NOT_SHOW; + int expectedSample = Event.REQUEST_SHIPPING | Event.REQUEST_METHOD_OTHER + | Event.COULD_NOT_SHOW | Event.NEEDS_COMPLETION_PAYMENT; Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "PaymentRequest.Events", expectedSample));
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/layouts/SceneOverlayTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/layouts/SceneOverlayTest.java index 2bbe02b6..59d4972 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/layouts/SceneOverlayTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/compositor/layouts/SceneOverlayTest.java
@@ -27,10 +27,10 @@ import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPanel; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; -import org.chromium.chrome.browser.compositor.overlays.toolbar.TopToolbarOverlayCoordinator; -import org.chromium.chrome.browser.compositor.scene_layer.ScrollingBottomViewSceneLayer; import org.chromium.chrome.browser.layouts.LayoutStateProvider; import org.chromium.chrome.browser.layouts.SceneOverlay; +import org.chromium.chrome.browser.toolbar.bottom.ScrollingBottomViewSceneLayer; +import org.chromium.chrome.browser.toolbar.top.TopToolbarOverlayCoordinator; import java.util.HashMap; import java.util.List;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediatorTest.java similarity index 87% rename from chrome/android/junit/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediatorTest.java rename to chrome/android/junit/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediatorTest.java index c8265b0..c26ac346 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/compositor/overlays/toolbar/TopToolbarOverlayMediatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/toolbar/top/TopToolbarOverlayMediatorTest.java
@@ -2,8 +2,9 @@ // 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.compositor.overlays.toolbar; +package org.chromium.chrome.browser.toolbar.top; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -20,8 +21,9 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.chromium.base.Callback; +import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider; import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl; import org.chromium.chrome.browser.tab.Tab; @@ -57,10 +59,10 @@ private ArgumentCaptor<BrowserControlsStateProvider.Observer> mBrowserControlsObserverCaptor; @Mock - private ActivityTabProvider mTabSupplier; + private ObservableSupplier<Tab> mTabSupplier; @Captor - private ArgumentCaptor<ActivityTabProvider.ActivityTabObserver> mActivityTabObserverCaptor; + private ArgumentCaptor<Callback<Tab>> mActivityTabObserverCaptor; @Before public void beforeTest() { @@ -81,12 +83,14 @@ .with(TopToolbarOverlayProperties.PROGRESS_BAR_INFO, null) .build(); + when(mTabSupplier.get()).thenReturn(mTab); mMediator = new TopToolbarOverlayMediator(mModel, mContext, mLayoutManager, (info) -> {}, mTabSupplier, mBrowserControlsProvider); mMediator.setIsAndroidViewVisible(true); - // Ensure the observer is added to the initial tab. - verify(mTabSupplier).addObserverAndTrigger(mActivityTabObserverCaptor.capture()); + // Ensure the observer is added to the initial tab. We have 2 observers added - + // one for various tab observer events, the other for tab switching itself. + verify(mTabSupplier, times(2)).addObserver(mActivityTabObserverCaptor.capture()); setTabSupplierTab(mTab); verify(mTab).addObserver(mTabObserverCaptor.capture()); @@ -97,7 +101,7 @@ /** Set the tab that will be returned by the supplier and trigger the observer event. */ private void setTabSupplierTab(Tab tab) { when(mTabSupplier.get()).thenReturn(tab); - mActivityTabObserverCaptor.getValue().onActivityTabChanged(tab, false); + mActivityTabObserverCaptor.getValue().onResult(tab); } @After @@ -107,15 +111,6 @@ } @Test - public void testTabObserverAfterTabSwitch() { - setTabSupplierTab(mTab2); - - // Make sure the tab observer for this overlay is only observing the "current" tab. - verify(mTab).removeObserver(mTabObserverCaptor.getValue()); - verify(mTab2).addObserver(mTabObserverCaptor.getValue()); - } - - @Test public void testShadowVisibility_browserControlsOffsets() { when(mBrowserControlsProvider.getBrowserControlHiddenRatio()).thenReturn(0.0f); mBrowserControlsObserverCaptor.getValue().onControlsOffsetChanged(0, 0, 0, 0, false);
diff --git a/chrome/android/profiles/newest.txt b/chrome/android/profiles/newest.txt index 02a736c..38c4f62 100644 --- a/chrome/android/profiles/newest.txt +++ b/chrome/android/profiles/newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-89.0.4337.0_rc-r1-merged.afdo.bz2 +chromeos-chrome-amd64-89.0.4339.0_rc-r1-merged.afdo.bz2
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index 794ec3e..69e5426 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -5935,6 +5935,9 @@ <message name="IDS_RESTORE_NOTIFICATION_TITLE" desc="This is the title of the notification for the user to select restore or not on startup."> Restore apps & pages? </message> + <message name="IDS_RESTORE_NOTIFICATION_MESSAGE" desc="This is the text message of the notification for the user to select restore or not on startup if the 'restore_apps_and_pages' setting is 'Ask every time', and the system is not crashed before reboot."> + Continue where you left off. + </message> </if> </grit-part>
diff --git a/chrome/app/chromeos_strings_grdp/IDS_RESTORE_NOTIFICATION_MESSAGE.png.sha1 b/chrome/app/chromeos_strings_grdp/IDS_RESTORE_NOTIFICATION_MESSAGE.png.sha1 new file mode 100644 index 0000000..ed4c242 --- /dev/null +++ b/chrome/app/chromeos_strings_grdp/IDS_RESTORE_NOTIFICATION_MESSAGE.png.sha1
@@ -0,0 +1 @@ +69bf591cd5c98c716673498e022daf621f118cd2 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings.grdp b/chrome/app/os_settings_strings.grdp index 112212e2..3373f41 100644 --- a/chrome/app/os_settings_strings.grdp +++ b/chrome/app/os_settings_strings.grdp
@@ -1142,9 +1142,24 @@ <message name="IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_SECOND_MESSAGE" desc="Description of the Account Manager Settings page for child users. Shown just below the link to learn more about account management."> Adding a school account enables easy sign-in to websites, extensions, and apps as a student while still operating under parental controls. </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_DESCRIPTION" desc="Description of the Account Manager Settings page for primary account. Shown above primary account picture."> + Your apps and OS settings will sync across Chromebooks where you're signed in with this account.<ph name="LINK_BEGIN"><a href="#"></ph>Sync Settings<ph name="LINK_END"></a></ph> + </message> <message name="IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER" desc="List header for Account List in Account Manager Settings page."> Accounts </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_V2" desc="List header for secondary account List in Account Manager Settings page."> + Secondary accounts + </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_CHILD" desc="List header for secondary account List in Account Manager Settings page for Child user."> + School accounts + </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP" desc="List tooltip for secondary account List in Account Manager Settings page."> + Apps and OS settings are not synced to secondary accounts. + </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP_NO_SECONDARY_ACCOUNTS" desc="List tooltip for secondary account List in Account Manager Settings page when user doesn't have secondary accounts."> + When you add a secondary account here, you may browse the web, download apps, check your Gmail and other Google services using that account. + </message> <message name="IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_TOOLTIP" desc="Tooltip for the primary account in accounts list in Settings describing how to sign out."> To sign out of the primary account on this device, click the time on your screen. In the menu that appears, click "Sign out". </message> @@ -1199,6 +1214,12 @@ <message name="IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_MANAGED_ACCOUNT" desc="Management status label for managed accounts. This will be e.g. 'Managed by google.com' for Enterprise accounts and 'Managed by Family Link' for child accounts."> Managed by <ph name="DOMAIN">$1<ex>google.com</ex></ph> </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS" desc="Management status label for managed accounts."> + This account is managed by <ph name="BEGIN_LINK"><a target="_blank"></ph><ph name="DOMAIN">$1<ex>google.com</ex></ph><ph name="END_LINK"></a></ph> + </message> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_CHILD" desc="Management status label for child accounts."> + This user is managed by Family Link + </message> <message name="IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_PRIMARY_ACCOUNT" desc="Indicates this account is the primary account, when the primary account is a child account."> Primary Account </message>
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_CHILD.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_CHILD.png.sha1 new file mode 100644 index 0000000..89e37766 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_CHILD.png.sha1
@@ -0,0 +1 @@ +9d1fc4834269b9f9c402d7fc3cb0635d7c4d6666 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_V2.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_V2.png.sha1 new file mode 100644 index 0000000..74f210c --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_V2.png.sha1
@@ -0,0 +1 @@ +e264e7b899afe17312b148a7ba570aa0b38ddd6d \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP.png.sha1 new file mode 100644 index 0000000..da0fc44 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP.png.sha1
@@ -0,0 +1 @@ +4e429597bf0d8fa44802507996668f25caa7aca2 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP_NO_SECONDARY_ACCOUNTS.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP_NO_SECONDARY_ACCOUNTS.png.sha1 new file mode 100644 index 0000000..74f210c --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP_NO_SECONDARY_ACCOUNTS.png.sha1
@@ -0,0 +1 @@ +e264e7b899afe17312b148a7ba570aa0b38ddd6d \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS.png.sha1 new file mode 100644 index 0000000..df469302 --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS.png.sha1
@@ -0,0 +1 @@ +3cc46e67d0b5717858d2e9e7090f0131bda8d615 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_CHILD.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_CHILD.png.sha1 new file mode 100644 index 0000000..2e71f1f --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_CHILD.png.sha1
@@ -0,0 +1 @@ +ff945af9a4d7096af626d1e6131cac6f73115976 \ No newline at end of file
diff --git a/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_DESCRIPTION.png.sha1 b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_DESCRIPTION.png.sha1 new file mode 100644 index 0000000..2e71f1f --- /dev/null +++ b/chrome/app/os_settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_DESCRIPTION.png.sha1
@@ -0,0 +1 @@ +ff945af9a4d7096af626d1e6131cac6f73115976 \ No newline at end of file
diff --git a/chrome/app/settings_chromium_strings.grdp b/chrome/app/settings_chromium_strings.grdp index fbcd2d8..e6e2905 100644 --- a/chrome/app/settings_chromium_strings.grdp +++ b/chrome/app/settings_chromium_strings.grdp
@@ -159,6 +159,11 @@ <message name="IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT_SECONDARY_WITH_ACCOUNT" desc="The secondary text displayed to prompt users to enable sync for an account that is alredy present in Chromium."> Sync and personalize Chromium across your devices </message> +<if expr="chromeos"> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2" desc="Description of the Account Manager Settings page. Shown just below the title of the page."> + If you have multiple Google Accounts, you can add them to your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph>. Your accounts will be available in Chromium browser and Play Store, as well as services like Gmail, Drive, and YouTube.<ph name="LINK_BEGIN"><a></ph>Learn more<ph name="LINK_END"></a></ph> + </message> +</if> <!-- Sync Page --> <message name="IDS_SETTINGS_SYNC_DATA_ENCRYPTED_TEXT" desc="Text alerting the user that synced data is encrypted.">
diff --git a/chrome/app/settings_chromium_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2.png.sha1 b/chrome/app/settings_chromium_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2.png.sha1 new file mode 100644 index 0000000..e3b4d5f0 --- /dev/null +++ b/chrome/app/settings_chromium_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2.png.sha1
@@ -0,0 +1 @@ +3b2082d4819066cf841fcc41e4ec7d76bc4f46d6 \ No newline at end of file
diff --git a/chrome/app/settings_google_chrome_strings.grdp b/chrome/app/settings_google_chrome_strings.grdp index c80badd..2659db4 100644 --- a/chrome/app/settings_google_chrome_strings.grdp +++ b/chrome/app/settings_google_chrome_strings.grdp
@@ -160,6 +160,11 @@ <message name="IDS_SETTINGS_PEOPLE_SIGN_IN_PROMPT_SECONDARY_WITH_ACCOUNT" desc="The secondary text displayed to prompt users to enable sync for an account that is alredy present in Chrome."> Sync and personalize Chrome across your devices </message> +<if expr="chromeos"> + <message name="IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2" desc="Description of the Account Manager Settings page. Shown just below the title of the page."> + If you have multiple Google Accounts, you can add them to your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph>. Your accounts will be available in Chrome browser and Play Store, as well as services like Gmail, Drive, and YouTube.<ph name="LINK_BEGIN"><a></ph>Learn more<ph name="LINK_END"></a></ph> + </message> +</if> <!-- Sync Page --> <message name="IDS_SETTINGS_SYNC_DATA_ENCRYPTED_TEXT" desc="Text alerting the user that synced data is encrypted.">
diff --git a/chrome/app/settings_google_chrome_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2.png.sha1 b/chrome/app/settings_google_chrome_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2.png.sha1 new file mode 100644 index 0000000..74f210c --- /dev/null +++ b/chrome/app/settings_google_chrome_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2.png.sha1
@@ -0,0 +1 @@ +e264e7b899afe17312b148a7ba570aa0b38ddd6d \ No newline at end of file
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 2059466..a1912a2 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -459,6 +459,15 @@ base::size(kReaderModeOfferInSettings), nullptr}}; #endif // OS_ANDROID +#if defined(OS_ANDROID) +const FeatureEntry::FeatureParam kDismissButtonWithNoThanks[] = { + {"dismiss_button", "no_thanks"}}; + +const FeatureEntry::FeatureVariation kMobileIdentityConsistencyVariations[] = { + {"Dismiss No Thanks", kDismissButtonWithNoThanks, + base::size(kDismissButtonWithNoThanks), nullptr}}; +#endif // OS_ANDROID + #if !defined(OS_CHROMEOS) const FeatureEntry::FeatureParam kForceDark_SimpleHsl[] = { {"inversion_method", "hsl_based"}, @@ -3335,6 +3344,10 @@ flag_descriptions::kDesktopPWAsRunOnOsLoginName, flag_descriptions::kDesktopPWAsRunOnOsLoginDescription, kOsWin, FEATURE_VALUE_TYPE(features::kDesktopPWAsRunOnOsLogin)}, + {"record-web-app-debug-info", + flag_descriptions::kRecordWebAppDebugInfoName, + flag_descriptions::kRecordWebAppDebugInfoDescription, kOsDesktop, + FEATURE_VALUE_TYPE(features::kRecordWebAppDebugInfo)}, {"use-sync-sandbox", flag_descriptions::kSyncSandboxName, flag_descriptions::kSyncSandboxDescription, kOsAll, SINGLE_VALUE_TYPE_AND_VALUE( @@ -5295,6 +5308,12 @@ flag_descriptions::kMobileIdentityConsistencyName, flag_descriptions::kMobileIdentityConsistencyDescription, kOsAndroid, FEATURE_VALUE_TYPE(signin::kMobileIdentityConsistency)}, + {"mobile-identity-consistency-var", + flag_descriptions::kMobileIdentityConsistencyVarName, + flag_descriptions::kMobileIdentityConsistencyVarDescription, kOsAndroid, + FEATURE_WITH_PARAMS_VALUE_TYPE(signin::kMobileIdentityConsistencyVar, + kMobileIdentityConsistencyVariations, + "MobileIdentityConsistencyVar")}, #endif // defined(OS_ANDROID) {"autofill-use-improved-label-disambiguation", @@ -6879,6 +6898,11 @@ FEATURE_VALUE_TYPE( password_manager::features::kUseOfHashAffiliationFetcher)}, + {"safety-check-weak-passwords", + flag_descriptions::kSafetyCheckWeakPasswordsName, + flag_descriptions::kSafetyCheckWeakPasswordsDescription, kOsDesktop, + FEATURE_VALUE_TYPE(features::kSafetyCheckWeakPasswords)}, + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 7a10db5..39839b1 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -320,15 +320,15 @@ <include name="IDR_OS_CREDITS_HTML" file="resources\chromeos\about_os_credits.html" flattenhtml="true" type="BINDATA" /> <if expr="optimize_webui"> <then> - <include name="IDR_INTERNET_CONFIG_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\vulcanized.html" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> - <include name="IDR_INTERNET_CONFIG_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\crisper.js" use_base_dir="false" flattenhtml="true" type="BINDATA" /> - <include name="IDR_INTERNET_DETAIL_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\vulcanized.html" use_base_dir="false" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> - <include name="IDR_INTERNET_DETAIL_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\crisper.js" use_base_dir="false" flattenhtml="true" type="BINDATA" /> + <include name="IDR_INTERNET_CONFIG_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\vulcanized.html" use_base_dir="false" preprocess="true" type="BINDATA" /> + <include name="IDR_INTERNET_CONFIG_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_config_dialog\crisper.js" use_base_dir="false" preprocess="true" type="BINDATA" /> + <include name="IDR_INTERNET_DETAIL_DIALOG_VULCANIZED_HTML" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\vulcanized.html" use_base_dir="false" preprocess="true" type="BINDATA" /> + <include name="IDR_INTERNET_DETAIL_DIALOG_CRISPER_JS" file="${root_gen_dir}\chrome\browser\resources\chromeos\internet_detail_dialog\crisper.js" use_base_dir="false" preprocess="true" type="BINDATA" /> </then> <else> - <include name="IDR_INTERNET_CONFIG_DIALOG_HTML" file="resources\chromeos\internet_config_dialog\internet_config_dialog.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" /> + <include name="IDR_INTERNET_CONFIG_DIALOG_HTML" file="resources\chromeos\internet_config_dialog\internet_config_dialog.html" type="chrome_html" /> <include name="IDR_INTERNET_CONFIG_DIALOG_JS" file="resources\chromeos\internet_config_dialog\internet_config_dialog.js" type="chrome_html" /> - <include name="IDR_INTERNET_DETAIL_DIALOG_HTML" file="resources\chromeos\internet_detail_dialog\internet_detail_dialog.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" /> + <include name="IDR_INTERNET_DETAIL_DIALOG_HTML" file="resources\chromeos\internet_detail_dialog\internet_detail_dialog.html" type="chrome_html" /> <include name="IDR_INTERNET_DETAIL_DIALOG_JS" file="resources\chromeos\internet_detail_dialog\internet_detail_dialog.js" type="chrome_html" /> </else> </if>
diff --git a/chrome/browser/chrome_back_forward_cache_browsertest.cc b/chrome/browser/chrome_back_forward_cache_browsertest.cc index a7ea953a..0853c0b 100644 --- a/chrome/browser/chrome_back_forward_cache_browsertest.cc +++ b/chrome/browser/chrome_back_forward_cache_browsertest.cc
@@ -348,10 +348,10 @@ // Use the WebNfc feature on the empty page. EXPECT_EQ("success", content::EvalJs(current_frame_host(), R"( - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); new Promise(async resolve => { try { - await writer.write("Hello"); + await ndef.write("Hello"); resolve('success'); } catch (error) { resolve(error.message);
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index bdcec705..f43d9af 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -336,6 +336,7 @@ "//gpu/ipc/host", "//gpu/ipc/service", "//media", + "//media/capture:capture_lib", "//media/capture:capture_switches", "//media/mojo/mojom", "//mojo/public/cpp/platform",
diff --git a/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.cc b/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.cc index 90778823..af63d8b 100644 --- a/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.cc +++ b/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.cc
@@ -121,7 +121,8 @@ if (is_new_app_setup_in_progress_) return; - base::Optional<PwaDomain> migrating_from = GetInstalledPwaDomain(); + base::Optional<PwaDomain> migrating_from = + GetInstalledPwaDomainForMigration(); // If the preferred domain is already installed, no migration is happening at // all. @@ -176,6 +177,18 @@ } base::Optional<PwaDomain> AndroidSmsAppManagerImpl::GetInstalledPwaDomain() { + PwaDomain preferred_domain = GetPreferredPwaDomain(); + if (setup_controller_->GetPwa(GetAndroidMessagesURL( + true /* use_install_url */, preferred_domain))) { + return preferred_domain; + } + + // If the preferred PWA app is not installed. Check all migration domains. + return GetInstalledPwaDomainForMigration(); +} + +base::Optional<PwaDomain> +AndroidSmsAppManagerImpl::GetInstalledPwaDomainForMigration() { for (auto* it = std::begin(kDomains); it != std::end(kDomains); ++it) { if (setup_controller_->GetPwa( GetAndroidMessagesURL(true /* use_install_url */, *it))) {
diff --git a/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.h b/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.h index ca187d1..d4ab70a5 100644 --- a/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.h +++ b/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl.h
@@ -76,6 +76,7 @@ void ExecuteOnAppRegistryReady(base::OnceClosure task) override; base::Optional<PwaDomain> GetInstalledPwaDomain(); + base::Optional<PwaDomain> GetInstalledPwaDomainForMigration(); void CompleteAsyncInitialization(); void NotifyInstalledAppUrlChangedIfNecessary(); void OnSetUpNewAppResult(const base::Optional<PwaDomain>& migrating_from,
diff --git a/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl_unittest.cc b/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl_unittest.cc index 447caa0..5a476fb 100644 --- a/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl_unittest.cc +++ b/chrome/browser/chromeos/android_sms/android_sms_app_manager_impl_unittest.cc
@@ -12,11 +12,13 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" +#include "base/test/scoped_feature_list.h" #include "base/test/test_simple_task_runner.h" #include "chrome/browser/apps/app_service/app_launch_params.h" #include "chrome/browser/chromeos/android_sms/android_sms_urls.h" #include "chrome/browser/chromeos/android_sms/fake_android_sms_app_setup_controller.h" #include "chrome/test/base/testing_profile.h" +#include "chromeos/constants/chromeos_features.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -359,6 +361,25 @@ EXPECT_TRUE(android_sms_app_manager()->HasAppBeenManuallyUninstalledByUser()); } +TEST_F(AndroidSmsAppManagerImplTest, TestGetCurrentAppUrl) { + // Enable staging flag and install both prod and staging apps. + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeature(features::kUseMessagesStagingUrl); + fake_android_sms_app_setup_controller()->SetAppAtUrl( + GetAndroidMessagesURL(true /* use_install_url */, PwaDomain::kProdGoogle), + kOldAppId); + fake_android_sms_app_setup_controller()->SetAppAtUrl( + GetAndroidMessagesURL(true /* use_install_url */, PwaDomain::kStaging), + kNewAppId); + CompleteAsyncInitialization(); + + // When both apps are installed GetCurrentAppUrl should always + // return the preferred app. + EXPECT_EQ( + GetAndroidMessagesURL(false /* use_install_url */, PwaDomain::kStaging), + android_sms_app_manager()->GetCurrentAppUrl()); +} + } // namespace android_sms } // namespace chromeos
diff --git a/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.cc b/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.cc index 4639ea3b..27f883a 100644 --- a/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.cc +++ b/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/web_applications/components/external_install_options.h" #include "chrome/browser/web_applications/components/install_finalizer.h" +#include "chrome/browser/web_applications/components/pending_app_manager.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/browser/web_applications/components/web_app_provider_base.h" @@ -264,9 +265,9 @@ size_t num_attempts_so_far, const GURL& app_url, const GURL& install_url, - web_app::PendingAppManager::InstallResult result) { - UMA_HISTOGRAM_ENUMERATION("AndroidSms.PWAInstallationResult", result.code); - const bool install_succeeded = web_app::IsSuccess(result.code); + web_app::InstallResultCode code) { + UMA_HISTOGRAM_ENUMERATION("AndroidSms.PWAInstallationResult", code); + const bool install_succeeded = web_app::IsSuccess(code); if (!install_succeeded && num_attempts_so_far < kMaxInstallRetryCount) { base::TimeDelta retry_delay = @@ -274,7 +275,7 @@ PA_LOG(VERBOSE) << "AndroidSmsAppSetupControllerImpl::OnAppInstallResult(): " << "PWA for " << install_url << " failed to install." - << "InstallResultCode: " << static_cast<int>(result.code) + << "InstallResultCode: " << static_cast<int>(code) << " Retrying again in " << retry_delay; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, @@ -291,7 +292,7 @@ PA_LOG(WARNING) << "AndroidSmsAppSetupControllerImpl::OnAppInstallResult(): " << "PWA for " << install_url << " failed to install. " - << "InstallResultCode: " << static_cast<int>(result.code); + << "InstallResultCode: " << static_cast<int>(code); std::move(callback).Run(false /* success */); return; }
diff --git a/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.h b/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.h index 41c0ac1b..5751813 100644 --- a/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.h +++ b/chrome/browser/chromeos/android_sms/android_sms_app_setup_controller_impl.h
@@ -9,7 +9,6 @@ #include "base/memory/weak_ptr.h" #include "base/unguessable_token.h" #include "chrome/browser/chromeos/android_sms/android_sms_app_setup_controller.h" -#include "chrome/browser/web_applications/components/pending_app_manager.h" #include "chrome/browser/web_applications/components/web_app_id.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_access_result.h" @@ -99,7 +98,7 @@ size_t num_attempts_so_far, const GURL& app_url, const GURL& install_url, - web_app::PendingAppManager::InstallResult result); + web_app::InstallResultCode code); void SetMigrationCookie(const GURL& app_url, const GURL& migrated_to_app_url, SuccessCallback callback);
diff --git a/chrome/browser/chromeos/browser_context_keyed_service_factories.cc b/chrome/browser/chromeos/browser_context_keyed_service_factories.cc index f6b7c0b..f2aab39f 100644 --- a/chrome/browser/chromeos/browser_context_keyed_service_factories.cc +++ b/chrome/browser/chromeos/browser_context_keyed_service_factories.cc
@@ -29,6 +29,7 @@ #include "chrome/browser/chromeos/platform_keys/key_permissions/key_permissions_service_factory.h" #include "chrome/browser/chromeos/platform_keys/key_permissions/user_private_token_kpm_service_factory.h" #include "chrome/browser/chromeos/plugin_vm/plugin_vm_engagement_metrics_service.h" +#include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h" #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder_factory.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater_factory.h" @@ -87,6 +88,7 @@ platform_keys::UserPrivateTokenKeyPermissionsManagerServiceFactory:: GetInstance(); plugin_vm::PluginVmEngagementMetricsService::Factory::GetInstance(); + policy::DlpRulesManagerFactory::GetInstance(); policy::PolicyCertServiceFactory::GetInstance(); policy::UserCloudPolicyTokenForwarderFactory::GetInstance(); policy::UserNetworkConfigurationUpdaterFactory::GetInstance();
diff --git a/chrome/browser/chromeos/dbus/vm/vm_permission_service_provider.cc b/chrome/browser/chromeos/dbus/vm/vm_permission_service_provider.cc index 0297d38..687de89b 100644 --- a/chrome/browser/chromeos/dbus/vm/vm_permission_service_provider.cc +++ b/chrome/browser/chromeos/dbus/vm/vm_permission_service_provider.cc
@@ -21,6 +21,7 @@ #include "chromeos/dbus/vm_permission_service/vm_permission_service.pb.h" #include "components/prefs/pref_service.h" #include "dbus/message.h" +#include "media/capture/video/chromeos/camera_hal_dispatcher_impl.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace { @@ -155,6 +156,9 @@ UpdateVmPermissions(vm.get()); const base::UnguessableToken token(base::UnguessableToken::Create()); + + media::CameraHalDispatcherImpl::GetInstance()->RegisterPluginVmToken(token); + vms_[token] = std::move(vm); vm_permission_service::RegisterVmResponse payload; @@ -193,6 +197,9 @@ return; } + media::CameraHalDispatcherImpl::GetInstance()->UnregisterPluginVmToken( + iter->first); + vms_.erase(iter); std::move(response_sender).Run(std::move(response));
diff --git a/chrome/browser/chromeos/drive/drive_integration_service.cc b/chrome/browser/chromeos/drive/drive_integration_service.cc index 64628a46..0abcc5f 100644 --- a/chrome/browser/chromeos/drive/drive_integration_service.cc +++ b/chrome/browser/chromeos/drive/drive_integration_service.cc
@@ -575,7 +575,7 @@ {base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::WithBaseSyncPrimitives()}); - if (util::IsDriveEnabledForProfile(profile)) { + if (util::IsDriveAvailableForProfile(profile)) { preference_watcher_ = std::make_unique<PreferenceWatcher>(profile->GetPrefs()); preference_watcher_->set_integration_service(this);
diff --git a/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc b/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc index 3a8a926..1d11f14 100644 --- a/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc +++ b/chrome/browser/chromeos/drive/drive_integration_service_browsertest.cc
@@ -39,8 +39,8 @@ return &fake_drivefs_helpers_[profile]->fake_drivefs(); } - private: - drive::DriveIntegrationService* CreateDriveIntegrationService( + protected: + virtual drive::DriveIntegrationService* CreateDriveIntegrationService( Profile* profile) { base::ScopedAllowBlockingForTesting allow_blocking; base::FilePath mount_path = profile->GetPath().Append("drivefs"); @@ -52,6 +52,7 @@ return integration_service; } + private: drive::DriveIntegrationServiceFactory::FactoryCallback create_drive_integration_service_; std::unique_ptr<drive::DriveIntegrationServiceFactory::ScopedFactoryForTest> @@ -215,4 +216,28 @@ run_loop.Run(); } } + +class DriveIntegrationServiceWithPrefDisabledBrowserTest + : public DriveIntegrationServiceBrowserTest { + drive::DriveIntegrationService* CreateDriveIntegrationService( + Profile* profile) override { + profile->GetPrefs()->SetBoolean(prefs::kDisableDrive, true); + return DriveIntegrationServiceBrowserTest::CreateDriveIntegrationService( + profile); + } +}; + +IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceWithPrefDisabledBrowserTest, + RenableAndDisableDrive) { + auto* profile = browser()->profile(); + auto* drive_service = DriveIntegrationServiceFactory::FindForProfile(profile); + EXPECT_FALSE(drive_service->is_enabled()); + + profile->GetPrefs()->SetBoolean(prefs::kDisableDrive, false); + EXPECT_TRUE(drive_service->is_enabled()); + + profile->GetPrefs()->SetBoolean(prefs::kDisableDrive, true); + EXPECT_FALSE(drive_service->is_enabled()); +} + } // namespace drive
diff --git a/chrome/browser/chromeos/drive/file_system_util.cc b/chrome/browser/chromeos/drive/file_system_util.cc index d920ef6..74a5a27 100644 --- a/chrome/browser/chromeos/drive/file_system_util.cc +++ b/chrome/browser/chromeos/drive/file_system_util.cc
@@ -72,7 +72,7 @@ return cache_root_path.Append(kFileCacheVersionDir); } -bool IsDriveEnabledForProfile(Profile* profile) { +bool IsDriveAvailableForProfile(Profile* profile) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Disable Drive for non-Gaia accounts. @@ -90,11 +90,6 @@ if (!user || !user->HasGaiaAccount()) return false; - // Disable Drive if preference is set. This can happen with commandline flag - // --disable-drive or enterprise policy, or with user settings. - if (profile->GetPrefs()->GetBoolean(prefs::kDisableDrive)) - return false; - // Disable drive if sync is disabled by command line flag. Outside tests, this // only occurs in cases already handled by the gaia account check above. if (!switches::IsSyncAllowedByFlag()) @@ -103,6 +98,15 @@ return true; } +bool IsDriveEnabledForProfile(Profile* profile) { + // Disable Drive if preference is set. This can happen with commandline flag + // --disable-drive or enterprise policy, or with user settings. + if (profile->GetPrefs()->GetBoolean(prefs::kDisableDrive)) + return false; + + return IsDriveAvailableForProfile(profile); +} + ConnectionStatusType GetDriveConnectionStatus(Profile* profile) { auto* drive_integration_service = GetIntegrationServiceByProfile(profile); if (!drive_integration_service)
diff --git a/chrome/browser/chromeos/drive/file_system_util.h b/chrome/browser/chromeos/drive/file_system_util.h index 02b58a7..b914be3 100644 --- a/chrome/browser/chromeos/drive/file_system_util.h +++ b/chrome/browser/chromeos/drive/file_system_util.h
@@ -31,7 +31,10 @@ // profile. base::FilePath GetCacheRootPath(Profile* profile); -// Returns true if Drive is enabled for the given Profile. +// Returns true if Drive is available for the given Profile. +bool IsDriveAvailableForProfile(Profile* profile); + +// Returns true if Drive is currently enabled for the given Profile. bool IsDriveEnabledForProfile(Profile* profile); // Enum type for describing the current connection status to Drive.
diff --git a/chrome/browser/chromeos/full_restore/full_restore_service.cc b/chrome/browser/chromeos/full_restore/full_restore_service.cc index 2c83e76..1f98340 100644 --- a/chrome/browser/chromeos/full_restore/full_restore_service.cc +++ b/chrome/browser/chromeos/full_restore/full_restore_service.cc
@@ -7,12 +7,14 @@ #include "ash/public/cpp/notification_utils.h" #include "base/strings/string_util.h" #include "chrome/app/vector_icons/vector_icons.h" +#include "chrome/browser/chromeos/full_restore/full_restore_prefs.h" #include "chrome/browser/chromeos/full_restore/full_restore_service_factory.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" +#include "components/prefs/pref_service.h" #include "ui/base/l10n/l10n_util.h" #include "ui/message_center/public/cpp/notification.h" @@ -20,6 +22,13 @@ constexpr char kRestoreForCrashNotificationId[] = "restore_for_crash_notification"; +constexpr char kRestoreNotificationId[] = "restore_notification"; + +// The restore notification button index. +enum class RestoreNotificationButtonIndex { + kRestore = 0, + kCancel, +}; } // namespace @@ -33,9 +42,24 @@ return; } - // TODO(crbug.com/909794):On startup for normal reboot, read - // |kRestoreAppsAndPagesPrefName| from the user pref, show the restore - // notification for the 'ask every time' option. + PrefService* prefs = profile->GetPrefs(); + DCHECK(prefs); + + // TODO(crbug.com/909794):Set the default value if + // |kRestoreAppsAndPagesPrefName| doesn't exist from the user pref. + + RestoreOption restore_pref = static_cast<RestoreOption>( + prefs->GetInteger(kRestoreAppsAndPagesPrefName)); + switch (restore_pref) { + case RestoreOption::kAlways: + // TODO(crbug.com/909794): Implement apps and pages restoration. + break; + case RestoreOption::kAskEveryTime: + ShowRestoreNotification(kRestoreNotificationId); + break; + case RestoreOption::kDoNotRestore: + return; + } } FullRestoreService::~FullRestoreService() = default; @@ -53,11 +77,15 @@ base::ToUpperASCII(IDS_RESTORE_NOTIFICATION_CANCEL_BUTTON))); notification_data.buttons.push_back(cancel_button); + int message_id = id == kRestoreForCrashNotificationId + ? IDS_RESTORE_FOR_CRASH_NOTIFICATION_MESSAGE + : IDS_RESTORE_NOTIFICATION_MESSAGE; + std::unique_ptr<message_center::Notification> notification = ash::CreateSystemNotification( message_center::NOTIFICATION_TYPE_SIMPLE, id, l10n_util::GetStringUTF16(IDS_RESTORE_NOTIFICATION_TITLE), - l10n_util::GetStringUTF16(IDS_RESTORE_FOR_CRASH_NOTIFICATION_MESSAGE), + l10n_util::GetStringUTF16(message_id), l10n_util::GetStringUTF16(IDS_RESTORE_NOTIFICATION_DISPLAY_SOURCE), GURL(), message_center::NotifierId( @@ -84,12 +112,18 @@ void FullRestoreService::HandleRestoreNotificationClicked( const std::string& id, base::Optional<int> button_index) { - // TODO(crbug.com/909794):Get the user selection and start the restoration. - if (!is_shut_down_) { NotificationDisplayService::GetForProfile(profile_)->Close( NotificationHandler::Type::TRANSIENT, id); } + + if (!button_index.has_value() || + button_index.value() != + static_cast<int>(RestoreNotificationButtonIndex::kRestore)) { + return; + } + + // TODO(crbug.com/909794):Get the user selection and start the restoration. } } // namespace full_restore
diff --git a/chrome/browser/chromeos/login/screens/gaia_screen.cc b/chrome/browser/chromeos/login/screens/gaia_screen.cc index 1c5c6bb7..67ef55d 100644 --- a/chrome/browser/chromeos/login/screens/gaia_screen.cc +++ b/chrome/browser/chromeos/login/screens/gaia_screen.cc
@@ -11,6 +11,7 @@ namespace { constexpr char kUserActionCancel[] = "cancel"; +constexpr char kUserActionStartEnrollment[] = "startEnrollment"; } // namespace namespace chromeos { @@ -22,6 +23,10 @@ return "Back"; case Result::CLOSE_DIALOG: return "CloseDialog"; + case Result::ENTERPRISE_ENROLL: + return "EnterpriseEnroll"; + case Result::START_CONSUMER_KIOSK: + return "StartConsumerKiosk"; } } @@ -79,9 +84,25 @@ } else { LoadOnline(EmptyAccountId()); } - } else { - BaseScreen::OnUserAction(action_id); + return; } + if (action_id == kUserActionStartEnrollment) { + exit_callback_.Run(Result::ENTERPRISE_ENROLL); + return; + } + BaseScreen::OnUserAction(action_id); +} + +bool GaiaScreen::HandleAccelerator(ash::LoginAcceleratorAction action) { + if (action == ash::LoginAcceleratorAction::kStartEnrollment) { + exit_callback_.Run(Result::ENTERPRISE_ENROLL); + return true; + } + if (action == ash::LoginAcceleratorAction::kEnableConsumerKiosk) { + exit_callback_.Run(Result::START_CONSUMER_KIOSK); + return true; + } + return false; } } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screens/gaia_screen.h b/chrome/browser/chromeos/login/screens/gaia_screen.h index 8fc23449..5709c04 100644 --- a/chrome/browser/chromeos/login/screens/gaia_screen.h +++ b/chrome/browser/chromeos/login/screens/gaia_screen.h
@@ -25,6 +25,8 @@ enum class Result { BACK, CLOSE_DIALOG, + ENTERPRISE_ENROLL, + START_CONSUMER_KIOSK, }; static std::string GetResultString(Result result); @@ -49,6 +51,7 @@ void ShowImpl() override; void HideImpl() override; void OnUserAction(const std::string& action_id) override; + bool HandleAccelerator(ash::LoginAcceleratorAction action) override; GaiaView* view_ = nullptr;
diff --git a/chrome/browser/chromeos/login/screens/packaged_license_screen.cc b/chrome/browser/chromeos/login/screens/packaged_license_screen.cc index 8eb9702..50df36b 100644 --- a/chrome/browser/chromeos/login/screens/packaged_license_screen.cc +++ b/chrome/browser/chromeos/login/screens/packaged_license_screen.cc
@@ -80,4 +80,13 @@ BaseScreen::OnUserAction(action_id); } +bool PackagedLicenseScreen::HandleAccelerator( + ash::LoginAcceleratorAction action) { + if (action == ash::LoginAcceleratorAction::kStartEnrollment) { + exit_callback_.Run(Result::ENROLL); + return true; + } + return false; +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screens/packaged_license_screen.h b/chrome/browser/chromeos/login/screens/packaged_license_screen.h index b7edd1a..8aca25f4 100644 --- a/chrome/browser/chromeos/login/screens/packaged_license_screen.h +++ b/chrome/browser/chromeos/login/screens/packaged_license_screen.h
@@ -55,6 +55,7 @@ void ShowImpl() override; void HideImpl() override; void OnUserAction(const std::string& action_id) override; + bool HandleAccelerator(ash::LoginAcceleratorAction action) override; private: PackagedLicenseView* view_ = nullptr;
diff --git a/chrome/browser/chromeos/login/ui/fake_login_display_host.cc b/chrome/browser/chromeos/login/ui/fake_login_display_host.cc index 61e7fed..00fb3c3c 100644 --- a/chrome/browser/chromeos/login/ui/fake_login_display_host.cc +++ b/chrome/browser/chromeos/login/ui/fake_login_display_host.cc
@@ -92,6 +92,8 @@ void FakeLoginDisplayHost::StartKiosk(const KioskAppId& kiosk_app_id, bool is_auto_launch) {} +void FakeLoginDisplayHost::AttemptShowEnableConsumerKioskScreen() {} + void FakeLoginDisplayHost::CompleteLogin(const UserContext& user_context) {} void FakeLoginDisplayHost::OnGaiaScreenReady() {} @@ -116,6 +118,8 @@ void FakeLoginDisplayHost::HideOobeDialog() {} +void FakeLoginDisplayHost::SetShelfButtonsEnabled(bool enabled) {} + void FakeLoginDisplayHost::UpdateOobeDialogState(ash::OobeDialogState state) {} void FakeLoginDisplayHost::CancelPasswordChangedFlow() {}
diff --git a/chrome/browser/chromeos/login/ui/fake_login_display_host.h b/chrome/browser/chromeos/login/ui/fake_login_display_host.h index da3df5b..107f24b5c4 100644 --- a/chrome/browser/chromeos/login/ui/fake_login_display_host.h +++ b/chrome/browser/chromeos/login/ui/fake_login_display_host.h
@@ -45,6 +45,7 @@ void PrewarmAuthentication() override; void StartDemoAppLaunch() override; void StartKiosk(const KioskAppId& kiosk_app_id, bool is_auto_launch) override; + void AttemptShowEnableConsumerKioskScreen() override; void CompleteLogin(const chromeos::UserContext& user_context) override; void OnGaiaScreenReady() override; void SetDisplayEmail(const std::string& email) override; @@ -57,6 +58,7 @@ const base::Optional<user_manager::UserType>& user_type) override; void ShowGaiaDialog(const AccountId& prefilled_account) override; void HideOobeDialog() override; + void SetShelfButtonsEnabled(bool enabled) override; void UpdateOobeDialogState(ash::OobeDialogState state) override; void CancelPasswordChangedFlow() override; void MigrateUserData(const std::string& old_password) override;
diff --git a/chrome/browser/chromeos/login/ui/login_display_host.h b/chrome/browser/chromeos/login/ui/login_display_host.h index a79e0b9..b7c75b7 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host.h +++ b/chrome/browser/chromeos/login/ui/login_display_host.h
@@ -146,6 +146,9 @@ virtual void StartKiosk(const KioskAppId& kiosk_app_id, bool is_auto_launch) = 0; + // Performs necessary check and shows consumer kiosk UI if eligible. + virtual void AttemptShowEnableConsumerKioskScreen() = 0; + // Show the gaia dialog. If available, `account` is preloaded in the gaia // dialog. virtual void ShowGaiaDialog(const AccountId& prefilled_account) = 0; @@ -153,6 +156,9 @@ // Hide any visible oobe dialog. virtual void HideOobeDialog() = 0; + // Sets whether shelf buttons are enabled. + virtual void SetShelfButtonsEnabled(bool enabled) = 0; + // Update the state of the oobe dialog. virtual void UpdateOobeDialogState(ash::OobeDialogState state) = 0;
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_common.cc b/chrome/browser/chromeos/login/ui/login_display_host_common.cc index 31aa656c..9f773cb1 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_common.cc +++ b/chrome/browser/chromeos/login/ui/login_display_host_common.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/chromeos/login/screens/gaia_screen.h" #include "chrome/browser/chromeos/login/screens/pin_setup_screen.h" #include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/ui/login_feedback.h" #include "chrome/browser/chromeos/login/ui/webui_accelerator_mapping.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" @@ -255,6 +256,15 @@ kiosk_launch_controller_->Start(kiosk_app_id, is_auto_launch); } +void LoginDisplayHostCommon::AttemptShowEnableConsumerKioskScreen() { + policy::BrowserPolicyConnectorChromeOS* connector = + g_browser_process->platform_part()->browser_policy_connector_chromeos(); + if (!connector->IsEnterpriseManaged() && + KioskAppManager::IsConsumerKioskEnabled()) { + ShowEnableConsumerKioskScreen(); + } +} + void LoginDisplayHostCommon::CompleteLogin(const UserContext& user_context) { if (GetExistingUserController()) { GetExistingUserController()->CompleteLogin(user_context); @@ -322,6 +332,15 @@ bool LoginDisplayHostCommon::HandleAccelerator( ash::LoginAcceleratorAction action) { DCHECK(GetOobeUI()); + if (action == ash::LoginAcceleratorAction::kShowFeedback) { + login_feedback_ = std::make_unique<LoginFeedback>( + ProfileHelper::Get()->GetSigninProfile()); + login_feedback_->Request( + std::string(), + base::BindOnce(&LoginDisplayHostCommon::OnFeedbackFinished, + weak_factory_.GetWeakPtr())); + return true; + } if (WizardController::default_controller() && WizardController::default_controller()->is_initialized()) { if (WizardController::default_controller()->HandleAccelerator(action)) @@ -444,4 +463,8 @@ BrowserList::RemoveObserver(this); } +void LoginDisplayHostCommon::OnFeedbackFinished() { + login_feedback_.reset(); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_common.h b/chrome/browser/chromeos/login/ui/login_display_host_common.h index ea3d4a2..ad3794c2 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_common.h +++ b/chrome/browser/chromeos/login/ui/login_display_host_common.h
@@ -25,6 +25,7 @@ namespace chromeos { class DemoAppLauncher; +class LoginFeedback; // LoginDisplayHostCommon contains code which is not specific to a particular UI // implementation - the goal is to reduce code duplication between @@ -47,6 +48,7 @@ void PrewarmAuthentication() final; void StartDemoAppLaunch() final; void StartKiosk(const KioskAppId& kiosk_app_id, bool is_auto_launch) final; + void AttemptShowEnableConsumerKioskScreen() final; void CompleteLogin(const UserContext& user_context) final; void OnGaiaScreenReady() final; void SetDisplayEmail(const std::string& email) final; @@ -87,6 +89,7 @@ virtual void OnStartUserAdding() = 0; virtual void OnFinalize() = 0; virtual void OnCancelPasswordChangedFlow() = 0; + virtual void ShowEnableConsumerKioskScreen() = 0; // Deletes `auth_prewarmer_`. void OnAuthPrewarmDone(); @@ -113,6 +116,8 @@ private: void Cleanup(); + // Callback invoked after the feedback is finished. + void OnFeedbackFinished(); // True if session start is in progress. bool session_starting_ = false; @@ -133,6 +138,8 @@ KioskAppMenuController kiosk_app_menu_controller_; + std::unique_ptr<LoginFeedback> login_feedback_; + base::WeakPtrFactory<LoginDisplayHostCommon> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LoginDisplayHostCommon);
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc b/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc index 73be1c0..08d1d2f 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc +++ b/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc
@@ -338,6 +338,11 @@ HideDialog(); } +void LoginDisplayHostMojo::SetShelfButtonsEnabled(bool enabled) { + // Do nothing as we do not need to disable the shelf buttons on lock/login + // screen. +} + void LoginDisplayHostMojo::UpdateOobeDialogState(ash::OobeDialogState state) { if (dialog_) dialog_->SetState(state); @@ -384,6 +389,10 @@ HideOobeDialog(); } +void LoginDisplayHostMojo::ShowEnableConsumerKioskScreen() { + NOTREACHED(); +} + void LoginDisplayHostMojo::HandleAuthenticateUserWithPasswordOrPin( const AccountId& account_id, const std::string& password,
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_mojo.h b/chrome/browser/chromeos/login/ui/login_display_host_mojo.h index b780a1dc..eb2a06b5 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_mojo.h +++ b/chrome/browser/chromeos/login/ui/login_display_host_mojo.h
@@ -83,8 +83,10 @@ void OnBrowserCreated() override; void ShowGaiaDialog(const AccountId& prefilled_account) override; void HideOobeDialog() override; + void SetShelfButtonsEnabled(bool enabled) override; void UpdateOobeDialogState(ash::OobeDialogState state) override; void OnCancelPasswordChangedFlow() override; + void ShowEnableConsumerKioskScreen() override; void HandleDisplayCaptivePortal() override; void UpdateAddUserButtonStatus() override; void RequestSystemInfoUpdate() override;
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_webui.cc b/chrome/browser/chromeos/login/ui/login_display_host_webui.cc index 305b838..c3e9d76f4 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_webui.cc +++ b/chrome/browser/chromeos/login/ui/login_display_host_webui.cc
@@ -1009,6 +1009,10 @@ NOTREACHED(); } +void LoginDisplayHostWebUI::SetShelfButtonsEnabled(bool enabled) { + ash::LoginScreen::Get()->EnableShelfButtons(enabled); +} + void LoginDisplayHostWebUI::UpdateOobeDialogState(ash::OobeDialogState state) { ash::LoginScreen::Get()->GetModel()->NotifyOobeDialogState(state); } @@ -1019,6 +1023,11 @@ void LoginDisplayHostWebUI::OnCancelPasswordChangedFlow() {} +void LoginDisplayHostWebUI::ShowEnableConsumerKioskScreen() { + if (GetExistingUserController()) + GetExistingUserController()->OnStartKioskEnableScreen(); +} + void LoginDisplayHostWebUI::UpdateAddUserButtonStatus() { NOTREACHED(); }
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_webui.h b/chrome/browser/chromeos/login/ui/login_display_host_webui.h index fd0e3375..8677a03 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_webui.h +++ b/chrome/browser/chromeos/login/ui/login_display_host_webui.h
@@ -83,11 +83,13 @@ void OnBrowserCreated() override; void ShowGaiaDialog(const AccountId& prefilled_account) override; void HideOobeDialog() override; + void SetShelfButtonsEnabled(bool enabled) override; void UpdateOobeDialogState(ash::OobeDialogState state) override; void HandleDisplayCaptivePortal() override; void UpdateAddUserButtonStatus() override; void RequestSystemInfoUpdate() override; void OnCancelPasswordChangedFlow() override; + void ShowEnableConsumerKioskScreen() override; bool HasUserPods() override; void VerifyOwnerForKiosk(base::OnceClosure) override; void ShowPasswordChangedDialog(const AccountId& account_id,
diff --git a/chrome/browser/chromeos/login/ui/login_display_mojo.cc b/chrome/browser/chromeos/login/ui/login_display_mojo.cc index 126f597..fa9f41b 100644 --- a/chrome/browser/chromeos/login/ui/login_display_mojo.cc +++ b/chrome/browser/chromeos/login/ui/login_display_mojo.cc
@@ -221,10 +221,6 @@ NOTIMPLEMENTED(); } -void LoginDisplayMojo::ShowKioskEnableScreen() { - NOTIMPLEMENTED(); -} - void LoginDisplayMojo::ShowKioskAutolaunchScreen() { NOTIMPLEMENTED(); }
diff --git a/chrome/browser/chromeos/login/ui/login_display_mojo.h b/chrome/browser/chromeos/login/ui/login_display_mojo.h index 112b73e6..6d728a2f 100644 --- a/chrome/browser/chromeos/login/ui/login_display_mojo.h +++ b/chrome/browser/chromeos/login/ui/login_display_mojo.h
@@ -50,7 +50,6 @@ bool IsSigninInProgress() const override; void OnSigninScreenReady() override; void ShowEnterpriseEnrollmentScreen() override; - void ShowKioskEnableScreen() override; void ShowKioskAutolaunchScreen() override; void ShowWrongHWIDScreen() override; void CancelUserAdding() override;
diff --git a/chrome/browser/chromeos/login/ui/login_display_webui.cc b/chrome/browser/chromeos/login/ui/login_display_webui.cc index f3912bb5..a94dcae 100644 --- a/chrome/browser/chromeos/login/ui/login_display_webui.cc +++ b/chrome/browser/chromeos/login/ui/login_display_webui.cc
@@ -201,11 +201,6 @@ delegate_->OnStartEnterpriseEnrollment(); } -void LoginDisplayWebUI::ShowKioskEnableScreen() { - if (delegate_) - delegate_->OnStartKioskEnableScreen(); -} - void LoginDisplayWebUI::ShowKioskAutolaunchScreen() { if (delegate_) delegate_->OnStartKioskAutolaunchScreen();
diff --git a/chrome/browser/chromeos/login/ui/login_display_webui.h b/chrome/browser/chromeos/login/ui/login_display_webui.h index 9d55f16..9223690 100644 --- a/chrome/browser/chromeos/login/ui/login_display_webui.h +++ b/chrome/browser/chromeos/login/ui/login_display_webui.h
@@ -51,7 +51,6 @@ void OnSigninScreenReady() override; void CancelUserAdding() override; void ShowEnterpriseEnrollmentScreen() override; - void ShowKioskEnableScreen() override; void ShowKioskAutolaunchScreen() override; void ShowWrongHWIDScreen() override; void SetWebUIHandler(LoginDisplayWebUIHandler* webui_handler) override;
diff --git a/chrome/browser/chromeos/login/ui/mock_login_display_host.h b/chrome/browser/chromeos/login/ui/mock_login_display_host.h index 804a0f9..89c504f 100644 --- a/chrome/browser/chromeos/login/ui/mock_login_display_host.h +++ b/chrome/browser/chromeos/login/ui/mock_login_display_host.h
@@ -58,8 +58,10 @@ MOCK_METHOD(void, PrewarmAuthentication, (), (override)); MOCK_METHOD(void, StartDemoAppLaunch, (), (override)); MOCK_METHOD(void, StartKiosk, (const KioskAppId&, bool), (override)); + MOCK_METHOD(void, AttemptShowEnableConsumerKioskScreen, (), (override)); MOCK_METHOD(void, ShowGaiaDialog, (const AccountId&), (override)); MOCK_METHOD(void, HideOobeDialog, (), (override)); + MOCK_METHOD(void, SetShelfButtonsEnabled, (bool), (override)); MOCK_METHOD(void, UpdateOobeDialogState, (ash::OobeDialogState state),
diff --git a/chrome/browser/chromeos/login/wizard_controller.cc b/chrome/browser/chromeos/login/wizard_controller.cc index 9510dc5d..6765c06 100644 --- a/chrome/browser/chromeos/login/wizard_controller.cc +++ b/chrome/browser/chromeos/login/wizard_controller.cc
@@ -924,7 +924,7 @@ AdvanceToScreen(GaiaView::kScreenId); break; case UserCreationScreen::Result::ENTERPRISE_ENROLL: - AdvanceToScreen(EnrollmentScreenView::kScreenId); + ShowEnrollmentScreenIfEligible(); break; case UserCreationScreen::Result::CANCEL: LoginDisplayHost::default_host()->HideOobeDialog(); @@ -941,6 +941,12 @@ case GaiaScreen::Result::CLOSE_DIALOG: LoginDisplayHost::default_host()->HideOobeDialog(); break; + case GaiaScreen::Result::ENTERPRISE_ENROLL: + ShowEnrollmentScreenIfEligible(); + break; + case GaiaScreen::Result::START_CONSUMER_KIOSK: + LoginDisplayHost::default_host()->AttemptShowEnableConsumerKioskScreen(); + break; } } @@ -2152,6 +2158,16 @@ SetCurrentScreen(screen); } +void WizardController::ShowEnrollmentScreenIfEligible() { + policy::BrowserPolicyConnectorChromeOS* connector = + g_browser_process->platform_part()->browser_policy_connector_chromeos(); + const bool enterprise_managed = connector->IsEnterpriseManaged(); + const bool has_users = !user_manager::UserManager::Get()->GetUsers().empty(); + if (!has_users && !enterprise_managed) { + AdvanceToScreen(EnrollmentScreenView::kScreenId); + } +} + void WizardController::NotifyScreenChanged() { for (ScreenObserver& obs : screen_observers_) obs.OnCurrentScreenChanged(current_screen_);
diff --git a/chrome/browser/chromeos/login/wizard_controller.h b/chrome/browser/chromeos/login/wizard_controller.h index 389ede6..bd8381f 100644 --- a/chrome/browser/chromeos/login/wizard_controller.h +++ b/chrome/browser/chromeos/login/wizard_controller.h
@@ -404,6 +404,7 @@ // Gaia credentials. If it is false, the screen may return after trying // attestation-based enrollment if appropriate. void StartEnrollmentScreen(bool force_interactive); + void ShowEnrollmentScreenIfEligible(); void NotifyScreenChanged();
diff --git a/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.cc b/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.cc index bc5d523..e83ad7e 100644 --- a/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.cc +++ b/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.cc
@@ -24,21 +24,28 @@ } DlpRulesManager::Level IsDstRestricted(const GURL& src, const GURL& dst) { - return DlpRulesManager::Get()->IsRestrictedDestination( - src, dst, DlpRulesManager::Restriction::kClipboard); + // Safe to not check for nullptr as DataTransferDlpController is owned by + // DlpRulesManager. + return DlpRulesManagerFactory::GetForPrimaryProfile() + ->IsRestrictedDestination(src, dst, + DlpRulesManager::Restriction::kClipboard); } DlpRulesManager::Level IsGuestOsRestricted(const GURL& src) { - return DlpRulesManager::Get()->IsRestrictedAnyOfComponents( - src, - std::vector<DlpRulesManager::Component>{ - DlpRulesManager::Component::kPluginVm, - DlpRulesManager::Component::kCrostini}, - DlpRulesManager::Restriction::kClipboard); + // Safe to not check for nullptr as DataTransferDlpController is owned by + // DlpRulesManager. + return DlpRulesManagerFactory::GetForPrimaryProfile() + ->IsRestrictedAnyOfComponents(src, + std::vector<DlpRulesManager::Component>{ + DlpRulesManager::Component::kPluginVm, + DlpRulesManager::Component::kCrostini}, + DlpRulesManager::Restriction::kClipboard); } DlpRulesManager::Level IsArcRestricted(const GURL& src) { - return DlpRulesManager::Get()->IsRestrictedComponent( + // Safe to not check for nullptr as DataTransferDlpController is owned by + // DlpRulesManager. + return DlpRulesManagerFactory::GetForPrimaryProfile()->IsRestrictedComponent( src, DlpRulesManager::Component::kArc, DlpRulesManager::Restriction::kClipboard); }
diff --git a/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_browsertest.cc b/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_browsertest.cc index bef0996..032450f 100644 --- a/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_browsertest.cc +++ b/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_browsertest.cc
@@ -4,14 +4,15 @@ #include <memory> +#include "base/json/json_writer.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.h" #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h" #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager_test_utils.h" -#include "chrome/browser/policy/policy_test_utils.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "components/policy/core/common/policy_map.h" +#include "chrome/browser/chromeos/policy/login_policy_test_base.h" +#include "chrome/browser/chromeos/policy/user_policy_test_helper.h" +#include "chrome/browser/profiles/profile_manager.h" #include "components/policy/policy_constants.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" @@ -29,17 +30,25 @@ } // namespace -class DataTransferDlpBrowserTest : public PolicyTest { +class DataTransferDlpBrowserTest : public LoginPolicyTestBase { public: DataTransferDlpBrowserTest() = default; + + void SetDlpRulesPolicy(const base::Value& rules) { + std::string json; + base::JSONWriter::Write(rules, &json); + + base::DictionaryValue policy; + policy.SetKey(key::kDataLeakPreventionRulesList, base::Value(json)); + user_policy_helper()->SetPolicyAndWait( + policy, /*recommended=*/base::DictionaryValue(), + ProfileManager::GetActiveUserProfile()); + } }; IN_PROC_BROWSER_TEST_F(DataTransferDlpBrowserTest, EmptyPolicy) { - PolicyMap policies; - policies.Set(key::kDataLeakPreventionRulesList, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, /*value=*/base::nullopt, - nullptr); - UpdateProviderPolicy(policies); + SkipToLoginScreen(); + LogIn(kAccountId, kAccountPassword, kEmptyServices); { ui::ScopedClipboardWriter writer(ui::ClipboardBuffer::kCopyPaste); @@ -54,6 +63,9 @@ } IN_PROC_BROWSER_TEST_F(DataTransferDlpBrowserTest, RestrictedUrl) { + SkipToLoginScreen(); + LogIn(kAccountId, kAccountPassword, kEmptyServices); + const std::string kUrl1 = "https://mail.google.com"; const std::string kUrl2 = "https://docs.google.com"; const std::string kUrl3 = "https://example.com"; @@ -85,11 +97,7 @@ /*dst_components=*/base::Value(base::Value::Type::LIST), std::move(restrictions2))); - PolicyMap policies; - policies.Set(key::kDataLeakPreventionRulesList, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, std::move(rules), - nullptr); - UpdateProviderPolicy(policies); + SetDlpRulesPolicy(rules); { ui::ScopedClipboardWriter writer(ui::ClipboardBuffer::kCopyPaste, @@ -129,6 +137,9 @@ } IN_PROC_BROWSER_TEST_F(DataTransferDlpBrowserTest, RestrictedComponent) { + SkipToLoginScreen(); + LogIn(kAccountId, kAccountPassword, kEmptyServices); + const std::string kUrl1 = "https://mail.google.com"; base::Value rules(base::Value::Type::LIST); @@ -146,11 +157,7 @@ /*dst_urls=*/base::Value(base::Value::Type::LIST), std::move(dst_components), std::move(restrictions))); - PolicyMap policies; - policies.Set(key::kDataLeakPreventionRulesList, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, std::move(rules), - nullptr); - UpdateProviderPolicy(policies); + SetDlpRulesPolicy(rules); { ui::ScopedClipboardWriter writer(ui::ClipboardBuffer::kCopyPaste,
diff --git a/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_unittest.cc b/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_unittest.cc index 0a27b0b..082c7ec 100644 --- a/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_unittest.cc +++ b/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller_unittest.cc
@@ -5,6 +5,8 @@ #include "chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.h" #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h" +#include "chrome/test/base/scoped_testing_local_state.h" +#include "chrome/test/base/testing_browser_process.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -20,7 +22,8 @@ class MockDlpRulesManager : public DlpRulesManager { public: - MockDlpRulesManager() = default; + explicit MockDlpRulesManager(PrefService* local_state) + : DlpRulesManager(local_state) {} ~MockDlpRulesManager() override = default; MOCK_CONST_METHOD3(IsRestrictedDestination, @@ -50,12 +53,17 @@ class DataTransferDlpControllerTest : public testing::Test { protected: - DataTransferDlpControllerTest() = default; + DataTransferDlpControllerTest() + : scoped_testing_local_state_(TestingBrowserProcess::GetGlobal()), + rules_manager_(scoped_testing_local_state_.Get()) { + DlpRulesManagerFactory::OverrideManagerForTesting(&rules_manager_); + } ~DataTransferDlpControllerTest() override = default; - ::testing::StrictMock<MockDlpController> dlp_controller_; + ScopedTestingLocalState scoped_testing_local_state_; ::testing::StrictMock<MockDlpRulesManager> rules_manager_; + ::testing::StrictMock<MockDlpController> dlp_controller_; }; TEST_F(DataTransferDlpControllerTest, NullSrc) {
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc b/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc index 539d22f..49cc5d2 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_manager.cc
@@ -224,9 +224,10 @@ DlpContentRestrictionSet DlpContentManager::GetRestrictionSetForURL( const GURL& url) const { DlpContentRestrictionSet set; - if (!DlpRulesManager::IsInitialized()) + DlpRulesManager* dlp_rules_manager = + DlpRulesManagerFactory::GetForPrimaryProfile(); + if (!dlp_rules_manager) return set; - DlpRulesManager* dlp_rules_manager = DlpRulesManager::Get(); const size_t kRestrictionsCount = 5; static constexpr std::array<
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc b/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc index 7e936b31..c4420d8 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc
@@ -5,12 +5,16 @@ #include "chrome/browser/chromeos/policy/dlp/dlp_content_manager.h" #include "ash/public/cpp/ash_features.h" +#include "base/json/json_writer.h" #include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h" #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager_test_utils.h" +#include "chrome/browser/chromeos/policy/login_policy_test_base.h" +#include "chrome/browser/chromeos/policy/user_policy_test_helper.h" #include "chrome/browser/notifications/notification_display_service_tester.h" #include "chrome/browser/policy/policy_test_utils.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/chrome_capture_mode_delegate.h" #include "chrome/browser/ui/ash/screenshot_area.h" #include "chrome/browser/ui/browser.h" @@ -44,6 +48,12 @@ "screen_capture_dlp_paused"; constexpr char kScreenCaptureResumedNotificationId[] = "screen_capture_dlp_resumed"; + +constexpr char kAllowedUrl[] = "https://example.com"; +constexpr char kUrl1[] = "https://example1.com"; +constexpr char kUrl2[] = "https://example2.com"; +constexpr char kUrl3[] = "https://example3.com"; +constexpr char kUrl4[] = "https://example4.com"; } // namespace class DlpContentManagerBrowserTest : public InProcessBrowserTest { @@ -283,18 +293,26 @@ kScreenCaptureResumedNotificationId)); } -class DlpContentManagerPolicyBrowserTest : public PolicyTest { +class DlpContentManagerPolicyBrowserTest : public LoginPolicyTestBase { public: DlpContentManagerPolicyBrowserTest() = default; + + void SetDlpRulesPolicy(const base::Value& rules) { + std::string json; + base::JSONWriter::Write(rules, &json); + + base::DictionaryValue policy; + policy.SetKey(key::kDataLeakPreventionRulesList, base::Value(json)); + user_policy_helper()->SetPolicyAndWait( + policy, /*recommended=*/base::DictionaryValue(), + ProfileManager::GetActiveUserProfile()); + } }; IN_PROC_BROWSER_TEST_F(DlpContentManagerPolicyBrowserTest, GetRestrictionSetForURL) { - const std::string kAllowedUrl = "https://example.com"; - const std::string kUrl1 = "https://example1.com"; - const std::string kUrl2 = "https://example2.com"; - const std::string kUrl3 = "https://example3.com"; - const std::string kUrl4 = "https://example4.com"; + SkipToLoginScreen(); + LogIn(kAccountId, kAccountPassword, kEmptyServices); base::Value rules(base::Value::Type::LIST); @@ -342,11 +360,7 @@ /*dst_components=*/base::Value(base::Value::Type::LIST), std::move(restrictions4))); - PolicyMap policies; - policies.Set(key::kDataLeakPreventionRulesList, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, std::move(rules), - nullptr); - UpdateProviderPolicy(policies); + SetDlpRulesPolicy(rules); DlpContentRestrictionSet screenshot_and_videocapture(kScreenshotRestricted); screenshot_and_videocapture.SetRestriction(
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.cc b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.cc index 7984c64..bb3e1a5 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.cc
@@ -16,11 +16,17 @@ #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/policy/profile_policy_connector.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_features.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/policy/core/browser/url_util.h" #include "components/policy/core/common/policy_pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" +#include "components/user_manager/user_manager.h" #include "url/gurl.h" #include "url/origin.h" @@ -138,36 +144,12 @@ return rule_ids; } -// A singleton instance of DlpRulesManager. Set from DlpRulesManager::Init(). -static DlpRulesManager* g_dlp_rules_manager = nullptr; +// A singleton instance of DlpRulesManager for testing. +static DlpRulesManager* g_dlp_rules_manager_for_testing = nullptr; } // namespace // static -void DlpRulesManager::Init() { - if (!IsInitialized()) - new DlpRulesManager(); -} - -// static -bool DlpRulesManager::IsInitialized() { - return g_dlp_rules_manager != nullptr; -} - -// static -DlpRulesManager* DlpRulesManager::Get() { - DCHECK(g_dlp_rules_manager); - return g_dlp_rules_manager; -} - -// static -void DlpRulesManager::DeleteInstanceForTesting() { - DCHECK(g_dlp_rules_manager); - delete g_dlp_rules_manager; - g_dlp_rules_manager = nullptr; -} - -// static void DlpRulesManager::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterListPref(policy_prefs::kDlpRulesList); } @@ -242,13 +224,7 @@ return min_level; } -DlpRulesManager::DlpRulesManager() { - g_dlp_rules_manager = this; - - auto* local_state = g_browser_process->local_state(); - if (!local_state) // Sometimes it's not available in tests. - return; - +DlpRulesManager::DlpRulesManager(PrefService* local_state) { pref_change_registrar_.Init(local_state); pref_change_registrar_.Add( policy_prefs::kDlpRulesList, @@ -383,4 +359,56 @@ return GetMaxJoinRestrictionLevel(restriction, intersection); } +// static +DlpRulesManagerFactory* DlpRulesManagerFactory::GetInstance() { + static base::NoDestructor<DlpRulesManagerFactory> factory; + return factory.get(); +} + +// static +DlpRulesManager* DlpRulesManagerFactory::GetForPrimaryProfile() { + if (g_dlp_rules_manager_for_testing) + return g_dlp_rules_manager_for_testing; + + Profile* profile = ProfileManager::GetPrimaryUserProfile(); + if (!profile) + return nullptr; + return static_cast<DlpRulesManager*>( + DlpRulesManagerFactory::GetInstance()->GetServiceForBrowserContext( + profile, /*create=*/false)); +} + +// static +void DlpRulesManagerFactory::OverrideManagerForTesting( + DlpRulesManager* manager) { + g_dlp_rules_manager_for_testing = manager; +} + +DlpRulesManagerFactory::DlpRulesManagerFactory() + : BrowserContextKeyedServiceFactory( + "DlpRulesManager", + BrowserContextDependencyManager::GetInstance()) {} + +bool DlpRulesManagerFactory::ServiceIsCreatedWithBrowserContext() const { + return true; +} + +KeyedService* DlpRulesManagerFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + Profile* profile = Profile::FromBrowserContext(context); + // UserManager might be not available in tests. + if (!user_manager::UserManager::IsInitialized() || !profile || + !chromeos::ProfileHelper::IsPrimaryProfile(profile) || + !profile->GetProfilePolicyConnector()->IsManaged()) { + return nullptr; + } + + PrefService* local_state = g_browser_process->local_state(); + // Might be not available in tests. + if (!local_state) + return nullptr; + + return new DlpRulesManager(local_state); +} + } // namespace policy
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h index da3a66504..efdabd5 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h
@@ -9,6 +9,9 @@ #include <memory> #include <set> +#include "base/no_destructor.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_change_registrar.h" #include "components/url_matcher/url_matcher.h" @@ -38,7 +41,7 @@ // DlpRulesManager parses the rules set by DataLeakPreventionRulesList policy // and serves as an available service which can be queried anytime about the // restrictions set by the policy. -class DlpRulesManager { +class DlpRulesManager : public KeyedService { public: // A restriction that can be set by DataLeakPreventionRulesList policy. enum class Restriction { @@ -78,18 +81,7 @@ using RuleId = int; using UrlConditionId = url_matcher::URLMatcherConditionSet::ID; - // Creates a singleton instance of the class. - static void Init(); - - // Returns whether DlpRulesManager was already created after user policy stack - // is initialized. - static bool IsInitialized(); - - // Returns a pointer to the existing instance of the class. - static DlpRulesManager* Get(); - - // Deletes an instance of the class. Is needed for testing purposes. - static void DeleteInstanceForTesting(); + ~DlpRulesManager() override; // Registers the policy pref. static void RegisterPrefs(PrefRegistrySimple* registry); @@ -126,8 +118,10 @@ Restriction restriction) const; protected: - DlpRulesManager(); - virtual ~DlpRulesManager(); + friend class DlpRulesManagerFactory; + friend class DlpRulesManagerTest; + + explicit DlpRulesManager(PrefService* local_state); private: void OnPolicyUpdate(); @@ -169,6 +163,30 @@ std::map<UrlConditionId, RuleId> dst_url_rules_mapping_; }; +// Initializes an instance of DlpRulesManager when a primary managed profile is +// being created, e.g. when managed user sign in. +class DlpRulesManagerFactory : public BrowserContextKeyedServiceFactory { + public: + static DlpRulesManagerFactory* GetInstance(); + // Returns nullptr if there is no primary profile, e.g. the session is not + // started. + static DlpRulesManager* GetForPrimaryProfile(); + + // TODO(crbug/1153146): Use TestingFactory instead. + static void OverrideManagerForTesting(DlpRulesManager* testing_manager); + + private: + friend class base::NoDestructor<DlpRulesManagerFactory>; + + DlpRulesManagerFactory(); + ~DlpRulesManagerFactory() override = default; + + // BrowserStateKeyedServiceFactory overrides: + bool ServiceIsCreatedWithBrowserContext() const override; + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; +}; + } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_DLP_DLP_RULES_MANAGER_H_
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_browsertest.cc b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_browsertest.cc index 94e4dae..d2101b4a 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_browsertest.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_browsertest.cc
@@ -2,10 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/json/json_writer.h" #include "base/values.h" #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h" #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager_test_utils.h" -#include "chrome/browser/policy/policy_test_utils.h" +#include "chrome/browser/chromeos/policy/login_policy_test_base.h" +#include "chrome/browser/chromeos/policy/user_policy_test_helper.h" +#include "chrome/browser/profiles/profile_manager.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/policy_constants.h" #include "content/public/test/browser_test.h" @@ -16,12 +19,26 @@ constexpr char kUrlStr1[] = "https://wwww.example.com"; } -class DlpRulesPolicyTest : public PolicyTest { +class DlpRulesPolicyTest : public LoginPolicyTestBase { public: DlpRulesPolicyTest() = default; + + void SetDlpRulesPolicy(const base::Value& rules) { + std::string json; + base::JSONWriter::Write(rules, &json); + + base::DictionaryValue policy; + policy.SetKey(key::kDataLeakPreventionRulesList, base::Value(json)); + user_policy_helper()->SetPolicyAndWait( + policy, /*recommended=*/base::DictionaryValue(), + ProfileManager::GetActiveUserProfile()); + } }; IN_PROC_BROWSER_TEST_F(DlpRulesPolicyTest, ParsePolicyPref) { + SkipToLoginScreen(); + LogIn(kAccountId, kAccountPassword, kEmptyServices); + base::Value rules(base::Value::Type::LIST); base::Value src_urls(base::Value::Type::LIST); @@ -37,14 +54,10 @@ /*dst_components=*/base::Value(base::Value::Type::LIST), std::move(restrictions))); - PolicyMap policies; - policies.Set(key::kDataLeakPreventionRulesList, POLICY_LEVEL_MANDATORY, - POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, std::move(rules), - nullptr); - UpdateProviderPolicy(policies); + SetDlpRulesPolicy(rules); EXPECT_EQ(DlpRulesManager::Level::kBlock, - DlpRulesManager::Get()->IsRestricted( + DlpRulesManagerFactory::GetForPrimaryProfile()->IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kScreenshot)); }
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_unittest.cc b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_unittest.cc index 3e6827c..93f9d31 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_unittest.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_rules_manager_unittest.cc
@@ -60,16 +60,8 @@ class DlpRulesManagerTest : public testing::Test { protected: DlpRulesManagerTest() - : testing_local_state_(TestingBrowserProcess::GetGlobal()) {} - - void SetUp() override { - testing::Test::SetUp(); - - DlpRulesManager::Init(); - dlp_rules_manager_ = DlpRulesManager::Get(); - } - - void TearDown() override { DlpRulesManager::DeleteInstanceForTesting(); } + : testing_local_state_(TestingBrowserProcess::GetGlobal()), + dlp_rules_manager_(testing_local_state_.Get()) {} void UpdatePolicyPref(base::Value rules_list) { DCHECK(rules_list.is_list()); @@ -77,20 +69,18 @@ std::move(rules_list)); } - DlpRulesManager* dlp_rules_manager_; - - private: ScopedTestingLocalState testing_local_state_; + DlpRulesManager dlp_rules_manager_; }; TEST_F(DlpRulesManagerTest, EmptyPref) { UpdatePolicyPref(base::Value(base::Value::Type::LIST)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kPrinting)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr2), DlpRulesManager::Restriction::kClipboard)); } @@ -135,34 +125,34 @@ UpdatePolicyPref(std::move(rules)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr2), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr4), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kScreenshot)); // Clear pref UpdatePolicyPref(base::Value(base::Value::Type::LIST)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr2), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr4), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kScreenshot)); } @@ -185,7 +175,7 @@ UpdatePolicyPref(std::move(rules_1)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kScreenshot)); // Second DLP rule @@ -206,10 +196,10 @@ UpdatePolicyPref(std::move(rules_2)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kScreenshot)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr2), DlpRulesManager::Restriction::kScreenshot)); } @@ -233,11 +223,11 @@ UpdatePolicyPref(std::move(rules)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedComponent( + dlp_rules_manager_.IsRestrictedComponent( GURL(kUrlStr1), DlpRulesManager::Component::kArc, DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedComponent( + dlp_rules_manager_.IsRestrictedComponent( GURL(kUrlStr1), DlpRulesManager::Component::kCrostini, DlpRulesManager::Restriction::kClipboard)); } @@ -248,7 +238,7 @@ UpdatePolicyPref(std::move(rules)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr1), DlpRulesManager::Restriction::kClipboard)); } @@ -276,11 +266,11 @@ EXPECT_EQ( DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ( DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr4), GURL(), DlpRulesManager::Restriction::kClipboard)); } @@ -306,14 +296,14 @@ UpdatePolicyPref(std::move(rules)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedAnyOfComponents( + dlp_rules_manager_.IsRestrictedAnyOfComponents( GURL(kUrlStr1), std::vector<DlpRulesManager::Component>{ DlpRulesManager::Component::kPluginVm, DlpRulesManager::Component::kCrostini}, DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedAnyOfComponents( + dlp_rules_manager_.IsRestrictedAnyOfComponents( GURL(kUrlStr1), std::vector<DlpRulesManager::Component>{ DlpRulesManager::Component::kArc, @@ -361,40 +351,40 @@ UpdatePolicyPref(std::move(rules)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern1})), GURL(base::StrCat({kHttpsPrefix, kUrlPattern2})), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern3})), GURL(base::StrCat({kHttpsPrefix, kUrlPattern4})), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern5})), GURL(base::StrCat({kHttpsPrefix, kUrlPattern2})), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern2})), GURL(base::StrCat({kHttpsPrefix, kUrlPattern3})), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern1})), GURL(kUrlStr2), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern2})), GURL(kUrlStr1), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern3})), GURL(kUrlStr2), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(base::StrCat({kHttpsPrefix, kUrlPattern4})), GURL(kUrlStr1), DlpRulesManager::Restriction::kClipboard)); } @@ -405,11 +395,11 @@ UpdatePolicyPref(std::move(rules)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr3), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kBlock, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kScreenshot)); // Disable feature @@ -419,11 +409,11 @@ UpdatePolicyPref(std::move(rules)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestrictedDestination( + dlp_rules_manager_.IsRestrictedDestination( GURL(kUrlStr1), GURL(kUrlStr3), DlpRulesManager::Restriction::kClipboard)); EXPECT_EQ(DlpRulesManager::Level::kAllow, - dlp_rules_manager_->IsRestricted( + dlp_rules_manager_.IsRestricted( GURL(kUrlStr1), DlpRulesManager::Restriction::kScreenshot)); }
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc index bd8137c..6934a88 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc
@@ -25,7 +25,6 @@ #include "chrome/browser/chromeos/login/users/chrome_user_manager_impl.h" #include "chrome/browser/chromeos/policy/arc_app_install_event_log_uploader.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" -#include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager.h" #include "chrome/browser/chromeos/policy/extension_install_event_log_uploader.h" #include "chrome/browser/chromeos/policy/policy_oauth2_token_fetcher.h" #include "chrome/browser/chromeos/policy/remote_commands/user_commands_factory_chromeos.h" @@ -271,10 +270,6 @@ std::make_unique<ArcAppInstallEventLogUploader>(client(), profile_); extension_install_event_log_uploader_ = std::make_unique<ExtensionInstallEventLogUploader>(profile_); - - // Initializes an instance of DlpRulesManager to be responsible for the rules - // of the data leak prevention policy. - policy::DlpRulesManager::Init(); } void UserCloudPolicyManagerChromeOS::OnAccessTokenAvailable(
diff --git a/chrome/browser/dev_ui_browser_resources.grd b/chrome/browser/dev_ui_browser_resources.grd index e7c2e52b..85397ea 100644 --- a/chrome/browser/dev_ui_browser_resources.grd +++ b/chrome/browser/dev_ui_browser_resources.grd
@@ -58,11 +58,11 @@ <include name="IDR_UI_GEOMETRY_MOJOM_LITE_JS" file="${root_gen_dir}\ui\gfx\geometry\mojom\geometry.mojom-lite.js" use_base_dir="false" type="BINDATA" /> <if expr="is_android or is_linux"> - <include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> + <include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" preprocess="true" type="BINDATA" /> <include name="IDR_SANDBOX_INTERNALS_JS" file="resources\sandbox_internals\sandbox_internals.js" type="BINDATA" /> </if> <if expr="is_win"> - <include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" preprocess="true" allowexternalscript="true" type="BINDATA" /> + <include name="IDR_SANDBOX_INTERNALS_HTML" file="resources\sandbox_internals\sandbox_internals.html" preprocess="true" type="BINDATA" /> <include name="IDR_SANDBOX_INTERNALS_JS" file="resources\sandbox_internals\sandbox_internals_win.js" type="BINDATA" /> </if>
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index fbdcee04..a290c998 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -3293,6 +3293,11 @@ "expiry_milestone": 90 }, { + "name": "mobile-identity-consistency-var", + "owners": [ "bsazonov", "aliceywang", "msarda", "triploblastic" ], + "expiry_milestone": 92 + }, + { "name": "modern-tab-strip", "owners": [ "nazerke", "bling-flags@google.com" ], "expiry_milestone": 92 @@ -3997,6 +4002,13 @@ "expiry_milestone": -1 }, { + "name": "record-web-app-debug-info", + "owners": [ "desktop-pwas-team@google.com" ], + // This flag is used for in-the-field debugging of preinstalled web apps on + // Chrome OS. + "expiry_milestone": -1 + }, + { "name": "recover-from-never-save-android", "owners": [ "ioanap" ], "expiry_milestone": 88 @@ -4163,6 +4175,15 @@ "expiry_milestone": 90 }, { + "name": "safety-check-weak-passwords", + "owners": [ + "rainhard", + "msramek", + "chrome-friendly-settings@google.com" + ], + "expiry_milestone": 93 + }, + { "name": "safety-tips", "owners": [ "jdeblasio", "estark", "meacer" ], "expiry_milestone": 89
diff --git a/chrome/browser/flag-never-expire-list.json b/chrome/browser/flag-never-expire-list.json index 951532a..45ce580 100644 --- a/chrome/browser/flag-never-expire-list.json +++ b/chrome/browser/flag-never-expire-list.json
@@ -81,6 +81,7 @@ "memlog-stack-mode", "overlay-strategies", "reader-mode-heuristics", + "record-web-app-debug-info", "release-notes-notification-all-channels", "set-market-url-for-testing", "show-autofill-type-predictions",
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 7f7ea4c..63a0c51 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1412,6 +1412,12 @@ const char kMobileIdentityConsistencyDescription[] = "Enables stronger identity consistency on mobile"; +const char kMobileIdentityConsistencyVarName[] = + "Mobile identity consistency variations"; +const char kMobileIdentityConsistencyVarDescription[] = + "Enables stronger identity consistency on mobile with different UI " + "variations"; + const char kMouseSubframeNoImplicitCaptureName[] = "Disable mouse implicit capture for iframe"; const char kMouseSubframeNoImplicitCaptureDescription[] = @@ -1886,6 +1892,11 @@ "A settings component for checking multiple areas of browser safety. " "Requires #password-check to also be enabled."; +const char kSafetyCheckWeakPasswordsName[] = "Safety check for weak passwords"; +const char kSafetyCheckWeakPasswordsDescription[] = + "If weak passwords were found, show them in safety check." + "Requires #passwords-weakness-check to also be enabled."; + const char kProminentDarkModeActiveTabTitleName[] = "Prominent Dark Mode Active Tab Titles"; const char kProminentDarkModeActiveTabTitleDescription[] = @@ -1935,6 +1946,11 @@ "Allow users to save tabs for later. Enables a new button and menu for " "accessing tabs saved for later."; +const char kRecordWebAppDebugInfoName[] = "Record web app debug info"; +const char kRecordWebAppDebugInfoDescription[] = + "Enables recording additional web app related debugging data to be " + "displayed in: chrome://internals/web-app"; + const char kRewriteLevelDBOnDeletionName[] = "Rewrite LevelDB instances after full deletions"; const char kRewriteLevelDBOnDeletionDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 494edb6..151f049c 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -838,6 +838,9 @@ extern const char kMobileIdentityConsistencyName[]; extern const char kMobileIdentityConsistencyDescription[]; +extern const char kMobileIdentityConsistencyVarName[]; +extern const char kMobileIdentityConsistencyVarDescription[]; + extern const char kMouseSubframeNoImplicitCaptureName[]; extern const char kMouseSubframeNoImplicitCaptureDescription[]; @@ -1105,6 +1108,9 @@ extern const char kSafetyCheckAndroidName[]; extern const char kSafetyCheckAndroidDescription[]; +extern const char kSafetyCheckWeakPasswordsName[]; +extern const char kSafetyCheckWeakPasswordsDescription[]; + extern const char kProminentDarkModeActiveTabTitleName[]; extern const char kProminentDarkModeActiveTabTitleDescription[]; @@ -1133,6 +1139,9 @@ extern const char kReadLaterName[]; extern const char kReadLaterDescription[]; +extern const char kRecordWebAppDebugInfoName[]; +extern const char kRecordWebAppDebugInfoDescription[]; + extern const char kRewriteLevelDBOnDeletionName[]; extern const char kRewriteLevelDBOnDeletionDescription[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index 4312e74..4fad004d 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -274,6 +274,7 @@ &safe_browsing::kSafeBrowsingSectionUIAndroid, &security_state::features::kMarkHttpAsFeature, &signin::kMobileIdentityConsistency, + &signin::kMobileIdentityConsistencyVar, &switches::kDecoupleSyncFromAndroidMasterSync, &switches::kSyncUseSessionsUnregisterDelay, &subresource_filter::kSafeBrowsingSubresourceFilter,
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java index 9d9dde8..0e5cff3 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java
@@ -332,6 +332,7 @@ public static final String MESSAGES_FOR_ANDROID_INFRASTRUCTURE = "MessagesForAndroidInfrastructure"; public static final String MOBILE_IDENTITY_CONSISTENCY = "MobileIdentityConsistency"; + public static final String MOBILE_IDENTITY_CONSISTENCY_VAR = "MobileIdentityConsistencyVar"; public static final String MODAL_PERMISSION_DIALOG_VIEW = "ModalPermissionDialogView"; public static final String METRICS_SETTINGS_ANDROID = "MetricsSettingsAndroid"; public static final String NEW_PHOTO_PICKER = "NewPhotoPicker";
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.cc index bf8f0af..4facef41 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.cc
@@ -55,9 +55,12 @@ } identity_manager_ = IdentityManagerFactory::GetForProfile(profile); + identity_manager_->AddObserver(this); } -KaleidoscopeIdentityManagerImpl::~KaleidoscopeIdentityManagerImpl() = default; +KaleidoscopeIdentityManagerImpl::~KaleidoscopeIdentityManagerImpl() { + identity_manager_->RemoveObserver(this); +} void KaleidoscopeIdentityManagerImpl::GetCredentials( GetCredentialsCallback cb) { @@ -145,3 +148,20 @@ signin_metrics::AccessPoint::ACCESS_POINT_KALEIDOSCOPE); #endif // defined(OS_CHROMEOS) } + +void KaleidoscopeIdentityManagerImpl::AddObserver( + mojo::PendingRemote<media::mojom::KaleidoscopeIdentityObserver> observer) { + identity_observers_.Add(std::move(observer)); +} + +void KaleidoscopeIdentityManagerImpl::OnRefreshTokenUpdatedForAccount( + const CoreAccountInfo& account_info) { + for (auto& observer : identity_observers_) + observer->OnSignedIn(); +} + +void KaleidoscopeIdentityManagerImpl::OnRefreshTokenRemovedForAccount( + const CoreAccountId& account_id) { + for (auto& observer : identity_observers_) + observer->OnSignedOut(); +}
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.h b/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.h index 599ce72..ec6c146 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.h +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_identity_manager_impl.h
@@ -8,9 +8,11 @@ #include <memory> #include "chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom.h" +#include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/google_service_auth_error.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote_set.h" namespace content { class WebUI; @@ -25,7 +27,8 @@ class Profile; class KaleidoscopeIdentityManagerImpl - : public media::mojom::KaleidoscopeIdentityManager { + : public media::mojom::KaleidoscopeIdentityManager, + public signin::IdentityManager::Observer { public: KaleidoscopeIdentityManagerImpl( mojo::PendingReceiver<media::mojom::KaleidoscopeIdentityManager> receiver, @@ -43,6 +46,15 @@ // media::mojom::KaleidoscopeIdentityManager implementation. void GetCredentials(GetCredentialsCallback cb) override; void SignIn() override; + void AddObserver( + mojo::PendingRemote<media::mojom::KaleidoscopeIdentityObserver> observer) + override; + + // signin::IdentityManager::Observer implementation. + void OnRefreshTokenUpdatedForAccount( + const CoreAccountInfo& account_info) override; + void OnRefreshTokenRemovedForAccount( + const CoreAccountId& account_id) override; private: // Called when an access token request completes (successfully or not). @@ -64,6 +76,9 @@ content::WebUI* web_ui_ = nullptr; Profile* profile_ = nullptr; + mojo::RemoteSet<media::mojom::KaleidoscopeIdentityObserver> + identity_observers_; + mojo::Receiver<media::mojom::KaleidoscopeIdentityManager> receiver_; };
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.cc index 1a33c4e..04da637d 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.cc
@@ -17,6 +17,8 @@ return KaleidoscopeMetricsRecorder::FirstRunProgress::kProviderSelection; case media::mojom::KaleidoscopeFirstRunExperienceStep::kMediaFeedsConsent: return KaleidoscopeMetricsRecorder::FirstRunProgress::kMediaFeedsConsent; + case media::mojom::KaleidoscopeFirstRunExperienceStep::kWelcome: + return KaleidoscopeMetricsRecorder::FirstRunProgress::kWelcome; } NOTREACHED(); }
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.h b/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.h index e2bf9393..d203df3d 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.h +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder.h
@@ -18,7 +18,8 @@ kCompleted = 0, kProviderSelection = 1, kMediaFeedsConsent = 2, - kMaxValue = kMediaFeedsConsent, + kWelcome = 3, + kMaxValue = kWelcome, }; KaleidoscopeMetricsRecorder();
diff --git a/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder_unittest.cc b/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder_unittest.cc index d33439a..78d0afb 100644 --- a/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder_unittest.cc +++ b/chrome/browser/media/kaleidoscope/kaleidoscope_metrics_recorder_unittest.cc
@@ -50,6 +50,9 @@ media::mojom::KaleidoscopeFirstRunExperienceStep::kProviderSelection); ExpectFirstRunProgressTotalCount(0); recorder().OnFirstRunExperienceStepChanged( + media::mojom::KaleidoscopeFirstRunExperienceStep::kWelcome); + ExpectFirstRunProgressTotalCount(0); + recorder().OnFirstRunExperienceStepChanged( media::mojom::KaleidoscopeFirstRunExperienceStep::kMediaFeedsConsent); ExpectFirstRunProgressTotalCount(0); recorder().OnExitPage();
diff --git a/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom b/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom index eff73d5..318c4bf 100644 --- a/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom +++ b/chrome/browser/media/kaleidoscope/mojom/kaleidoscope.mojom
@@ -44,6 +44,7 @@ kCompleted, kProviderSelection, kMediaFeedsConsent, + kWelcome, }; // Provides data for the kaleidoscope page. @@ -119,7 +120,25 @@ GetCredentials() => (Credentials? credentials, CredentialsResult result); // Will trigger a browser signin. + // The caller has to use KaleidoscopeIdentityObserver in order to be notified + // if the user signs in. This method doesn't notify the caller directly given + // that the user may take no action. SignIn(); + + // Add an observer to be notified when the user signs in or out of Chrome. + AddObserver(pending_remote<KaleidoscopeIdentityObserver> observer); +}; + +// Interface to be implemented by clients of KaleidoscopeIdentityManager that +// want to be notified when a sign in or sign out occurs. This must be used in +// order to be notified if a call to SignIn() ultimately leads to the user +// signing in. +interface KaleidoscopeIdentityObserver { + // Called when the user signs in. + OnSignedIn(); + + // Called when the user signs out. + OnSignedOut(); }; enum GetCollectionsResult {
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc index 4247b8f3..032e49e 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc
@@ -272,6 +272,7 @@ nearby_process_observer_.Add(process_manager_); power_client_->AddObserver(this); + certificate_manager_->AddObserver(this); settings_.AddSettingsObserver(settings_receiver_.BindNewPipeAndPassRemote()); @@ -318,6 +319,7 @@ process_manager_->StopProcess(profile_); power_client_->RemoveObserver(this); + certificate_manager_->RemoveObserver(this); // TODO(crbug/1147652): The call to update the advertising interval is // removed to prevent a Bluez crash. We need to either reduce the global @@ -361,6 +363,7 @@ } process_shutdown_pending_timer_.Stop(); + rotate_background_advertisement_timer_.Stop(); // |profile_| has now been shut down so we shouldn't use it anymore. profile_ = nullptr; @@ -958,6 +961,22 @@ // TODO(vecore): handle visible contacts change } +void NearbySharingServiceImpl::OnPublicCertificatesDownloaded() { + // TODO(https://crbug.com/1152158): Possibly restart scanning after public + // certificates are downloaded. +} + +void NearbySharingServiceImpl::OnPrivateCertificatesChanged() { + // If we are currently advertising, restart advertising using the updated + // private certificates. + if (rotate_background_advertisement_timer_.IsRunning()) { + NS_LOG(VERBOSE) + << __func__ + << ": Private certificates changed; rotating background advertisement."; + rotate_background_advertisement_timer_.FireNow(); + } +} + void NearbySharingServiceImpl::OnEndpointDiscovered( const std::string& endpoint_id, const std::vector<uint8_t>& endpoint_info) { @@ -1054,6 +1073,10 @@ if (encrypted_metadata_key) { salt = encrypted_metadata_key->salt(); encrypted_key = encrypted_metadata_key->encrypted_key(); + } else { + NS_LOG(WARNING) << __func__ + << ": Failed to encrypt private certificate metadata key " + << "for advertisement."; } } @@ -1607,7 +1630,7 @@ nearby_connections_manager_->StartAdvertising( *endpoint_info, - /* listener= */ this, power_level, data_usage, + /*listener=*/this, power_level, data_usage, base::BindOnce(&NearbySharingServiceImpl::OnStartAdvertisingResult, weak_ptr_factory_.GetWeakPtr(), device_name.has_value())); @@ -1664,7 +1687,7 @@ ClearOutgoingShareTargetInfoMap(); nearby_connections_manager_->StartDiscovery( - /* listener= */ this, settings_.GetDataUsage(), + /*listener=*/this, settings_.GetDataUsage(), base::BindOnce([](NearbyConnectionsManager::ConnectionsStatus status) { NS_LOG(VERBOSE) << __func__ << ": Scanning start attempted over Nearby Connections "
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h index f185be44..77c20b7 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.h
@@ -57,6 +57,7 @@ class NearbySharingServiceImpl : public NearbySharingService, public nearby_share::mojom::NearbyShareSettingsObserver, + public NearbyShareCertificateManager::Observer, public NearbyProcessManager::Observer, public device::BluetoothAdapter::Observer, public NearbyConnectionsManager::IncomingConnectionListener, @@ -135,6 +136,10 @@ void OnAllowedContactsChanged( const std::vector<std::string>& allowed_contacts) override; + // NearbyShareCertificateManager::Observer: + void OnPublicCertificatesDownloaded() override; + void OnPrivateCertificatesChanged() override; + // NearbyConnectionsManager::DiscoveryListener: void OnEndpointDiscovered(const std::string& endpoint_id, const std::vector<uint8_t>& endpoint_info) override;
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc index 280d6d8..a7c657a 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl_unittest.cc
@@ -3569,8 +3569,7 @@ service_.reset(); } -TEST_F(NearbySharingServiceImplTest, - PeriodicallyRotateBackgroundAdvertisement) { +TEST_F(NearbySharingServiceImplTest, RotateBackgroundAdvertisement_Periodic) { certificate_manager()->set_next_salt({0x00, 0x01}); SetVisibility(nearby_share::mojom::Visibility::kAllContacts); NiceMock<MockTransferUpdateCallback> callback; @@ -3588,3 +3587,23 @@ fake_nearby_connections_manager_->advertising_endpoint_info(); EXPECT_NE(endpoint_info_initial, endpoint_info_rotated); } + +TEST_F(NearbySharingServiceImplTest, + RotateBackgroundAdvertisement_PrivateCertificatesChange) { + certificate_manager()->set_next_salt({0x00, 0x01}); + SetVisibility(nearby_share::mojom::Visibility::kAllContacts); + NiceMock<MockTransferUpdateCallback> callback; + NearbySharingService::StatusCodes result = service_->RegisterReceiveSurface( + &callback, NearbySharingService::ReceiveSurfaceState::kBackground); + EXPECT_EQ(result, NearbySharingService::StatusCodes::kOk); + EXPECT_TRUE(fake_nearby_connections_manager_->IsAdvertising()); + auto endpoint_info_initial = + fake_nearby_connections_manager_->advertising_endpoint_info(); + + certificate_manager()->set_next_salt({0x00, 0x02}); + certificate_manager()->NotifyPrivateCertificatesChanged(); + EXPECT_TRUE(fake_nearby_connections_manager_->IsAdvertising()); + auto endpoint_info_rotated = + fake_nearby_connections_manager_->advertising_endpoint_info(); + EXPECT_NE(endpoint_info_initial, endpoint_info_rotated); +}
diff --git a/chrome/browser/privacy_sandbox/OWNERS b/chrome/browser/privacy_sandbox/OWNERS new file mode 100644 index 0000000..6143a2f --- /dev/null +++ b/chrome/browser/privacy_sandbox/OWNERS
@@ -0,0 +1,7 @@ +andzaytsev@google.com +harrisonsean@chromium.org +msramek@chromium.org +sauski@google.com + +# COMPONENT: UI>Settings>Privacy +# TEAM: chrome-friendly-settings@google.com
diff --git a/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.cc b/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.cc index f4e7273..6837be8 100644 --- a/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.cc +++ b/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.cc
@@ -13,16 +13,23 @@ const char kPrivacySandboxApisEnabled[] = "privacy_sandbox.apis_enabled"; -const char kPrivacySandboxManauallyControlled[] = +const char kPrivacySandboxManuallyControlled[] = "privacy_sandbox.manually_controlled"; +const char kPrivacySandboxUiAvailable[] = "privacy_sandbox.ui_available"; + } // namespace prefs namespace privacy_sandbox { void RegisterProfilePrefs(PrefRegistrySimple* registry) { - registry->RegisterBooleanPref(prefs::kPrivacySandboxApisEnabled, false); - registry->RegisterBooleanPref(prefs::kPrivacySandboxManauallyControlled, - false); + registry->RegisterBooleanPref( + prefs::kPrivacySandboxApisEnabled, false, + user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); + registry->RegisterBooleanPref( + prefs::kPrivacySandboxManuallyControlled, false, + user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); + registry->RegisterBooleanPref(prefs::kPrivacySandboxUiAvailable, false); } + } // namespace privacy_sandbox
diff --git a/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.h b/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.h index 60cc44b8..fc60498 100644 --- a/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.h +++ b/chrome/browser/privacy_sandbox/privacy_sandbox_prefs.h
@@ -5,19 +5,23 @@ #ifndef CHROME_BROWSER_PRIVACY_SANDBOX_PRIVACY_SANDBOX_PREFS_H_ #define CHROME_BROWSER_PRIVACY_SANDBOX_PRIVACY_SANDBOX_PREFS_H_ -#include "components/prefs/pref_registry_simple.h" +class PrefRegistrySimple; namespace prefs { -// Boolean that is true when Privacy Sandbox APIs are enabled. If the +// Synced boolean that is true when Privacy Sandbox APIs are enabled. If the // PrivacySandboxSettings feature is enabled, this Boolean is controlled by the // associated UI; if it is disabled, it is controlled by third party cookie // blocking settings. extern const char kPrivacySandboxApisEnabled[]; -// Boolean that indicates if a user has manually toggled the settings associated -// with the PrivacySandboxSettings feature. -extern const char kPrivacySandboxManauallyControlled[]; +// Synced boolean that indicates if a user has manually toggled the settings +// associated with the PrivacySandboxSettings feature. +extern const char kPrivacySandboxManuallyControlled[]; + +// Boolean to indicate whether or not the UI for Privacy Sandbox settings has +// been made available on the device. +extern const char kPrivacySandboxUiAvailable[]; } // namespace prefs
diff --git a/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.html b/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.html index 8045de7..44f70af 100644 --- a/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.html +++ b/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.html
@@ -48,7 +48,7 @@ padding-bottom: 12px; } </style> - <cr-dialog id="helpDialog"> + <cr-dialog id="helpDialog" on-close="onClose_"> <!-- Title --> <div id="helpDialogTitle" slot="title"> <slot name="title">[[i18nDynamic(locale, titleKey)]]</slot>
diff --git a/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.js b/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.js index af17849..107c19c6 100644 --- a/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.js +++ b/chrome/browser/resources/chromeos/login/components/oobe_help_dialog.js
@@ -26,6 +26,7 @@ /* Shows the help dialog and changes the focus to the close button. */ showDialog: function() { + chrome.send('enableShelfButtons', [false]); this.$.helpDialog.showModal(); this.$.closeButton.focus(); }, @@ -34,4 +35,8 @@ this.$.helpDialog.close(); }, + onClose_() { + chrome.send('enableShelfButtons', [true]); + }, + });
diff --git a/chrome/browser/resources/chromeos/login/cr_ui.js b/chrome/browser/resources/chromeos/login/cr_ui.js index 15834e6..099fe2f 100644 --- a/chrome/browser/resources/chromeos/login/cr_ui.js +++ b/chrome/browser/resources/chromeos/login/cr_ui.js
@@ -267,6 +267,7 @@ chrome.send('completeLogin', [gaia_id, username, password, false]); } else { waitForOobeScreen('gaia-signin', function() { + // TODO(crbug.com/1100910): migrate logic to dedicated test api. chrome.send('toggleEnrollmentScreen'); chrome.send('toggleFakeEnrollment'); }); @@ -321,6 +322,7 @@ * Begin enterprise enrollment for telemetry. */ Oobe.switchToEnterpriseEnrollmentForTesting = function() { + // TODO(crbug.com/1100910): migrate logic to dedicated test api. chrome.send('toggleEnrollmentScreen'); };
diff --git a/chrome/browser/resources/chromeos/login/screen_gaia_signin.js b/chrome/browser/resources/chromeos/login/screen_gaia_signin.js index 000a653..72db0bee 100644 --- a/chrome/browser/resources/chromeos/login/screen_gaia_signin.js +++ b/chrome/browser/resources/chromeos/login/screen_gaia_signin.js
@@ -960,7 +960,7 @@ */ onMenuItemClicked_(e) { if (e.detail == 'ee') { - cr.ui.Oobe.handleAccelerator(ACCELERATOR_ENROLLMENT); + this.userActed('startEnrollment'); } },
diff --git a/chrome/browser/resources/component_extension_resources.grd b/chrome/browser/resources/component_extension_resources.grd index a30eb06e..916f7bca 100644 --- a/chrome/browser/resources/component_extension_resources.grd +++ b/chrome/browser/resources/component_extension_resources.grd
@@ -39,7 +39,7 @@ <include name="IDR_FEEDBACK_ASSISTANT_LOGS_INFO_JS" file="feedback/js/assistant_logs_info.js" type="BINDATA" /> <include name="IDR_FEEDBACK_FEEDBACK_UTIL_JS" file="feedback/js/feedback_util.js" type="BINDATA" /> <include name="IDR_FEEDBACK_EVENT_HANDLER_JS" file="feedback/js/event_handler.js" flattenhtml="true" type="BINDATA" /> - <include name="IDR_FEEDBACK_FEEDBACK_JS" file="feedback/js/feedback.js" flattenhtml="true" type="BINDATA" /> + <include name="IDR_FEEDBACK_FEEDBACK_JS" file="feedback/js/feedback.js" preprocess="true" type="BINDATA" /> <include name="IDR_FEEDBACK_SYSINFO_JS" file="feedback/js/sys_info.js" type="BINDATA" /> <include name="IDR_FEEDBACK_TAKE_SCREENSHOT_JS" file="feedback/js/take_screenshot.js" type="BINDATA" /> <include name="IDR_FEEDBACK_TOPBAR_HANDLER_JS" file="feedback/js/topbar_handlers.js" type="BINDATA" />
diff --git a/chrome/browser/resources/new_tab_page/realbox.js b/chrome/browser/resources/new_tab_page/realbox.js index 6df803b..013f657 100644 --- a/chrome/browser/resources/new_tab_page/realbox.js +++ b/chrome/browser/resources/new_tab_page/realbox.js
@@ -267,11 +267,10 @@ const firstMatch = hasMatches ? this.result_.matches[0] : null; if (firstMatch && firstMatch.allowedToBeDefaultMatch) { this.$.matches.selectFirst(); - const inlineAutocompletion = - decodeString16(firstMatch.inlineAutocompletion); - if (inlineAutocompletion) { - this.updateInput_({inline: inlineAutocompletion}); - } + this.updateInput_({ + text: this.lastQueriedInput_, + inline: decodeString16(firstMatch.inlineAutocompletion) || '', + }); // Navigate to the default up-to-date match if the user typed and pressed // 'Enter' too fast.
diff --git a/chrome/browser/resources/pdf/gesture_detector.js b/chrome/browser/resources/pdf/gesture_detector.js index a259d31d..827725f 100644 --- a/chrome/browser/resources/pdf/gesture_detector.js +++ b/chrome/browser/resources/pdf/gesture_detector.js
@@ -164,6 +164,11 @@ event.preventDefault(); + // Disable wheel gestures in Presentation mode. + if (document.fullscreenElement !== null) { + return; + } + const wheelScale = Math.exp(-event.deltaY / 100); // Clamp scale changes from the wheel event as they can be // quite dramatic for non-synthetic ctrl-wheels.
diff --git a/chrome/browser/resources/pdf/pdf_viewer.html b/chrome/browser/resources/pdf/pdf_viewer.html index 15373b4..c7b3775 100644 --- a/chrome/browser/resources/pdf/pdf_viewer.html +++ b/chrome/browser/resources/pdf/pdf_viewer.html
@@ -121,6 +121,11 @@ overflow: auto; position: relative; } + + /* Hide scrollbars when in Presentation mode. */ + #scroller:fullscreen { + overflow: hidden; + } </style> <template is="dom-if" if="[[!pdfViewerUpdateEnabled_]]">
diff --git a/chrome/browser/resources/pdf/pdf_viewer.js b/chrome/browser/resources/pdf/pdf_viewer.js index b92e97e..395c56c 100644 --- a/chrome/browser/resources/pdf/pdf_viewer.js +++ b/chrome/browser/resources/pdf/pdf_viewer.js
@@ -683,7 +683,11 @@ /** @private */ onFullscreenClick_() { assert(this.presentationModeEnabled_); - this.shadowRoot.querySelector('#main').requestFullscreen(); + this.shadowRoot.querySelector('#scroller').requestFullscreen().then(() => { + this.forceFit(FittingType.FIT_TO_HEIGHT); + // Nothing else to do here. The viewport will be updated as a result of a + // 'resize' event callback. + }); } /**
diff --git a/chrome/browser/resources/pdf/viewport.js b/chrome/browser/resources/pdf/viewport.js index 3fd15ee..584aa6d 100644 --- a/chrome/browser/resources/pdf/viewport.js +++ b/chrome/browser/resources/pdf/viewport.js
@@ -454,12 +454,20 @@ * @private */ resize_() { + // Force fit-to-height when resizing happens as a result of entering full + // screen mode. + if (document.fullscreenElement !== null) { + this.fittingType_ = FittingType.FIT_TO_HEIGHT; + this.window_.dispatchEvent( + new CustomEvent('fitting-type-changed-for-testing')); + } + if (this.fittingType_ === FittingType.FIT_TO_PAGE) { this.fitToPageInternal_(false); } else if (this.fittingType_ === FittingType.FIT_TO_WIDTH) { this.fitToWidth(); } else if (this.fittingType_ === FittingType.FIT_TO_HEIGHT) { - this.fitToHeightInternal_(false); + this.fitToHeightInternal_(document.fullscreenElement !== null); } else if (this.internalZoom_ === 0) { this.fitToNone(); } else { @@ -1502,6 +1510,11 @@ * @private */ onPinchStart_(e) { + // Disable pinch gestures in Presentation mode. + if (document.fullscreenElement !== null) { + return; + } + // We also use rAF for pinch start, so that if there is a pinch end event // scheduled by rAF, this pinch start will be sent after. window.requestAnimationFrame(() => {
diff --git a/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.html b/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.html index 4e67cb4..1e2d075 100644 --- a/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.html +++ b/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.html
@@ -25,12 +25,35 @@ --add-account-margin-top: 16px; } + .account-manager-description { + color: var(--cr-secondary-text-color); + display: block; + max-width: 560px; + } + .profile-icon { + --profile-icon-size: 40px; background: center / cover no-repeat; - border-radius: 20px; + border-radius: 50%; flex-shrink: 0; - height: 40px; - width: 40px; + height: var(--profile-icon-size); + width: var(--profile-icon-size); + } + + .profile-icon.device-account-icon { + --profile-icon-size: 60px; + margin-top: 20px; + } + + .device-account-container { + align-items: center; + display: flex; + flex-direction: column; + } + + .device-account-container .primary { + font-weight: 500; + margin-top: 15px; } .account-list-item { @@ -38,11 +61,6 @@ padding-inline-start: 0; } - .account-manager-description { - /* Up to 70 characters. */ - max-width: 35em; - } - #outer { margin-inline-end: var(--cr-section-padding); margin-inline-start: 60px; @@ -61,13 +79,9 @@ align-items: flex-end; } - #account-description { - align-items: flex-start; - flex-direction: column; - } - - #account-description > p { - margin-bottom: 0; + .secondary-accounts-tooltip { + margin-inline-start: 5px; + width: 15px; } #account-list-header > h2 { @@ -113,6 +127,42 @@ right: 60%; } + .managed-badge { + --badge-offset: calc(100% - var(--badge-size) + - 2 * var(--padding-size)); + --badge-size: 10px; + --padding-size: 4px; + background: var(--google-blue-600); + border-radius: 50%; + height: var(--badge-size); + left: var(--badge-offset); + padding: var(--padding-size); + position: relative; + top: var(--badge-offset); + width: var(--badge-size); + } + + .managed-badge > iron-icon { + --iron-icon-fill-color: white; + --iron-icon-height: var(--badge-size); + --iron-icon-width: var(--badge-size); + display: block; + } + + :host-context([dir='rtl']) .managed-badge { + left: auto; + right: var(--badge-offset); + } + + .managed-message { + color: var(--cr-secondary-text-color); + justify-content: center; + } + + .managed-message > iron-icon { + margin-inline-end: 5px; + } + .management-status { color: var(--cr-secondary-text-color); overflow: hidden; @@ -131,18 +181,70 @@ } </style> - <div id="account-description" class="settings-box first"> + <!-- Account management description --> + <div class="settings-box first account-manager-description"> <settings-localized-link - class="account-manager-description" localized-string="[[getAccountManagerDescription_()]]" link-url="$i18nRaw{accountManagerLearnMoreUrl}"> </settings-localized-link> - <template is="dom-if" if="[[isChildUser_]]"> + <div hidden$="[[!isChildUser_]]"> <p>$i18n{accountManagerChildFirstMessage}</p> <p>$i18n{accountManagerChildSecondMessage}</p> - </template> + </div> </div> + <template is="dom-if" if="[[isAccountManagementFlowsV2Enabled_]]"> + <!-- Primary account description --> + <div class="settings-box first"> + <div class="start two-line account-manager-description"> + <div> + <h2>$i18n{accountManagerUnmanagedLabel}</h2> + <settings-localized-link + localized-string= + "$i18n{accountManagerPrimaryAccountDescription}" + on-link-clicked="goToSyncSettings_"> + </settings-localized-link> + </div> + </div> + </div> + + <template is="dom-if" if="[[isDeviceAccountManaged_]]"> + <div class="settings-box first managed-message"> + <iron-icon icon="[[getManagedAccountTooltipIcon_(isChildUser_, + isDeviceAccountManaged_)]]"> + </iron-icon> + <settings-localized-link + localized-string= + "[[getManagementDescription_(isChildUser_, deviceAccount_)]]" + link-url="$i18nRaw{accountManagerChromeUIManagementURL}"> + </settings-localized-link> + </div> + </template> + + <!-- Primary account icon, name and email --> + <div class="device-account-container" tabIndex="0" + aria-labelledby="deviceAccountFullName" + aria-describedby="deviceAccountEmail"> + <div class="profile-icon device-account-icon" + style="background-image: [[getIconImageSet_(deviceAccount_.pic)]]"> + <template is="dom-if" + if="[[shouldShowManagedBadge_(isDeviceAccountManaged_, + isChildUser_)]]"> + <div class="managed-badge"> + <iron-icon icon="cr:work"></iron-icon> + </div> + </template> + </div> + <span id="deviceAccountFullName" class="primary" aria-hidden="true"> + [[deviceAccount_.fullName]] + </span> + <span id="deviceAccountEmail" class="secondary" aria-hidden="true"> + [[deviceAccount_.email]] + </span> + </div> + </template> + + <!-- Message saying that secondary account signin is not allowed --> <div id="settings-box-user-message" class="settings-box first user-message" hidden="[[isSecondaryGoogleAccountSigninAllowed_]]"> <cr-policy-pref-indicator class="secondary-accounts-policy-indicator" @@ -154,9 +256,21 @@ </div> </div> + <!-- Secondary Accounts list header --> <div class="settings-box first"> - <div id="account-list-header" class="flex"> - <h2>$i18n{accountListHeader}</h2> + <div id="account-list-header" class="start"> + <h2> + [[getAccountListHeader_(isChildUser_)]] + <template is="dom-if" if="[[isAccountManagementFlowsV2Enabled_]]"> + <cr-tooltip-icon + aria-hidden="true" + class="secondary-accounts-tooltip" + icon-class="cr:info-outline" + tooltip-text="[[getSecondaryAccountsTooltip_(accounts_)]]" + icon-aria-label="[[getSecondaryAccountsTooltip_(accounts_)]]"> + </cr-tooltip-icon> + </template> + </h2> </div> <cr-button disabled="[[!isSecondaryGoogleAccountSigninAllowed_]]" id="add-account-button" on-click="addAccount_" @@ -167,8 +281,12 @@ </cr-button> </div> + <!-- Secondary Accounts list --> <div id="outer" class="layout vertical nowrap" role="list"> - <template is="dom-repeat" id="account-list" items="[[accounts_]]"> + <!-- TODO(crbug.com/1144113): display a message when there are no + secondary accounts --> + <template is="dom-repeat" id="account-list" + items="[[getAccounts_(accounts_)]]"> <div class="settings-box account-list-item" role="listitem"> <div class="profile-icon" @@ -224,13 +342,13 @@ <template is="dom-if" if="[[!item.isDeviceAccount]]"> <!-- Display EDU account labels on secondary accounts for Child users --> - <template is="dom-if" if="[[isChildUser_]]" restamp> - <span class="management-status edu-account-label" - id="edu-account-label-[[index]]" - aria-hidden="true"> - $i18n{accountManagerEducationAccountLabel} - </span> - </template> + <span hidden$="[[!shouldDisplayEduSecondaryAccountLabel_( + isChildUser_)]]" + class="management-status edu-account-label" + id="edu-account-label-[[index]]" + aria-hidden="true"> + $i18n{accountManagerEducationAccountLabel} + </span> <cr-icon-button class="icon-more-vert" title="[[getMoreActionsTitle_(item)]]" aria-label="[[getMoreActionsTitle_(item)]]"
diff --git a/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.js b/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.js index 5460fd6..1cb86131 100644 --- a/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.js +++ b/chrome/browser/resources/settings/chromeos/os_people_page/account_manager.js
@@ -31,6 +31,12 @@ }, /** + * Primary / Device account. + * @private {?settings.Account} + */ + deviceAccount_: Object, + + /** * The targeted account for menu operations. * @private {?settings.Account} */ @@ -45,6 +51,30 @@ }, /** + * True if device account is managed. + * @private {boolean} + */ + isDeviceAccountManaged_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('isDeviceAccountManaged'); + }, + readOnly: true, + }, + + /** + * True if redesign of account management flows is enabled. + * @private + */ + isAccountManagementFlowsV2Enabled_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('isAccountManagementFlowsV2Enabled'); + }, + readOnly: true, + }, + + /** * @return {boolean} True if secondary account sign-ins are allowed, false * otherwise. * @private @@ -119,6 +149,18 @@ }, /** + * @return {string} accounts list header (e.g. 'Secondary accounts' for + * regular users or 'School accounts' for child users). + * @private + */ + getAccountListHeader_() { + if (this.isAccountManagementFlowsV2Enabled_ && this.isChildUser_) { + return loadTimeData.getString('accountListHeaderChild'); + } + return loadTimeData.getString('accountListHeader'); + }, + + /** * @return {string} 'Secondary Accounts disabled' message depending on * account type * @private @@ -148,6 +190,16 @@ }, /** + * @return {string} tooltip text + * @private + */ + getSecondaryAccountsTooltip_() { + return this.getAccounts_().length === 0 ? + this.i18n('accountListTooltipNoSecondaryAccounts') : + this.i18n('accountListTooltip'); + }, + + /** * @param {string} iconUrl * @return {string} A CSS image-set for multiple scale factors. * @private @@ -182,6 +234,24 @@ }, /** + * @return {boolean} True if 'School account' label should be displayed for + * secondary accounts. + * @private + */ + shouldDisplayEduSecondaryAccountLabel_() { + return this.isChildUser_ && !this.isAccountManagementFlowsV2Enabled_; + }, + + /** + * @return {boolean} True if managed badge should be shown next to the device + * account picture. + * @private + */ + shouldShowManagedBadge_() { + return this.isDeviceAccountManaged_ && !this.isChildUser_; + }, + + /** * @param {!settings.Account} account * @return {string} An appropriate management status label. e.g. * "Primary account" for unmanaged accounts, "Managed by <Domain>" @@ -197,6 +267,46 @@ }, /** + * @return {string} icon + * @private + */ + getManagedAccountTooltipIcon_() { + if (this.isChildUser_) { + return 'cr20:kite'; + } + if (this.isDeviceAccountManaged_) { + return 'cr20:domain'; + } + return ''; + }, + + /** + * @return {string} description text + * @private + */ + getManagementDescription_() { + if (this.isChildUser_) { + return loadTimeData.getString('accountManagerManagementDescription'); + } + if (!this.deviceAccount_) { + return ''; + } + if (!this.deviceAccount_.organization) { + if (this.isDeviceAccountManaged_) { + console.error( + 'The device account is managed, but the organization is not set.'); + } + return ''; + } + // Format: 'This account is managed by + // <a target="_blank" href="chrome://management">google.com</a>'. + // Where href will be set by <settings-localized-link>. + return loadTimeData.getStringF( + 'accountManagerManagementDescription', + this.deviceAccount_.organization); + }, + + /** * @param {boolean} unmigrated * @private */ @@ -235,6 +345,20 @@ }, /** + * @return {!Array<settings.Account>} list of accounts. + * @private + */ + getAccounts_() { + // TODO(crbug.com/1152711): rename the method to `getSecondaryAccounts_`. + if (this.isAccountManagementFlowsV2Enabled_) { + // Return only secondary accounts. + return this.accounts_.filter(account => !account.isDeviceAccount); + } + + return this.accounts_; + }, + + /** * @param {!CustomEvent<!{model: !{item: !settings.Account}}>} event * @private */ @@ -252,6 +376,12 @@ refreshAccounts_() { this.browserProxy_.getAccounts().then(accounts => { this.set('accounts_', accounts); + const deviceAccount = accounts.find(account => account.isDeviceAccount); + if (!deviceAccount) { + console.error('Cannot find device account.'); + return; + } + this.deviceAccount_ = deviceAccount; }); }, @@ -283,5 +413,18 @@ this.browserProxy_.removeAccount( /** @type {?settings.Account} */ (this.actionMenuAccount_)); this.closeActionMenu_(); - } + }, + + /** + * @param {Event} event + * @private + */ + goToSyncSettings_(event) { + event.detail.event.preventDefault(); + if (loadTimeData.getBoolean('splitSettingsSyncEnabled')) { + settings.Router.getInstance().navigateTo(settings.routes.OS_SYNC); + } else { + settings.Router.getInstance().navigateTo(settings.routes.SYNC_ADVANCED); + } + }, });
diff --git a/chrome/browser/resources/web_app_internals/web_app_internals.html b/chrome/browser/resources/web_app_internals/web_app_internals.html index 2982293..ac10019c 100644 --- a/chrome/browser/resources/web_app_internals/web_app_internals.html +++ b/chrome/browser/resources/web_app_internals/web_app_internals.html
@@ -1,7 +1,11 @@ <style> h2 { - margin-bottom: 10px; - margin-top: 0; + margin-bottom: 0; + margin-top: 10px; + } + + h3 { + margin-bottom: 0; } .section { @@ -47,7 +51,8 @@ </div> <div class="section"> - <h2>Page index:</h2> + <h2>Page Index:</h2> + <h3><a href="#installed">Installed Web Apps</a></h3> <template is="dom-repeat" items="[[webAppList_]]"> <div> <a href="#[[item.id]]"> @@ -56,11 +61,21 @@ </a> </div> </template> - <a href="#external">Externally installed web app prefs</a> + + <h3><a href="#preinstalled">Preinstalled Web Apps</a></h3> + <template is="dom-if" if="[[preinstalledWebAppDebugInfo_]]"> + <div><a href="#preinstalled-errors">Parse Errors</a></div> + <div><a href="#preinstalled-enabled">Enabled Configs</a></div> + <div><a href="#preinstalled-disabled">Disabled Configs</a></div> + <div><a href="#preinstalled-installs">Install Results</a></div> + <div><a href="#preinstalled-uninstalls">Uninstall Results</a></div> + </template> + + <h3><a href="#external-prefs">Externally Installed Web App Prefs</a></h3> </div> <div class="section"> - <h2 id="details">Web apps details:</h2> + <h2 id="installed">Installed Web Apps</h2> <template is="dom-repeat" items="[[webAppList_]]"> <div class="section web-app" id="[[item.id]]"> <h2>[[item.name]]</h2> @@ -70,7 +85,78 @@ </template> </div> -<div class="section" id="external"> - <h2>Externally installed web app prefs:</h2> +<div class="section"> + <h2 id="preinstalled">Preinstalled Web Apps</h2> + <template is="dom-if" if="[[!preinstalledWebAppDebugInfo_]]"> + <p> + No debugging info available! Please enable + <a href="chrome://flags/#record-web-app-debug-info">chrome://flags/#record-web-app-debug-info</a>. + </p> + </template> + + <template is="dom-if" if="[[preinstalledWebAppDebugInfo_]]"> + <p> + <a href="chrome://flags/#record-web-app-debug-info">chrome://flags/#record-web-app-debug-info</a> + flag is enabled, debugging info is being captured. + </p> + + <p> + Is start up task complete (also required for debug info): + <b>[[preinstalledWebAppDebugInfo_.isStartUpTaskComplete]]</b> + </p> + + <h3 id="preinstalled-errors">Parse Errors</h3> + <ul> + <template is="dom-repeat" + items="[[preinstalledWebAppDebugInfo_.parseErrors]]"> + <li>[[item]]</li> + </template> + </ul> + + <h3 id="preinstalled-enabled">Enabled Configs</h3> + <ul> + <template is="dom-repeat" + items="[[preinstalledWebAppDebugInfo_.enabledConfigs]]"> + <li><pre>[[item]]</pre></li> + </template> + </ul> + + <h3 id="preinstalled-disabled">Disabled Configs</h3> + <ul> + <template is="dom-repeat" + items="[[preinstalledWebAppDebugInfo_.disabledConfigs]]"> + <li> + <b>[[item.reason]]</b> + <pre>[[item.config]]</pre> + </li> + </template> + </ul> + + <h3 id="preinstalled-installs">Install Results</h3> + <ul> + <template is="dom-repeat" + items="[[preinstalledWebAppDebugInfo_.installResults]]"> + <li> + <div>Install URL: [[item.installUrl]]</div> + <div>InstallResultCode: [[item.installResultCode]]</div> + </li> + </template> + </ul> + + <h3 id="preinstalled-uninstalls">Uninstall Results</h3> + <ul> + <template is="dom-repeat" + items="[[preinstalledWebAppDebugInfo_.uninstallResults]]"> + <li> + <div>Install URL: [[item.installUrl]]</div> + <div>Success: [[item.isSuccess]]</div> + </li> + </template> + </ul> + </template> +</div> + +<div class="section"> + <h2 id="external-prefs">Externally Installed Web App Prefs</h2> <pre>[[externallyInstalledWebAppPrefs_]]</pre> </div>
diff --git a/chrome/browser/resources/web_app_internals/web_app_internals.js b/chrome/browser/resources/web_app_internals/web_app_internals.js index dfc512aa..ea38e13 100644 --- a/chrome/browser/resources/web_app_internals/web_app_internals.js +++ b/chrome/browser/resources/web_app_internals/web_app_internals.js
@@ -25,6 +25,12 @@ webAppList_: Array, /** + * Debug information about preinstalled web apps. + * @private {!mojom.webAppInternals.PreinstalledWebAppDebugInfo|null} + */ + preinstalledWebAppDebugInfo_: Object, + + /** * Prefs associated with non-user installed web apps. * @private {!string} */ @@ -45,6 +51,9 @@ this.webAppList_ = (await remote.getWebApps()).webAppList; this.webAppList_.sort((a, b) => a.name.localeCompare(b.name)); + this.preinstalledWebAppDebugInfo_ = + (await remote.getPreinstalledWebAppDebugInfo()).status; + this.externallyInstalledWebAppPrefs_ = (await remote.getExternallyInstalledWebAppPrefs()) .externallyInstalledWebAppPrefs;
diff --git a/chrome/browser/safe_browsing/client_side_detection_host.cc b/chrome/browser/safe_browsing/client_side_detection_host.cc index 1e8ecbd..463551c 100644 --- a/chrome/browser/safe_browsing/client_side_detection_host.cc +++ b/chrome/browser/safe_browsing/client_side_detection_host.cc
@@ -16,7 +16,6 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/sequenced_task_runner_helpers.h" -#include "base/strings/utf_string_conversions.h" #include "base/time/default_tick_clock.h" #include "base/time/tick_clock.h" #include "chrome/browser/browser_process.h" @@ -25,24 +24,18 @@ #include "chrome/browser/safe_browsing/client_side_detection_service_factory.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/browser/safe_browsing/user_interaction_observer.h" -#include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/content/common/safe_browsing.mojom-shared.h" #include "components/safe_browsing/content/common/safe_browsing.mojom.h" -#include "components/safe_browsing/core/common/safe_browsing_prefs.h" #include "components/safe_browsing/core/db/allowlist_checker_client.h" #include "components/safe_browsing/core/db/database_manager.h" -#include "components/safe_browsing/core/proto/csd.pb.h" #include "components/security_interstitials/content/unsafe_resource_util.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/navigation_controller.h" -#include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/url_constants.h" #include "net/base/ip_endpoint.h" #include "net/http/http_response_headers.h" #include "services/service_manager/public/cpp/interface_provider.h" @@ -50,7 +43,6 @@ #include "url/gurl.h" using content::BrowserThread; -using content::NavigationEntry; using content::WebContents; namespace safe_browsing { @@ -305,7 +297,6 @@ csd_service_(nullptr), tab_(tab), classification_request_(nullptr), - pageload_complete_(false), tick_clock_(base::DefaultTickClock::GetInstance()) { DCHECK(tab); // Note: csd_service_ and sb_service will be nullptr here in testing. @@ -356,8 +347,6 @@ current_url_ = navigation_handle->GetURL(); - pageload_complete_ = false; - // Check whether we can cassify the current URL for phishing. classification_request_ = new ShouldClassifyUrlRequest( navigation_handle,
diff --git a/chrome/browser/safe_browsing/client_side_detection_host.h b/chrome/browser/safe_browsing/client_side_detection_host.h index e94704a..a743450 100644 --- a/chrome/browser/safe_browsing/client_side_detection_host.h +++ b/chrome/browser/safe_browsing/client_side_detection_host.h
@@ -9,15 +9,11 @@ #include <memory> #include <string> -#include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "chrome/browser/safe_browsing/client_side_model_loader.h" #include "chrome/browser/safe_browsing/ui_manager.h" -#include "components/safe_browsing/content/common/safe_browsing.mojom-shared.h" #include "components/safe_browsing/core/db/database_manager.h" -#include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents_observer.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -89,12 +85,6 @@ GURL phishing_url, bool is_phishing); - // Returns true if the user has seen a regular SafeBrowsing - // interstitial for the current page. This is only true if the user has - // actually clicked through the warning. This method is called on the UI - // thread. - bool DidShowSBInterstitial() const; - // Used for testing. This function does not take ownership of the service // class. void set_client_side_detection_service(ClientSideDetectionService* service); @@ -116,15 +106,9 @@ scoped_refptr<ShouldClassifyUrlRequest> classification_request_; // The current URL GURL current_url_; - // Current host, used to help determine cur_host_redirects_. - std::string cur_host_; // The currently active message pipe to the renderer PhishingDetector. mojo::Remote<mojom::PhishingDetector> phishing_detector_; - // Max number of ips we save for each browse - static const size_t kMaxIPsPerBrowse; - bool pageload_complete_; - // Records the start time of when phishing detection started. base::TimeTicks phishing_detection_start_time_; const base::TickClock* tick_clock_;
diff --git a/chrome/browser/tab/BUILD.gn b/chrome/browser/tab/BUILD.gn index 887da91..1e88b05 100644 --- a/chrome/browser/tab/BUILD.gn +++ b/chrome/browser/tab/BUILD.gn
@@ -88,3 +88,20 @@ "$proto_path/shopping_persisted_tab_data.proto", ] } + +android_library("junit") { + bypass_platform_checks = true + testonly = true + sources = + [ "java/src/org/chromium/chrome/browser/tab/CurrentTabObserverTest.java" ] + + deps = [ + ":java", + "//base:base_java", + "//base:base_java_test_support", + "//base:base_junit_test_support", + "//third_party/android_deps:robolectric_all_java", + "//third_party/junit", + "//third_party/mockito:mockito_java", + ] +}
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/CurrentTabObserver.java b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/CurrentTabObserver.java index 95797b07..33a877f 100644 --- a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/CurrentTabObserver.java +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/CurrentTabObserver.java
@@ -36,6 +36,7 @@ mTabObserver = tabObserver; mCallbackController = new CallbackController(); mTabSupplierCallback = mCallbackController.makeCancelable((tab) -> { + if (mTab == tab) return; if (mTab != null) mTab.removeObserver(mTabObserver); mTab = tab; if (mTab != null) mTab.addObserver(mTabObserver); @@ -43,6 +44,11 @@ mTabSupplier.addObserver(mTabSupplierCallback); } + /** Trigger the event callback for this observer with the current tab. */ + public void triggerWithCurrentTab() { + mTabSupplierCallback.onResult(mTabSupplier.get()); + } + /** Destroy the current tab observer. This should be called after use. */ public void destroy() { if (mTab != null) mTab.removeObserver(mTabObserver);
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/CurrentTabObserverTest.java b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/CurrentTabObserverTest.java new file mode 100644 index 0000000..4224290b --- /dev/null +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/CurrentTabObserverTest.java
@@ -0,0 +1,69 @@ +// 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.tab; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import org.chromium.base.supplier.ObservableSupplierImpl; +import org.chromium.base.test.BaseRobolectricTestRunner; + +/** Tests for CurrentTabObserver. */ +@RunWith(BaseRobolectricTestRunner.class) +public class CurrentTabObserverTest { + private CurrentTabObserver mCurrentTabObserver; + + private ObservableSupplierImpl<Tab> mTabSupplier; + + @Mock + private Tab mTab; + + @Mock + private Tab mTab2; + + @Mock + private TabObserver mTabObserver; + + @Before + public void beforeTest() { + MockitoAnnotations.initMocks(this); + + mTabSupplier = new ObservableSupplierImpl<>(); + mCurrentTabObserver = new CurrentTabObserver(mTabSupplier, mTabObserver); + } + + @Test + public void testTriggerWithCurrentTab() { + mCurrentTabObserver.triggerWithCurrentTab(); + verify(mTab, times(0)).addObserver(mTabObserver); + + // Set the current tab to |mTab|. This adds the observer. + // The following |triggerWithCurrentTab| invokes the event callback as well + // but the observer is not added again as the current tab hasn't changed. + mTabSupplier.set(mTab); + mCurrentTabObserver.triggerWithCurrentTab(); + verify(mTab, times(1)).addObserver(mTabObserver); + } + + @Test + public void testTabObserverAfterTabSwitch() { + // Make sure the tab observer for this overlay is only observing the "current" tab. + mTabSupplier.set(mTab); + verify(mTab).addObserver(mTabObserver); + + mTabSupplier.set(mTab2); + verify(mTab).removeObserver(mTabObserver); + verify(mTab2).addObserver(mTabObserver); + + mTabSupplier.set(null); + verify(mTab2).removeObserver(mTabObserver); + } +}
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/DEPS b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/DEPS index 753a71e..a3c66ba 100644 --- a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/DEPS +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/DEPS
@@ -25,4 +25,8 @@ "-components", "+components/embedder_support/android/java/src/org/chromium/components/embedder_support/view", ], + + 'CurrentTabObserverTest.java': [ + "+base/test/android/junit", + ] }
diff --git a/chrome/browser/ui/ash/test_login_screen.cc b/chrome/browser/ui/ash/test_login_screen.cc index 9f3b317..b84e901 100644 --- a/chrome/browser/ui/ash/test_login_screen.cc +++ b/chrome/browser/ui/ash/test_login_screen.cc
@@ -43,6 +43,8 @@ void TestLoginScreen::EnableShutdownButton(bool enable) {} +void TestLoginScreen::EnableShelfButtons(bool enable) {} + void TestLoginScreen::SetIsFirstSigninStep(bool is_first) {} void TestLoginScreen::ShowParentAccessButton(bool show) {}
diff --git a/chrome/browser/ui/ash/test_login_screen.h b/chrome/browser/ui/ash/test_login_screen.h index a11b477..ec2b025 100644 --- a/chrome/browser/ui/ash/test_login_screen.h +++ b/chrome/browser/ui/ash/test_login_screen.h
@@ -33,6 +33,7 @@ bool IsReadyForPassword() override; void EnableAddUserButton(bool enable) override; void EnableShutdownButton(bool enable) override; + void EnableShelfButtons(bool enable) override; void SetIsFirstSigninStep(bool is_first) override; void ShowParentAccessButton(bool show) override; void SetAllowLoginAsGuest(bool allow_guest) override;
diff --git a/chrome/browser/ui/cocoa/permission_bubble/OWNERS b/chrome/browser/ui/cocoa/permission_bubble/OWNERS deleted file mode 100644 index 555e79f..0000000 --- a/chrome/browser/ui/cocoa/permission_bubble/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -estark@chromium.org -felt@chromium.org -rsesek@chromium.org
diff --git a/chrome/browser/ui/cocoa/permission_bubble/permission_bubble_views_cocoa_browsertest.mm b/chrome/browser/ui/cocoa/permission_bubble/permission_bubble_views_cocoa_browsertest.mm deleted file mode 100644 index 79f21f9..0000000 --- a/chrome/browser/ui/cocoa/permission_bubble/permission_bubble_views_cocoa_browsertest.mm +++ /dev/null
@@ -1,98 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> - -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_commands_mac.h" -#include "chrome/browser/ui/browser_finder.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" -#include "chrome/browser/ui/exclusive_access/exclusive_access_test.h" -#include "chrome/browser/ui/exclusive_access/fullscreen_controller.h" -#include "chrome/browser/ui/permission_bubble/permission_bubble_browser_test_util.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h" -#include "chrome/test/permissions/permission_request_manager_test_api.h" -#include "content/public/test/browser_test.h" -#import "testing/gtest_mac.h" -#include "ui/base/test/scoped_fake_nswindow_fullscreen.h" - -// This file now tests the views permission bubble, on a Cocoa browser window. - -namespace { - -// Shows a test bubble using the permission request manager rather than any -// toolkit-specific bubble implementation. -void ShowBubble(Browser* browser) { - auto test_api = - std::make_unique<test::PermissionRequestManagerTestApi>(browser); - EXPECT_TRUE(test_api->manager()); - - test_api->AddSimpleRequest( - browser->tab_strip_model()->GetActiveWebContents()->GetMainFrame(), - ContentSettingsType::GEOLOCATION); - - // The PermissionRequestManager displays prompts asynchronously. - EXPECT_FALSE(test_api->GetPromptWindow()); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(test_api->GetPromptWindow()); -} - -bool HasVisibleLocationBarForBrowser(Browser* browser) { - return browser->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR); -} - -} // namespace - -IN_PROC_BROWSER_TEST_F(PermissionBubbleBrowserTest, HasLocationBarByDefault) { - ShowBubble(browser()); - HasVisibleLocationBarForBrowser(browser()); -} - -IN_PROC_BROWSER_TEST_F(PermissionBubbleBrowserTest, - TabFullscreenHasNoLocationBar) { - ShowBubble(browser()); - EXPECT_TRUE(HasVisibleLocationBarForBrowser(browser())); - - FullscreenController* controller = - browser()->exclusive_access_manager()->fullscreen_controller(); - { - FullscreenNotificationObserver fullscreen_observer(browser()); - controller->EnterFullscreenModeForTab( - browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()); - fullscreen_observer.Wait(); - } - EXPECT_TRUE(controller->IsTabFullscreen()); - EXPECT_FALSE(HasVisibleLocationBarForBrowser(browser())); - - { - FullscreenNotificationObserver fullscreen_observer(browser()); - controller->ExitFullscreenModeForTab( - browser()->tab_strip_model()->GetActiveWebContents()); - fullscreen_observer.Wait(); - } - EXPECT_FALSE(controller->IsTabFullscreen()); - EXPECT_TRUE(HasVisibleLocationBarForBrowser(browser())); -} - -IN_PROC_BROWSER_TEST_F(PermissionBubbleBrowserTest, AppHasNoLocationBar) { - content::WebContents* app_contents = OpenExtensionAppWindow(); - - Browser* app_browser = chrome::FindBrowserWithWebContents(app_contents); - ASSERT_TRUE(app_browser->is_type_app()); - - // ShowBubble(app_browser) doesn't actually show a bubble for extension app - // windows, so create one directly. - auto prompt = std::make_unique<PermissionPromptImpl>( - app_browser, app_contents, test_delegate()); - EXPECT_FALSE(HasVisibleLocationBarForBrowser(app_browser)); -} - -IN_PROC_BROWSER_TEST_F(PermissionBubbleKioskBrowserTest, - KioskHasNoLocationBar) { - ShowBubble(browser()); - // Kiosk mode on Mac has no location bar. - EXPECT_FALSE(HasVisibleLocationBarForBrowser(browser())); -}
diff --git a/chrome/browser/ui/hats/hats_service.cc b/chrome/browser/ui/hats/hats_service.cc index 98bef78..7f9eda43 100644 --- a/chrome/browser/ui/hats/hats_service.cc +++ b/chrome/browser/ui/hats/hats_service.cc
@@ -34,8 +34,14 @@ constexpr char kHatsSurveyTriggerSatisfaction[] = "satisfaction"; constexpr char kHatsSurveyTriggerSettings[] = "settings"; constexpr char kHatsSurveyTriggerSettingsPrivacy[] = "settings-privacy"; +constexpr char kHatsSurveyTriggerDevToolsIssuesCOEP[] = "devtools-issues-coep"; +constexpr char kHatsSurveyTriggerDevToolsIssuesMixedContent[] = + "devtools-issues-mixed-content"; constexpr char kHatsSurveyTriggerDevToolsIssuesCookiesSameSite[] = "devtools-issues-cookies-samesite"; +constexpr char kHatsSurveyTriggerDevToolsIssuesHeavyAd[] = + "devtools-issues-heavy-ad"; +constexpr char kHatsSurveyTriggerDevToolsIssuesCSP[] = "devtools-issues-csp"; constexpr char kHatsNextSurveyTriggerIDTesting[] = "zishSVViB0kPN8UwQ150VGjBKuBP"; @@ -47,7 +53,11 @@ const base::Feature* survey_features[] = { &features::kHappinessTrackingSurveysForDesktop, + &features::kHaTSDesktopDevToolsIssuesCOEP, + &features::kHaTSDesktopDevToolsIssuesMixedContent, &features::kHappinessTrackingSurveysForDesktopDevToolsIssuesCookiesSameSite, + &features::kHaTSDesktopDevToolsIssuesHeavyAd, + &features::kHaTSDesktopDevToolsIssuesCSP, &features::kHappinessTrackingSurveysForDesktopSettings, &features::kHappinessTrackingSurveysForDesktopSettingsPrivacy};
diff --git a/chrome/browser/ui/hats/hats_service.h b/chrome/browser/ui/hats/hats_service.h index 2685c4d..2381925 100644 --- a/chrome/browser/ui/hats/hats_service.h +++ b/chrome/browser/ui/hats/hats_service.h
@@ -32,7 +32,11 @@ extern const char kHatsSurveyTriggerSatisfaction[]; extern const char kHatsSurveyTriggerSettings[]; extern const char kHatsSurveyTriggerSettingsPrivacy[]; +extern const char kHatsSurveyTriggerDevToolsIssuesCOEP[]; +extern const char kHatsSurveyTriggerDevToolsIssuesMixedContent[]; extern const char kHatsSurveyTriggerDevToolsIssuesCookiesSameSite[]; +extern const char kHatsSurveyTriggerDevToolsIssuesHeavyAd[]; +extern const char kHatsSurveyTriggerDevToolsIssuesCSP[]; // The Trigger ID for a test HaTS Next survey which is available for testing // and demo purposes when the migration feature flag is enabled.
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc index f7f4af18..ff7811d 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_view_browsertest.cc
@@ -472,9 +472,8 @@ kURL); } -// TODO(crbug.com/1144065): Flaky on multiple platforms. IN_PROC_BROWSER_TEST_F(ProfilePickerCreationFlowBrowserTest, - DISABLED_CreateSignedInProfileSigninAlreadyExists) { + CreateSignedInProfileSigninAlreadyExists) { ASSERT_EQ(1u, BrowserList::GetInstance()->size()); // Create a pre-existing profile syncing with the same account as the profile
diff --git a/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc b/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc index 61ac40f..74ab79d 100644 --- a/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc +++ b/chrome/browser/ui/web_applications/test/web_app_browsertest_util.cc
@@ -220,8 +220,8 @@ std::move(install_options), base::BindLambdaForTesting( [&result_code, &run_loop](const GURL& provided_url, - PendingAppManager::InstallResult result) { - result_code = result.code; + InstallResultCode code) { + result_code = code; run_loop.Quit(); })); run_loop.Run();
diff --git a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc index a12ee0b..6743b40 100644 --- a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc +++ b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc
@@ -164,11 +164,10 @@ windows_closed_requests_map_[app_id].push_back(std::move(callback)); } -bool WebAppUiManagerImpl::UninstallAndReplaceIfExists( +void WebAppUiManagerImpl::UninstallAndReplaceIfExists( const std::vector<AppId>& from_apps, const AppId& to_app) { bool has_migrated = false; - bool did_uninstall = false; for (const AppId& from_app : from_apps) { apps::AppServiceProxy* proxy = apps::AppServiceProxyFactory::GetForProfile(profile_); @@ -222,10 +221,7 @@ proxy->UninstallSilently(from_app, apps::mojom::UninstallSource::kMigration); - did_uninstall = true; } - - return did_uninstall; } bool WebAppUiManagerImpl::CanAddAppToQuickLaunchBar() const {
diff --git a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h index 1f9b910..03be401 100644 --- a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h +++ b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h
@@ -47,7 +47,7 @@ size_t GetNumWindowsForApp(const AppId& app_id) override; void NotifyOnAllAppWindowsClosed(const AppId& app_id, base::OnceClosure callback) override; - bool UninstallAndReplaceIfExists(const std::vector<AppId>& from_apps, + void UninstallAndReplaceIfExists(const std::vector<AppId>& from_apps, const AppId& to_app) override; bool CanAddAppToQuickLaunchBar() const override; void AddAppToQuickLaunchBar(const AppId& app_id) override;
diff --git a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc index 90d7db0..0b5d8cc 100644 --- a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc
@@ -157,6 +157,7 @@ AddCallback("hideOobeDialog", &CoreOobeHandler::HandleHideOobeDialog); AddCallback("updateOobeUIState", &CoreOobeHandler::HandleUpdateOobeUIState); + AddCallback("enableShelfButtons", &CoreOobeHandler::HandleEnableShelfButtons); } void CoreOobeHandler::ShowSignInError( @@ -237,6 +238,11 @@ LoginDisplayHost::default_host()->HideOobeDialog(); } +void CoreOobeHandler::HandleEnableShelfButtons(bool enable) { + if (LoginDisplayHost::default_host()) + LoginDisplayHost::default_host()->SetShelfButtonsEnabled(enable); +} + void CoreOobeHandler::HandleSkipToLoginForTesting() { WizardController* controller = WizardController::default_controller(); if (controller && controller->is_initialized())
diff --git a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h index f1ed4c57..ccb97dd 100644 --- a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h +++ b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.h
@@ -152,6 +152,7 @@ // Handlers for JS WebUI messages. void HandleHideOobeDialog(); + void HandleEnableShelfButtons(bool enable); void HandleInitialized(); void HandleUpdateCurrentScreen(const std::string& screen); void HandleSkipToLoginForTesting();
diff --git a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc index fbb4314..f581f60 100644 --- a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc
@@ -51,7 +51,6 @@ #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/ui/login_display_host_webui.h" #include "chrome/browser/chromeos/login/ui/login_display_webui.h" -#include "chrome/browser/chromeos/login/ui/login_feedback.h" #include "chrome/browser/chromeos/login/users/chrome_user_manager_util.h" #include "chrome/browser/chromeos/login/users/multi_profile_user_controller.h" #include "chrome/browser/chromeos/login/wizard_controller.h" @@ -102,7 +101,6 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/api/extensions_api_client.h" -#include "extensions/browser/api/feedback_private/feedback_private_delegate.h" #include "google_apis/gaia/gaia_auth_util.h" #include "third_party/cros_system_api/dbus/service_constants.h" #include "ui/base/ime/chromeos/ime_keyboard.h" @@ -410,10 +408,9 @@ AddCallback("launchSAMLPublicSession", &SigninScreenHandler::HandleLaunchSAMLPublicSession); AddRawCallback("offlineLogin", &SigninScreenHandler::HandleOfflineLogin); + // TODO(crbug.com/1100910): migrate logic to dedicated test api. AddCallback("toggleEnrollmentScreen", &SigninScreenHandler::HandleToggleEnrollmentScreen); - AddCallback("toggleKioskEnableScreen", - &SigninScreenHandler::HandleToggleKioskEnableScreen); AddCallback("accountPickerReady", &SigninScreenHandler::HandleAccountPickerReady); AddCallback("openInternetDetailDialog", @@ -437,7 +434,6 @@ &SigninScreenHandler::HandleFirstIncorrectPasswordAttempt); AddCallback("maxIncorrectPasswordAttempts", &SigninScreenHandler::HandleMaxIncorrectPasswordAttempts); - AddCallback("sendFeedback", &SigninScreenHandler::HandleSendFeedback); } void SigninScreenHandler::Show(bool oobe_ui) { @@ -1053,14 +1049,6 @@ delegate_->ShowEnterpriseEnrollmentScreen(); } -void SigninScreenHandler::HandleToggleKioskEnableScreen() { - if (delegate_ && !webui::IsEnterpriseManaged() && - KioskAppManager::IsConsumerKioskEnabled() && - LoginDisplayHost::default_host()) { - delegate_->ShowKioskEnableScreen(); - } -} - void SigninScreenHandler::HandleToggleKioskAutolaunchScreen() { if (delegate_ && !webui::IsEnterpriseManaged()) delegate_->ShowKioskAutolaunchScreen(); @@ -1268,14 +1256,6 @@ RecordReauthReason(account_id, ReauthReason::INCORRECT_PASSWORD_ENTERED); } -void SigninScreenHandler::HandleSendFeedback() { - login_feedback_ = - std::make_unique<LoginFeedback>(Profile::FromWebUI(web_ui())); - login_feedback_->Request( - std::string(), base::BindOnce(&SigninScreenHandler::OnFeedbackFinished, - weak_factory_.GetWeakPtr())); -} - bool SigninScreenHandler::AllAllowlistedUsersPresent() { CrosSettings* cros_settings = CrosSettings::Get(); bool allow_new_user = false; @@ -1333,8 +1313,4 @@ CallJS("login.AccountPickerScreen.setCapsLockState", enabled); } -void SigninScreenHandler::OnFeedbackFinished() { - login_feedback_.reset(); -} - } // namespace chromeos
diff --git a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h index ee7f7a1..614c9c3 100644 --- a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h +++ b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h
@@ -55,7 +55,6 @@ class CoreOobeView; class ErrorScreensHistogramHelper; class GaiaScreenHandler; -class LoginFeedback; class User; class UserContext; @@ -98,9 +97,6 @@ // Shows Enterprise Enrollment screen. virtual void ShowEnterpriseEnrollmentScreen() = 0; - // Shows Kiosk Enable screen. - virtual void ShowKioskEnableScreen() = 0; - // Shows Reset screen. virtual void ShowKioskAutolaunchScreen() = 0; @@ -274,7 +270,6 @@ void HandleLaunchSAMLPublicSession(const std::string& email); void HandleOfflineLogin(const base::ListValue* args); void HandleToggleEnrollmentScreen(); - void HandleToggleKioskEnableScreen(); void HandleToggleResetScreen(); void HandleToggleKioskAutolaunchScreen(); @@ -303,7 +298,6 @@ void HandleLogRemoveUserWarningShown(); void HandleFirstIncorrectPasswordAttempt(const AccountId& account_id); void HandleMaxIncorrectPasswordAttempts(const AccountId& account_id); - void HandleSendFeedback(); // Implements user sign-in. void AuthenticateExistingUser(const AccountId& account_id, @@ -339,9 +333,6 @@ void OnCapsLockChanged(bool enabled) override; void OnLayoutChanging(const std::string& layout_name) override {} - // Callback invoked after the feedback is finished. - void OnFeedbackFinished(); - // After proxy auth information has been supplied, this function re-enables // responding to network state notifications. void ReenableNetworkStateUpdatesAfterProxyAuth(); @@ -410,8 +401,6 @@ std::unique_ptr<ErrorScreensHistogramHelper> histogram_helper_; - std::unique_ptr<LoginFeedback> login_feedback_; - std::unique_ptr<AccountId> focused_pod_account_id_; base::Optional<system::SystemClock::ScopedHourClockType> focused_user_clock_type_;
diff --git a/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom b/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom index 0a05fca..6efafdd6 100644 --- a/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom +++ b/chrome/browser/ui/webui/internals/web_app/web_app_internals.mojom
@@ -15,6 +15,51 @@ string debug_info; }; +struct DisabledConfig { + // The string representation of the config. + string config; + + // The reason the config was disabled. + string reason; +}; + +struct InstallResult { + // The install_url of the config being installed. + string install_url; + + // The InstallResultCode returned by the installation process. + string install_result_code; +}; + +struct UninstallResult { + // The install_url of the config being uninstalled. + string install_url; + + // Whether the uninstallation was successful. + bool is_success; +}; + +struct PreinstalledWebAppDebugInfo { + // Whether preinstalled web apps have completed start up synchronization. + bool is_start_up_task_complete; + + // Errors encountered when parsing preinstalled web app configs. + array<string> parse_errors; + + // String representations of enabled preinstalled app configs. + array<string> enabled_configs; + + // String representations of disabled preinstalled app configs plus the reason + // why they are disabled. + array<DisabledConfig> disabled_configs; + + // The results of any new preinstalled app installations. + array<InstallResult> install_results; + + // The results of any preinstalled app removals. + array<UninstallResult> uninstall_results; +}; + // Provides access to browser side internal information about installed web apps // (also known as PWAs) for chrome://internals/web-app. interface WebAppInternalsPageHandler { @@ -24,6 +69,9 @@ // Returns details of all the installed web apps for the current profile. GetWebApps() => (array<WebApp> web_app_list); + // Returns debug information about the state of preinstalled web apps. + GetPreinstalledWebAppDebugInfo() => (PreinstalledWebAppDebugInfo? status); + // Returns the prefs used for keeping track of non-user installed web apps. GetExternallyInstalledWebAppPrefs() => (string externally_installed_web_app_prefs);
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 8fe88ca..339fc5a 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
@@ -2,13 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <sstream> - #include "chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h" +#include <sstream> +#include <utility> + #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/web_applications/components/web_app_provider_base.h" +#include "chrome/browser/web_applications/components/web_app_constants.h" +#include "chrome/browser/web_applications/external_web_app_manager.h" #include "chrome/browser/web_applications/web_app.h" +#include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" @@ -16,6 +19,15 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui_data_source.h" +namespace { + +template <typename T> +std::string ConvertToString(const T& value) { + return (std::stringstream() << value).str(); +} + +} // namespace + WebAppInternalsPageHandlerImpl::WebAppInternalsPageHandlerImpl(Profile* profile) : profile_(profile) {} @@ -37,7 +49,7 @@ } void WebAppInternalsPageHandlerImpl::GetWebApps(GetWebAppsCallback callback) { - auto* provider = web_app::WebAppProviderBase::GetProviderBase(profile_); + auto* provider = web_app::WebAppProvider::Get(profile_); if (!provider) { std::move(callback).Run({}); return; @@ -52,22 +64,73 @@ std::vector<mojom::web_app_internals::WebAppPtr> result; for (const web_app::WebApp& web_app : registrar->GetAppsIncludingStubs()) { - mojom::web_app_internals::WebAppPtr info( - mojom::web_app_internals::WebApp::New()); + auto info = mojom::web_app_internals::WebApp::New(); info->name = web_app.name(); info->id = web_app.app_id(); - std::stringstream ss; - ss << web_app; - info->debug_info = ss.str(); + info->debug_info = ConvertToString(web_app); result.push_back(std::move(info)); } std::move(callback).Run(std::move(result)); } +void WebAppInternalsPageHandlerImpl::GetPreinstalledWebAppDebugInfo( + GetPreinstalledWebAppDebugInfoCallback callback) { + auto* provider = web_app::WebAppProvider::Get(profile_); + if (!provider) { + std::move(callback).Run({}); + return; + } + + const web_app::ExternalWebAppManager::DebugInfo* debug_info = + provider->external_web_app_manager().debug_info(); + if (!debug_info) { + std::move(callback).Run({}); + return; + } + + auto info = mojom::web_app_internals::PreinstalledWebAppDebugInfo::New(); + + info->is_start_up_task_complete = debug_info->is_start_up_task_complete; + + info->parse_errors = debug_info->parse_errors; + + for (const web_app::ExternalInstallOptions& config : + debug_info->enabled_configs) { + info->enabled_configs.push_back(ConvertToString(config)); + } + + for (const std::pair<web_app::ExternalInstallOptions, std::string>& + disabled_config : debug_info->disabled_configs) { + auto disabled_config_info = mojom::web_app_internals::DisabledConfig::New(); + disabled_config_info->config = ConvertToString(disabled_config.first); + disabled_config_info->reason = disabled_config.second; + info->disabled_configs.push_back(std::move(disabled_config_info)); + } + + for (std::pair<const GURL&, const web_app::InstallResultCode&> + install_result : debug_info->install_results) { + auto install_result_info = mojom::web_app_internals::InstallResult::New(); + install_result_info->install_url = install_result.first.spec(); + install_result_info->install_result_code = + ConvertToString(install_result.second); + info->install_results.push_back(std::move(install_result_info)); + } + + for (std::pair<const GURL&, const bool&> uninstall_result : + debug_info->uninstall_results) { + auto uninstall_result_info = + mojom::web_app_internals::UninstallResult::New(); + uninstall_result_info->install_url = uninstall_result.first.spec(); + uninstall_result_info->is_success = uninstall_result.second; + info->uninstall_results.push_back(std::move(uninstall_result_info)); + } + + std::move(callback).Run(std::move(info)); +} + void WebAppInternalsPageHandlerImpl::GetExternallyInstalledWebAppPrefs( GetExternallyInstalledWebAppPrefsCallback callback) { - std::stringstream ss; - ss << *profile_->GetPrefs()->GetDictionary(prefs::kWebAppsExtensionIDs); - std::move(callback).Run(ss.str()); + std::move(callback).Run(ConvertToString( + *profile_->GetPrefs()->GetDictionary(prefs::kWebAppsExtensionIDs))); }
diff --git a/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h b/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h index ac2d034..b962b6f 100644 --- a/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h +++ b/chrome/browser/ui/webui/internals/web_app/web_app_internals_page_handler_impl.h
@@ -29,6 +29,8 @@ // mojom::web_app_internals::WebAppInternalsPageHandler: void IsBmoEnabled(IsBmoEnabledCallback callback) override; void GetWebApps(GetWebAppsCallback callback) override; + void GetPreinstalledWebAppDebugInfo( + GetPreinstalledWebAppDebugInfoCallback callback) override; void GetExternallyInstalledWebAppPrefs( GetExternallyInstalledWebAppPrefsCallback callback) override;
diff --git a/chrome/browser/ui/webui/settings/chromeos/people_section.cc b/chrome/browser/ui/webui/settings/chromeos/people_section.cc index 45789c43..2a24cde 100644 --- a/chrome/browser/ui/webui/settings/chromeos/people_section.cc +++ b/chrome/browser/ui/webui/settings/chromeos/people_section.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/chromeos/account_manager/account_manager_util.h" #include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/supervised_user/supervised_user_service.h" #include "chrome/browser/ui/ui_features.h" @@ -52,6 +53,7 @@ #include "services/network/public/mojom/content_security_policy.mojom.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" +#include "ui/chromeos/devicetype_utils.h" #include "ui/chromeos/resources/grit/ui_chromeos_resources.h" namespace chromeos { @@ -329,16 +331,20 @@ return *tags; } -void AddAccountManagerPageStrings(content::WebUIDataSource* html_source) { +void AddAccountManagerPageStrings(content::WebUIDataSource* html_source, + Profile* profile) { static constexpr webui::LocalizedString kLocalizedStrings[] = { - {"accountManagerDescription", IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION}, + {"accountManagerPrimaryAccountDescription", + IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_DESCRIPTION}, {"accountManagerChildDescription", IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_DESCRIPTION}, {"accountManagerChildFirstMessage", IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_FIRST_MESSAGE}, {"accountManagerChildSecondMessage", IDS_SETTINGS_ACCOUNT_MANAGER_CHILD_SECOND_MESSAGE}, - {"accountListHeader", IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER}, + {"accountListTooltip", IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP}, + {"accountListTooltipNoSecondaryAccounts", + IDS_SETTINGS_ACCOUNT_MANAGER_LIST_TOOLTIP_NO_SECONDARY_ACCOUNTS}, {"accountManagerPrimaryAccountTooltip", IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_TOOLTIP}, {"accountManagerEducationAccountLabel", @@ -373,11 +379,34 @@ html_source->AddString("accountManagerLearnMoreUrl", chrome::kAccountManagerLearnMoreURL); - html_source->AddLocalizedString( - "addAccountLabel", chromeos::features::IsAccountManagementFlowsV2Enabled() - ? IDS_SETTINGS_ACCOUNT_MANAGER_ADD_ACCOUNT_LABEL_V2 - : IDS_SETTINGS_ACCOUNT_MANAGER_ADD_ACCOUNT_LABEL); + "accountManagerManagementDescription", + profile->IsChild() ? IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS_CHILD + : IDS_SETTINGS_ACCOUNT_MANAGER_MANAGEMENT_STATUS); + html_source->AddString("accountManagerChromeUIManagementURL", + base::UTF8ToUTF16(chrome::kChromeUIManagementURL)); + + if (chromeos::features::IsAccountManagementFlowsV2Enabled()) { + static constexpr webui::LocalizedString kLocalizedStringsV2[] = { + {"addAccountLabel", IDS_SETTINGS_ACCOUNT_MANAGER_ADD_ACCOUNT_LABEL_V2}, + {"accountListHeader", IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_V2}, + {"accountListHeaderChild", + IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER_CHILD}, + }; + AddLocalizedStringsBulk(html_source, kLocalizedStringsV2); + + html_source->AddString( + "accountManagerDescription", + l10n_util::GetStringFUTF16(IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION_V2, + ui::GetChromeOSDeviceName())); + } else { + static constexpr webui::LocalizedString kLocalizedStringsV1[] = { + {"accountManagerDescription", IDS_SETTINGS_ACCOUNT_MANAGER_DESCRIPTION}, + {"addAccountLabel", IDS_SETTINGS_ACCOUNT_MANAGER_ADD_ACCOUNT_LABEL}, + {"accountListHeader", IDS_SETTINGS_ACCOUNT_MANAGER_LIST_HEADER}, + }; + AddLocalizedStringsBulk(html_source, kLocalizedStringsV1); + } } void AddLockScreenPageStrings(content::WebUIDataSource* html_source, @@ -757,16 +786,13 @@ }; AddLocalizedStringsBulk(html_source, kLocalizedStrings); - html_source->AddBoolean( - "isAccountManagementFlowsV2Enabled", - chromeos::features::IsAccountManagementFlowsV2Enabled()); + user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile()); + DCHECK(user); + if (chromeos::features::IsAccountManagementFlowsV2Enabled()) { html_source->AddLocalizedString("osPeoplePageTitle", IDS_OS_SETTINGS_PEOPLE_V2); - user_manager::User* user = - ProfileHelper::Get()->GetUserByProfile(profile()); - DCHECK(user); // This string is not used if the flag is disabled. html_source->AddString("osProfileName", l10n_util::GetStringFUTF16( IDS_OS_SETTINGS_PROFILE_NAME, @@ -786,6 +812,13 @@ // Toggles the Chrome OS Account Manager submenu in the People section. html_source->AddBoolean("isAccountManagerEnabled", account_manager_ != nullptr); + html_source->AddBoolean( + "isAccountManagementFlowsV2Enabled", + chromeos::features::IsAccountManagementFlowsV2Enabled()); + html_source->AddBoolean( + "isDeviceAccountManaged", + user->IsActiveDirectoryUser() || + profile()->GetProfilePolicyConnector()->IsManaged()); if (chromeos::features::ShouldUseBrowserSyncConsent()) { static constexpr webui::LocalizedString kTurnOffStrings[] = { @@ -822,7 +855,7 @@ "driveSuggestAvailable", base::FeatureList::IsEnabled(omnibox::kDocumentProvider)); - AddAccountManagerPageStrings(html_source); + AddAccountManagerPageStrings(html_source, profile()); KerberosAccountsHandler::AddLoadTimeKerberosStrings( html_source, kerberos_credentials_manager_); AddLockScreenPageStrings(html_source, profile()->GetPrefs());
diff --git a/chrome/browser/ui/webui/settings/safety_check_handler.cc b/chrome/browser/ui/webui/settings/safety_check_handler.cc index 65063ade..be940e1 100644 --- a/chrome/browser/ui/webui/settings/safety_check_handler.cc +++ b/chrome/browser/ui/webui/settings/safety_check_handler.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/ui/webui/settings/safety_check_handler.h" #include "base/bind.h" +#include "base/feature_list.h" #include "base/i18n/number_formatting.h" #include "base/macros.h" #include "base/metrics/histogram_functions.h" @@ -19,6 +20,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/version_ui.h" #include "chrome/common/channel_info.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/chromium_strings.h" @@ -649,9 +651,19 @@ base::FormatNumber(total.value())); } case PasswordsStatus::kSafe: + // TODO(crbug.com/1128904): Clean up the old code path. + if (!base::FeatureList::IsEnabled(features::kSafetyCheckWeakPasswords)) { + return l10n_util::GetPluralStringFUTF16( + IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT, 0); + } return l10n_util::GetStringUTF16( IDS_SETTINGS_SAFETY_CHECK_PASSWORDS_SAFE); case PasswordsStatus::kCompromisedExist: + // TODO(crbug.com/1128904): Clean up the old code path. + if (!base::FeatureList::IsEnabled(features::kSafetyCheckWeakPasswords)) { + return l10n_util::GetPluralStringFUTF16( + IDS_SETTINGS_COMPROMISED_PASSWORDS_COUNT, compromised.value()); + } if (weak.value() == 0) { // Only compromised passwords, no weak passwords. return l10n_util::GetPluralStringFUTF16( @@ -874,7 +886,10 @@ size_t num_compromised = passwords_delegate_->GetCompromisedCredentials().size(); size_t num_weak = passwords_delegate_->GetWeakCredentials().size(); - if (num_compromised == 0 && num_weak == 0) { + // TODO(crbug.com/1128904): Clean up the old code path. + if (num_compromised == 0 && + (num_weak == 0 || + !base::FeatureList::IsEnabled(features::kSafetyCheckWeakPasswords))) { // If there are no |OnCredentialDone| callbacks with is_leaked = true, no // need to wait for InsecureCredentialsManager callbacks any longer, since // there should be none for the current password check.
diff --git a/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc b/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc index 2a01caa..2270f7d 100644 --- a/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/safety_check_handler_unittest.cc
@@ -16,6 +16,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/metrics/user_action_tester.h" +#include "base/test/scoped_feature_list.h" #include "base/types/strong_alias.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -24,6 +25,7 @@ #include "chrome/browser/extensions/test_extension_service.h" #include "chrome/browser/ui/webui/help/test_version_updater.h" #include "chrome/common/channel_info.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/extensions/api/passwords_private.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/crx_file/id_util.h" @@ -299,6 +301,7 @@ content::TestWebUI test_web_ui_; std::unique_ptr<TestingSafetyCheckHandler> safety_check_; base::HistogramTester histogram_tester_; + base::test::ScopedFeatureList feature_list_; #if defined(OS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) TestChromeCleanerControllerDelegate test_chrome_cleaner_controller_delegate_; #endif @@ -307,6 +310,8 @@ void SafetyCheckHandlerTest::SetUp() { ChromeRenderViewHostTestHarness::SetUp(); + feature_list_.InitWithFeatures({features::kSafetyCheckWeakPasswords}, {}); + // The unique pointer to a TestVersionUpdater gets moved to // SafetyCheckHandler, but a raw pointer is retained here to change its // state.
diff --git a/chrome/browser/web_applications/components/external_install_options.cc b/chrome/browser/web_applications/components/external_install_options.cc index 752583b..674ab3f 100644 --- a/chrome/browser/web_applications/components/external_install_options.cc +++ b/chrome/browser/web_applications/components/external_install_options.cc
@@ -35,39 +35,45 @@ bool ExternalInstallOptions::operator==( const ExternalInstallOptions& other) const { - return std::tie(install_url, user_display_mode, install_source, - add_to_applications_menu, add_to_desktop, - add_to_quick_launch_bar, add_to_search, add_to_management, - run_on_os_login, is_disabled, - override_previous_user_uninstall, only_for_new_users, - user_type_allowlist, gate_on_feature, + auto AsTuple = [](const ExternalInstallOptions& options) { + // Keep in order declared in external_install_options.h. + return std::tie( + // clang-format off + options.install_url, + options.user_display_mode, + options.install_source, + options.add_to_applications_menu, + options.add_to_desktop, + options.add_to_quick_launch_bar, + options.add_to_search, + options.add_to_management, + options.run_on_os_login, + options.is_disabled, + options.override_previous_user_uninstall, + options.only_for_new_users, + options.user_type_allowlist, + options.gate_on_feature, #if BUILDFLAG(IS_CHROMEOS_ASH) - disable_if_arc_supported, disable_if_tablet_form_factor, + options.disable_if_arc_supported, + options.disable_if_tablet_form_factor, #endif // BUILDFLAG(IS_CHROMEOS_ASH) - bypass_service_worker_check, require_manifest, - force_reinstall, wait_for_windows_closed, install_placeholder, - reinstall_placeholder, launch_query_params, - load_and_await_service_worker_registration, - service_worker_registration_url, uninstall_and_replace, - additional_search_terms, only_use_app_info_factory) == - std::tie( - other.install_url, other.user_display_mode, other.install_source, - other.add_to_applications_menu, other.add_to_desktop, - other.add_to_quick_launch_bar, other.add_to_search, - other.add_to_management, other.run_on_os_login, other.is_disabled, - other.override_previous_user_uninstall, other.only_for_new_users, - other.user_type_allowlist, other.gate_on_feature, -#if BUILDFLAG(IS_CHROMEOS_ASH) - other.disable_if_arc_supported, - other.disable_if_tablet_form_factor, -#endif // BUILDFLAG(IS_CHROMEOS_ASH) - other.bypass_service_worker_check, other.require_manifest, - other.force_reinstall, other.wait_for_windows_closed, - other.install_placeholder, other.reinstall_placeholder, - other.launch_query_params, - other.load_and_await_service_worker_registration, - other.service_worker_registration_url, other.uninstall_and_replace, - other.additional_search_terms, other.only_use_app_info_factory); + options.bypass_service_worker_check, + options.require_manifest, + options.force_reinstall, + options.wait_for_windows_closed, + options.install_placeholder, + options.reinstall_placeholder, + options.launch_query_params, + options.load_and_await_service_worker_registration, + options.service_worker_registration_url, + options.uninstall_and_replace, + options.additional_search_terms, + options.only_use_app_info_factory, + options.app_info_factory + // clang-format on + ); + }; + return AsTuple(*this) == AsTuple(other); } namespace { @@ -99,8 +105,7 @@ const ExternalInstallOptions& install_options) { return out << "install_url: " << install_options.install_url - << "\n user_display_mode: " - << static_cast<int32_t>(install_options.user_display_mode) + << "\n user_display_mode: " << install_options.user_display_mode << "\n install_source: " << static_cast<int32_t>(install_options.install_source) << "\n add_to_applications_menu: " @@ -137,12 +142,13 @@ << install_options.load_and_await_service_worker_registration << "\n service_worker_registration_url: " << install_options.service_worker_registration_url.value_or(GURL()) - << "\n uninstall_and_replace:\n " - << base::JoinString(install_options.uninstall_and_replace, "\n ") - << "\n only_use_app_info_factory:\n " - << install_options.only_use_app_info_factory - << "\n additional_search_terms:\n " - << base::JoinString(install_options.additional_search_terms, "\n "); + << "\n uninstall_and_replace:\n " + << base::JoinString(install_options.uninstall_and_replace, "\n ") + << "\n additional_search_terms:\n " + << base::JoinString(install_options.additional_search_terms, "\n ") + << "\n only_use_app_info_factory: " + << install_options.only_use_app_info_factory << "\n app_info_factory: " + << !install_options.app_info_factory.is_null(); } InstallManager::InstallParams ConvertExternalInstallOptionsToParams(
diff --git a/chrome/browser/web_applications/components/os_integration_manager.cc b/chrome/browser/web_applications/components/os_integration_manager.cc index 104df09f..898bb480 100644 --- a/chrome/browser/web_applications/components/os_integration_manager.cc +++ b/chrome/browser/web_applications/components/os_integration_manager.cc
@@ -178,39 +178,46 @@ scoped_refptr<OsHooksBarrier> barrier = base::MakeRefCounted<OsHooksBarrier>(os_hooks, std::move(callback)); - if (os_hooks[OsHookType::kShortcutsMenu]) { - bool success = UnregisterShortcutsMenu(app_id); + if (os_hooks[OsHookType::kShortcutsMenu] && + ShouldRegisterShortcutsMenuWithOs()) { + bool success = UnregisterShortcutsMenuWithOs(app_id, profile_->GetPath()); if (!success) barrier->OnError(OsHookType::kShortcutsMenu); } if (os_hooks[OsHookType::kShortcuts] || os_hooks[OsHookType::kRunOnOsLogin]) { - std::unique_ptr<ShortcutInfo> shortcut_info = BuildShortcutInfo(app_id); + std::unique_ptr<ShortcutInfo> shortcut_info = + shortcut_manager_->BuildShortcutInfo(app_id); base::FilePath shortcut_data_dir = internals::GetShortcutDataDir(*shortcut_info); if (os_hooks[OsHookType::kRunOnOsLogin] && base::FeatureList::IsEnabled(features::kDesktopPWAsRunOnOsLogin)) { - UnregisterRunOnOsLogin( + ScheduleUnregisterRunOnOsLogin( shortcut_info->profile_path, shortcut_info->title, barrier->CreateBarrierCallbackForType(OsHookType::kRunOnOsLogin)); } if (os_hooks[OsHookType::kShortcuts]) { - DeleteShortcuts( - app_id, shortcut_data_dir, std::move(shortcut_info), - barrier->CreateBarrierCallbackForType(OsHookType::kShortcuts)); + internals::ScheduleDeletePlatformShortcuts( + shortcut_data_dir, std::move(shortcut_info), + base::BindOnce( + &OsIntegrationManager::OnShortcutsDeleted, + weak_ptr_factory_.GetWeakPtr(), app_id, + barrier->CreateBarrierCallbackForType(OsHookType::kShortcuts))); } } // TODO(https://crbug.com/1108109) we should return the result of file handler // unregistration and record errors during unregistration. if (os_hooks[OsHookType::kFileHandlers]) - UnregisterFileHandlers(app_id); + file_handler_manager_->DisableAndUnregisterOsFileHandlers(app_id); // There is a chance uninstallation point was created with feature flag // enabled so we need to clean it up regardless of feature flag state. - if (os_hooks[OsHookType::kUninstallationViaOsSettings]) - UnregisterWebAppOsUninstallation(app_id); + if (os_hooks[OsHookType::kUninstallationViaOsSettings] && + ShouldRegisterUninstallationViaOsSettingsWithOs()) { + UnegisterUninstallationViaOsSettingsWithOs(app_id, profile_); + } } void OsIntegrationManager::UpdateOsHooks( @@ -332,8 +339,6 @@ shortcuts_menu_item_infos, const ShortcutsMenuIconsBitmaps& shortcuts_menu_icons_bitmaps, base::OnceCallback<void(bool success)> callback) { - if (!ShouldRegisterShortcutsMenuWithOs()) - std::move(callback).Run(true); shortcut_manager_->RegisterShortcutsMenuWithOs( app_id, shortcuts_menu_item_infos, shortcuts_menu_icons_bitmaps); @@ -346,9 +351,6 @@ void OsIntegrationManager::ReadAllShortcutsMenuIconsAndRegisterShortcutsMenu( const AppId& app_id, base::OnceCallback<void(bool success)> callback) { - if (!ShouldRegisterShortcutsMenuWithOs()) - std::move(callback).Run(true); - shortcut_manager_->ReadAllShortcutsMenuIconsAndRegisterShortcutsMenu( app_id, std::move(callback)); } @@ -387,48 +389,6 @@ } } -bool OsIntegrationManager::UnregisterShortcutsMenu(const AppId& app_id) { - if (!ShouldRegisterShortcutsMenuWithOs()) - return true; - return UnregisterShortcutsMenuWithOs(app_id, profile_->GetPath()); -} - -void OsIntegrationManager::UnregisterRunOnOsLogin( - const base::FilePath& profile_path, - const base::string16& shortcut_title, - UnregisterRunOnOsLoginCallback callback) { - ScheduleUnregisterRunOnOsLogin(profile_path, shortcut_title, - std::move(callback)); -} - -void OsIntegrationManager::DeleteShortcuts( - const AppId& app_id, - const base::FilePath& shortcuts_data_dir, - std::unique_ptr<ShortcutInfo> shortcut_info, - DeleteShortcutsCallback callback) { - internals::ScheduleDeletePlatformShortcuts( - shortcuts_data_dir, std::move(shortcut_info), - base::BindOnce(&OsIntegrationManager::OnShortcutsDeleted, - weak_ptr_factory_.GetWeakPtr(), app_id, - std::move(callback))); -} - -void OsIntegrationManager::UnregisterFileHandlers(const AppId& app_id) { - file_handler_manager_->DisableAndUnregisterOsFileHandlers(app_id); -} - -void OsIntegrationManager::UnregisterWebAppOsUninstallation( - const AppId& app_id) { - if (ShouldRegisterUninstallationViaOsSettingsWithOs()) - UnegisterUninstallationViaOsSettingsWithOs(app_id, profile_); -} - -std::unique_ptr<ShortcutInfo> OsIntegrationManager::BuildShortcutInfo( - const AppId& app_id) { - DCHECK(shortcut_manager_); - return shortcut_manager_->BuildShortcutInfo(app_id); -} - void OsIntegrationManager::OnShortcutsCreated( const AppId& app_id, std::unique_ptr<WebApplicationInfo> web_app_info,
diff --git a/chrome/browser/web_applications/components/os_integration_manager.h b/chrome/browser/web_applications/components/os_integration_manager.h index ad5df33a..b768b99 100644 --- a/chrome/browser/web_applications/components/os_integration_manager.h +++ b/chrome/browser/web_applications/components/os_integration_manager.h
@@ -160,7 +160,6 @@ bool add_to_desktop, CreateShortcutsCallback callback); - // Installation: virtual void RegisterFileHandlers( const AppId& app_id, base::OnceCallback<void(bool success)> callback); @@ -180,21 +179,6 @@ virtual void RegisterWebAppOsUninstallation(const AppId& app_id, const std::string& name); - // Uninstallation: - virtual bool UnregisterShortcutsMenu(const AppId& app_id); - virtual void UnregisterRunOnOsLogin(const base::FilePath& profile_path, - const base::string16& shortcut_title, - UnregisterRunOnOsLoginCallback callback); - virtual void DeleteShortcuts(const AppId& app_id, - const base::FilePath& shortcuts_data_dir, - std::unique_ptr<ShortcutInfo> shortcut_info, - DeleteShortcutsCallback callback); - virtual void UnregisterFileHandlers(const AppId& app_id); - virtual void UnregisterWebAppOsUninstallation(const AppId& app_id); - - // Utility mathods: - virtual std::unique_ptr<ShortcutInfo> BuildShortcutInfo(const AppId& app_id); - private: class OsHooksBarrier;
diff --git a/chrome/browser/web_applications/components/os_integration_manager_unittest.cc b/chrome/browser/web_applications/components/os_integration_manager_unittest.cc index 0ef6c71..ec0bb7a 100644 --- a/chrome/browser/web_applications/components/os_integration_manager_unittest.cc +++ b/chrome/browser/web_applications/components/os_integration_manager_unittest.cc
@@ -7,29 +7,23 @@ #include <memory> #include "base/bind.h" -#include "base/files/file_path.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/gmock_callback_support.h" #include "base/test/task_environment.h" -#include "build/build_config.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/web_app.h" -#include "chrome/common/chrome_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" namespace web_app { -namespace { - class MockOsIntegrationManager : public OsIntegrationManager { public: MockOsIntegrationManager() : OsIntegrationManager(nullptr, nullptr, nullptr, nullptr) {} ~MockOsIntegrationManager() override = default; - // Installation: MOCK_METHOD(void, CreateShortcuts, (const AppId& app_id, @@ -74,65 +68,12 @@ RegisterWebAppOsUninstallation, (const AppId& app_id, const std::string& name), (override)); - - // Uninstallation: - MOCK_METHOD(bool, UnregisterShortcutsMenu, (const AppId& app_id), (override)); - MOCK_METHOD(void, - UnregisterRunOnOsLogin, - (const base::FilePath& profile_path, - const base::string16& shortcut_title, - UnregisterRunOnOsLoginCallback callback), - (override)); - MOCK_METHOD(void, - DeleteShortcuts, - (const AppId& app_id, - const base::FilePath& shortcuts_data_dir, - std::unique_ptr<ShortcutInfo> shortcut_info, - DeleteShortcutsCallback callback), - (override)); - MOCK_METHOD(void, UnregisterFileHandlers, (const AppId& app_id), (override)); - MOCK_METHOD(void, - UnregisterWebAppOsUninstallation, - (const AppId& app_id), - (override)); - - // Utility methods: - MOCK_METHOD(std::unique_ptr<ShortcutInfo>, - BuildShortcutInfo, - (const AppId& app_id), - (override)); }; -#if defined(OS_WIN) -const base::FilePath::CharType kFakeProfilePath[] = - FILE_PATH_LITERAL("\\profile\\path"); -#else -const base::FilePath::CharType kFakeProfilePath[] = - FILE_PATH_LITERAL("/profile/path"); -#endif // defined(OS_WIN) - -const char kFakeAppUrl[] = "https://fake.com"; - -std::unique_ptr<ShortcutInfo> CreateTestShorcutInfo( - const web_app::AppId& app_id) { - auto shortcut_info = std::make_unique<ShortcutInfo>(); - shortcut_info->profile_path = base::FilePath(kFakeProfilePath); - shortcut_info->extension_id = app_id; - shortcut_info->url = GURL(kFakeAppUrl); - return shortcut_info; -} - -class OsIntegrationManagerTest : public testing::Test { - public: - OsIntegrationManagerTest() = default; - ~OsIntegrationManagerTest() override = default; - - private: +TEST(OsIntegrationManagerTest, InstallOsHooksOnlyShortcuts) { base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::MainThreadType::UI}; -}; -TEST_F(OsIntegrationManagerTest, InstallOsHooksOnlyShortcuts) { base::RunLoop run_loop; OsHooksResults install_results; @@ -157,7 +98,10 @@ EXPECT_TRUE(install_results[OsHookType::kShortcuts]); } -TEST_F(OsIntegrationManagerTest, InstallOsHooksEverything) { +TEST(OsIntegrationManagerTest, InstallOsHooksEverything) { + base::test::TaskEnvironment task_environment_{ + base::test::TaskEnvironment::MainThreadType::UI}; + base::RunLoop run_loop; OsHooksResults install_results; @@ -179,7 +123,7 @@ EXPECT_CALL(manager, AddAppToQuickLaunchBar(app_id)).Times(1); EXPECT_CALL(manager, ReadAllShortcutsMenuIconsAndRegisterShortcutsMenu( app_id, testing::_)) - .WillOnce(base::test::RunOnceCallback<1>(true)); + .Times(1); InstallOsHooksOptions options; options.add_to_desktop = true; @@ -197,44 +141,4 @@ EXPECT_TRUE(install_results[OsHookType::kShortcutsMenu]); EXPECT_TRUE(install_results[OsHookType::kUninstallationViaOsSettings]); } - -TEST_F(OsIntegrationManagerTest, UninstallOsHooksEverything) { - base::RunLoop run_loop; - - OsHooksResults uninstall_results; - UninstallOsHooksCallback callback = - base::BindLambdaForTesting([&](OsHooksResults results) { - uninstall_results = results; - run_loop.Quit(); - }); - - const AppId app_id = "test"; - - const base::FilePath kExpectedShortcutPath = - base::FilePath(kFakeProfilePath) - .Append(chrome::kWebAppDirname) - .AppendASCII("_crx_test"); - - testing::StrictMock<MockOsIntegrationManager> manager; - EXPECT_CALL(manager, BuildShortcutInfo(app_id)) - .WillOnce( - testing::Return(testing::ByMove(CreateTestShorcutInfo(app_id)))); - EXPECT_CALL(manager, DeleteShortcuts(app_id, kExpectedShortcutPath, - testing::_, testing::_)) - .WillOnce(base::test::RunOnceCallback<3>(true)); - EXPECT_CALL(manager, UnregisterFileHandlers(app_id)).Times(1); - EXPECT_CALL(manager, UnregisterWebAppOsUninstallation(app_id)).Times(1); - EXPECT_CALL(manager, UnregisterShortcutsMenu(app_id)) - .WillOnce(testing::Return(true)); - - manager.UninstallAllOsHooks(app_id, std::move(callback)); - run_loop.Run(); - EXPECT_TRUE(uninstall_results[OsHookType::kShortcuts]); - EXPECT_TRUE(uninstall_results[OsHookType::kFileHandlers]); - EXPECT_TRUE(uninstall_results[OsHookType::kRunOnOsLogin]); - EXPECT_TRUE(uninstall_results[OsHookType::kShortcutsMenu]); - EXPECT_TRUE(uninstall_results[OsHookType::kUninstallationViaOsSettings]); -} - -} // namespace } // namespace web_app
diff --git a/chrome/browser/web_applications/components/pending_app_manager.cc b/chrome/browser/web_applications/components/pending_app_manager.cc index 477590c..be5db1b6 100644 --- a/chrome/browser/web_applications/components/pending_app_manager.cc +++ b/chrome/browser/web_applications/components/pending_app_manager.cc
@@ -17,12 +17,6 @@ namespace web_app { -bool PendingAppManager::InstallResult::operator==( - const InstallResult& other) const { - return std::tie(code, did_uninstall_and_replace) == - std::tie(other.code, other.did_uninstall_and_replace); -} - PendingAppManager::SynchronizeRequest::SynchronizeRequest( SynchronizeCallback callback, int remaining_requests) @@ -89,7 +83,7 @@ if (urls_to_remove.empty() && desired_apps_install_options.empty()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(std::move(callback), std::map<GURL, InstallResult>(), + base::BindOnce(std::move(callback), std::map<GURL, InstallResultCode>(), std::map<GURL, bool>())); return; } @@ -133,17 +127,16 @@ void PendingAppManager::InstallForSynchronizeCallback( ExternalInstallSource source, const GURL& app_url, - PendingAppManager::InstallResult result) { - if (!IsSuccess(result.code)) { + InstallResultCode code) { + if (!IsSuccess(code)) { LOG(ERROR) << app_url << " from install source " << static_cast<int>(source) - << " failed to install with reason " - << static_cast<int>(result.code); + << " failed to install with reason " << static_cast<int>(code); } auto source_and_request = synchronize_requests_.find(source); DCHECK(source_and_request != synchronize_requests_.end()); SynchronizeRequest& request = source_and_request->second; - request.install_results[app_url] = result; + request.install_results[app_url] = code; OnAppSynchronized(source, app_url); }
diff --git a/chrome/browser/web_applications/components/pending_app_manager.h b/chrome/browser/web_applications/components/pending_app_manager.h index 5ba6cd31..cc9151d 100644 --- a/chrome/browser/web_applications/components/pending_app_manager.h +++ b/chrome/browser/web_applications/components/pending_app_manager.h
@@ -38,23 +38,18 @@ // should wait for the update request to finish before uninstalling the app. class PendingAppManager { public: - struct InstallResult { - InstallResultCode code; - bool did_uninstall_and_replace = false; - bool operator==(const InstallResult& other) const; - }; - using OnceInstallCallback = - base::OnceCallback<void(const GURL& app_url, InstallResult result)>; + base::OnceCallback<void(const GURL& app_url, InstallResultCode code)>; using RepeatingInstallCallback = - base::RepeatingCallback<void(const GURL& app_url, InstallResult result)>; + base::RepeatingCallback<void(const GURL& app_url, + InstallResultCode code)>; using RegistrationCallback = base::RepeatingCallback<void(const GURL& launch_url, RegistrationResultCode code)>; using UninstallCallback = base::RepeatingCallback<void(const GURL& app_url, bool succeeded)>; using SynchronizeCallback = - base::OnceCallback<void(std::map<GURL, InstallResult> install_results, + base::OnceCallback<void(std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results)>; PendingAppManager(); @@ -149,14 +144,14 @@ SynchronizeCallback callback; int remaining_requests; - std::map<GURL, InstallResult> install_results; + std::map<GURL, InstallResultCode> install_results; std::map<GURL, bool> uninstall_results; }; void InstallForSynchronizeCallback(ExternalInstallSource source, const GURL& app_url, - PendingAppManager::InstallResult result); + InstallResultCode code); void UninstallForSynchronizeCallback(ExternalInstallSource source, const GURL& app_url, bool succeeded);
diff --git a/chrome/browser/web_applications/components/pending_app_manager_unittest.cc b/chrome/browser/web_applications/components/pending_app_manager_unittest.cc index 65d8b6767..dfd8b928 100644 --- a/chrome/browser/web_applications/components/pending_app_manager_unittest.cc +++ b/chrome/browser/web_applications/components/pending_app_manager_unittest.cc
@@ -39,8 +39,7 @@ std::move(install_options_list), ExternalInstallSource::kInternalDefault, base::BindLambdaForTesting( - [&run_loop, urls](std::map<GURL, PendingAppManager::InstallResult> - install_results, + [&run_loop, urls](std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { run_loop.Quit(); })); @@ -115,8 +114,7 @@ std::move(install_options_list), ExternalInstallSource::kInternalDefault, base::BindLambdaForTesting( - [&](std::map<GURL, PendingAppManager::InstallResult> - install_results, + [&](std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { run_loop.Quit(); })); run_loop.Run(); }
diff --git a/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc b/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc index 83e3505..98a61ab 100644 --- a/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc +++ b/chrome/browser/web_applications/components/policy/web_app_policy_manager.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" -#include "base/metrics/histogram_functions.h" #include "base/values.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/web_applications/components/external_install_options.h" @@ -167,16 +166,14 @@ } void WebAppPolicyManager::OnAppsSynchronized( - std::map<GURL, PendingAppManager::InstallResult> install_results, + std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { is_refreshing_ = false; if (needs_refresh_) RefreshPolicyInstalledApps(); - for (const auto& url_and_result : install_results) { - base::UmaHistogramEnumeration(kInstallResultHistogramName, - url_and_result.second.code); - } + RecordExternalAppInstallResultCode(kInstallResultHistogramName, + install_results); } } // namespace web_app
diff --git a/chrome/browser/web_applications/components/policy/web_app_policy_manager.h b/chrome/browser/web_applications/components/policy/web_app_policy_manager.h index 2e4de42..f0e7392 100644 --- a/chrome/browser/web_applications/components/policy/web_app_policy_manager.h +++ b/chrome/browser/web_applications/components/policy/web_app_policy_manager.h
@@ -51,9 +51,8 @@ void InitChangeRegistrarAndRefreshPolicyInstalledApps(); void RefreshPolicyInstalledApps(); - void OnAppsSynchronized( - std::map<GURL, PendingAppManager::InstallResult> install_results, - std::map<GURL, bool> uninstall_results); + void OnAppsSynchronized(std::map<GURL, InstallResultCode> install_results, + std::map<GURL, bool> uninstall_results); Profile* profile_; PrefService* pref_service_;
diff --git a/chrome/browser/web_applications/components/web_app_constants.cc b/chrome/browser/web_applications/components/web_app_constants.cc index 60f1314..1ab0970 100644 --- a/chrome/browser/web_applications/components/web_app_constants.cc +++ b/chrome/browser/web_applications/components/web_app_constants.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/web_applications/components/web_app_constants.h" +#include <ostream> + #include "base/compiler_specific.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/common/content_features.h" @@ -57,6 +59,55 @@ return IsSuccess(code) && code != InstallResultCode::kSuccessAlreadyInstalled; } +std::ostream& operator<<(std::ostream& os, InstallResultCode code) { + switch (code) { + case InstallResultCode::kSuccessNewInstall: + return os << "kSuccessNewInstall"; + case InstallResultCode::kSuccessAlreadyInstalled: + return os << "kSuccessAlreadyInstalled"; + case InstallResultCode::kGetWebApplicationInfoFailed: + return os << "kGetWebApplicationInfoFailed"; + case InstallResultCode::kPreviouslyUninstalled: + return os << "kPreviouslyUninstalled"; + case InstallResultCode::kWebContentsDestroyed: + return os << "kWebContentsDestroyed"; + case InstallResultCode::kWriteDataFailed: + return os << "kWriteDataFailed"; + case InstallResultCode::kUserInstallDeclined: + return os << "kUserInstallDeclined"; + case InstallResultCode::kNotValidManifestForWebApp: + return os << "kNotValidManifestForWebApp"; + case InstallResultCode::kIntentToPlayStore: + return os << "kIntentToPlayStore"; + case InstallResultCode::kWebAppDisabled: + return os << "kWebAppDisabled"; + case InstallResultCode::kInstallURLRedirected: + return os << "kInstallURLRedirected"; + case InstallResultCode::kInstallURLLoadFailed: + return os << "kInstallURLLoadFailed"; + case InstallResultCode::kExpectedAppIdCheckFailed: + return os << "kExpectedAppIdCheckFailed"; + case InstallResultCode::kInstallURLLoadTimeOut: + return os << "kInstallURLLoadTimeOut"; + case InstallResultCode::kFailedPlaceholderUninstall: + return os << "kFailedPlaceholderUninstall"; + case InstallResultCode::kNotInstallable: + return os << "kNotInstallable"; + case InstallResultCode::kBookmarkExtensionInstallError: + return os << "kBookmarkExtensionInstallError"; + case InstallResultCode::kApkWebAppInstallFailed: + return os << "kApkWebAppInstallFailed"; + case InstallResultCode::kCancelledOnWebAppProviderShuttingDown: + return os << "kCancelledOnWebAppProviderShuttingDown"; + case InstallResultCode::kWebAppProviderNotReady: + return os << "kWebAppProviderNotReady"; + case InstallResultCode::kSuccessOfflineOnlyInstall: + return os << "kSuccessOfflineOnlyInstall"; + case InstallResultCode::kSuccessOfflineFallbackInstall: + return os << "kSuccessOfflineFallbackInstall"; + } +} + DisplayMode ResolveEffectiveDisplayMode( DisplayMode app_display_mode, const std::vector<DisplayMode>& app_display_mode_overrides,
diff --git a/chrome/browser/web_applications/components/web_app_constants.h b/chrome/browser/web_applications/components/web_app_constants.h index 208f874..6899ef1 100644 --- a/chrome/browser/web_applications/components/web_app_constants.h +++ b/chrome/browser/web_applications/components/web_app_constants.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_WEB_APPLICATIONS_COMPONENTS_WEB_APP_CONSTANTS_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_COMPONENTS_WEB_APP_CONSTANTS_H_ +#include <iosfwd> #include <vector> #include "components/services/app_service/public/mojom/types.mojom-forward.h" @@ -119,6 +120,8 @@ // Checks if InstallResultCode indicates a new app was installed. bool IsNewInstall(InstallResultCode code); +std::ostream& operator<<(std::ostream& os, InstallResultCode code); + // PendingAppManager: Where an app was installed from. This affects what flags // will be used when installing the app. //
diff --git a/chrome/browser/web_applications/components/web_app_install_utils.cc b/chrome/browser/web_applications/components/web_app_install_utils.cc index eeead0f..68f6a95 100644 --- a/chrome/browser/web_applications/components/web_app_install_utils.cc +++ b/chrome/browser/web_applications/components/web_app_install_utils.cc
@@ -9,6 +9,7 @@ #include <utility> #include "base/feature_list.h" +#include "base/metrics/histogram_functions.h" #include "base/optional.h" #include "base/stl_util.h" #include "base/strings/string16.h" @@ -427,4 +428,11 @@ return install_source; } +void RecordExternalAppInstallResultCode( + const char* histogram_name, + std::map<GURL, InstallResultCode> install_results) { + for (const auto& url_and_result : install_results) + base::UmaHistogramEnumeration(histogram_name, url_and_result.second); +} + } // namespace web_app
diff --git a/chrome/browser/web_applications/components/web_app_install_utils.h b/chrome/browser/web_applications/components/web_app_install_utils.h index 39ab386..7c774074e 100644 --- a/chrome/browser/web_applications/components/web_app_install_utils.h +++ b/chrome/browser/web_applications/components/web_app_install_utils.h
@@ -64,6 +64,10 @@ WebappInstallSource ConvertExternalInstallSourceToInstallSource( ExternalInstallSource external_install_source); +void RecordExternalAppInstallResultCode( + const char* histogram_name, + std::map<GURL, InstallResultCode> install_results); + } // namespace web_app #endif // CHROME_BROWSER_WEB_APPLICATIONS_COMPONENTS_WEB_APP_INSTALL_UTILS_H_
diff --git a/chrome/browser/web_applications/components/web_app_ui_manager.h b/chrome/browser/web_applications/components/web_app_ui_manager.h index ecca1fa..56e247c 100644 --- a/chrome/browser/web_applications/components/web_app_ui_manager.h +++ b/chrome/browser/web_applications/components/web_app_ui_manager.h
@@ -47,8 +47,7 @@ // Uninstalls the the apps in |from_apps| and migrates an |to_app|'s OS // attributes (e.g pin position, app list folder/position, shortcuts) to the // first |from_app| found. - // Returns whether any |from_apps| were uninstalled. - virtual bool UninstallAndReplaceIfExists(const std::vector<AppId>& from_apps, + virtual void UninstallAndReplaceIfExists(const std::vector<AppId>& from_apps, const AppId& to_app) = 0; virtual bool CanAddAppToQuickLaunchBar() const = 0;
diff --git a/chrome/browser/web_applications/extensions/pending_app_install_task_unittest.cc b/chrome/browser/web_applications/extensions/pending_app_install_task_unittest.cc index c715efa..9d169ff 100644 --- a/chrome/browser/web_applications/extensions/pending_app_install_task_unittest.cc +++ b/chrome/browser/web_applications/extensions/pending_app_install_task_unittest.cc
@@ -49,6 +49,8 @@ namespace web_app { +using Result = PendingAppInstallTask::Result; + namespace { // Returns a factory that will return |data_retriever| the first time it gets @@ -391,18 +393,17 @@ task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { base::Optional<AppId> id = ExternallyInstalledWebAppPrefs(profile()->GetPrefs()) .LookupAppId(WebAppUrl()); EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_FALSE(IsPlaceholderApp(profile(), WebAppUrl())); - EXPECT_EQ(app_id.value(), id.value()); + EXPECT_EQ(result.app_id.value(), id.value()); EXPECT_EQ(1u, os_integration_manager()->num_create_shortcuts_calls()); EXPECT_TRUE(os_integration_manager()->did_add_to_desktop().value()); @@ -433,14 +434,13 @@ task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { base::Optional<AppId> id = ExternallyInstalledWebAppPrefs(profile()->GetPrefs()) .LookupAppId(WebAppUrl()); EXPECT_EQ(InstallResultCode::kGetWebApplicationInfoFailed, result.code); - EXPECT_FALSE(app_id.has_value()); + EXPECT_FALSE(result.app_id.has_value()); EXPECT_FALSE(id.has_value()); @@ -462,10 +462,9 @@ task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_EQ(1u, os_integration_manager()->num_create_shortcuts_calls()); EXPECT_FALSE(os_integration_manager()->did_add_to_desktop().value()); @@ -492,10 +491,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_EQ(1u, os_integration_manager()->num_create_shortcuts_calls()); EXPECT_TRUE(os_integration_manager()->did_add_to_desktop().value()); @@ -524,10 +522,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_EQ(1u, os_integration_manager()->num_create_shortcuts_calls()); EXPECT_FALSE(os_integration_manager()->did_add_to_desktop().value()); @@ -553,10 +550,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_TRUE(web_app_info().open_as_window); run_loop.Quit(); })); @@ -574,10 +570,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_FALSE(web_app_info().open_as_window); run_loop.Quit(); })); @@ -594,10 +589,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_EQ(WebappInstallSource::INTERNAL_DEFAULT, finalize_options().install_source); @@ -616,10 +610,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_EQ(WebappInstallSource::EXTERNAL_POLICY, finalize_options().install_source); @@ -638,10 +631,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kRedirectedUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_TRUE(IsPlaceholderApp(profile(), WebAppUrl())); @@ -675,10 +667,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kRedirectedUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_TRUE(IsPlaceholderApp(profile(), WebAppUrl())); @@ -712,15 +703,13 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kRedirectedUrlLoaded, - base::BindLambdaForTesting( - [&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - placeholder_app_id = app_id.value(); + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + placeholder_app_id = result.app_id.value(); - EXPECT_EQ(1u, finalizer()->finalize_options_list().size()); - run_loop.Quit(); - })); + EXPECT_EQ(1u, finalizer()->finalize_options_list().size()); + run_loop.Quit(); + })); run_loop.Run(); } @@ -729,10 +718,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kRedirectedUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(placeholder_app_id, app_id.value()); + EXPECT_EQ(placeholder_app_id, result.app_id.value()); // There shouldn't be a second call to the finalizer. EXPECT_EQ(1u, finalizer()->finalize_options_list().size()); @@ -755,15 +743,13 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kRedirectedUrlLoaded, - base::BindLambdaForTesting( - [&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - placeholder_app_id = app_id.value(); + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + placeholder_app_id = result.app_id.value(); - EXPECT_EQ(1u, finalizer()->finalize_options_list().size()); - run_loop.Quit(); - })); + EXPECT_EQ(1u, finalizer()->finalize_options_list().size()); + run_loop.Quit(); + })); run_loop.Run(); } @@ -775,10 +761,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_FALSE(IsPlaceholderApp(profile(), WebAppUrl())); EXPECT_EQ(1u, finalizer()->uninstall_external_web_app_urls().size()); @@ -802,16 +787,14 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kRedirectedUrlLoaded, - base::BindLambdaForTesting( - [&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - placeholder_app_id = app_id.value(); + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + placeholder_app_id = result.app_id.value(); - EXPECT_EQ(1u, finalizer()->finalize_options_list().size()); + EXPECT_EQ(1u, finalizer()->finalize_options_list().size()); - run_loop.Quit(); - })); + run_loop.Quit(); + })); run_loop.Run(); } @@ -824,10 +807,9 @@ base::RunLoop run_loop; task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kFailedPlaceholderUninstall, result.code); - EXPECT_FALSE(app_id.has_value()); + EXPECT_FALSE(result.app_id.has_value()); EXPECT_TRUE(IsPlaceholderApp(profile(), WebAppUrl())); EXPECT_EQ(1u, finalizer()->uninstall_external_web_app_urls().size()); @@ -854,10 +836,8 @@ auto task = GetInstallationTaskWithTestMocks(options); task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> installed_app_id, - PendingAppManager::InstallResult - result) { - app_id = *installed_app_id; + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { + app_id = *result.app_id; EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); EXPECT_EQ(app_id, @@ -879,16 +859,14 @@ auto task = GetInstallationTaskWithTestMocks(options); task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting( - [&](base::Optional<AppId> installed_app_id, - PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(app_id, *installed_app_id); + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + EXPECT_EQ(app_id, *result.app_id); - EXPECT_TRUE(ui_manager()->DidUninstallAndReplace("app3", app_id)); + EXPECT_TRUE(ui_manager()->DidUninstallAndReplace("app3", app_id)); - run_loop.Quit(); - })); + run_loop.Quit(); + })); run_loop.Run(); } } @@ -914,14 +892,12 @@ profile(), registrar(), os_integration_manager(), ui_manager(), finalizer(), install_manager(), install_options); - install_task.Install(web_contents(), result_pair.loader_result, - base::BindLambdaForTesting( - [&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { - EXPECT_EQ(result.code, - result_pair.install_result); - run_loop.Quit(); - })); + install_task.Install( + web_contents(), result_pair.loader_result, + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { + EXPECT_EQ(result.code, result_pair.install_result); + run_loop.Quit(); + })); run_loop.Run(); } @@ -938,9 +914,7 @@ install_task.Install( web_contents(), WebAppUrlLoader::Result::kFailedWebContentsDestroyed, base::BindLambdaForTesting( - [&](base::Optional<AppId>, PendingAppManager::InstallResult) { - NOTREACHED(); - })); + [&](PendingAppInstallTask::Result) { NOTREACHED(); })); base::RunLoop().RunUntilIdle(); } @@ -958,10 +932,9 @@ task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_EQ(1u, os_integration_manager()->num_create_shortcuts_calls()); EXPECT_TRUE(os_integration_manager()->did_add_to_desktop().value()); @@ -992,10 +965,9 @@ task->Install( web_contents(), WebAppUrlLoader::Result::kUrlLoaded, - base::BindLambdaForTesting([&](base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + base::BindLambdaForTesting([&](PendingAppInstallTask::Result result) { EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_TRUE(app_id.has_value()); + EXPECT_TRUE(result.app_id.has_value()); EXPECT_EQ(1u, os_integration_manager()->num_create_shortcuts_calls()); EXPECT_TRUE(os_integration_manager()->did_add_to_desktop().value());
diff --git a/chrome/browser/web_applications/external_web_app_manager.cc b/chrome/browser/web_applications/external_web_app_manager.cc index d633bb4..3da14c1 100644 --- a/chrome/browser/web_applications/external_web_app_manager.cc +++ b/chrome/browser/web_applications/external_web_app_manager.cc
@@ -18,7 +18,7 @@ #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/json/json_reader.h" -#include "base/metrics/histogram_macros.h" +#include "base/metrics/histogram_functions.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/stl_util.h" @@ -44,6 +44,7 @@ #include "components/prefs/pref_service.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" +#include "third_party/abseil-cpp/absl/types/variant.h" #include "url/gurl.h" #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -75,7 +76,7 @@ struct LoadedConfigs { std::vector<LoadedConfig> configs; - int error_count = 0; + std::vector<std::string> errors; }; LoadedConfigs LoadConfigsBlocking(const base::FilePath& config_dir) { @@ -98,8 +99,10 @@ std::unique_ptr<base::Value> app_config = deserializer.Deserialize(nullptr, &error_msg); if (!app_config) { - LOG(ERROR) << file.value() << " was not valid JSON: " << error_msg; - ++result.error_count; + result.errors.push_back( + (std::stringstream() << file << " was not valid JSON: " << error_msg) + .str()); + VLOG(1) << result.errors.back(); continue; } result.configs.push_back( @@ -110,30 +113,104 @@ struct ParsedConfigs { std::vector<ExternalInstallOptions> options_list; - int error_count = 0; + std::vector<std::string> errors; }; ParsedConfigs ParseConfigsBlocking(const base::FilePath& config_dir, LoadedConfigs loaded_configs) { ParsedConfigs result; - result.error_count = loaded_configs.error_count; + result.errors = std::move(loaded_configs.errors); auto file_utils = g_file_utils_for_testing ? g_file_utils_for_testing->Clone() : std::make_unique<FileUtilsWrapper>(); for (const LoadedConfig& loaded_config : loaded_configs.configs) { - base::Optional<ExternalInstallOptions> parse_result = ParseConfig( + OptionsOrError parse_result = ParseConfig( *file_utils, config_dir, loaded_config.file, loaded_config.contents); - if (parse_result) - result.options_list.push_back(std::move(*parse_result)); - else - ++result.error_count; + if (ExternalInstallOptions* options = + absl::get_if<ExternalInstallOptions>(&parse_result)) { + result.options_list.push_back(std::move(*options)); + } else { + result.errors.push_back(std::move(absl::get<std::string>(parse_result))); + VLOG(1) << result.errors.back(); + } } return result; } +base::Optional<std::string> GetDisableReason( + const ExternalInstallOptions& options, + Profile* profile, + bool is_new_user, + const std::string& user_type) { + // Remove if not applicable to current user type. + DCHECK_GT(options.user_type_allowlist.size(), 0u); + if (!base::Contains(options.user_type_allowlist, user_type)) { + return options.install_url.spec() + " disabled for user type: " + user_type; + } + + // Remove if gated on a disabled feature. + if (options.gate_on_feature && + !IsExternalAppInstallFeatureEnabled(*options.gate_on_feature)) { + return options.install_url.spec() + + " disabled because feature is disabled: " + *options.gate_on_feature; + } + +#if BUILDFLAG(IS_CHROMEOS_ASH) + // Remove if ARC is supported and app should be disabled. + if (options.disable_if_arc_supported && arc::IsArcAvailable()) { + return options.install_url.spec() + " disabled because ARC is available."; + } + + // Remove if device is tablet and app should be disabled. + if (options.disable_if_tablet_form_factor && + chromeos::switches::IsTabletFormFactor()) { + return options.install_url.spec() + " disabled because device is tablet."; + } +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + + // Remove if only for new users, user isn't new and app was not + // installed previously. + if (options.only_for_new_users && !is_new_user) { + bool was_previously_installed = + ExternallyInstalledWebAppPrefs(profile->GetPrefs()) + .LookupAppId(options.install_url) + .has_value(); + if (!was_previously_installed) { + return options.install_url.spec() + + " disabled because user was not new when config was added."; + } + } + + // Remove if any apps to replace are blocked by admin policy. + for (const AppId& app_id : options.uninstall_and_replace) { + if (extensions::IsExtensionBlockedByPolicy(profile, app_id)) { + return options.install_url.spec() + + " disabled due to admin policy blocking replacement " + "Extension."; + } + } + + // Keep if any apps to replace are installed. + for (const AppId& app_id : options.uninstall_and_replace) { + if (extensions::IsExtensionInstalled(profile, app_id)) { + return base::nullopt; + } + } + + // Remove if any apps to replace were previously uninstalled. + for (const AppId& app_id : options.uninstall_and_replace) { + if (extensions::IsExternalExtensionUninstalled(profile, app_id)) { + return options.install_url.spec() + + " disabled because apps to replace were uninstalled."; + } + } + + return base::nullopt; +} + } // namespace const char* ExternalWebAppManager::kHistogramEnabledCount = @@ -142,8 +219,6 @@ "WebApp.Preinstalled.DisabledCount"; const char* ExternalWebAppManager::kHistogramConfigErrorCount = "WebApp.Preinstalled.ConfigErrorCount"; -const char* ExternalWebAppManager::kHistogramUninstallAndReplaceCount = - "WebApp.Preinstalled.UninstallAndReplaceCount"; void ExternalWebAppManager::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { @@ -171,7 +246,11 @@ } ExternalWebAppManager::ExternalWebAppManager(Profile* profile) - : profile_(profile) {} + : profile_(profile) { + if (base::FeatureList::IsEnabled(features::kRecordWebAppDebugInfo)) { + debug_info_ = std::make_unique<DebugInfo>(); + } +} ExternalWebAppManager::~ExternalWebAppManager() = default; @@ -181,8 +260,11 @@ } void ExternalWebAppManager::Start() { - if (!g_skip_startup_for_testing_) - LoadAndSynchronize({}); + if (!g_skip_startup_for_testing_) { + LoadAndSynchronize( + base::BindOnce(&ExternalWebAppManager::OnStartUpTaskCompleted, + weak_ptr_factory_.GetWeakPtr())); + } } void ExternalWebAppManager::LoadForTesting(ConsumeInstallOptions callback) { @@ -248,83 +330,38 @@ for (ExternalInstallOptions& options : GetPreinstalledWebApps()) parsed_configs.options_list.push_back(std::move(options)); - const int total_count = parsed_configs.options_list.size(); - int disabled_count = 0; bool is_new_user = IsNewUser(); std::string user_type = apps::DetermineUserType(profile_); + size_t disabled_count = 0; base::EraseIf( parsed_configs.options_list, [&](const ExternalInstallOptions& options) { - // Remove if not applicable to current user type. - DCHECK_GT(options.user_type_allowlist.size(), 0u); - if (!base::Contains(options.user_type_allowlist, user_type)) { + base::Optional<std::string> disable_reason = + GetDisableReason(options, profile_, is_new_user, user_type); + if (disable_reason) { + VLOG(1) << *disable_reason; ++disabled_count; - return true; - } - - // Remove if gated on a disabled feature. - if (options.gate_on_feature && - !IsExternalAppInstallFeatureEnabled(*options.gate_on_feature)) { - ++disabled_count; - return true; - } - -#if BUILDFLAG(IS_CHROMEOS_ASH) - // Remove if ARC is supported and app should be disabled. - if (options.disable_if_arc_supported && arc::IsArcAvailable()) { - ++disabled_count; - return true; - } - - // Remove if device is tablet and app should be disabled. - if (options.disable_if_tablet_form_factor && - chromeos::switches::IsTabletFormFactor()) { - ++disabled_count; - return true; - } -#endif // BUILDFLAG(IS_CHROMEOS_ASH) - - // Remove if only for new users, user isn't new and app was not - // installed previously. - if (options.only_for_new_users && !is_new_user) { - bool was_previously_installed = - ExternallyInstalledWebAppPrefs(profile_->GetPrefs()) - .LookupAppId(options.install_url) - .has_value(); - if (!was_previously_installed) - return true; - } - - // Remove if any apps to replace are blocked by admin policy. - for (const AppId& app_id : options.uninstall_and_replace) { - if (extensions::IsExtensionBlockedByPolicy(profile_, app_id)) { - ++disabled_count; - return true; + if (debug_info_) { + debug_info_->disabled_configs.emplace_back( + std::move(options), std::move(*disable_reason)); } + return true; } - - // Keep if any apps to replace are installed. - for (const AppId& app_id : options.uninstall_and_replace) { - if (extensions::IsExtensionInstalled(profile_, app_id)) - return false; - } - - // Remove if any apps to replace were previously uninstalled. - for (const AppId& app_id : options.uninstall_and_replace) { - if (extensions::IsExternalExtensionUninstalled(profile_, app_id)) - return true; - } - return false; }); - UMA_HISTOGRAM_COUNTS_100(ExternalWebAppManager::kHistogramEnabledCount, - total_count - disabled_count); - UMA_HISTOGRAM_COUNTS_100(ExternalWebAppManager::kHistogramDisabledCount, - disabled_count); - UMA_HISTOGRAM_COUNTS_100(ExternalWebAppManager::kHistogramConfigErrorCount, - parsed_configs.error_count); + if (debug_info_) { + debug_info_->parse_errors = parsed_configs.errors; + debug_info_->enabled_configs = parsed_configs.options_list; + } - std::move(callback).Run(std::move(parsed_configs.options_list)); + base::UmaHistogramCounts100(ExternalWebAppManager::kHistogramEnabledCount, + parsed_configs.options_list.size()); + base::UmaHistogramCounts100(ExternalWebAppManager::kHistogramDisabledCount, + disabled_count); + base::UmaHistogramCounts100(ExternalWebAppManager::kHistogramConfigErrorCount, + parsed_configs.errors.size()); + + std::move(callback).Run(parsed_configs.options_list); } void ExternalWebAppManager::Synchronize( @@ -341,7 +378,7 @@ void ExternalWebAppManager::OnExternalWebAppsSynchronized( PendingAppManager::SynchronizeCallback callback, - std::map<GURL, PendingAppManager::InstallResult> install_results, + std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { // Note that we are storing the Chrome version instead of a "has synchronised" // bool in order to do version update specific logic in the future. @@ -349,23 +386,24 @@ prefs::kWebAppsLastPreinstallSynchronizeVersion, version_info::GetMajorVersionNumber()); - size_t uninstall_and_replace_count = 0; - for (const auto& url_and_result : install_results) { - UMA_HISTOGRAM_ENUMERATION("Webapp.InstallResult.Default", - url_and_result.second.code); - if (url_and_result.second.did_uninstall_and_replace) - ++uninstall_and_replace_count; - } - UMA_HISTOGRAM_COUNTS_100( - ExternalWebAppManager::kHistogramUninstallAndReplaceCount, - uninstall_and_replace_count); - + RecordExternalAppInstallResultCode("Webapp.InstallResult.Default", + install_results); if (callback) { std::move(callback).Run(std::move(install_results), std::move(uninstall_results)); } } +void ExternalWebAppManager::OnStartUpTaskCompleted( + std::map<GURL, InstallResultCode> install_results, + std::map<GURL, bool> uninstall_results) { + if (debug_info_) { + debug_info_->is_start_up_task_complete = true; + debug_info_->install_results = std::move(install_results); + debug_info_->uninstall_results = std::move(uninstall_results); + } +} + base::FilePath ExternalWebAppManager::GetConfigDir() { base::FilePath dir; @@ -408,4 +446,8 @@ return ExternallyInstalledWebAppPrefs(prefs).HasNoApps(); } +ExternalWebAppManager::DebugInfo::DebugInfo() = default; + +ExternalWebAppManager::DebugInfo::~DebugInfo() = default; + } // namespace web_app
diff --git a/chrome/browser/web_applications/external_web_app_manager.h b/chrome/browser/web_applications/external_web_app_manager.h index 90e14d9e..3e141456 100644 --- a/chrome/browser/web_applications/external_web_app_manager.h +++ b/chrome/browser/web_applications/external_web_app_manager.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_WEB_APPLICATIONS_EXTERNAL_WEB_APP_MANAGER_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_EXTERNAL_WEB_APP_MANAGER_H_ +#include <map> +#include <memory> #include <vector> #include "base/callback_forward.h" @@ -13,6 +15,7 @@ #include "chrome/browser/web_applications/components/external_install_options.h" #include "chrome/browser/web_applications/components/pending_app_manager.h" #include "chrome/browser/web_applications/file_utils_wrapper.h" +#include "url/gurl.h" namespace base { class FilePath; @@ -48,7 +51,6 @@ static const char* kHistogramEnabledCount; static const char* kHistogramDisabledCount; static const char* kHistogramConfigErrorCount; - static const char* kHistogramUninstallAndReplaceCount; static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); @@ -72,6 +74,22 @@ void LoadForTesting(ConsumeInstallOptions callback); + // Debugging info used by: chrome://internals/web-app + struct DebugInfo { + DebugInfo(); + ~DebugInfo(); + + bool is_start_up_task_complete = false; + std::vector<std::string> parse_errors; + std::vector<ExternalInstallOptions> enabled_configs; + using DisabledConfigWithReason = + std::pair<ExternalInstallOptions, std::string>; + std::vector<DisabledConfigWithReason> disabled_configs; + std::map<GURL, InstallResultCode> install_results; + std::map<GURL, bool> uninstall_results; + }; + const DebugInfo* debug_info() const { return debug_info_.get(); } + private: void LoadAndSynchronize(SynchronizeCallback callback); @@ -86,8 +104,10 @@ std::vector<ExternalInstallOptions>); void OnExternalWebAppsSynchronized( PendingAppManager::SynchronizeCallback callback, - std::map<GURL, PendingAppManager::InstallResult> install_results, + std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results); + void OnStartUpTaskCompleted(std::map<GURL, InstallResultCode> install_results, + std::map<GURL, bool> uninstall_results); base::FilePath GetConfigDir(); @@ -98,6 +118,8 @@ PendingAppManager* pending_app_manager_ = nullptr; Profile* const profile_; + std::unique_ptr<DebugInfo> debug_info_; + base::WeakPtrFactory<ExternalWebAppManager> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/web_applications/external_web_app_manager_browsertest.cc b/chrome/browser/web_applications/external_web_app_manager_browsertest.cc index c10a959c..216eab5 100644 --- a/chrome/browser/web_applications/external_web_app_manager_browsertest.cc +++ b/chrome/browser/web_applications/external_web_app_manager_browsertest.cc
@@ -60,10 +60,9 @@ base::RunLoop run_loop; WebAppProvider::Get(browser()->profile()) - ->external_web_app_manager_for_testing() + ->external_web_app_manager() .LoadAndSynchronizeForTesting(base::BindLambdaForTesting( - [&](std::map<GURL, PendingAppManager::InstallResult> - install_results, + [&](std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { EXPECT_EQ(install_results.size(), 0u); EXPECT_EQ(uninstall_results.size(), 0u); @@ -98,14 +97,13 @@ base::Optional<InstallResultCode> code; base::RunLoop sync_run_loop; WebAppProvider::Get(browser()->profile()) - ->external_web_app_manager_for_testing() + ->external_web_app_manager() .LoadAndSynchronizeForTesting(base::BindLambdaForTesting( - [&](std::map<GURL, PendingAppManager::InstallResult> - install_results, + [&](std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { auto it = install_results.find(install_url); if (it != install_results.end()) - code = it->second.code; + code = it->second; sync_run_loop.Quit(); })); sync_run_loop.Run(); @@ -499,73 +497,59 @@ auto& provider = *WebAppProvider::Get(browser()->profile()); - struct Expectation { - const char* app_id; - const char* install_url; - const char* launch_url; - } kExpectations[] = { -#if BUILDFLAG(IS_CHROMEOS_ASH) - { - kGoogleCalendarAppId, - "https://calendar.google.com/calendar/installwebapp?usp=chrome_default", - "https://calendar.google.com/calendar/r?usp=installed_webapp", - }, -#endif // BUILDFLAG(IS_CHROMEOS_ASH) - { - kGoogleDocsAppId, - "https://docs.google.com/document/installwebapp?usp=chrome_default", - "https://docs.google.com/document/?usp=installed_webapp", - }, - { - kGoogleSlidesAppId, - "https://docs.google.com/presentation/installwebapp?usp=chrome_default", - "https://docs.google.com/presentation/?usp=installed_webapp", - }, - { - kGoogleSheetsAppId, - "https://docs.google.com/spreadsheets/installwebapp?usp=chrome_default", - "https://docs.google.com/spreadsheets/?usp=installed_webapp", - }, - { - kGoogleDriveAppId, - "https://drive.google.com/drive/installwebapp?usp=chrome_default", - "https://drive.google.com/?lfhs=2&usp=installed_webapp", - }, - { - kGmailAppId, - "https://mail.google.com/mail/installwebapp?usp=chrome_default", - "https://mail.google.com/?usp=installed_webapp", - }, - { - kYoutubeAppId, - "https://www.youtube.com/s/notifications/manifest/cr_install.html", - "https://www.youtube.com/?feature=ytca", - }, - }; - base::RunLoop run_loop; - provider.external_web_app_manager_for_testing().LoadAndSynchronizeForTesting( + provider.external_web_app_manager().LoadAndSynchronizeForTesting( base::BindLambdaForTesting( - [&](std::map<GURL, PendingAppManager::InstallResult> install_results, + [&](std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { - EXPECT_EQ(install_results.size(), - base::span<Expectation>(kExpectations).size()); - - for (const Expectation& expectation : kExpectations) { - EXPECT_EQ(install_results[GURL(expectation.install_url)].code, - InstallResultCode::kSuccessOfflineOnlyInstall); - } - + EXPECT_THAT( + install_results, + UnorderedElementsAre( +#if BUILDFLAG(IS_CHROMEOS_ASH) + Pair(GURL("https://calendar.google.com/calendar/" + "installwebapp?usp=chrome_default"), + InstallResultCode::kSuccessOfflineOnlyInstall), +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + Pair(GURL("https://docs.google.com/document/" + "installwebapp?usp=chrome_default"), + InstallResultCode::kSuccessOfflineOnlyInstall), + Pair(GURL("https://docs.google.com/presentation/" + "installwebapp?usp=chrome_default"), + InstallResultCode::kSuccessOfflineOnlyInstall), + Pair(GURL("https://docs.google.com/spreadsheets/" + "installwebapp?usp=chrome_default"), + InstallResultCode::kSuccessOfflineOnlyInstall), + Pair(GURL("https://drive.google.com/drive/" + "installwebapp?usp=chrome_default"), + InstallResultCode::kSuccessOfflineOnlyInstall), + Pair(GURL("https://mail.google.com/mail/" + "installwebapp?usp=chrome_default"), + InstallResultCode::kSuccessOfflineOnlyInstall), + Pair(GURL("https://www.youtube.com/s/notifications/" + "manifest/cr_install.html"), + InstallResultCode::kSuccessOfflineOnlyInstall))); EXPECT_EQ(uninstall_results.size(), 0u); - run_loop.Quit(); })); run_loop.Run(); - for (const Expectation& expectation : kExpectations) { - EXPECT_EQ(provider.registrar().GetAppLaunchUrl(expectation.app_id), - GURL(expectation.launch_url)); - } +#if BUILDFLAG(IS_CHROMEOS_ASH) + EXPECT_EQ( + provider.registrar().GetAppLaunchUrl(kGoogleCalendarAppId), + GURL("https://calendar.google.com/calendar/r?usp=installed_webapp")); +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + EXPECT_EQ(provider.registrar().GetAppLaunchUrl(kGoogleDocsAppId), + GURL("https://docs.google.com/document/?usp=installed_webapp")); + EXPECT_EQ(provider.registrar().GetAppLaunchUrl(kGoogleSlidesAppId), + GURL("https://docs.google.com/presentation/?usp=installed_webapp")); + EXPECT_EQ(provider.registrar().GetAppLaunchUrl(kGoogleSheetsAppId), + GURL("https://docs.google.com/spreadsheets/?usp=installed_webapp")); + EXPECT_EQ(provider.registrar().GetAppLaunchUrl(kGoogleDriveAppId), + GURL("https://drive.google.com/?lfhs=2&usp=installed_webapp")); + EXPECT_EQ(provider.registrar().GetAppLaunchUrl(kGmailAppId), + GURL("https://mail.google.com/?usp=installed_webapp")); + EXPECT_EQ(provider.registrar().GetAppLaunchUrl(kYoutubeAppId), + GURL("https://www.youtube.com/?feature=ytca")); } #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
diff --git a/chrome/browser/web_applications/external_web_app_migration_browsertest.cc b/chrome/browser/web_applications/external_web_app_migration_browsertest.cc index 25bbf4a..96abb68 100644 --- a/chrome/browser/web_applications/external_web_app_migration_browsertest.cc +++ b/chrome/browser/web_applications/external_web_app_migration_browsertest.cc
@@ -168,12 +168,13 @@ base::RunLoop run_loop; auto callback = base::BindLambdaForTesting( - [&](std::map<GURL, PendingAppManager::InstallResult> install_results, + [&](std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { if (expect_install) { - InstallResultCode code = install_results.at(GetWebAppUrl()).code; - EXPECT_TRUE(code == InstallResultCode::kSuccessNewInstall || - code == InstallResultCode::kSuccessOfflineOnlyInstall); + InstallResultCode result = install_results.at(GetWebAppUrl()); + EXPECT_TRUE(result == InstallResultCode::kSuccessNewInstall || + result == + InstallResultCode::kSuccessOfflineOnlyInstall); } else { EXPECT_EQ(install_results.find(GetWebAppUrl()), install_results.end()); @@ -198,7 +199,7 @@ ExternalWebAppManager::SetConfigsForTesting(&app_configs); WebAppProvider::Get(profile()) - ->external_web_app_manager_for_testing() + ->external_web_app_manager() .LoadAndSynchronizeForTesting(std::move(callback)); run_loop.Run(); @@ -246,7 +247,6 @@ EXPECT_TRUE(IsExtensionAppInstalled()); { - base::HistogramTester histograms; extensions::TestExtensionRegistryObserver uninstall_observer( extensions::ExtensionRegistry::Get(profile())); @@ -257,8 +257,6 @@ uninstall_observer.WaitForExtensionUninstalled(); EXPECT_EQ(uninstalled_app->id(), kExtensionId); EXPECT_FALSE(IsExtensionAppInstalled()); - histograms.ExpectUniqueSample( - ExternalWebAppManager::kHistogramUninstallAndReplaceCount, 1, 1); } } @@ -275,7 +273,6 @@ // Re-run migration. { - base::HistogramTester histograms; base::AutoReset<bool> testing_scope = SetExternalAppInstallFeatureAlwaysEnabledForTesting(); ASSERT_TRUE(IsExternalAppInstallFeatureEnabled(kMigrationFlag)); @@ -290,8 +287,6 @@ uninstall_observer.WaitForExtensionUninstalled(); EXPECT_EQ(uninstalled_app->id(), kExtensionId); EXPECT_FALSE(IsExtensionAppInstalled()); - histograms.ExpectUniqueSample( - ExternalWebAppManager::kHistogramUninstallAndReplaceCount, 1, 1); } } @@ -347,7 +342,6 @@ EXPECT_TRUE(IsExtensionAppInstalled()); { - base::HistogramTester histograms; extensions::TestExtensionRegistryObserver uninstall_observer( extensions::ExtensionRegistry::Get(profile())); @@ -358,8 +352,6 @@ uninstall_observer.WaitForExtensionUninstalled(); EXPECT_EQ(uninstalled_app->id(), kExtensionId); EXPECT_FALSE(IsExtensionAppInstalled()); - histograms.ExpectUniqueSample( - ExternalWebAppManager::kHistogramUninstallAndReplaceCount, 1, 1); } } @@ -503,8 +495,6 @@ ExternalWebAppManager::kHistogramDisabledCount, 0, 1); histograms.ExpectUniqueSample( ExternalWebAppManager::kHistogramConfigErrorCount, 0, 1); - histograms.ExpectUniqueSample( - ExternalWebAppManager::kHistogramUninstallAndReplaceCount, 1, 1); } } }
diff --git a/chrome/browser/web_applications/external_web_app_utils.cc b/chrome/browser/web_applications/external_web_app_utils.cc index fd2052df..8b3414d 100644 --- a/chrome/browser/web_applications/external_web_app_utils.cc +++ b/chrome/browser/web_applications/external_web_app_utils.cc
@@ -149,36 +149,35 @@ } // namespace -base::Optional<ExternalInstallOptions> ParseConfig( - FileUtilsWrapper& file_utils, - const base::FilePath& dir, - const base::FilePath& file, - const base::Value& app_config) { +OptionsOrError ParseConfig(FileUtilsWrapper& file_utils, + const base::FilePath& dir, + const base::FilePath& file, + const base::Value& app_config) { ExternalInstallOptions options(GURL(), DisplayMode::kStandalone, ExternalInstallSource::kExternalDefault); options.require_manifest = true; if (app_config.type() != base::Value::Type::DICTIONARY) { - LOG(ERROR) << file << " was not a dictionary as the top level"; - return base::nullopt; + return (std::stringstream() + << file << " was not a dictionary as the top level") + .str(); } // user_type const base::Value* value = app_config.FindListKey(kUserType); if (!value) { - VLOG(1) << file << " missing " << kUserType; - return base::nullopt; + return (std::stringstream() << file << " missing " << kUserType).str(); } for (const auto& item : value->GetList()) { if (!item.is_string()) { - VLOG(1) << file << " has invalid " << kUserType << item; - return base::nullopt; + return (std::stringstream() + << file << " has invalid " << kUserType << item) + .str(); } options.user_type_allowlist.push_back(item.GetString()); } if (options.user_type_allowlist.empty()) { - VLOG(1) << file << " has empty " << kUserType; - return base::nullopt; + return (std::stringstream() << file << " has empty " << kUserType).str(); } // feature_name @@ -189,21 +188,20 @@ // app_url value = app_config.FindKeyOfType(kAppUrl, base::Value::Type::STRING); if (!value) { - LOG(ERROR) << file << " had a missing " << kAppUrl; - return base::nullopt; + return (std::stringstream() << file << " had a missing " << kAppUrl).str(); } options.install_url = GURL(value->GetString()); if (!options.install_url.is_valid()) { - LOG(ERROR) << file << " had an invalid " << kAppUrl; - return base::nullopt; + return (std::stringstream() << file << " had an invalid " << kAppUrl).str(); } // only_for_new_users value = app_config.FindKey(kOnlyForNewUsers); if (value) { if (!value->is_bool()) { - LOG(ERROR) << file << " had an invalid " << kOnlyForNewUsers; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kOnlyForNewUsers) + .str(); } options.only_for_new_users = value->GetBool(); } @@ -213,8 +211,9 @@ value = app_config.FindKey(kHideFromUser); if (value) { if (!value->is_bool()) { - LOG(ERROR) << file << " had an invalid " << kHideFromUser; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kHideFromUser) + .str(); } hide_from_user = value->GetBool(); } @@ -227,8 +226,9 @@ value = app_config.FindKey(kCreateShortcuts); if (value) { if (!value->is_bool()) { - LOG(ERROR) << file << " had an invalid " << kCreateShortcuts; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kCreateShortcuts) + .str(); } create_shortcuts = value->GetBool(); } @@ -242,8 +242,9 @@ value = app_config.FindKey(kDisableIfArcSupported); if (value) { if (!value->is_bool()) { - LOG(ERROR) << file << " had an invalid " << kDisableIfArcSupported; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kDisableIfArcSupported) + .str(); } options.disable_if_arc_supported = value->GetBool(); } @@ -252,8 +253,9 @@ value = app_config.FindKey(kDisableIfTabletFormFactor); if (value) { if (!value->is_bool()) { - LOG(ERROR) << file << " had an invalid " << kDisableIfTabletFormFactor; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kDisableIfTabletFormFactor) + .str(); } options.disable_if_tablet_form_factor = value->GetBool(); } @@ -261,8 +263,9 @@ // launch_container value = app_config.FindKeyOfType(kLaunchContainer, base::Value::Type::STRING); if (!value) { - LOG(ERROR) << file << " had an invalid " << kLaunchContainer; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kLaunchContainer) + .str(); } std::string launch_container_str = value->GetString(); if (launch_container_str == kLaunchContainerTab) { @@ -270,16 +273,19 @@ } else if (launch_container_str == kLaunchContainerWindow) { options.user_display_mode = DisplayMode::kStandalone; } else { - LOG(ERROR) << file << " had an invalid " << kLaunchContainer; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kLaunchContainer << ": " + << launch_container_str) + .str(); } // launch_query_params value = app_config.FindKey(kLaunchQueryParams); if (value) { if (!value->is_string()) { - LOG(ERROR) << file << " had an invalid " << kLaunchQueryParams; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kLaunchQueryParams) + .str(); } options.launch_query_params = value->GetString(); } @@ -288,9 +294,9 @@ value = app_config.FindKey(kLoadAndAwaitServiceWorkerRegistration); if (value) { if (!value->is_bool()) { - LOG(ERROR) << file << " had an invalid " - << kLoadAndAwaitServiceWorkerRegistration; - return base::nullopt; + return (std::stringstream() << file << " had an invalid " + << kLoadAndAwaitServiceWorkerRegistration) + .str(); } options.load_and_await_service_worker_registration = value->GetBool(); } @@ -299,18 +305,22 @@ value = app_config.FindKey(kServiceWorkerRegistrationUrl); if (value) { if (!options.load_and_await_service_worker_registration) { - LOG(ERROR) << file << " should not specify a " - << kServiceWorkerRegistrationUrl << " while " - << kLoadAndAwaitServiceWorkerRegistration << " is disabled"; + return (std::stringstream() + << file << " should not specify a " + << kServiceWorkerRegistrationUrl << " while " + << kLoadAndAwaitServiceWorkerRegistration << " is disabled") + .str(); } if (!value->is_string()) { - LOG(ERROR) << file << " had an invalid " << kServiceWorkerRegistrationUrl; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kServiceWorkerRegistrationUrl) + .str(); } options.service_worker_registration_url.emplace(value->GetString()); if (!options.service_worker_registration_url->is_valid()) { - LOG(ERROR) << file << " had an invalid " << kServiceWorkerRegistrationUrl; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kServiceWorkerRegistrationUrl) + .str(); } } @@ -318,31 +328,29 @@ value = app_config.FindKey(kUninstallAndReplace); if (value) { if (!value->is_list()) { - LOG(ERROR) << file << " had an invalid " << kUninstallAndReplace; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kUninstallAndReplace) + .str(); } base::Value::ConstListView uninstall_and_replace_values = value->GetList(); - bool had_error = false; for (const auto& app_id_value : uninstall_and_replace_values) { if (!app_id_value.is_string()) { - had_error = true; - LOG(ERROR) << file << " had an invalid " << kUninstallAndReplace - << " entry"; - break; + return (std::stringstream() << file << " had an invalid " + << kUninstallAndReplace << " entry") + .str(); } options.uninstall_and_replace.push_back(app_id_value.GetString()); } - if (had_error) - return base::nullopt; } // only_use_offline_manifest value = app_config.FindKey(kOnlyUseOfflineManifest); if (value) { if (!value->is_bool()) { - LOG(ERROR) << file << " had an invalid " << kOnlyUseOfflineManifest; - return base::nullopt; + return (std::stringstream() + << file << " had an invalid " << kOnlyUseOfflineManifest) + .str(); } options.only_use_app_info_factory = value->GetBool(); } @@ -350,25 +358,27 @@ // offline_manifest value = app_config.FindDictKey(kOfflineManifest); if (value) { - base::Optional<WebApplicationInfoFactory> offline_manifest_result = + WebApplicationInfoFactoryOrError offline_manifest_result = ParseOfflineManifest(file_utils, dir, file, *value); - if (!offline_manifest_result.has_value()) { - // Error already logged by |ParseOfflineManifest|. - return base::nullopt; + if (std::string* error = + absl::get_if<std::string>(&offline_manifest_result)) { + return std::move(*error); } - options.app_info_factory = std::move(offline_manifest_result.value()); + options.app_info_factory = std::move( + absl::get<WebApplicationInfoFactory>(offline_manifest_result)); } if (options.only_use_app_info_factory && !options.app_info_factory) { - LOG(ERROR) << file << kOnlyUseOfflineManifest << " set with no " - << kOfflineManifest << " available"; - return base::nullopt; + return (std::stringstream() + << file << kOnlyUseOfflineManifest << " set with no " + << kOfflineManifest << " available") + .str(); } return options; } -base::Optional<WebApplicationInfoFactory> ParseOfflineManifest( +WebApplicationInfoFactoryOrError ParseOfflineManifest( FileUtilsWrapper& file_utils, const base::FilePath& dir, const base::FilePath& file, @@ -379,69 +389,77 @@ const std::string* name_string = offline_manifest.FindStringKey(kOfflineManifestName); if (!name_string) { - LOG(ERROR) << file << " " << kOfflineManifest << " " << kOfflineManifestName - << " missing or invalid."; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " << kOfflineManifestName + << " missing or invalid.") + .str(); } if (!base::UTF8ToUTF16(name_string->data(), name_string->size(), &app_info.title) || app_info.title.empty()) { - LOG(ERROR) << file << " " << kOfflineManifest << " " << kOfflineManifestName - << " invalid: " << *name_string; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " << kOfflineManifestName + << " invalid: " << *name_string) + .str(); } // start_url const std::string* start_url_string = offline_manifest.FindStringKey(kOfflineManifestStartUrl); if (!start_url_string) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestStartUrl << " missing or invalid."; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " + << kOfflineManifestStartUrl << " missing or invalid.") + .str(); } app_info.start_url = GURL(*start_url_string); if (!app_info.start_url.is_valid()) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestStartUrl << " invalid: " << *start_url_string; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " + << kOfflineManifestStartUrl << " invalid: " << *start_url_string) + .str(); } // scope const std::string* scope_string = offline_manifest.FindStringKey(kOfflineManifestScope); if (!scope_string) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestScope << " missing or invalid."; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " << kOfflineManifestScope + << " missing or invalid.") + .str(); } app_info.scope = GURL(*scope_string); if (!app_info.scope.is_valid()) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestScope << " invalid: " << *scope_string; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " << kOfflineManifestScope + << " invalid: " << *scope_string) + .str(); } if (!base::StartsWith(app_info.start_url.path(), app_info.scope.path(), base::CompareCase::SENSITIVE)) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestScope << " (" << app_info.start_url - << ") not within " << kOfflineManifestScope << " (" - << app_info.scope << ")."; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " << kOfflineManifestScope + << " (" << app_info.start_url << ") not within " + << kOfflineManifestScope << " (" << app_info.scope << ").") + .str(); } // display const std::string* display_string = offline_manifest.FindStringKey(kOfflineManifestDisplay); if (!display_string) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestDisplay << " missing or invalid."; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " << kOfflineManifestDisplay + << " missing or invalid.") + .str(); } DisplayMode display = blink::DisplayModeFromString(*display_string); if (display == DisplayMode::kUndefined) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestDisplay << " invalid: " << display_string; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " << kOfflineManifestDisplay + << " invalid: " << display_string) + .str(); } app_info.display_mode = display; @@ -449,43 +467,44 @@ const base::Value* icon_files = offline_manifest.FindListKey(kOfflineManifestIconAnyPngs); if (!icon_files || icon_files->GetList().empty()) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestIconAnyPngs << " missing, empty or invalid."; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " + << kOfflineManifestIconAnyPngs << " missing, empty or invalid.") + .str(); } for (const base::Value& icon_file : icon_files->GetList()) { if (!icon_file.is_string()) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestIconAnyPngs << " " << icon_file - << " invalid."; - return base::nullopt; + return (std::stringstream() + << file << " " << kOfflineManifest << " " + << kOfflineManifestIconAnyPngs << " " << icon_file << " invalid.") + .str(); } base::FilePath icon_path = dir.AppendASCII(icon_file.GetString()); std::string icon_data; if (!file_utils.ReadFileToString(icon_path, &icon_data)) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestIconAnyPngs << " " << icon_file - << " failed to read."; - return base::nullopt; + return (std::stringstream() << file << " " << kOfflineManifest << " " + << kOfflineManifestIconAnyPngs << " " + << icon_file << " failed to read.") + .str(); } SkBitmap bitmap; if (!gfx::PNGCodec::Decode( reinterpret_cast<const unsigned char*>(icon_data.c_str()), icon_data.size(), &bitmap)) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestIconAnyPngs << " " << icon_file - << " failed to decode."; - return base::nullopt; + return (std::stringstream() << file << " " << kOfflineManifest << " " + << kOfflineManifestIconAnyPngs << " " + << icon_file << " failed to decode.") + .str(); } if (bitmap.width() != bitmap.height()) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestIconAnyPngs << " " << icon_file - << " must be square: " << bitmap.width() << "x" - << bitmap.height(); - return base::nullopt; + return (std::stringstream() << file << " " << kOfflineManifest << " " + << kOfflineManifestIconAnyPngs << " " + << icon_file << " must be square: " + << bitmap.width() << "x" << bitmap.height()) + .str(); } app_info.icon_bitmaps_any[bitmap.width()] = std::move(bitmap); @@ -502,10 +521,10 @@ SkColor theme_color; if (!theme_color_argb_hex || !base::HexStringToUInt(*theme_color_argb_hex, &theme_color)) { - LOG(ERROR) << file << " " << kOfflineManifest << " " - << kOfflineManifestThemeColorArgbHex - << " invalid: " << *theme_color_value; - return base::nullopt; + return (std::stringstream() << file << " " << kOfflineManifest << " " + << kOfflineManifestThemeColorArgbHex + << " invalid: " << *theme_color_value) + .str(); } app_info.theme_color = SkColorSetA(theme_color, SK_AlphaOPAQUE); }
diff --git a/chrome/browser/web_applications/external_web_app_utils.h b/chrome/browser/web_applications/external_web_app_utils.h index 5a954b0b..dd735f4 100644 --- a/chrome/browser/web_applications/external_web_app_utils.h +++ b/chrome/browser/web_applications/external_web_app_utils.h
@@ -9,6 +9,7 @@ #include "base/optional.h" #include "chrome/browser/web_applications/components/external_install_options.h" +#include "third_party/abseil-cpp/absl/types/variant.h" namespace base { class FilePath; @@ -19,13 +20,17 @@ class FileUtilsWrapper; -base::Optional<ExternalInstallOptions> ParseConfig( - FileUtilsWrapper& file_utils, - const base::FilePath& dir, - const base::FilePath& file, - const base::Value& app_config); +using OptionsOrError = absl::variant<ExternalInstallOptions, std::string>; -base::Optional<WebApplicationInfoFactory> ParseOfflineManifest( +OptionsOrError ParseConfig(FileUtilsWrapper& file_utils, + const base::FilePath& dir, + const base::FilePath& file, + const base::Value& app_config); + +using WebApplicationInfoFactoryOrError = + absl::variant<WebApplicationInfoFactory, std::string>; + +WebApplicationInfoFactoryOrError ParseOfflineManifest( FileUtilsWrapper& file_utils, const base::FilePath& dir, const base::FilePath& file,
diff --git a/chrome/browser/web_applications/external_web_app_utils_unittest.cc b/chrome/browser/web_applications/external_web_app_utils_unittest.cc index 2bf77aa85..6e8a832 100644 --- a/chrome/browser/web_applications/external_web_app_utils_unittest.cc +++ b/chrome/browser/web_applications/external_web_app_utils_unittest.cc
@@ -45,9 +45,14 @@ base::JSONReader::Read(app_config_string); DCHECK(app_config); FileUtilsWrapper file_utils; - return ::web_app::ParseConfig(file_utils, /*dir=*/base::FilePath(), - /*file=*/base::FilePath(), - app_config.value()); + OptionsOrError result = + ::web_app::ParseConfig(file_utils, /*dir=*/base::FilePath(), + /*file=*/base::FilePath(), app_config.value()); + if (ExternalInstallOptions* options = + absl::get_if<ExternalInstallOptions>(&result)) { + return std::move(*options); + } + return base::nullopt; } base::Optional<WebApplicationInfoFactory> ParseOfflineManifest( @@ -55,10 +60,15 @@ base::Optional<base::Value> offline_manifest = base::JSONReader::Read(offline_manifest_string); DCHECK(offline_manifest); - return ::web_app::ParseOfflineManifest( + WebApplicationInfoFactoryOrError result = ::web_app::ParseOfflineManifest( *file_utils_, base::FilePath(FILE_PATH_LITERAL("test_dir")), base::FilePath(FILE_PATH_LITERAL("test_dir/test.json")), *offline_manifest); + if (WebApplicationInfoFactory* factory = + absl::get_if<WebApplicationInfoFactory>(&result)) { + return std::move(*factory); + } + return base::nullopt; } protected:
diff --git a/chrome/browser/web_applications/manifest_update_manager_browsertest.cc b/chrome/browser/web_applications/manifest_update_manager_browsertest.cc index bee93011..d68545ad 100644 --- a/chrome/browser/web_applications/manifest_update_manager_browsertest.cc +++ b/chrome/browser/web_applications/manifest_update_manager_browsertest.cc
@@ -293,10 +293,9 @@ GetProvider().pending_app_manager().Install( std::move(install_options), base::BindLambdaForTesting( - [&](const GURL& installed_app_url, - PendingAppManager::InstallResult result) { + [&](const GURL& installed_app_url, InstallResultCode code) { EXPECT_EQ(installed_app_url, app_url); - EXPECT_EQ(result.code, InstallResultCode::kSuccessNewInstall); + EXPECT_EQ(code, InstallResultCode::kSuccessNewInstall); run_loop.Quit(); })); run_loop.Run();
diff --git a/chrome/browser/web_applications/pending_app_install_task.cc b/chrome/browser/web_applications/pending_app_install_task.cc index 3d48a8e..c879884 100644 --- a/chrome/browser/web_applications/pending_app_install_task.cc +++ b/chrome/browser/web_applications/pending_app_install_task.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" -#include "base/metrics/histogram_functions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/favicon/favicon_utils.h" @@ -28,6 +27,16 @@ namespace web_app { +PendingAppInstallTask::Result::Result(InstallResultCode code, + base::Optional<AppId> app_id) + : code(code), app_id(std::move(app_id)) { + DCHECK_EQ(IsNewInstall(code), app_id.has_value()); +} + +PendingAppInstallTask::Result::Result(Result&&) = default; + +PendingAppInstallTask::Result::~Result() = default; + // static void PendingAppInstallTask::CreateTabHelpers( content::WebContents* web_contents) { @@ -114,8 +123,7 @@ base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(std::move(retry_on_failure), /*app_id=*/base::nullopt, - PendingAppManager::InstallResult{.code = code})); + base::BindOnce(std::move(retry_on_failure), Result(code, base::nullopt))); } void PendingAppInstallTask::InstallFromInfo(ResultCallback result_callback) { @@ -164,8 +172,8 @@ LOG(ERROR) << "Failed to uninstall placeholder for: " << install_options_.install_url; std::move(result_callback) - .Run(/*app_id=*/base::nullopt, - {.code = InstallResultCode::kFailedPlaceholderUninstall}); + .Run(Result(InstallResultCode::kFailedPlaceholderUninstall, + base::nullopt)); return; } ContinueWebAppInstall(web_contents, std::move(result_callback)); @@ -195,9 +203,8 @@ // No need to install a placeholder app again. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(std::move(callback), app_id, - PendingAppManager::InstallResult{ - .code = InstallResultCode::kSuccessNewInstall})); + base::BindOnce(std::move(callback), + Result(InstallResultCode::kSuccessNewInstall, app_id))); return; } @@ -234,11 +241,11 @@ const AppId& app_id, InstallResultCode code) { if (!IsNewInstall(code)) { - std::move(result_callback).Run(/*app_id=*/base::nullopt, {.code = code}); + std::move(result_callback).Run(Result(code, base::nullopt)); return; } - bool did_uninstall_and_replace = ui_manager_->UninstallAndReplaceIfExists( + ui_manager_->UninstallAndReplaceIfExists( install_options().uninstall_and_replace, app_id); externally_installed_app_prefs_.Insert(install_options_.install_url, app_id, @@ -251,11 +258,8 @@ ? InstallResultCode::kSuccessOfflineOnlyInstall : InstallResultCode::kSuccessOfflineFallbackInstall; } - base::ScopedClosureRunner scoped_closure(base::BindOnce( - std::move(result_callback), app_id, - PendingAppManager::InstallResult{ - .code = code, - .did_uninstall_and_replace = did_uninstall_and_replace})); + base::ScopedClosureRunner scoped_closure( + base::BindOnce(std::move(result_callback), Result(code, app_id))); if (!is_placeholder) { return; @@ -293,13 +297,12 @@ void PendingAppInstallTask::TryAppInfoFactoryOnFailure( ResultCallback result_callback, - base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { + Result result) { if (!IsSuccess(result.code) && install_options().app_info_factory) { InstallFromInfo(std::move(result_callback)); return; } - std::move(result_callback).Run(std::move(app_id), std::move(result)); + std::move(result_callback).Run(std::move(result)); } } // namespace web_app
diff --git a/chrome/browser/web_applications/pending_app_install_task.h b/chrome/browser/web_applications/pending_app_install_task.h index 22b3386..35d5d49 100644 --- a/chrome/browser/web_applications/pending_app_install_task.h +++ b/chrome/browser/web_applications/pending_app_install_task.h
@@ -14,7 +14,6 @@ #include "chrome/browser/web_applications/components/external_install_options.h" #include "chrome/browser/web_applications/components/externally_installed_web_app_prefs.h" #include "chrome/browser/web_applications/components/os_integration_manager.h" -#include "chrome/browser/web_applications/components/pending_app_manager.h" #include "chrome/browser/web_applications/components/web_app_id.h" #include "chrome/browser/web_applications/components/web_app_install_utils.h" #include "chrome/browser/web_applications/components/web_app_url_loader.h" @@ -38,9 +37,19 @@ // PendingAppManager. Can only be called from the UI thread. class PendingAppInstallTask { public: - using ResultCallback = - base::OnceCallback<void(base::Optional<AppId> app_id, - PendingAppManager::InstallResult result)>; + // TODO(loyso): Use InstallManager::OnceInstallCallback directly. + struct Result { + Result(InstallResultCode code, base::Optional<AppId> app_id); + Result(Result&&); + Result(const Result&) = delete; + Result& operator=(const Result&) = delete; + ~Result(); + + const InstallResultCode code; + const base::Optional<AppId> app_id; + }; + + using ResultCallback = base::OnceCallback<void(Result)>; // Ensures the tab helpers necessary for installing an app are present. static void CreateTabHelpers(content::WebContents* web_contents); @@ -91,8 +100,7 @@ const AppId& app_id, InstallResultCode code); void TryAppInfoFactoryOnFailure(ResultCallback result_callback, - base::Optional<AppId> app_id, - PendingAppManager::InstallResult result); + Result result); void OnOsHooksCreated(const AppId& app_id, base::ScopedClosureRunner scoped_closure, const OsHooksResults os_hooks_results);
diff --git a/chrome/browser/web_applications/pending_app_manager_impl.cc b/chrome/browser/web_applications/pending_app_manager_impl.cc index 43425d5..b23c213 100644 --- a/chrome/browser/web_applications/pending_app_manager_impl.cc +++ b/chrome/browser/web_applications/pending_app_manager_impl.cc
@@ -179,8 +179,7 @@ // Otherwise no need to do anything. std::move(front->callback) .Run(install_options.install_url, - {.code = InstallResultCode::kSuccessAlreadyInstalled, - .did_uninstall_and_replace = false}); + InstallResultCode::kSuccessAlreadyInstalled); continue; } @@ -191,8 +190,7 @@ !install_options.override_previous_user_uninstall) { std::move(front->callback) .Run(install_options.install_url, - {.code = InstallResultCode::kPreviouslyUninstalled, - .did_uninstall_and_replace = false}); + InstallResultCode::kPreviouslyUninstalled); continue; } @@ -274,10 +272,14 @@ weak_ptr_factory_.GetWeakPtr())); } -void PendingAppManagerImpl::OnInstalled( - base::Optional<AppId> app_id, - PendingAppManager::InstallResult result) { - if (app_id && IsSuccess(result.code)) { +void PendingAppManagerImpl::OnInstalled(PendingAppInstallTask::Result result) { + CurrentInstallationFinished(result.app_id, result.code); +} + +void PendingAppManagerImpl::CurrentInstallationFinished( + const base::Optional<AppId>& app_id, + InstallResultCode code) { + if (app_id && IsSuccess(code)) { MaybeEnqueueServiceWorkerRegistration( current_install_->task->install_options()); } @@ -290,7 +292,7 @@ std::unique_ptr<TaskAndCallback> task_and_callback; task_and_callback.swap(current_install_); std::move(task_and_callback->callback) - .Run(task_and_callback->task->install_options().install_url, result); + .Run(task_and_callback->task->install_options().install_url, code); } void PendingAppManagerImpl::MaybeEnqueueServiceWorkerRegistration(
diff --git a/chrome/browser/web_applications/pending_app_manager_impl.h b/chrome/browser/web_applications/pending_app_manager_impl.h index af3e144d..37f8da4 100644 --- a/chrome/browser/web_applications/pending_app_manager_impl.h +++ b/chrome/browser/web_applications/pending_app_manager_impl.h
@@ -82,8 +82,10 @@ void OnUrlLoaded(WebAppUrlLoader::Result result); - void OnInstalled(base::Optional<AppId> app_id, - PendingAppManager::InstallResult result); + void OnInstalled(PendingAppInstallTask::Result result); + + void CurrentInstallationFinished(const base::Optional<std::string>& app_id, + InstallResultCode code); void MaybeEnqueueServiceWorkerRegistration( const ExternalInstallOptions& install_options);
diff --git a/chrome/browser/web_applications/pending_app_manager_impl_browsertest.cc b/chrome/browser/web_applications/pending_app_manager_impl_browsertest.cc index 2e117d8..1c8ac34 100644 --- a/chrome/browser/web_applications/pending_app_manager_impl_browsertest.cc +++ b/chrome/browser/web_applications/pending_app_manager_impl_browsertest.cc
@@ -404,12 +404,12 @@ ExternalInstallSource::kExternalPolicy, base::BindLambdaForTesting( [&run_loop, &app_url]( - std::map<GURL, PendingAppManager::InstallResult> install_results, + std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { EXPECT_TRUE(uninstall_results.empty()); EXPECT_EQ(install_results.size(), 1U); - EXPECT_EQ(install_results[app_url].code, - InstallResultCode::kSuccessNewInstall); + EXPECT_EQ(install_results[app_url], + InstallResultCode ::kSuccessNewInstall); run_loop.Quit(); })); run_loop.Run();
diff --git a/chrome/browser/web_applications/pending_app_manager_impl_unittest.cc b/chrome/browser/web_applications/pending_app_manager_impl_unittest.cc index 46f0ca32..c9d6dc8a 100644 --- a/chrome/browser/web_applications/pending_app_manager_impl_unittest.cc +++ b/chrome/browser/web_applications/pending_app_manager_impl_unittest.cc
@@ -105,7 +105,11 @@ ExternalInstallOptions options(FooWebAppUrl(), DisplayMode::kBrowser, ExternalInstallSource::kExternalPolicy); options.only_use_app_info_factory = true; - options.app_info_factory = base::BindRepeating(&GetFooWebApplicationInfo); + // Static to ensure re-use across multiple function calls for + // ExternalInstallOptions equality checking. + static WebApplicationInfoFactory app_info_factory = + base::BindRepeating(&GetFooWebApplicationInfo); + options.app_info_factory = app_info_factory; if (override_previous_user_uninstall.has_value()) options.override_previous_user_uninstall = @@ -269,7 +273,7 @@ externally_installed_app_prefs_.SetIsPlaceholder(install_url, is_placeholder); } - std::move(callback).Run(app_id, {.code = result_code}); + std::move(callback).Run({result_code, app_id}); } void Install(content::WebContents* web_contents, WebAppUrlLoader::Result url_loaded_result, @@ -393,21 +397,20 @@ pending_app_manager_impl()->Install( std::move(install_options), - base::BindLambdaForTesting( - [&](const GURL& u, PendingAppManager::InstallResult result) { - url = u; - code = result.code; - run_loop.Quit(); - })); + base::BindLambdaForTesting([&](const GURL& u, InstallResultCode c) { + url = u; + code = c; + run_loop.Quit(); + })); run_loop.Run(); return {url.value(), code.value()}; } - InstallAppsResults InstallAppsAndWait( + std::vector<std::pair<GURL, InstallResultCode>> InstallAppsAndWait( PendingAppManager* pending_app_manager, std::vector<ExternalInstallOptions> apps_to_install) { - InstallAppsResults results; + std::vector<std::pair<GURL, InstallResultCode>> results; base::RunLoop run_loop; auto barrier_closure = @@ -415,8 +418,8 @@ pending_app_manager_impl()->InstallApps( std::move(apps_to_install), base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - results.emplace_back(url, result.code); + [&](const GURL& url, InstallResultCode code) { + results.emplace_back(url, code); barrier_closure.Run(); })); run_loop.Run(); @@ -598,31 +601,29 @@ base::RunLoop run_loop; pending_app_manager_impl()->Install( GetFooInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(FooWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(FooWebAppUrl(), url); - // Two installations tasks should have run at this point, - // one from the last call to install (which gets higher priority), - // and another one for this call to install. - EXPECT_EQ(2u, install_run_count()); - EXPECT_EQ(GetFooInstallOptions(), last_install_options()); + // Two installations tasks should have run at this point, + // one from the last call to install (which gets higher priority), + // and another one for this call to install. + EXPECT_EQ(2u, install_run_count()); + EXPECT_EQ(GetFooInstallOptions(), last_install_options()); - run_loop.Quit(); - })); + run_loop.Quit(); + })); pending_app_manager_impl()->Install( GetBarInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(BarWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(BarWebAppUrl(), url); - // The last call gets higher priority so only one - // installation task should have run at this point. - EXPECT_EQ(1u, install_run_count()); - EXPECT_EQ(GetBarInstallOptions(), last_install_options()); - })); + // The last call gets higher priority so only one + // installation task should have run at this point. + EXPECT_EQ(1u, install_run_count()); + EXPECT_EQ(GetBarInstallOptions(), last_install_options()); + })); run_loop.Run(); } @@ -642,32 +643,30 @@ pending_app_manager_impl()->Install( GetFooInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(FooWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(FooWebAppUrl(), url); - EXPECT_EQ(1u, install_run_count()); - EXPECT_EQ(GetFooInstallOptions(), last_install_options()); + EXPECT_EQ(1u, install_run_count()); + EXPECT_EQ(GetFooInstallOptions(), last_install_options()); - foo_run_loop.Quit(); - })); + foo_run_loop.Quit(); + })); // Make sure the installation has started. base::RunLoop().RunUntilIdle(); url_loader()->AddPrepareForLoadResults({WebAppUrlLoader::Result::kUrlLoaded}); pending_app_manager_impl()->Install( GetBarInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(BarWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(BarWebAppUrl(), url); - EXPECT_EQ(2u, install_run_count()); - EXPECT_EQ(GetBarInstallOptions(), last_install_options()); + EXPECT_EQ(2u, install_run_count()); + EXPECT_EQ(GetBarInstallOptions(), last_install_options()); - bar_run_loop.Quit(); - })); + bar_run_loop.Quit(); + })); url_loader()->ProcessLoadUrlRequests(); foo_run_loop.Run(); @@ -688,9 +687,8 @@ pending_app_manager_impl()->Install( GetFooInstallOptionsWithWebAppInfo(), - base::BindLambdaForTesting([&](const GURL& url, - PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); EXPECT_EQ(FooWebAppUrl(), url); EXPECT_EQ(1u, install_run_count()); @@ -739,9 +737,8 @@ pending_app_manager_impl()->Install( GetFooInstallOptionsWithWebAppInfo(), - base::BindLambdaForTesting([&](const GURL& url, - PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); EXPECT_EQ(FooWebAppUrl(), url); EXPECT_EQ(1u, install_run_count()); @@ -753,9 +750,8 @@ pending_app_manager_impl()->Install( GetFooInstallOptionsWithWebAppInfo(), - base::BindLambdaForTesting([&](const GURL& url, - PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessAlreadyInstalled, result.code); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessAlreadyInstalled, code); EXPECT_EQ(FooWebAppUrl(), url); EXPECT_EQ(1u, install_run_count()); @@ -785,30 +781,28 @@ url_loader()->SetPrepareForLoadResultLoaded(); pending_app_manager_impl()->Install( GetFooInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kWebAppDisabled, result.code); - EXPECT_EQ(FooWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kWebAppDisabled, code); + EXPECT_EQ(FooWebAppUrl(), url); - EXPECT_EQ(1u, install_run_count()); + EXPECT_EQ(1u, install_run_count()); - foo_run_loop.Quit(); - })); + foo_run_loop.Quit(); + })); // Make sure the installation has started. base::RunLoop().RunUntilIdle(); pending_app_manager_impl()->Install( GetBarInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(BarWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(BarWebAppUrl(), url); - EXPECT_EQ(2u, install_run_count()); - EXPECT_EQ(GetBarInstallOptions(), last_install_options()); + EXPECT_EQ(2u, install_run_count()); + EXPECT_EQ(GetBarInstallOptions(), last_install_options()); - bar_run_loop.Quit(); - })); + bar_run_loop.Quit(); + })); url_loader()->ProcessLoadUrlRequests(); foo_run_loop.Run(); @@ -836,18 +830,18 @@ WebAppUrlLoader::Result::kUrlLoaded); base::RunLoop run_loop; - auto final_callback = base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + auto final_callback = + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); EXPECT_EQ(BarWebAppUrl(), url); EXPECT_EQ(2u, install_run_count()); EXPECT_EQ(GetBarInstallOptions(), last_install_options()); run_loop.Quit(); }); - auto reentrant_callback = base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + auto reentrant_callback = + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); EXPECT_EQ(FooWebAppUrl(), url); EXPECT_EQ(1u, install_run_count()); @@ -909,33 +903,31 @@ pending_app_manager_impl()->Install( GetFooInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - // kSuccessAlreadyInstalled because the last call to Install gets - // higher priority. - EXPECT_EQ(InstallResultCode::kSuccessAlreadyInstalled, result.code); - EXPECT_EQ(FooWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + // kSuccessAlreadyInstalled because the last call to Install gets higher + // priority. + EXPECT_EQ(InstallResultCode::kSuccessAlreadyInstalled, code); + EXPECT_EQ(FooWebAppUrl(), url); - // Only one installation task should run because the app was already - // installed. - EXPECT_EQ(1u, install_run_count()); + // Only one installation task should run because the app was already + // installed. + EXPECT_EQ(1u, install_run_count()); - EXPECT_TRUE(first_callback_ran); + EXPECT_TRUE(first_callback_ran); - run_loop.Quit(); - })); + run_loop.Quit(); + })); pending_app_manager_impl()->Install( GetFooInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(FooWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(FooWebAppUrl(), url); - EXPECT_EQ(1u, install_run_count()); - EXPECT_EQ(GetFooInstallOptions(), last_install_options()); - first_callback_ran = true; - })); + EXPECT_EQ(1u, install_run_count()); + EXPECT_EQ(GetFooInstallOptions(), last_install_options()); + first_callback_ran = true; + })); run_loop.Run(); EXPECT_EQ(1u, install_run_count()); @@ -1145,8 +1137,8 @@ pending_app_manager_impl()->InstallApps( std::move(apps_to_install), base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + [&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); EXPECT_EQ(FooWebAppUrl(), url); EXPECT_EQ(1u, install_run_count()); @@ -1161,8 +1153,8 @@ pending_app_manager_impl()->InstallApps( std::move(apps_to_install), base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); + [&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); EXPECT_EQ(BarWebAppUrl(), url); EXPECT_EQ(2u, install_run_count()); @@ -1206,38 +1198,36 @@ int callback_calls = 0; pending_app_manager_impl()->InstallApps( std::move(apps_to_install), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - ++callback_calls; - if (callback_calls == 1) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(FooWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + ++callback_calls; + if (callback_calls == 1) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(FooWebAppUrl(), url); - EXPECT_EQ(2u, install_run_count()); - EXPECT_EQ(GetFooInstallOptions(), last_install_options()); - } else if (callback_calls == 2) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(BarWebAppUrl(), url); + EXPECT_EQ(2u, install_run_count()); + EXPECT_EQ(GetFooInstallOptions(), last_install_options()); + } else if (callback_calls == 2) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(BarWebAppUrl(), url); - EXPECT_EQ(3u, install_run_count()); - EXPECT_EQ(GetBarInstallOptions(), last_install_options()); - } else { - NOTREACHED(); - } - })); + EXPECT_EQ(3u, install_run_count()); + EXPECT_EQ(GetBarInstallOptions(), last_install_options()); + } else { + NOTREACHED(); + } + })); // Queue through Install. pending_app_manager_impl()->Install( GetQuxInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(QuxWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(QuxWebAppUrl(), url); - // The install request from Install should be processed first. - EXPECT_EQ(1u, install_run_count()); - EXPECT_EQ(GetQuxInstallOptions(), last_install_options()); - })); + // The install request from Install should be processed first. + EXPECT_EQ(1u, install_run_count()); + EXPECT_EQ(GetQuxInstallOptions(), last_install_options()); + })); WebAppRegistrationWaiter(pending_app_manager_impl()) .AwaitNextRegistration(QuxWebAppUrl(), RegistrationResultCode::kSuccess); @@ -1271,15 +1261,14 @@ // Queue through Install. pending_app_manager_impl()->Install( GetQuxInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(QuxWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(QuxWebAppUrl(), url); - // The install request from Install should be processed first. - EXPECT_EQ(1u, install_run_count()); - EXPECT_EQ(GetQuxInstallOptions(), last_install_options()); - })); + // The install request from Install should be processed first. + EXPECT_EQ(1u, install_run_count()); + EXPECT_EQ(GetQuxInstallOptions(), last_install_options()); + })); // Queue through InstallApps. std::vector<ExternalInstallOptions> apps_to_install; @@ -1289,31 +1278,30 @@ int callback_calls = 0; pending_app_manager_impl()->InstallApps( std::move(apps_to_install), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - ++callback_calls; - if (callback_calls == 1) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(FooWebAppUrl(), url); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + ++callback_calls; + if (callback_calls == 1) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(FooWebAppUrl(), url); - // The install requests from InstallApps should be processed next. - EXPECT_EQ(2u, install_run_count()); - EXPECT_EQ(GetFooInstallOptions(), last_install_options()); + // The install requests from InstallApps should be processed next. + EXPECT_EQ(2u, install_run_count()); + EXPECT_EQ(GetFooInstallOptions(), last_install_options()); - return; - } - if (callback_calls == 2) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(BarWebAppUrl(), url); + return; + } + if (callback_calls == 2) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(BarWebAppUrl(), url); - EXPECT_EQ(3u, install_run_count()); - EXPECT_EQ(GetBarInstallOptions(), last_install_options()); + EXPECT_EQ(3u, install_run_count()); + EXPECT_EQ(GetBarInstallOptions(), last_install_options()); - run_loop.Quit(); - return; - } - NOTREACHED(); - })); + run_loop.Quit(); + return; + } + NOTREACHED(); + })); run_loop.Run(); } @@ -1476,12 +1464,11 @@ base::RunLoop run_loop; pending_app_manager_impl()->Install( GetFooInstallOptions(), - base::BindLambdaForTesting( - [&](const GURL& url, PendingAppManager::InstallResult result) { - EXPECT_EQ(InstallResultCode::kSuccessNewInstall, result.code); - EXPECT_EQ(FooWebAppUrl(), url); - run_loop.Quit(); - })); + base::BindLambdaForTesting([&](const GURL& url, InstallResultCode code) { + EXPECT_EQ(InstallResultCode::kSuccessNewInstall, code); + EXPECT_EQ(FooWebAppUrl(), url); + run_loop.Quit(); + })); install_finalizer()->SetNextUninstallExternalWebAppResult(FooWebAppUrl(), false);
diff --git a/chrome/browser/web_applications/system_web_app_manager.cc b/chrome/browser/web_applications/system_web_app_manager.cc index 75ec659c..2a7ff73 100644 --- a/chrome/browser/web_applications/system_web_app_manager.cc +++ b/chrome/browser/web_applications/system_web_app_manager.cc
@@ -715,17 +715,16 @@ } void SystemWebAppManager::RecordSystemWebAppInstallResults( - const std::map<GURL, PendingAppManager::InstallResult>& install_results) - const { + const std::map<GURL, InstallResultCode>& install_results) const { // Report install result codes. Exclude kSuccessAlreadyInstalled from metrics. // This result means the installation pipeline is a no-op (which happens every // time user logs in, and if there hasn't been a version upgrade). This skews // the install success rate. - std::map<GURL, PendingAppManager::InstallResult> results_to_report; + std::map<GURL, InstallResultCode> results_to_report; std::copy_if(install_results.begin(), install_results.end(), std::inserter(results_to_report, results_to_report.end()), [](const auto& url_and_result) { - return url_and_result.second.code != + return url_and_result.second != InstallResultCode::kSuccessAlreadyInstalled; }); @@ -735,14 +734,14 @@ kInstallResultHistogramName, shutting_down_ ? InstallResultCode::kCancelledOnWebAppProviderShuttingDown - : url_and_result.second.code); + : url_and_result.second); // Record per-profile result. base::UmaHistogramEnumeration( install_result_per_profile_histogram_name_, shutting_down_ ? InstallResultCode::kCancelledOnWebAppProviderShuttingDown - : url_and_result.second.code); + : url_and_result.second); } // Record per-app result. @@ -757,7 +756,7 @@ app_histogram_name, shutting_down_ ? InstallResultCode::kCancelledOnWebAppProviderShuttingDown - : url_and_result->second.code); + : url_and_result->second); } } } @@ -765,7 +764,7 @@ void SystemWebAppManager::OnAppsSynchronized( bool did_force_install_apps, const base::TimeTicks& install_start_time, - std::map<GURL, PendingAppManager::InstallResult> install_results, + std::map<GURL, InstallResultCode> install_results, std::map<GURL, bool> uninstall_results) { // TODO(crbug.com/1053371): Clean up File Handler install. We install SWA file // handlers here, because the code that registers file handlers for regular
diff --git a/chrome/browser/web_applications/system_web_app_manager.h b/chrome/browser/web_applications/system_web_app_manager.h index c40ea69..074f37f 100644 --- a/chrome/browser/web_applications/system_web_app_manager.h +++ b/chrome/browser/web_applications/system_web_app_manager.h
@@ -255,11 +255,10 @@ bool AppHasFileHandlingOriginTrial(SystemAppType type); - void OnAppsSynchronized( - bool did_force_install_apps, - const base::TimeTicks& install_start_time, - std::map<GURL, PendingAppManager::InstallResult> install_results, - std::map<GURL, bool> uninstall_results); + void OnAppsSynchronized(bool did_force_install_apps, + const base::TimeTicks& install_start_time, + std::map<GURL, InstallResultCode> install_results, + std::map<GURL, bool> uninstall_results); bool ShouldForceInstallApps() const; void UpdateLastAttemptedInfo(); // Returns if we have exceeded the number of retry attempts allowed for this @@ -267,8 +266,7 @@ bool CheckAndIncrementRetryAttempts(); void RecordSystemWebAppInstallResults( - const std::map<GURL, PendingAppManager::InstallResult>& install_results) - const; + const std::map<GURL, InstallResultCode>& install_results) const; void RecordSystemWebAppInstallDuration( const base::TimeDelta& time_duration) const;
diff --git a/chrome/browser/web_applications/system_web_app_manager_unittest.cc b/chrome/browser/web_applications/system_web_app_manager_unittest.cc index f5d0450..5acbfcc 100644 --- a/chrome/browser/web_applications/system_web_app_manager_unittest.cc +++ b/chrome/browser/web_applications/system_web_app_manager_unittest.cc
@@ -634,9 +634,8 @@ } pending_app_manager().SetHandleInstallRequestCallback( - base::BindLambdaForTesting([](const ExternalInstallOptions&) - -> PendingAppManager::InstallResult { - return {.code = InstallResultCode::kWebAppDisabled}; + base::BindLambdaForTesting([](const ExternalInstallOptions&) { + return InstallResultCode::kWebAppDisabled; })); { @@ -725,11 +724,10 @@ system_web_app_manager().SetSystemAppsForTesting(system_apps); pending_app_manager().SetHandleInstallRequestCallback( - base::BindLambdaForTesting([](const ExternalInstallOptions& opts) - -> PendingAppManager::InstallResult { + base::BindLambdaForTesting([](const ExternalInstallOptions& opts) { if (opts.install_url == AppUrl1()) - return {.code = InstallResultCode::kSuccessAlreadyInstalled}; - return {.code = InstallResultCode::kSuccessNewInstall}; + return InstallResultCode::kSuccessAlreadyInstalled; + return InstallResultCode::kSuccessNewInstall; })); StartAndWaitForAppsToSynchronize(); @@ -758,11 +756,10 @@ { pending_app_manager().SetHandleInstallRequestCallback( - base::BindLambdaForTesting([](const ExternalInstallOptions& opts) - -> PendingAppManager::InstallResult { + base::BindLambdaForTesting([](const ExternalInstallOptions& opts) { if (opts.install_url == AppUrl1()) - return {.code = InstallResultCode::kWriteDataFailed}; - return {.code = InstallResultCode::kSuccessNewInstall}; + return InstallResultCode::kWriteDataFailed; + return InstallResultCode::kSuccessNewInstall; })); StartAndWaitForAppsToSynchronize(); @@ -775,11 +772,10 @@ { pending_app_manager().SetHandleInstallRequestCallback( - base::BindLambdaForTesting([](const ExternalInstallOptions& opts) - -> PendingAppManager::InstallResult { + base::BindLambdaForTesting([](const ExternalInstallOptions& opts) { if (opts.install_url == AppUrl1()) - return {.code = InstallResultCode::kSuccessNewInstall}; - return {.code = InstallResultCode::kSuccessAlreadyInstalled}; + return InstallResultCode::kSuccessNewInstall; + return InstallResultCode::kSuccessAlreadyInstalled; })); StartAndWaitForAppsToSynchronize();
diff --git a/chrome/browser/web_applications/test/test_pending_app_manager.cc b/chrome/browser/web_applications/test/test_pending_app_manager.cc index d0c62dc..4c5453e 100644 --- a/chrome/browser/web_applications/test/test_pending_app_manager.cc +++ b/chrome/browser/web_applications/test/test_pending_app_manager.cc
@@ -63,7 +63,7 @@ } install_requests_.push_back(install_options); } - std::move(std::move(callback)).Run(url, {.code = result_code}); + std::move(std::move(callback)).Run(url, result_code); })); }
diff --git a/chrome/browser/web_applications/test/test_pending_app_manager_impl.h b/chrome/browser/web_applications/test/test_pending_app_manager_impl.h index 73ff215..209ac71 100644 --- a/chrome/browser/web_applications/test/test_pending_app_manager_impl.h +++ b/chrome/browser/web_applications/test/test_pending_app_manager_impl.h
@@ -38,8 +38,7 @@ } using HandleInstallRequestCallback = - base::RepeatingCallback<PendingAppManager::InstallResult( - const ExternalInstallOptions&)>; + base::RepeatingCallback<InstallResultCode(const ExternalInstallOptions&)>; // Set a callback to handle install requests. If set, this callback will be // used in place of the real installation process. The callback takes a const
diff --git a/chrome/browser/web_applications/test/test_web_app_ui_manager.cc b/chrome/browser/web_applications/test/test_web_app_ui_manager.cc index 64be713..15372c32 100644 --- a/chrome/browser/web_applications/test/test_web_app_ui_manager.cc +++ b/chrome/browser/web_applications/test/test_web_app_ui_manager.cc
@@ -54,13 +54,12 @@ })); } -bool TestWebAppUiManager::UninstallAndReplaceIfExists( +void TestWebAppUiManager::UninstallAndReplaceIfExists( const std::vector<AppId>& from_apps, const AppId& to_app) { for (const AppId& from_app : from_apps) { uninstall_and_replace_map_[from_app] = to_app; } - return false; } bool TestWebAppUiManager::CanAddAppToQuickLaunchBar() const {
diff --git a/chrome/browser/web_applications/test/test_web_app_ui_manager.h b/chrome/browser/web_applications/test/test_web_app_ui_manager.h index 324a4f65..95d4d454 100644 --- a/chrome/browser/web_applications/test/test_web_app_ui_manager.h +++ b/chrome/browser/web_applications/test/test_web_app_ui_manager.h
@@ -30,7 +30,7 @@ size_t GetNumWindowsForApp(const AppId& app_id) override; void NotifyOnAllAppWindowsClosed(const AppId& app_id, base::OnceClosure callback) override; - bool UninstallAndReplaceIfExists(const std::vector<AppId>& from_apps, + void UninstallAndReplaceIfExists(const std::vector<AppId>& from_apps, const AppId& to_app) override; bool CanAddAppToQuickLaunchBar() const override; void AddAppToQuickLaunchBar(const AppId& app_id) override;
diff --git a/chrome/browser/web_applications/web_app_provider.h b/chrome/browser/web_applications/web_app_provider.h index f3c22bb..0170c79 100644 --- a/chrome/browser/web_applications/web_app_provider.h +++ b/chrome/browser/web_applications/web_app_provider.h
@@ -92,7 +92,7 @@ return on_registry_ready_; } - ExternalWebAppManager& external_web_app_manager_for_testing() { + ExternalWebAppManager& external_web_app_manager() { return *external_web_app_manager_; }
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 16133f8..a2964ee6 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-master-1606780634-867f063cb43c5794bf65123662fce4e91b9de4cb.profdata +chrome-linux-master-1606802354-d1c692a560ec6fde56aef2f398f74e894835d223.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 0d4cde7a..5b3d3fa 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-master-1606780634-1ea1516e4fb1522afac8d06bcea54ae6d1ecbcd2.profdata +chrome-mac-master-1606802354-31ea8b5273cb9879cfc7599870323fbd7fd3af58.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index b97906a0..5977438f 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-master-1606649289-a1ddd7e3579fd6803de4501ea269c51715a31009.profdata +chrome-win32-master-1606759191-849e6110591039c862ea10277c9aceb1aa0b28d5.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 00533cb2..8cc1983 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-master-1606748271-2b69dce80f38ecf2d66f6209245527ea06788f5d.profdata +chrome-win64-master-1606780634-4bcba867177e99782f7fa7f8d4c0822ffa36a5f3.profdata
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 89ce501..763632a6 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -445,6 +445,16 @@ "HappinessTrackingSurveysForDesktopDemo", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables or disables the Happiness Tracking System for COEP issues in Chrome +// DevTools on Desktop. +const base::Feature kHaTSDesktopDevToolsIssuesCOEP{ + "HaTSDesktopDevToolsIssuesCOEP", base::FEATURE_DISABLED_BY_DEFAULT}; + +// Enables or disables the Happiness Tracking System for Mixed Content issues in +// Chrome DevTools on Desktop. +const base::Feature kHaTSDesktopDevToolsIssuesMixedContent{ + "HaTSDesktopDevToolsIssuesMixedContent", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables or disables the Happiness Tracking System for same-site cookies // issues in Chrome DevTools on Desktop. const base::Feature @@ -452,6 +462,16 @@ "HappinessTrackingSurveysForDesktopDevToolsIssuesCookiesSameSite", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables or disables the Happiness Tracking System for Heavy Ad issues in +// Chrome DevTools on Desktop. +const base::Feature kHaTSDesktopDevToolsIssuesHeavyAd{ + "HaTSDesktopDevToolsIssuesHeavyAd", base::FEATURE_DISABLED_BY_DEFAULT}; + +// Enables or disables the Happiness Tracking System for CSP issues in Chrome +// DevTools on Desktop. +const base::Feature kHaTSDesktopDevToolsIssuesCSP{ + "HaTSDesktopDevToolsIssuesCSP", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables the migration of Happiness Tracking Surveys on Desktop (to the latest // version). const base::Feature kHappinessTrackingSurveysForDesktopMigration{ @@ -712,6 +732,11 @@ const base::Feature kQuietNotificationPrompts{"QuietNotificationPrompts", base::FEATURE_ENABLED_BY_DEFAULT}; +// Enables recording additional web app related debugging data to be displayed +// in: chrome://internals/web-app +const base::Feature kRecordWebAppDebugInfo{"RecordWebAppDebugInfo", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables notification permission revocation for abusive origins. const base::Feature kAbusiveNotificationPermissionRevocation{ "AbusiveOriginNotificationPermissionRevocation", @@ -733,6 +758,9 @@ "SafetyCheckChromeCleanerChild", base::FEATURE_DISABLED_BY_DEFAULT}; #endif +const base::Feature kSafetyCheckWeakPasswords{ + "SafetyCheckWeakPasswords", base::FEATURE_DISABLED_BY_DEFAULT}; + #if BUILDFLAG(IS_CHROMEOS_ASH) // Enable support for multiple scheduler configurations. const base::Feature kSchedulerConfiguration{"SchedulerConfiguration",
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index 71a8ec1..b50e08c 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -310,8 +310,20 @@ extern const base::Feature kHappinessTrackingSurveysForDesktopSettingsPrivacy; COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::Feature kHaTSDesktopDevToolsIssuesCOEP; + +COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::Feature kHaTSDesktopDevToolsIssuesMixedContent; + +COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kHappinessTrackingSurveysForDesktopDevToolsIssuesCookiesSameSite; + +COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::Feature kHaTSDesktopDevToolsIssuesHeavyAd; + +COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::Feature kHaTSDesktopDevToolsIssuesCSP; #endif #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -476,6 +488,9 @@ extern const base::Feature kQuietNotificationPrompts; COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::Feature kRecordWebAppDebugInfo; + +COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kAbusiveNotificationPermissionRevocation; #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -493,6 +508,9 @@ extern const base::Feature kSafetyCheckChromeCleanerChild; #endif +COMPONENT_EXPORT(CHROME_FEATURES) +extern const base::Feature kSafetyCheckWeakPasswords; + #if BUILDFLAG(IS_CHROMEOS_ASH) COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kSchedulerConfiguration;
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index d4435bb..e166f7a4 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2959,7 +2959,6 @@ "../browser/ui/cocoa/apps/app_shim_menu_controller_mac_browsertest.mm", "../browser/ui/cocoa/apps/native_app_window_cocoa_browsertest.mm", "../browser/ui/cocoa/browser_window_mac_browsertest.mm", - "../browser/ui/cocoa/permission_bubble/permission_bubble_views_cocoa_browsertest.mm", "../browser/ui/cocoa/renderer_context_menu/render_view_context_menu_mac_cocoa_browsertest.mm", "../browser/ui/cocoa/share_menu_controller_browsertest.mm", "../browser/ui/cocoa/task_manager_mac_browsertest.mm",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeTabbedActivityTestRule.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeTabbedActivityTestRule.java index c45154f..65e683d2 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeTabbedActivityTestRule.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeTabbedActivityTestRule.java
@@ -53,9 +53,8 @@ public void resumeMainActivityFromLauncher() throws Exception { Assert.assertNotNull(getActivity()); - @ActivityState - int state = ApplicationStatus.getStateForActivity(getActivity()); - Assert.assertTrue(state == ActivityState.STOPPED || state == ActivityState.PAUSED); + Assert.assertEquals( + ApplicationStatus.getStateForActivity(getActivity()), ActivityState.STOPPED); Intent launchIntent = getActivity().getPackageManager().getLaunchIntentForPackage( getActivity().getPackageName());
diff --git a/chrome/test/data/pdf/BUILD.gn b/chrome/test/data/pdf/BUILD.gn index f148aeb..f2fbbe1 100644 --- a/chrome/test/data/pdf/BUILD.gn +++ b/chrome/test/data/pdf/BUILD.gn
@@ -130,6 +130,7 @@ js_library("fullscreen_test") { deps = [ "../webui:test_util.m", + "//chrome/browser/resources/pdf:constants", "//chrome/browser/resources/pdf:pdf_viewer", ] externs_list = [ "$externs_path/test.js" ]
diff --git a/chrome/test/data/pdf/fullscreen_test.js b/chrome/test/data/pdf/fullscreen_test.js index 7366e05..e92ed96 100644 --- a/chrome/test/data/pdf/fullscreen_test.js +++ b/chrome/test/data/pdf/fullscreen_test.js
@@ -3,19 +3,35 @@ // found in the LICENSE file. import {eventToPromise} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/_test_resources/webui/test_util.m.js'; +import {FittingType} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/constants.js'; import {PDFViewerElement} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer.js'; const tests = [ - function testFullscreen() { + async function testFullscreen() { const viewer = /** @type {!PDFViewerElement} */ ( document.body.querySelector('pdf-viewer')); + const scroller = /** @type {!HTMLElement} */ ( + viewer.shadowRoot.querySelector('#scroller')); + chrome.test.assertTrue(scroller !== null); + + chrome.test.assertEq(FittingType.NONE, viewer.viewport.fittingType); + + const whenFitToTypeChanged = + eventToPromise('fitting-type-changed-for-testing', scroller); + const whenFullscreenChange = eventToPromise('fullscreenchange', scroller); + const toolbar = viewer.shadowRoot.querySelector('viewer-pdf-toolbar-new'); toolbar.dispatchEvent(new CustomEvent('fullscreen-click')); - eventToPromise('fullscreenchange', viewer).then(e => { - chrome.test.assertEq( - viewer.shadowRoot.querySelector('#main'), e.composedPath()[0]); - chrome.test.succeed(); - }); + await whenFitToTypeChanged; + await whenFullscreenChange; + + // Check that the scrollbars are hidden. + chrome.test.assertEq('hidden', window.getComputedStyle(scroller).overflow); + // Check that the `fittingType` has changed. + chrome.test.assertEq( + FittingType.FIT_TO_HEIGHT, viewer.viewport.fittingType); + + chrome.test.succeed(); }, ];
diff --git a/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js b/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js index ac350f2..99a75ba 100644 --- a/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js +++ b/chrome/test/data/webui/chromeos/scanning/scanning_app_test.js
@@ -561,6 +561,14 @@ // enabled, and the cancel button shouldn't be visible. assertTrue(isVisible(scanButton)); assertFalse(isVisible(cancelButton)); + assertTrue(scanningApp.$$('#toast').open); + assertFalse(isVisible( + /** @type {!HTMLElement} */ (scanningApp.$$('#infoIcon')))); + assertFalse(isVisible( + /** @type {!HTMLElement} */ (scanningApp.$$('#getHelpLink')))); + assertEquals( + scanningApp.i18n('scanCanceledToastText'), + scanningApp.$$('#toastText').textContent.trim()); }); }); @@ -608,6 +616,10 @@ .then(() => { // After canceling fails, the error toast should pop up. assertTrue(scanningApp.$$('#toast').open); + assertTrue(isVisible( + /** @type {!HTMLElement} */ (scanningApp.$$('#infoIcon')))); + assertTrue(isVisible( + /** @type {!HTMLElement} */ (scanningApp.$$('#getHelpLink')))); assertEquals( scanningApp.i18n('cancelFailedToastText'), scanningApp.$$('#toastText').textContent.trim()); @@ -649,6 +661,10 @@ }) .then(() => { assertTrue(scanningApp.$$('#toast').open); + assertTrue(isVisible( + /** @type {!HTMLElement} */ (scanningApp.$$('#infoIcon')))); + assertTrue(isVisible( + /** @type {!HTMLElement} */ (scanningApp.$$('#getHelpLink')))); assertEquals( scanningApp.i18n('startScanFailedToast'), scanningApp.$$('#toastText').textContent.trim());
diff --git a/chrome/test/data/webui/new_tab_page/realbox_test.js b/chrome/test/data/webui/new_tab_page/realbox_test.js index 2962a94..e3c48e73 100644 --- a/chrome/test/data/webui/new_tab_page/realbox_test.js +++ b/chrome/test/data/webui/new_tab_page/realbox_test.js
@@ -532,7 +532,12 @@ }); assertEquals(1, testProxy.handler.getCallCount('queryAutocomplete')); - const matches = [createSearchMatch(), createUrlMatch()]; + const matches = [ + createSearchMatch({ + allowedToBeDefaultMatch: true, + }), + createUrlMatch() + ]; testProxy.callbackRouterRemote.autocompleteResultChanged({ input: mojoString16(realbox.$.input.value.trimLeft()), matches, @@ -547,6 +552,14 @@ assertEquals(2, matchEls.length); verifyMatch(matches[0], matchEls[0]); verifyMatch(matches[1], matchEls[1]); + + // First match is selected. + assertTrue(matchEls[0].classList.contains(CLASSES.SELECTED)); + + assertEquals(' hello world', realbox.$.input.value); + let start = realbox.$.input.selectionStart; + let end = realbox.$.input.selectionEnd; + assertEquals('', realbox.$.input.value.substring(start, end)); }); test('autocomplete response with inline autocompletion', async () => { @@ -578,6 +591,9 @@ assertEquals(1, matchEls.length); verifyMatch(matches[0], matchEls[0]); + // First match is selected. + assertTrue(matchEls[0].classList.contains(CLASSES.SELECTED)); + assertEquals('hello world', realbox.$.input.value); let start = realbox.$.input.selectionStart; let end = realbox.$.input.selectionEnd;
diff --git a/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js b/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js index b1b7ae2..0577e85 100644 --- a/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js +++ b/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js
@@ -1382,6 +1382,11 @@ var OSSettingsPeoplePageAccountManagerTest = class extends OSSettingsBrowserTest { /** @override */ + get featureList() { + return {disabled: ['chromeos::features::kAccountManagementFlowsV2']}; + } + + /** @override */ get browsePreload() { return super.browsePreload + 'chromeos/os_people_page/account_manager.html'; } @@ -1401,6 +1406,21 @@ }); // eslint-disable-next-line no-var +var OSSettingsPeoplePageAccountManagerTestWithAccountManagementFlowsV2Enabled = + class extends OSSettingsPeoplePageAccountManagerTest { + /** @override */ + get featureList() { + return {enabled: ['chromeos::features::kAccountManagementFlowsV2']}; + } +}; + +TEST_F( + 'OSSettingsPeoplePageAccountManagerTestWithAccountManagementFlowsV2Enabled', + 'AllJsTests', () => { + mocha.run(); + }); + +// eslint-disable-next-line no-var var OSSettingsPeoplePageChangePictureTest = class extends OSSettingsBrowserTest { /** @override */
diff --git a/chrome/test/data/webui/settings/chromeos/os_settings_v3_browsertest.js b/chrome/test/data/webui/settings/chromeos/os_settings_v3_browsertest.js index 34e35fb..1995abb 100644 --- a/chrome/test/data/webui/settings/chromeos/os_settings_v3_browsertest.js +++ b/chrome/test/data/webui/settings/chromeos/os_settings_v3_browsertest.js
@@ -96,6 +96,35 @@ TEST_F('OSSettingsNearbyShareSubPageV3Test', 'All', () => mocha.run()); +// eslint-disable-next-line no-var +var OSSettingsPeoplePageAccountManagerV3Test = + class extends OSSettingsV3BrowserTest { + /** @override */ + get browsePreload() { + return 'chrome://os-settings/test_loader.html?module=settings/chromeos/people_page_account_manager_test.m.js'; + } + + /** @override */ + get featureList() { + return {disabled: ['chromeos::features::kAccountManagementFlowsV2']}; + } +}; + +TEST_F('OSSettingsPeoplePageAccountManagerV3Test', 'All', () => mocha.run()); + +// eslint-disable-next-line no-var +var OSSettingsPeoplePageAccountManagerV3TestWithAccountManagementFlowsV2Enabled = + class extends OSSettingsPeoplePageAccountManagerV3Test { + /** @override */ + get featureList() { + return {enabled: ['chromeos::features::kAccountManagementFlowsV2']}; + } +}; + +TEST_F( + 'OSSettingsPeoplePageAccountManagerV3TestWithAccountManagementFlowsV2Enabled', + 'All', () => mocha.run()); + [['AboutPage', 'os_about_page_tests.m.js'], ['AmbientModePage', 'ambient_mode_page_test.m.js'], ['BluetoothPage', 'bluetooth_page_tests.m.js'], @@ -134,7 +163,6 @@ ['NearbyShareReceiveDialog', 'nearby_share_receive_dialog_tests.m.js'], ['ParentalControlsPage', 'parental_controls_page_test.m.js'], ['PeoplePage', 'os_people_page_test.m.js'], - ['PeoplePageAccountManager', 'people_page_account_manager_test.m.js'], ['PeoplePageChangePicture', 'people_page_change_picture_test.m.js'], ['PeoplePageKerberosAccounts', 'people_page_kerberos_accounts_test.m.js'], ['PersonalizationPage', 'personalization_page_test.m.js'],
diff --git a/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js b/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js index ed940bf..9c97563 100644 --- a/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js +++ b/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js
@@ -135,7 +135,9 @@ let accountManager = null; let accountList = null; - suiteSetup(function() {}); + suiteSetup(function() { + loadTimeData.overrideValues({isDeviceAccountManaged: true}); + }); setup(function() { browserProxy = new TestAccountManagerBrowserProxy(); @@ -158,8 +160,14 @@ test('AccountListIsPopulatedAtStartup', function() { return browserProxy.whenCalled('getAccounts').then(() => { Polymer.dom.flush(); - // 4 accounts were added in |getAccounts()| mock above. - assertEquals(4, accountList.items.length); + if (accountManager.isAccountManagementFlowsV2Enabled_) { + // 1 device account + 3 secondary accounts were added in + // |getAccounts()| mock above. + assertEquals(3, accountList.items.length); + } else { + // 4 accounts were added in |getAccounts()| mock above. + assertEquals(4, accountList.items.length); + } }); }); @@ -252,10 +260,17 @@ return browserProxy.whenCalled('getAccounts').then(() => { Polymer.dom.flush(); - const managementLabel = - accountManager.root.querySelectorAll('.management-status')[0] - .innerHTML.trim(); - assertEquals('Managed by Family Link', managementLabel); + if (accountManager.isAccountManagementFlowsV2Enabled_) { + const managedBadge = accountManager.root.querySelector( + '.device-account-icon .managed-badge'); + // Managed badge should be shown for managed accounts. + assertFalse(managedBadge.hidden); + } else { + const managementLabel = + accountManager.root.querySelectorAll('.management-status')[0] + .innerHTML.trim(); + assertEquals('Managed by Family Link', managementLabel); + } }); }); }); @@ -265,6 +280,10 @@ let accountManager = null; let accountList = null; + suiteSetup(function() { + loadTimeData.overrideValues({isDeviceAccountManaged: false}); + }); + setup(function() { browserProxy = new TestAccountManagerBrowserProxyForUnmanagedAccounts(); settings.AccountManagerBrowserProxyImpl.instance_ = browserProxy; @@ -286,10 +305,17 @@ return browserProxy.whenCalled('getAccounts').then(() => { Polymer.dom.flush(); - const managementLabel = - accountManager.root.querySelectorAll('.management-status')[0] - .innerHTML.trim(); - assertEquals('Primary account', managementLabel); + if (accountManager.isAccountManagementFlowsV2Enabled_) { + const managedBadge = accountManager.root.querySelector( + '.device-account-icon .managed-badge'); + // Managed badge should not be shown for unmanaged accounts. + assertEquals(null, managedBadge); + } else { + const managementLabel = + accountManager.root.querySelectorAll('.management-status')[0] + .innerHTML.trim(); + assertEquals('Primary account', managementLabel); + } }); }); });
diff --git a/chromeos/chromeos_strings.grd b/chromeos/chromeos_strings.grd index f2c1f57..55cc657e 100644 --- a/chromeos/chromeos_strings.grd +++ b/chromeos/chromeos_strings.grd
@@ -585,6 +585,9 @@ <message name="IDS_SCANNING_APP_CANCEL_FAILED_TOAST_TEXT" desc="The error message displayed when a user attempts to cancel a scan job but the cancel request fails."> Couldn't cancel scanning </message> + <message name="IDS_SCANNING_APP_SCAN_CANCELED_TOAST_TEXT" desc="The message displayed when a scan job is successfully canceled."> + Scanning has been canceled + </message> <!-- Diagnostics App --> <!-- TODO(michaelcheco): Update with finalized copies of the strings -->
diff --git a/chromeos/chromeos_strings_grd/IDS_SCANNING_APP_SCAN_CANCELED_TOAST_TEXT.png.sha1 b/chromeos/chromeos_strings_grd/IDS_SCANNING_APP_SCAN_CANCELED_TOAST_TEXT.png.sha1 new file mode 100644 index 0000000..1bec07f --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_SCANNING_APP_SCAN_CANCELED_TOAST_TEXT.png.sha1
@@ -0,0 +1 @@ +90b295e3dd019d9bab0ddee82c11c290284d157f \ No newline at end of file
diff --git a/chromeos/components/camera_app_ui/resources/images/camera_app_icons_128.png b/chromeos/components/camera_app_ui/resources/images/camera_app_icons_128.png index 4841b83..90509ec2b 100644 --- a/chromeos/components/camera_app_ui/resources/images/camera_app_icons_128.png +++ b/chromeos/components/camera_app_ui/resources/images/camera_app_icons_128.png Binary files differ
diff --git a/chromeos/components/camera_app_ui/resources/images/camera_app_icons_192.png b/chromeos/components/camera_app_ui/resources/images/camera_app_icons_192.png index c5603807..1fb5226 100644 --- a/chromeos/components/camera_app_ui/resources/images/camera_app_icons_192.png +++ b/chromeos/components/camera_app_ui/resources/images/camera_app_icons_192.png Binary files differ
diff --git a/chromeos/components/camera_app_ui/resources/images/camera_app_icons_48.png b/chromeos/components/camera_app_ui/resources/images/camera_app_icons_48.png index 92538b0..51168f0 100644 --- a/chromeos/components/camera_app_ui/resources/images/camera_app_icons_48.png +++ b/chromeos/components/camera_app_ui/resources/images/camera_app_icons_48.png Binary files differ
diff --git a/chromeos/components/camera_app_ui/resources/js/gallerybutton.js b/chromeos/components/camera_app_ui/resources/js/gallerybutton.js index 699e3317..ab414ec 100644 --- a/chromeos/components/camera_app_ui/resources/js/gallerybutton.js +++ b/chromeos/components/camera_app_ui/resources/js/gallerybutton.js
@@ -65,11 +65,8 @@ */ static async create(file) { const isVideo = filesystem.hasVideoPrefix(file); - const fileUrl = await filesystem.pictureURL(file); const thumbnail = - await util.scalePicture(fileUrl, isVideo, THUMBNAIL_WIDTH); - URL.revokeObjectURL(fileUrl); - + await util.scalePicture(await file.file(), isVideo, THUMBNAIL_WIDTH); return new CoverPhoto(file, URL.createObjectURL(thumbnail)); } } @@ -183,15 +180,7 @@ * @override */ async savePhoto(blob, name) { - const orientedPhoto = await new Promise((resolve) => { - // Ignore errors since it is better to save something than - // nothing. - // TODO(yuli): Support showing images by EXIF orientation - // instead. - util.orientPhoto(blob, resolve, () => resolve(blob)); - }); - const file = await filesystem.saveBlob(orientedPhoto, name); - assert(file !== null); + const file = await filesystem.saveBlob(blob, name); await this.updateCover_(file); }
diff --git a/chromeos/components/camera_app_ui/resources/js/util.js b/chromeos/components/camera_app_ui/resources/js/util.js index 92693ac..cdc7008 100644 --- a/chromeos/components/camera_app_ui/resources/js/util.js +++ b/chromeos/components/camera_app_ui/resources/js/util.js
@@ -33,152 +33,6 @@ } /** - * Gets the clockwise rotation and flip that can orient a photo to its upright - * position of the photo and drop its orientation information. - * @param {!Blob} blob JPEG blob that might contain EXIF orientation field. - * @return {!Promise<{rotation: number, flip: boolean, blob: !Blob}>} The - * rotation, flip information of photo and the photo blob after drop those - * information. - */ -function dropPhotoOrientation(blob) { - let /** !Blob */ blobWithoutOrientation = blob; - const getOrientation = (async () => { - const buffer = await blob.arrayBuffer(); - const view = new DataView(buffer); - if (view.getUint16(0, false) !== 0xFFD8) { - return 1; - } - const length = view.byteLength; - let offset = 2; - while (offset < length) { - if (view.getUint16(offset + 2, false) <= 8) { - break; - } - const marker = view.getUint16(offset, false); - offset += 2; - if (marker === 0xFFE1) { - if (view.getUint32(offset += 2, false) !== 0x45786966) { - break; - } - - const little = view.getUint16(offset += 6, false) === 0x4949; - offset += view.getUint32(offset + 4, little); - const tags = view.getUint16(offset, little); - offset += 2; - for (let i = 0; i < tags; i++) { - if (view.getUint16(offset + (i * 12), little) === 0x0112) { - offset += (i * 12) + 8; - const orientation = view.getUint16(offset, little); - view.setUint16(offset, 1, little); - blobWithoutOrientation = new Blob([buffer]); - return orientation; - } - } - } else if ((marker & 0xFF00) !== 0xFF00) { - break; - } else { - offset += view.getUint16(offset, false); - } - } - return 1; - })(); - - return getOrientation - .then((orientation) => { - switch (orientation) { - case 1: - return {rotation: 0, flip: false}; - case 2: - return {rotation: 0, flip: true}; - case 3: - return {rotation: 180, flip: false}; - case 4: - return {rotation: 180, flip: true}; - case 5: - return {rotation: 90, flip: true}; - case 6: - return {rotation: 90, flip: false}; - case 7: - return {rotation: 270, flip: true}; - case 8: - return {rotation: 270, flip: false}; - default: - return {rotation: 0, flip: false}; - } - }) - .then((orientInfo) => { - return Object.assign(orientInfo, {blob: blobWithoutOrientation}); - }); -} - -/** - * Orients a photo to the upright orientation. - * @param {!Blob} blob Photo as a blob. - * @param {function(!Blob)} onSuccess Success callback with the result photo as - * a blob. - * @param {function()} onFailure Failure callback. - */ -export function orientPhoto(blob, onSuccess, onFailure) { - // TODO(shenghao): Revise or remove this function if it's no longer - // applicable. - const drawPhoto = function(original, orientation, onSuccess, onFailure) { - const canvasSquareLength = Math.max(original.width, original.height); - const {canvas, ctx} = newDrawingCanvas( - {width: canvasSquareLength, height: canvasSquareLength}); - - const [centerX, centerY] = [canvas.width / 2, canvas.height / 2]; - ctx.translate(centerX, centerY); - ctx.rotate(orientation.rotation * Math.PI / 180); - if (orientation.flip) { - ctx.scale(-1, 1); - } - ctx.drawImage( - original, -original.width / 2, -original.height / 2, original.width, - original.height); - if (orientation.flip) { - ctx.scale(-1, 1); - } - ctx.rotate(-orientation.rotation * Math.PI / 180); - ctx.translate(-centerX, -centerY); - - const outputSize = (() => { - if (orientation.rotation === 90 || orientation.rotation === 270) { - return {width: original.height, height: original.width}; - } else { - return {width: original.width, height: original.height}; - } - })(); - const {canvas: outputCanvas, ctx: outputCtx} = newDrawingCanvas(outputSize); - const imageData = ctx.getImageData( - (canvasSquareLength - outputCanvas.width) / 2, - (canvasSquareLength - outputCanvas.height) / 2, outputCanvas.width, - outputCanvas.height); - outputCtx.putImageData(imageData, 0, 0); - - outputCanvas.toBlob(function(blob) { - if (blob) { - onSuccess(blob); - } else { - onFailure(); - } - }, 'image/jpeg'); - }; - - dropPhotoOrientation(blob).then((orientation) => { - if (orientation.rotation === 0 && !orientation.flip) { - onSuccess(blob); - } else { - const original = dom.create('img', HTMLImageElement); - original.onload = function() { - drawPhoto(original, orientation, onSuccess, onFailure); - }; - original.onerror = onFailure; - original.src = URL.createObjectURL(orientation.blob); - } - }); -} - -/** * Cancels animating the element by removing 'animate' class. * @param {!HTMLElement} element Element for canceling animation. * @return {!Promise} Promise resolved when ongoing animation is canceled and @@ -350,7 +204,7 @@ /** * Scales the input picture to target width and height with respect to original * aspect ratio. - * @param {string} url Picture as an URL. + * @param {!Blob} blob Blob of photo or video to be scaled. * @param {boolean} isVideo Picture is a video. * @param {number} width Target width to be scaled to. * @param {number=} height Target height to be scaled to. In default, set to @@ -358,61 +212,61 @@ * ratio of input picture. * @return {!Promise<!Blob>} Promise for the result. */ -export async function scalePicture(url, isVideo, width, height = undefined) { +export async function scalePicture(blob, isVideo, width, height = undefined) { const element = isVideo ? dom.create('video', HTMLVideoElement) : dom.create('img', HTMLImageElement); if (isVideo) { element.preload = 'auto'; } - await new Promise((resolve, reject) => { - element.addEventListener(isVideo ? 'canplay' : 'load', resolve); - element.addEventListener('error', () => { - if (isVideo) { - let msg = 'Failed to load video'; - /** - * https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error - * @type {?MediaError} - */ - const err = element.error; - if (err !== null) { - msg += `: ${err.message}`; + try { + await new Promise((resolve, reject) => { + element.addEventListener(isVideo ? 'canplay' : 'load', resolve); + element.addEventListener('error', () => { + if (isVideo) { + let msg = 'Failed to load video'; + /** + * https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error + * @type {?MediaError} + */ + const err = element.error; + if (err !== null) { + msg += `: ${err.message}`; + } + reject(new Error(msg)); + } else { + reject(new Error('Failed to load image')); } - reject(new Error(msg)); - } else { - reject(new Error('Failed to load image')); - } + }); + element.src = URL.createObjectURL(blob); }); - element.src = url; - }); - if (height === undefined) { - const ratio = isVideo ? element.videoHeight / element.videoWidth : - element.height / element.width; - height = Math.round(width * ratio); - } - const {canvas, ctx} = newDrawingCanvas({width, height}); - ctx.drawImage(element, 0, 0, width, height); + if (height === undefined) { + const ratio = isVideo ? element.videoHeight / element.videoWidth : + element.height / element.width; + height = Math.round(width * ratio); + } + const {canvas, ctx} = newDrawingCanvas({width, height}); + ctx.drawImage(element, 0, 0, width, height); - /** - * @type {!Uint8ClampedArray} A one-dimensional pixels array in RGBA order. - */ - const data = ctx.getImageData(0, 0, width, height).data; - if (data.every((byte) => byte === 0)) { - reportError( - ErrorType.BROKEN_THUMBNAIL, ErrorLevel.ERROR, - new Error('The thumbnail content is broken.')); - // Do not throw an error here. A black thumbnail is still better than no - // thumbnail to let user open the corresponding picutre in gallery. - } + /** + * @type {!Uint8ClampedArray} A one-dimensional pixels array in RGBA order. + */ + const data = ctx.getImageData(0, 0, width, height).data; + if (data.every((byte) => byte === 0)) { + reportError( + ErrorType.BROKEN_THUMBNAIL, ErrorLevel.ERROR, + new Error('The thumbnail content is broken.')); + // Do not throw an error here. A black thumbnail is still better than no + // thumbnail to let user open the corresponding picutre in gallery. + } - return new Promise((resolve, reject) => { - canvas.toBlob((blob) => { - if (blob) { - resolve(blob); - } else { - reject(new Error('Failed to create thumbnail.')); - } - }, 'image/jpeg'); - }); + return new Promise((resolve) => { + // TODO(b/174190121): Patch important exif entries from input blob to + // result blob. + canvas.toBlob(resolve, 'image/jpeg'); + }); + } finally { + URL.revokeObjectURL(element.src); + } } /**
diff --git a/chromeos/components/camera_app_ui/resources/js/views/camera/mode/square.js b/chromeos/components/camera_app_ui/resources/js/views/camera/mode/square.js index c2bb850..9e09f7b 100644 --- a/chromeos/components/camera_app_ui/resources/js/views/camera/mode/square.js +++ b/chromeos/components/camera_app_ui/resources/js/views/camera/mode/square.js
@@ -21,15 +21,21 @@ */ async function cropSquare(blob) { const img = await util.blobToImage(blob); - const side = Math.min(img.width, img.height); - const {canvas, ctx} = util.newDrawingCanvas({width: side, height: side}); - ctx.drawImage( - img, Math.floor((img.width - side) / 2), - Math.floor((img.height - side) / 2), side, side, 0, 0, side, side); - const croppedBlob = await new Promise((resolve) => { - canvas.toBlob(resolve, 'image/jpeg'); - }); - return croppedBlob; + try { + const side = Math.min(img.width, img.height); + const {canvas, ctx} = util.newDrawingCanvas({width: side, height: side}); + ctx.drawImage( + img, Math.floor((img.width - side) / 2), + Math.floor((img.height - side) / 2), side, side, 0, 0, side, side); + const croppedBlob = await new Promise((resolve) => { + // TODO(b/174190121): Patch important exif entries from input blob to + // result blob. + canvas.toBlob(resolve, 'image/jpeg'); + }); + return croppedBlob; + } finally { + URL.revokeObjectURL(img.src); + } } /** @@ -51,11 +57,6 @@ * @override */ async handleResultPhoto(result, ...args) { - // Since the image blob after square cut will lose its EXIF including - // orientation information. Corrects the orientation before the square - // cut. - result.blob = await new Promise( - (resolve, reject) => util.orientPhoto(result.blob, resolve, reject)); result.blob = await cropSquare(result.blob); await this.handler_.handleResultPhoto(result, ...args); }
diff --git a/chromeos/components/camera_app_ui/resources/js/views/camera_intent.js b/chromeos/components/camera_app_ui/resources/js/views/camera_intent.js index d7dedbc..faae3fb 100644 --- a/chromeos/components/camera_app_ui/resources/js/views/camera_intent.js +++ b/chromeos/components/camera_app_ui/resources/js/views/camera_intent.js
@@ -56,7 +56,7 @@ const ratio = Math.sqrt( DOWNSCALE_INTENT_MAX_PIXEL_NUM / (image.width * image.height)); blob = await util.scalePicture( - image.src, false, Math.floor(image.width * ratio), + blob, false, Math.floor(image.width * ratio), Math.floor(image.height * ratio)); } const buf = await blob.arrayBuffer();
diff --git a/chromeos/components/scanning/resources/scanning_app.html b/chromeos/components/scanning/resources/scanning_app.html index 904ae9a7..56792bbf 100644 --- a/chromeos/components/scanning/resources/scanning_app.html +++ b/chromeos/components/scanning/resources/scanning_app.html
@@ -180,11 +180,13 @@ </div> <cr-toast id="toast" duration="5000"> <div id="toastDiv"> - <iron-icon id="infoIcon" icon="cr:info-outline"></iron-icon> + <iron-icon id="infoIcon" icon="cr:info-outline" + hidden="[[!showToastInfoIcon_]]"></iron-icon> <span id="toastText">[[i18n(toastMessageKey_)]]</span> <!-- TODO(gavinwill): Add href to the help link when available --> <div id="getHelpDiv"> - <a id="getHelpLink" href="#">[[i18n('getHelpLinkText')]]</a> + <a id="getHelpLink" href="#" hidden="[[!showToastHelpLink_]]"> + [[i18n('getHelpLinkText')]]</a> </div> </div> </cr-toast>
diff --git a/chromeos/components/scanning/resources/scanning_app.js b/chromeos/components/scanning/resources/scanning_app.js index aea6c8d8..19df781 100644 --- a/chromeos/components/scanning/resources/scanning_app.js +++ b/chromeos/components/scanning/resources/scanning_app.js
@@ -185,7 +185,22 @@ * The key to retrieve the appropriate string to display in the toast. * @private {string} */ - toastMessageKey_: String, + toastMessageKey_: { + type: String, + observer: 'onToastMessageKeyChange_', + }, + + /** @private {boolean} */ + showToastInfoIcon_: { + type: Boolean, + value: false, + }, + + /** @private {boolean} */ + showToastHelpLink_: { + type: Boolean, + value: false, + }, }, /** @override */ @@ -267,6 +282,7 @@ return; } + this.showToast_('scanCanceledToastText'); this.setAppState_(AppState.READY); }, @@ -494,4 +510,10 @@ this.toastMessageKey_ = toastMessageKey; this.$.toast.show(); }, + + /** @private */ + onToastMessageKeyChange_() { + this.showToastInfoIcon_ = this.toastMessageKey_ !== 'scanCanceledToastText'; + this.showToastHelpLink_ = this.toastMessageKey_ !== 'scanCanceledToastText'; + }, });
diff --git a/chromeos/components/scanning/scanning_ui.cc b/chromeos/components/scanning/scanning_ui.cc index 7fdc8b8..4f111bd6 100644 --- a/chromeos/components/scanning/scanning_ui.cc +++ b/chromeos/components/scanning/scanning_ui.cc
@@ -84,6 +84,7 @@ {"resolutionDropdownLabel", IDS_SCANNING_APP_RESOLUTION_DROPDOWN_LABEL}, {"resolutionOptionText", IDS_SCANNING_APP_RESOLUTION_OPTION_TEXT}, {"scanButtonText", IDS_SCANNING_APP_SCAN_BUTTON_TEXT}, + {"scanCanceledToastText", IDS_SCANNING_APP_SCAN_CANCELED_TOAST_TEXT}, {"scanPreviewHelperText", IDS_SCANNING_APP_SCAN_PREVIEW_HELPER_TEXT}, {"scanPreviewProgressText", IDS_SCANNING_APP_SCAN_PREVIEW_PROGRESS_TEXT}, {"scanToDropdownLabel", IDS_SCANNING_APP_SCAN_TO_DROPDOWN_LABEL},
diff --git a/chromeos/dbus/tpm_manager/fake_tpm_manager_client.cc b/chromeos/dbus/tpm_manager/fake_tpm_manager_client.cc index 8f7f8e5..f68d00ad 100644 --- a/chromeos/dbus/tpm_manager/fake_tpm_manager_client.cc +++ b/chromeos/dbus/tpm_manager/fake_tpm_manager_client.cc
@@ -61,7 +61,9 @@ void FakeTpmManagerClient::ClearStoredOwnerPassword( const ::tpm_manager::ClearStoredOwnerPasswordRequest& request, ClearStoredOwnerPasswordCallback callback) { - NOTIMPLEMENTED(); + ++clear_stored_owner_password_count_; + PostProtoResponse(std::move(callback), + ::tpm_manager::ClearStoredOwnerPasswordReply()); } TpmManagerClient::TestInterface* FakeTpmManagerClient::GetTestInterface() { @@ -78,4 +80,8 @@ return &version_info_reply_; } +int FakeTpmManagerClient::clear_stored_owner_password_count() const { + return clear_stored_owner_password_count_; +} + } // namespace chromeos
diff --git a/chromeos/dbus/tpm_manager/fake_tpm_manager_client.h b/chromeos/dbus/tpm_manager/fake_tpm_manager_client.h index 25e962d6..4cbb435 100644 --- a/chromeos/dbus/tpm_manager/fake_tpm_manager_client.h +++ b/chromeos/dbus/tpm_manager/fake_tpm_manager_client.h
@@ -46,10 +46,12 @@ ::tpm_manager::GetTpmNonsensitiveStatusReply* mutable_nonsensitive_status_reply() override; ::tpm_manager::GetVersionInfoReply* mutable_version_info_reply() override; + int clear_stored_owner_password_count() const override; private: ::tpm_manager::GetTpmNonsensitiveStatusReply nonsensitive_status_reply_; ::tpm_manager::GetVersionInfoReply version_info_reply_; + int clear_stored_owner_password_count_ = 0; }; } // namespace chromeos
diff --git a/chromeos/dbus/tpm_manager/tpm_manager_client.h b/chromeos/dbus/tpm_manager/tpm_manager_client.h index a6567151..bc8c8df 100644 --- a/chromeos/dbus/tpm_manager/tpm_manager_client.h +++ b/chromeos/dbus/tpm_manager/tpm_manager_client.h
@@ -45,6 +45,8 @@ // Gets a mutable reply that is returned when `GetVersionInfo()` is called. virtual ::tpm_manager::GetVersionInfoReply* mutable_version_info_reply() = 0; + // Gets the count of `ClearStoredOwnerPassword()` being called. + virtual int clear_stored_owner_password_count() const = 0; }; // Not copyable or movable.
diff --git a/chromeos/profiles/atom.afdo.newest.txt b/chromeos/profiles/atom.afdo.newest.txt index d4c5533a..6479d00 100644 --- a/chromeos/profiles/atom.afdo.newest.txt +++ b/chromeos/profiles/atom.afdo.newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-atom-89-4324.9-1606733211-benchmark-89.0.4337.0-r1-redacted.afdo.xz +chromeos-chrome-amd64-atom-89-4324.9-1606733211-benchmark-89.0.4339.0-r1-redacted.afdo.xz
diff --git a/chromeos/profiles/bigcore.afdo.newest.txt b/chromeos/profiles/bigcore.afdo.newest.txt index 988b2415..abcd66c8 100644 --- a/chromeos/profiles/bigcore.afdo.newest.txt +++ b/chromeos/profiles/bigcore.afdo.newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-bigcore-89-4324.9-1606737320-benchmark-89.0.4337.0-r1-redacted.afdo.xz +chromeos-chrome-amd64-bigcore-89-4324.9-1606737320-benchmark-89.0.4339.0-r1-redacted.afdo.xz
diff --git a/chromeos/profiles/orderfile.newest.txt b/chromeos/profiles/orderfile.newest.txt index b7a2b78da..30d730195 100644 --- a/chromeos/profiles/orderfile.newest.txt +++ b/chromeos/profiles/orderfile.newest.txt
@@ -1 +1 @@ -chromeos-chrome-orderfile-field-89-4324.9-1606128713-benchmark-89.0.4335.0-r1.orderfile.xz +chromeos-chrome-orderfile-field-89-4324.9-1606128713-benchmark-89.0.4337.0-r1.orderfile.xz
diff --git a/chromeos/tpm/install_attributes.cc b/chromeos/tpm/install_attributes.cc index 2180304..77d471a 100644 --- a/chromeos/tpm/install_attributes.cc +++ b/chromeos/tpm/install_attributes.cc
@@ -290,10 +290,12 @@ return; } - // Clearing the TPM password seems to be always a good deal. - if (tpm_util::TpmIsEnabled() && tpm_util::TpmIsOwned()) { - cryptohome_client_->CallTpmClearStoredPasswordAndBlock(); - } + // Clearing the TPM password seems to be always a good deal. At this point + // install attributes is ready, which implies TPM readiness as well. + TpmManagerClient::Get()->ClearStoredOwnerPassword( + ::tpm_manager::ClearStoredOwnerPasswordRequest(), + base::BindOnce(&InstallAttributes::OnClearStoredOwnerPassword, + weak_ptr_factory_.GetWeakPtr())); // Make sure we really have a working InstallAttrs. if (tpm_util::InstallAttributesIsInvalid()) { @@ -441,6 +443,12 @@ } } +void InstallAttributes::OnClearStoredOwnerPassword( + const ::tpm_manager::ClearStoredOwnerPasswordReply& reply) { + LOG_IF(WARNING, reply.status() != ::tpm_manager::STATUS_SUCCESS) + << "Failed to call ClearStoredOwnerPassword; status: " << reply.status(); +} + // Warning: The values for these keys (but not the keys themselves) are stored // in the protobuf with a trailing zero. Also note that some of these constants // have been copied to login_manager/device_policy_service.cc. Please make sure
diff --git a/chromeos/tpm/install_attributes.h b/chromeos/tpm/install_attributes.h index c805f7fa..2224a47 100644 --- a/chromeos/tpm/install_attributes.h +++ b/chromeos/tpm/install_attributes.h
@@ -218,6 +218,11 @@ int dbus_retries_remaining, const ::tpm_manager::GetTpmNonsensitiveStatusReply& reply); + // Callback for `ClearStoredOwnerPassword()` D-Bus call. Logs status code if + // the call fails. + void OnClearStoredOwnerPassword( + const ::tpm_manager::ClearStoredOwnerPasswordReply& reply); + CryptohomeClient* cryptohome_client_; base::WeakPtrFactory<InstallAttributes> weak_ptr_factory_{this};
diff --git a/chromeos/tpm/install_attributes_unittest.cc b/chromeos/tpm/install_attributes_unittest.cc index f2fef3a..52cf5a33 100644 --- a/chromeos/tpm/install_attributes_unittest.cc +++ b/chromeos/tpm/install_attributes_unittest.cc
@@ -102,6 +102,10 @@ LockDeviceAndWaitForResult(policy::DEVICE_MODE_ENTERPRISE, kTestDomain, std::string(), // realm kTestDeviceId)); + EXPECT_EQ(TpmManagerClient::Get() + ->GetTestInterface() + ->clear_stored_owner_password_count(), + 1); // Locking an already locked device should succeed if the parameters match. EXPECT_EQ(
diff --git a/components/autofill/content/browser/BUILD.gn b/components/autofill/content/browser/BUILD.gn index d54493f..1c63bc5 100644 --- a/components/autofill/content/browser/BUILD.gn +++ b/components/autofill/content/browser/BUILD.gn
@@ -34,6 +34,7 @@ "//components/resources", "//components/strings", "//components/user_prefs", + "//components/version_info", "//content/public/browser", "//content/public/common", "//gpu/config", @@ -77,6 +78,7 @@ "//components/autofill/core/browser", "//components/autofill/core/browser:test_support", "//components/autofill/core/common", + "//components/version_info", "//content/public/browser", "//content/public/common", "//content/test:test_support",
diff --git a/components/autofill/content/browser/DEPS b/components/autofill/content/browser/DEPS index c98729d3..06dd7608 100644 --- a/components/autofill/content/browser/DEPS +++ b/components/autofill/content/browser/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+content/public/browser", "+components/keyed_service/content", + "+components/version_info", "+crypto/random.h", "+gpu/config/gpu_info.h", "+services/device/public",
diff --git a/components/autofill/content/browser/content_autofill_driver.cc b/components/autofill/content/browser/content_autofill_driver.cc index f03b1475..ba0c5dd 100644 --- a/components/autofill/content/browser/content_autofill_driver.cc +++ b/components/autofill/content/browser/content_autofill_driver.cc
@@ -18,6 +18,7 @@ #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/payments/payments_service_url.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/version_info/channel.h" #include "content/public/browser/back_forward_cache.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_controller.h" @@ -36,6 +37,24 @@ #include "ui/gfx/geometry/size_f.h" #include "url/origin.h" +namespace { + +bool ShouldEnableHeavyFormDataScraping(const version_info::Channel channel) { + switch (channel) { + case version_info::Channel::CANARY: + case version_info::Channel::DEV: + return true; + case version_info::Channel::STABLE: + case version_info::Channel::BETA: + case version_info::Channel::UNKNOWN: + return false; + } + NOTREACHED(); + return false; +} + +} // namespace + namespace autofill { ContentAutofillDriver::ContentAutofillDriver( @@ -56,6 +75,9 @@ SetAutofillManager(std::make_unique<AutofillManager>( this, client, app_locale, enable_download_manager)); } + if (client && ShouldEnableHeavyFormDataScraping(client->GetChannel())) { + GetAutofillAgent()->EnableHeavyFormDataScraping(); + } } ContentAutofillDriver::~ContentAutofillDriver() = default;
diff --git a/components/autofill/content/browser/content_autofill_driver_unittest.cc b/components/autofill/content/browser/content_autofill_driver_unittest.cc index 3862c76d..b062881 100644 --- a/components/autofill/content/browser/content_autofill_driver_unittest.cc +++ b/components/autofill/content/browser/content_autofill_driver_unittest.cc
@@ -21,6 +21,7 @@ #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/form_data_predictions.h" +#include "components/version_info/version_info.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/ssl_status.h" #include "content/public/browser/storage_partition.h" @@ -141,6 +142,7 @@ // Mocked mojom::AutofillAgent methods: MOCK_METHOD0(FirstUserGestureObservedInTab, void()); + MOCK_METHOD0(EnableHeavyFormDataScraping, void()); private: void CallDone() { @@ -456,4 +458,30 @@ EXPECT_EQ(input_value, output_value); } +TEST_F(ContentAutofillDriverTest, EnableHeavyFormDataScraping) { + struct TestCase { + version_info::Channel channel; + bool heavy_scraping_enabled; + } kTestCases[] = {{version_info::Channel::CANARY, true}, + {version_info::Channel::DEV, true}, + {version_info::Channel::UNKNOWN, false}, + {version_info::Channel::BETA, false}, + {version_info::Channel::STABLE, false}}; + + for (auto test_case : kTestCases) { + SCOPED_TRACE(testing::Message() + << "channel: " + << version_info::GetChannelString(test_case.channel)); + test_autofill_client_->set_channel_for_testing(test_case.channel); + EXPECT_CALL(fake_agent_, EnableHeavyFormDataScraping()) + .Times(test_case.heavy_scraping_enabled ? 1 : 0); + + std::unique_ptr<ContentAutofillDriver> driver(new TestContentAutofillDriver( + web_contents()->GetMainFrame(), test_autofill_client_.get())); + + base::RunLoop().RunUntilIdle(); + testing::Mock::VerifyAndClearExpectations(&fake_agent_); + } +} + } // namespace autofill
diff --git a/components/autofill/content/common/mojom/autofill_agent.mojom b/components/autofill/content/common/mojom/autofill_agent.mojom index 28e6bd73..2817725 100644 --- a/components/autofill/content/common/mojom/autofill_agent.mojom +++ b/components/autofill/content/common/mojom/autofill_agent.mojom
@@ -78,6 +78,10 @@ // Set whether or not an assistant action is currently running an action. SetAssistantActionState(bool running); + + // Allows heavy scraping of form data (e.g., button titles for + // unowned forms). + EnableHeavyFormDataScraping(); }; // There is one instance of this interface per render frame in the render
diff --git a/components/autofill/content/renderer/autofill_agent.cc b/components/autofill/content/renderer/autofill_agent.cc index 1aed939..3e933a51 100644 --- a/components/autofill/content/renderer/autofill_agent.cc +++ b/components/autofill/content/renderer/autofill_agent.cc
@@ -758,6 +758,10 @@ } } +void AutofillAgent::EnableHeavyFormDataScraping() { + is_heavy_form_data_scraping_enabled_ = true; +} + void AutofillAgent::QueryAutofillSuggestions( const WebFormControlElement& element, bool autoselect_first_suggestion) {
diff --git a/components/autofill/content/renderer/autofill_agent.h b/components/autofill/content/renderer/autofill_agent.h index a6d4cbe..bc877bda 100644 --- a/components/autofill/content/renderer/autofill_agent.h +++ b/components/autofill/content/renderer/autofill_agent.h
@@ -100,6 +100,7 @@ const std::vector<std::string>& selectors, GetElementFormAndFieldDataCallback callback) override; void SetAssistantActionState(bool running) override; + void EnableHeavyFormDataScraping() override; void FormControlElementClicked(const blink::WebFormControlElement& element, bool was_focused); @@ -124,6 +125,10 @@ FormTracker* form_tracker_for_testing() { return &form_tracker_; } + bool is_heavy_form_data_scraping_enabled() { + return is_heavy_form_data_scraping_enabled_; + } + void SelectWasUpdated(const blink::WebFormControlElement& element); protected: @@ -367,6 +372,10 @@ // is. bool is_screen_reader_enabled_ = false; + // Whether agents should enable heavy scraping of form data (e.g., button + // titles for unowned forms). + bool is_heavy_form_data_scraping_enabled_ = false; + const scoped_refptr<FieldDataManager> field_data_manager_; base::WeakPtrFactory<AutofillAgent> weak_ptr_factory_{this};
diff --git a/components/autofill/content/renderer/form_autofill_util.cc b/components/autofill/content/renderer/form_autofill_util.cc index f42cf808..8b1232e 100644 --- a/components/autofill/content/renderer/form_autofill_util.cc +++ b/components/autofill/content/renderer/form_autofill_util.cc
@@ -99,15 +99,6 @@ FILTER_NON_FOCUSABLE_ELEMENTS, }; -// Returns whether sending autofill field metadata to the server is enabled. -// TODO(crbug.com/938804): Remove this when button titles are crowdsourced in -// all channels. -bool IsAutofillFieldMetadataEnabled() { - static base::NoDestructor<std::string> kGroupName( - base::FieldTrialList::FindFullName("AutofillFieldMetadata")); - return base::StartsWith(*kGroupName, "Enabled", base::CompareCase::SENSITIVE); -} - void TruncateString(base::string16* str, size_t max_length) { if (str->length() > max_length) str->resize(max_length); @@ -2211,9 +2202,10 @@ ButtonTitleList GetButtonTitles(const WebFormElement& web_form, const WebDocument& document, ButtonTitlesCache* button_titles_cache) { - DCHECK(button_titles_cache); - if (!IsAutofillFieldMetadataEnabled() && web_form.IsNull()) + if (!button_titles_cache) { + // Button titles scraping is disabled for this form. return ButtonTitleList(); + } // True if the cache has no entry for |web_form|. bool cache_miss = true;
diff --git a/components/autofill/content/renderer/form_autofill_util_browsertest.cc b/components/autofill/content/renderer/form_autofill_util_browsertest.cc index 34575e7..17593a6d 100644 --- a/components/autofill/content/renderer/form_autofill_util_browsertest.cc +++ b/components/autofill/content/renderer/form_autofill_util_browsertest.cc
@@ -360,12 +360,6 @@ } TEST_F(FormAutofillUtilsTest, GetButtonTitles_Formless) { - // Button titles computation and crowdsourcing for <form>less forms are - // enabled only if |AutofillFieldMetadata| (Dev and Canary) is enabled. - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.Init(); - base::FieldTrialList::CreateFieldTrial("AutofillFieldMetadata", "Enabled"); - constexpr char kNoFormHtml[] = "<div class='reg-form'>" " <input type='button' value='\n Show\t password '>" @@ -400,13 +394,10 @@ VerifyButtonTitleCache(form_target, expected, cache); } -TEST_F(FormAutofillUtilsTest, GetButtonTitles_Formless_DisabledByDefault) { - // Button titles computation and crowdsourcing for <form>less forms should be - // disabled if |AutofillFieldMetadata| is disabled. - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.Init(); - base::FieldTrialList::CreateFieldTrial("AutofillFieldMetadata", "Disabled"); - +TEST_F(FormAutofillUtilsTest, GetButtonTitles_DisabledIfNoCache) { + // Button titles scraping for unowned forms can be time-consuming and disabled + // in Beta and Stable. To disable button titles computation, |buttons_cache| + // should be null. constexpr char kNoFormHtml[] = "<div class='reg-form'>" " <input type='button' value='\n Show\t password '>" @@ -425,13 +416,11 @@ ASSERT_NE(nullptr, web_frame); WebFormElement form_target; ASSERT_FALSE(web_frame->GetDocument().Body().IsNull()); - ButtonTitlesCache cache; autofill::ButtonTitleList actual = - GetButtonTitles(form_target, web_frame->GetDocument(), &cache); + GetButtonTitles(form_target, web_frame->GetDocument(), nullptr); EXPECT_TRUE(actual.empty()); - EXPECT_TRUE(cache.empty()); } TEST_F(FormAutofillUtilsTest, IsEnabled) {
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc index 83a970cc..6c96ee2 100644 --- a/components/autofill/content/renderer/password_autofill_agent.cc +++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -1370,7 +1370,9 @@ return nullptr; return CreateFormDataFromUnownedInputElements( *web_frame, field_data_manager_.get(), &username_detector_cache_, - &button_titles_cache_); + autofill_agent_ && autofill_agent_->is_heavy_form_data_scraping_enabled() + ? &button_titles_cache_ + : nullptr); } void PasswordAutofillAgent::InformAboutFormClearing(
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index e812c2f..20427bb 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -546,6 +546,7 @@ "//components/translate/core/browser:test_support", "//components/ukm", "//components/ukm:test_support", + "//components/version_info:version_info", "//google_apis:test_support", "//services/network:test_support", "//services/network/public/cpp",
diff --git a/components/autofill/core/browser/test_autofill_client.cc b/components/autofill/core/browser/test_autofill_client.cc index 952ffdf..a69e6c7 100644 --- a/components/autofill/core/browser/test_autofill_client.cc +++ b/components/autofill/core/browser/test_autofill_client.cc
@@ -9,6 +9,7 @@ #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/payments/local_card_migration_manager.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" +#include "components/version_info/channel.h" #if !defined(OS_IOS) #include "components/autofill/core/browser/payments/test_internal_authenticator.h" @@ -22,6 +23,10 @@ TestAutofillClient::~TestAutofillClient() {} +version_info::Channel TestAutofillClient::GetChannel() const { + return channel_for_testing_; +} + PersonalDataManager* TestAutofillClient::GetPersonalDataManager() { return &test_personal_data_manager_; }
diff --git a/components/autofill/core/browser/test_autofill_client.h b/components/autofill/core/browser/test_autofill_client.h index 64c13900..722359f 100644 --- a/components/autofill/core/browser/test_autofill_client.h +++ b/components/autofill/core/browser/test_autofill_client.h
@@ -28,6 +28,7 @@ #include "components/translate/core/browser/language_state.h" #include "components/translate/core/browser/mock_translate_driver.h" #include "components/ukm/test_ukm_recorder.h" +#include "components/version_info/channel.h" #include "services/metrics/public/cpp/delegating_ukm_recorder.h" #if !defined(OS_IOS) @@ -43,6 +44,7 @@ ~TestAutofillClient() override; // AutofillClient: + version_info::Channel GetChannel() const override; PersonalDataManager* GetPersonalDataManager() override; AutocompleteHistoryManager* GetAutocompleteHistoryManager() override; PrefService* GetPrefs() override; @@ -230,6 +232,10 @@ autofill_offer_manager_ = std::move(autofill_offer_manager); } + void set_channel_for_testing(const version_info::Channel channel) { + channel_for_testing_ = channel; + } + GURL form_origin() { return form_origin_; } ukm::TestUkmRecorder* GetTestUkmRecorder(); @@ -265,6 +271,8 @@ // otherwise. base::Optional<bool> credit_card_name_fix_flow_bubble_was_shown_; + version_info::Channel channel_for_testing_ = version_info::Channel::UNKNOWN; + // Populated if local save or upload was offered. base::Optional<SaveCreditCardOptions> save_credit_card_options_;
diff --git a/components/autofill_assistant/browser/actions/action.cc b/components/autofill_assistant/browser/actions/action.cc index 7e657f36..e515dbd 100644 --- a/components/autofill_assistant/browser/actions/action.cc +++ b/components/autofill_assistant/browser/actions/action.cc
@@ -191,8 +191,8 @@ case ActionProto::ActionInfoCase::kSendKeystrokeEvents: out << "SendKeystrokeEvents"; break; - case ActionProto::ActionInfoCase::kSetFieldValue: - out << "SetFieldValue"; + case ActionProto::ActionInfoCase::kSendChangeEvent: + out << "SendChangeEvent"; break; case ActionProto::ActionInfoCase::kSetElementAttribute: out << "SetElementAttribute";
diff --git a/components/autofill_assistant/browser/dom_action.proto b/components/autofill_assistant/browser/dom_action.proto index 3533297..a929240c 100644 --- a/components/autofill_assistant/browser/dom_action.proto +++ b/components/autofill_assistant/browser/dom_action.proto
@@ -12,67 +12,89 @@ import "action_value.proto"; +// Identifier for elements on the client. This is used to store and retrieve +// elements. To store an element and create a usable |ClientIdProto| use a +// |WaitForDomProto| with a |ClientIdProto| annotated |ElementConditionProto|. message ClientIdProto { optional string identifier = 1; } +// Scroll the element into the view center. message ScrollIntoViewProto { optional ClientIdProto client_id = 1; } +// Wait for the document ready status to be at least "interactive". message WaitForDocumentToBecomeInteractiveProto { optional ClientIdProto client_id = 1; optional int32 timeout_in_ms = 2; } +// Wait for the document ready status to be "complete". message WaitForDocumentToBecomeCompleteProto { optional ClientIdProto client_id = 1; optional int32 timeout_in_ms = 2; } +// Wait until an element has become stable, i.e. didn't move for the last few +// rounds. message WaitForElementToBecomeStableProto { optional ClientIdProto client_id = 1; optional int32 stable_check_max_rounds = 2 [default = 50]; optional int32 stable_check_interval_ms = 3 [default = 200]; } +// Check that the element is on top and not currently covered by any other +// element. message CheckElementIsOnTopProto { optional ClientIdProto client_id = 1; } +// Send a mousedown followed by a mouseup event on the element. message SendClickEventProto { optional ClientIdProto client_id = 1; } +// Send a touchdown followed by a touchup event on the element. message SendTapEventProto { optional ClientIdProto client_id = 1; } +// Use JavaScript to click an element. message JsClickProto { optional ClientIdProto client_id = 1; } +// Send a keydown followed by a keyup event per character to the element. This +// requires the element to have focus to receive them. Some characters (like +// new line) are treated as special keys. message SendKeystrokeEventsProto { optional ClientIdProto client_id = 1; optional TextValue value = 2; optional int32 delay_in_ms = 3; } -message SetFieldValueProto { +// Send a change event on the element. +message SendChangeEventProto { optional ClientIdProto client_id = 1; - optional TextValue value = 2; } +// Set a potentially nested attribute of an element. Depending on the attribute +// (e.g. "value", "checked" or similar) it may be necessary to additionally +// send an additional change using |SendChangeEventProto|. message SetElementAttributeProto { optional ClientIdProto client_id = 1; repeated string attribute = 2; optional TextValue value = 3; } +// Select the text value of a field. This requires to be used on an |input| or +// |textarea|. message SelectFieldValueProto { optional ClientIdProto client_id = 1; } +// Focus a field. message FocusFieldProto { optional ClientIdProto client_id = 1; }
diff --git a/components/autofill_assistant/browser/protocol_utils.cc b/components/autofill_assistant/browser/protocol_utils.cc index 712fc85..40702397 100644 --- a/components/autofill_assistant/browser/protocol_utils.cc +++ b/components/autofill_assistant/browser/protocol_utils.cc
@@ -286,13 +286,11 @@ base::BindOnce(&WebController::SendTextInput, delegate->GetWebController()->GetWeakPtr(), action.send_keystroke_events().delay_in_ms()))); - case ActionProto::ActionInfoCase::kSetFieldValue: + case ActionProto::ActionInfoCase::kSendChangeEvent: return PerformOnSingleElementAction::WithClientId( - delegate, action, action.set_field_value().client_id(), - base::BindOnce(&action_delegate_util::PerformWithTextValue, delegate, - action.set_field_value().value(), - base::BindOnce(&ActionDelegate::SetValueAttribute, - delegate->GetWeakPtr()))); + delegate, action, action.send_change_event().client_id(), + base::BindOnce(&WebController::SendChangeEvent, + delegate->GetWebController()->GetWeakPtr())); case ActionProto::ActionInfoCase::kSetElementAttribute: { std::vector<std::string> attributes; for (const auto& attribute : action.set_element_attribute().attribute()) {
diff --git a/components/autofill_assistant/browser/script_executor.cc b/components/autofill_assistant/browser/script_executor.cc index 5cbf7bc..86b779d 100644 --- a/components/autofill_assistant/browser/script_executor.cc +++ b/components/autofill_assistant/browser/script_executor.cc
@@ -222,7 +222,7 @@ case ActionProto::ActionInfoCase::kSendTapEvent: case ActionProto::ActionInfoCase::kJsClick: case ActionProto::ActionInfoCase::kSendKeystrokeEvents: - case ActionProto::ActionInfoCase::kSetFieldValue: + case ActionProto::ActionInfoCase::kSendChangeEvent: case ActionProto::ActionInfoCase::kSetElementAttribute: case ActionProto::ActionInfoCase::kSelectFieldValue: case ActionProto::ActionInfoCase::kFocusField:
diff --git a/components/autofill_assistant/browser/service.proto b/components/autofill_assistant/browser/service.proto index 096e5f8..9e85239 100644 --- a/components/autofill_assistant/browser/service.proto +++ b/components/autofill_assistant/browser/service.proto
@@ -628,7 +628,7 @@ SendTapEventProto send_tap_event = 61; JsClickProto js_click = 62; SendKeystrokeEventsProto send_keystroke_events = 63; - SetFieldValueProto set_field_value = 64; + SendChangeEventProto send_change_event = 64; SetElementAttributeProto set_element_attribute = 65; SelectFieldValueProto select_field_value = 66; FocusFieldProto focus_field = 67; @@ -946,6 +946,9 @@ // Waiting for a certain document ready state failed. WAIT_FOR_DOCUMENT_READY_STATE = 18; + + // Trigger a change event. + SEND_CHANGE_EVENT = 19; } // The web-action that failed. This is usually a step in an execution chain
diff --git a/components/autofill_assistant/browser/web/web_controller.cc b/components/autofill_assistant/browser/web/web_controller.cc index a3a025f3..12132a5 100644 --- a/components/autofill_assistant/browser/web/web_controller.cc +++ b/components/autofill_assistant/browser/web/web_controller.cc
@@ -181,6 +181,13 @@ }) )"; +const char* const kSendChangeEventScript = + R"(function () { + const e = document.createEvent('HTMLEvents'); + e.initEvent('change', true, true); + this.dispatchEvent(e); + })"; + // Converts a int that correspond to the DocumentReadyState enum into an // equivalent quoted Javascript string. std::string DocumentReadyStateToQuotedJsString(int state) { @@ -1419,6 +1426,23 @@ std::move(callback)))); } +void WebController::SendChangeEvent( + const ElementFinder::Result& element, + base::OnceCallback<void(const ClientStatus&)> callback) { + devtools_client_->GetRuntime()->CallFunctionOn( + runtime::CallFunctionOnParams::Builder() + .SetObjectId(element.object_id()) + .SetFunctionDeclaration(std::string(kSendChangeEventScript)) + .SetReturnByValue(true) + .Build(), + element.node_frame_id(), + base::BindOnce( + &WebController::OnJavaScriptResult, weak_ptr_factory_.GetWeakPtr(), + base::BindOnce(&DecorateWebControllerStatus, + WebControllerErrorInfoProto::SEND_CHANGE_EVENT, + std::move(callback)))); +} + base::WeakPtr<WebController> WebController::GetWeakPtr() const { return weak_ptr_factory_.GetWeakPtr(); }
diff --git a/components/autofill_assistant/browser/web/web_controller.h b/components/autofill_assistant/browser/web/web_controller.h index 1d1399d..86b7bfe 100644 --- a/components/autofill_assistant/browser/web/web_controller.h +++ b/components/autofill_assistant/browser/web/web_controller.h
@@ -274,6 +274,11 @@ DocumentReadyState, base::TimeDelta)> callback); + // Trigger a "change" event on the |element|. + virtual void SendChangeEvent( + const ElementFinder::Result& element, + base::OnceCallback<void(const ClientStatus&)> callback); + virtual base::WeakPtr<WebController> GetWeakPtr() const; private:
diff --git a/components/autofill_assistant/browser/web/web_controller_browsertest.cc b/components/autofill_assistant/browser/web/web_controller_browsertest.cc index 3d0b368..8cdd3a39 100644 --- a/components/autofill_assistant/browser/web/web_controller_browsertest.cc +++ b/components/autofill_assistant/browser/web/web_controller_browsertest.cc
@@ -480,6 +480,36 @@ std::move(done_callback), result_output, element_tag_output)); } + ClientStatus SendChangeEvent(const Selector& selector) { + base::RunLoop run_loop; + ClientStatus result; + + web_controller_->FindElement( + selector, /* strict= */ true, + base::BindOnce( + &WebControllerBrowserTest::FindSendChangeEventElementCallback, + base::Unretained(this), run_loop.QuitClosure(), &result)); + + run_loop.Run(); + EXPECT_EQ(ACTION_APPLIED, result.proto_status()); + return result; + } + + void FindSendChangeEventElementCallback( + base::OnceClosure done_callback, + ClientStatus* result_output, + const ClientStatus& element_status, + std::unique_ptr<ElementFinder::Result> element_result) { + EXPECT_EQ(ACTION_APPLIED, element_status.proto_status()); + ASSERT_TRUE(element_result != nullptr); + const ElementFinder::Result* element_result_ptr = element_result.get(); + web_controller_->SendChangeEvent( + *element_result_ptr, + base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, + base::Unretained(this), std::move(element_result), + std::move(done_callback), result_output)); + } + ClientStatus CheckOnTop(const ElementFinder::Result& element) { ClientStatus captured_status; base::RunLoop run_loop; @@ -2679,4 +2709,14 @@ EXPECT_EQ("STRONG", element_tag); } +IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SendChangeEvent) { + Selector selector({"#input_with_onchange"}); + + GetFieldsValue({selector}, {"0"}); + EXPECT_EQ(ACTION_APPLIED, SendChangeEvent(selector).proto_status()); + GetFieldsValue({selector}, {"1"}); + EXPECT_EQ(ACTION_APPLIED, SendChangeEvent(selector).proto_status()); + GetFieldsValue({selector}, {"2"}); +} + } // namespace autofill_assistant
diff --git a/components/captive_portal/DIR_METADATA b/components/captive_portal/DIR_METADATA new file mode 100644 index 0000000..709d8280 --- /dev/null +++ b/components/captive_portal/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "Internals>Network" +} + +team_email: "net-dev@chromium.org"
diff --git a/components/captive_portal/OWNERS b/components/captive_portal/OWNERS index 7e5ec6e..fb59c70 100644 --- a/components/captive_portal/OWNERS +++ b/components/captive_portal/OWNERS
@@ -1,3 +1 @@ file://net/OWNERS -# COMPONENT: Internals>Network -# TEAM: net-dev@chromium.org
diff --git a/components/cbor/DIR_METADATA b/components/cbor/DIR_METADATA new file mode 100644 index 0000000..566b704f --- /dev/null +++ b/components/cbor/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "Blink>WebAuthentication" +} + +team_email: "security-dev@chromium.org"
diff --git a/components/cbor/OWNERS b/components/cbor/OWNERS index e2dc0468..c2ed450 100644 --- a/components/cbor/OWNERS +++ b/components/cbor/OWNERS
@@ -1,5 +1,3 @@ jochen@chromium.org engedy@chromium.org file://base/SECURITY_OWNERS -# COMPONENT: Blink>WebAuthentication -# TEAM: security-dev@chromium.org
diff --git a/components/cdm/DIR_METADATA b/components/cdm/DIR_METADATA new file mode 100644 index 0000000..5efaeb59 --- /dev/null +++ b/components/cdm/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Internals>Media>Encrypted" +}
diff --git a/components/cdm/OWNERS b/components/cdm/OWNERS index 741c7d0..f09af45 100644 --- a/components/cdm/OWNERS +++ b/components/cdm/OWNERS
@@ -1,4 +1,2 @@ jrummell@chromium.org xhwang@chromium.org - -# COMPONENT: Internals>Media>Encrypted
diff --git a/components/chromeos_camera/DIR_METADATA b/components/chromeos_camera/DIR_METADATA new file mode 100644 index 0000000..b9aba2ea --- /dev/null +++ b/components/chromeos_camera/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "OS>Kernel>Camera" +} + +team_email: "chromeos-camera@chromium.org"
diff --git a/components/chromeos_camera/OWNERS b/components/chromeos_camera/OWNERS index 63bd952..cb465fc 100644 --- a/components/chromeos_camera/OWNERS +++ b/components/chromeos_camera/OWNERS
@@ -5,6 +5,3 @@ # Chromium-specific owners chfremer@chromium.org mcasas@chromium.org - -# TEAM: chromeos-camera@chromium.org -# COMPONENT: OS>Kernel>Camera
diff --git a/components/cloud_devices/DIR_METADATA b/components/cloud_devices/DIR_METADATA new file mode 100644 index 0000000..a87a2c8c --- /dev/null +++ b/components/cloud_devices/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Services>CloudPrint" +}
diff --git a/components/cloud_devices/OWNERS b/components/cloud_devices/OWNERS index f87c3ce1..6fbeb6a 100644 --- a/components/cloud_devices/OWNERS +++ b/components/cloud_devices/OWNERS
@@ -1,4 +1,2 @@ thestig@chromium.org vitalybuka@chromium.org - -# COMPONENT: Services>CloudPrint
diff --git a/components/component_updater/DIR_METADATA b/components/component_updater/DIR_METADATA new file mode 100644 index 0000000..f29e6cf --- /dev/null +++ b/components/component_updater/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "Internals>Installer>Components" +} + +team_email: "chrome-updates-dev@chromium.org"
diff --git a/components/component_updater/OWNERS b/components/component_updater/OWNERS index 833b82c..ec81839 100644 --- a/components/component_updater/OWNERS +++ b/components/component_updater/OWNERS
@@ -1,5 +1,2 @@ sorin@chromium.org waffles@chromium.org - -# COMPONENT: Internals>Installer>Components -# TEAM: chrome-updates-dev@chromium.org
diff --git a/components/consent_auditor/DIR_METADATA b/components/consent_auditor/DIR_METADATA new file mode 100644 index 0000000..db7a5c4a --- /dev/null +++ b/components/consent_auditor/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Privacy" +}
diff --git a/components/consent_auditor/OWNERS b/components/consent_auditor/OWNERS index ec03682..0e2c1661 100644 --- a/components/consent_auditor/OWNERS +++ b/components/consent_auditor/OWNERS
@@ -2,5 +2,3 @@ markusheintz@chromium.org msramek@chromium.org vitaliii@chromium.org - -# COMPONENT: Privacy
diff --git a/components/constrained_window/DIR_METADATA b/components/constrained_window/DIR_METADATA new file mode 100644 index 0000000..f573c65 --- /dev/null +++ b/components/constrained_window/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Internals>Views" +}
diff --git a/components/constrained_window/OWNERS b/components/constrained_window/OWNERS index 299ed89d5..8b25c36 100644 --- a/components/constrained_window/OWNERS +++ b/components/constrained_window/OWNERS
@@ -1,5 +1,3 @@ gbillock@chromium.org msw@chromium.org wittman@chromium.org - -# COMPONENT: Internals>Views
diff --git a/components/content_capture/DIR_METADATA b/components/content_capture/DIR_METADATA new file mode 100644 index 0000000..2c9d7f4 --- /dev/null +++ b/components/content_capture/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Internals>ContentCapture" +}
diff --git a/components/content_capture/OWNERS b/components/content_capture/OWNERS index 8a32de7..e63fd7ee 100644 --- a/components/content_capture/OWNERS +++ b/components/content_capture/OWNERS
@@ -1,5 +1,3 @@ changwan@chromium.org michaelbai@chromium.org tobiasjs@chromium.org - -# COMPONENT: Internals>ContentCapture
diff --git a/components/contextual_search/DIR_METADATA b/components/contextual_search/DIR_METADATA new file mode 100644 index 0000000..747bdf5 --- /dev/null +++ b/components/contextual_search/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "UI>Browser>Search>ContextualSearch" +} + +team_email: "contextual-search-dev@chromium.org"
diff --git a/components/contextual_search/OWNERS b/components/contextual_search/OWNERS index 6ceed8d..1ae3bf18 100644 --- a/components/contextual_search/OWNERS +++ b/components/contextual_search/OWNERS
@@ -3,6 +3,3 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS - -# TEAM: contextual-search-dev@chromium.org -# COMPONENT: UI>Browser>Search>ContextualSearch
diff --git a/components/cookie_config/DIR_METADATA b/components/cookie_config/DIR_METADATA new file mode 100644 index 0000000..da096a8 --- /dev/null +++ b/components/cookie_config/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Internals>Network>Cookies" +}
diff --git a/components/cookie_config/OWNERS b/components/cookie_config/OWNERS index d35842a2..39557cd 100644 --- a/components/cookie_config/OWNERS +++ b/components/cookie_config/OWNERS
@@ -1,3 +1 @@ blundell@chromium.org - -# COMPONENT: Internals>Network>Cookies
diff --git a/components/country_codes/DIR_METADATA b/components/country_codes/DIR_METADATA new file mode 100644 index 0000000..2aaf8e2eed --- /dev/null +++ b/components/country_codes/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Internals>Core" +}
diff --git a/components/country_codes/OWNERS b/components/country_codes/OWNERS index fc3fe26..67c1e3afa 100644 --- a/components/country_codes/OWNERS +++ b/components/country_codes/OWNERS
@@ -1,4 +1,2 @@ jdonnelly@chromium.org pkasting@chromium.org - -# COMPONENT: Internals>Core
diff --git a/components/crash_strings_grdp/DIR_METADATA b/components/crash_strings_grdp/DIR_METADATA new file mode 100644 index 0000000..030c855 --- /dev/null +++ b/components/crash_strings_grdp/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Internals>CrashReporting" +}
diff --git a/components/crash_strings_grdp/OWNERS b/components/crash_strings_grdp/OWNERS index 05e3163..21fa106 100644 --- a/components/crash_strings_grdp/OWNERS +++ b/components/crash_strings_grdp/OWNERS
@@ -1,2 +1 @@ file://components/crash/OWNERS -# COMPONENT: Internals>CrashReporting
diff --git a/components/cronet/DIR_METADATA b/components/cronet/DIR_METADATA new file mode 100644 index 0000000..9e5f77e --- /dev/null +++ b/components/cronet/DIR_METADATA
@@ -0,0 +1,5 @@ +monorail { + component: "Internals>Network>Library" +} + +team_email: "net-dev@chromium.org"
diff --git a/components/cronet/OWNERS b/components/cronet/OWNERS index c847a8b9..fb59c70 100644 --- a/components/cronet/OWNERS +++ b/components/cronet/OWNERS
@@ -1,4 +1 @@ file://net/OWNERS - -# COMPONENT: Internals>Network>Library -# TEAM: net-dev@chromium.org
diff --git a/components/crx_file/DIR_METADATA b/components/crx_file/DIR_METADATA new file mode 100644 index 0000000..55432ec --- /dev/null +++ b/components/crx_file/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail { + component: "Platform>Extensions" +}
diff --git a/components/crx_file/OWNERS b/components/crx_file/OWNERS index bb2286c..9d0aa6a 100644 --- a/components/crx_file/OWNERS +++ b/components/crx_file/OWNERS
@@ -3,5 +3,3 @@ # if the above are unavailable file://extensions/OWNERS - -# COMPONENT: Platform>Extensions
diff --git a/components/payments/content/android/BUILD.gn b/components/payments/content/android/BUILD.gn index d470e380..701495b 100644 --- a/components/payments/content/android/BUILD.gn +++ b/components/payments/content/android/BUILD.gn
@@ -128,6 +128,7 @@ "java/src/org/chromium/components/payments/PaymentHandlerHost.java", "java/src/org/chromium/components/payments/PaymentManifestDownloader.java", "java/src/org/chromium/components/payments/PaymentManifestParser.java", + "java/src/org/chromium/components/payments/PaymentNotShownError.java", "java/src/org/chromium/components/payments/PaymentOptionsUtils.java", "java/src/org/chromium/components/payments/PaymentRequestParams.java", "java/src/org/chromium/components/payments/PaymentRequestService.java",
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentNotShownError.java b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentNotShownError.java new file mode 100644 index 0000000..f9e17b1 --- /dev/null +++ b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentNotShownError.java
@@ -0,0 +1,46 @@ +// 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.PaymentErrorReason; + +/** The error of payment UIs not being shown. */ +public class PaymentNotShownError { + private final int mNotShownReason; + private final String mErrorMessage; + private final int mReason; + + /** + * Creates an instance with the error details. + * @param notShownReason The reason of not showing UI, defined in {@link NotShownReason}. + * @param errorMessage The error message for informing the web developer. + * @param paymentErrorReason The reason of the payment error, defined in {@link + * PaymentErrorReason}. + */ + /* package */ PaymentNotShownError( + int notShownReason, String errorMessage, int paymentErrorReason) { + assert notShownReason <= NotShownReason.MAX; + assert paymentErrorReason >= PaymentErrorReason.MIN_VALUE; + assert paymentErrorReason <= PaymentErrorReason.MAX_VALUE; + mNotShownReason = notShownReason; + mErrorMessage = errorMessage; + mReason = paymentErrorReason; + } + + /** @return The reason of not showing UI, defined in {@link NotShownReason}. */ + public int getNotShownReason() { + return mNotShownReason; + } + + /** @return The error message for informing the web developer. */ + public String getErrorMessage() { + return mErrorMessage; + } + + /** @return The reason of the error, defined in {@link PaymentErrorReason}.*/ + public int getPaymentErrorReason() { + return mReason; + } +}
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java index bc66bd4..e5c7965 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java
@@ -746,11 +746,14 @@ // Always return false when can make payment is disabled. mHasEnrolledInstrument &= mDelegate.prefsCanMakePayment(); - if (mIsShowCalled && disconnectIfNoPaymentMethodsSupported()) return; - mBrowserPaymentRequest.notifyPaymentUiOfPendingApps(mPendingApps); mPendingApps.clear(); if (mIsShowCalled) { + PaymentNotShownError notShownError = ensureHasSupportedPaymentMethods(); + if (notShownError != null) { + onShowFailed(notShownError); + return; + } String error = mBrowserPaymentRequest.showAppSelector(mIsShowWaitingForUpdatedDetails, mSpec.getRawTotal(), mSpec.getPaymentOptions(), mIsUserGestureShow); if (error != null) { @@ -778,6 +781,11 @@ onShowFailed(NotShownReason.OTHER, error, PaymentErrorReason.USER_CANCEL); } + private void onShowFailed(PaymentNotShownError error) { + onShowFailed( + error.getNotShownReason(), error.getErrorMessage(), error.getPaymentErrorReason()); + } + // notShowReason is defined in NotShownReason. // paymentErrorReason is defined in PaymentErrorReason. private void onShowFailed(int notShowReason, String error, int paymentErrorReason) { @@ -787,12 +795,14 @@ } /** - * If no payment methods are supported, disconnect from the client and return true. - * @return Whether client has been disconnected. + * Ensures the available payment apps can make payment. + * @return The error if the payment cannot be made; null otherwise. */ - private boolean disconnectIfNoPaymentMethodsSupported() { - if (!mCanMakePayment - || (mPendingApps.isEmpty() && !mBrowserPaymentRequest.hasAvailableApps())) { + @Nullable + private PaymentNotShownError ensureHasSupportedPaymentMethods() { + assert mIsShowCalled; + assert mIsFinishedQueryingPaymentApps; + if (!mCanMakePayment || !mBrowserPaymentRequest.hasAvailableApps()) { // All factories have responded, but none of them have apps. It's possible to add credit // cards, but the merchant does not support them either. The payment request must be // rejected. @@ -821,31 +831,32 @@ : " " + mRejectShowErrorMessage); paymentErrorReason = PaymentErrorReason.NOT_SUPPORTED; } - onShowFailed(notShowReason, debugMessage, paymentErrorReason); - return true; + return new PaymentNotShownError(notShowReason, debugMessage, paymentErrorReason); } - return disconnectForStrictShow(mIsUserGestureShow); + return ensureHasSupportedPaymentMethodsForStrictShow(mIsUserGestureShow); } /** - * If strict show() conditions are not satisfied, disconnect from client and return true. + * Ensures the available payment apps can make payment under the strict show() conditions. * @param isUserGestureShow Whether the PaymentRequest.show() is triggered by user gesture. - * @return Whether client has been disconnected. + * @return The error if the payment cannot be made; null otherwise. */ - private boolean disconnectForStrictShow(boolean isUserGestureShow) { + @Nullable + private PaymentNotShownError ensureHasSupportedPaymentMethodsForStrictShow( + boolean isUserGestureShow) { if (!isUserGestureShow || !mSpec.getMethodData().containsKey(MethodStrings.BASIC_CARD) || mHasEnrolledInstrument || mHasNonAutofillApp || !PaymentFeatureList.isEnabledOrExperimentalFeaturesEnabled( PaymentFeatureList.STRICT_HAS_ENROLLED_AUTOFILL_INSTRUMENT)) { - return false; + return null; } mRejectShowErrorMessage = ErrorStrings.STRICT_BASIC_CARD_SHOW_REJECT; String debugMessage = ErrorMessageUtil.getNotSupportedErrorMessage(mSpec.getMethodData().keySet()) + " " + mRejectShowErrorMessage; - onShowFailed(NotShownReason.OTHER, debugMessage, PaymentErrorReason.NOT_SUPPORTED); - return true; + return new PaymentNotShownError( + NotShownReason.OTHER, debugMessage, PaymentErrorReason.NOT_SUPPORTED); } private boolean isInTwa() { @@ -1024,7 +1035,11 @@ mJourneyLogger.setTriggerTime(); if (mIsFinishedQueryingPaymentApps) { - if (disconnectIfNoPaymentMethodsSupported()) return; + PaymentNotShownError notShownError = ensureHasSupportedPaymentMethods(); + if (notShownError != null) { + onShowFailed(notShownError); + return; + } String error = mBrowserPaymentRequest.showAppSelector(mIsShowWaitingForUpdatedDetails, mSpec.getRawTotal(), mSpec.getPaymentOptions(), mIsUserGestureShow); if (error != null) {
diff --git a/components/resources/version_ui_resources.grdp b/components/resources/version_ui_resources.grdp index c76e749..7686906 100644 --- a/components/resources/version_ui_resources.grdp +++ b/components/resources/version_ui_resources.grdp
@@ -1,6 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <grit-part> <include name="IDR_VERSION_UI_CSS" file="../version_ui/resources/about_version.css" type="BINDATA" /> - <include name="IDR_VERSION_UI_HTML" file="../version_ui/resources/about_version.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> + <include name="IDR_VERSION_UI_HTML" file="../version_ui/resources/about_version.html" preprocess="true" type="BINDATA" /> <include name="IDR_VERSION_UI_JS" file="../version_ui/resources/about_version.js" type="BINDATA" /> </grit-part>
diff --git a/components/signin/public/base/account_consistency_method.cc b/components/signin/public/base/account_consistency_method.cc index 330614d3..403f237 100644 --- a/components/signin/public/base/account_consistency_method.cc +++ b/components/signin/public/base/account_consistency_method.cc
@@ -12,6 +12,10 @@ #if defined(OS_ANDROID) const base::Feature kMobileIdentityConsistency{ "MobileIdentityConsistency", base::FEATURE_DISABLED_BY_DEFAULT}; +// This feature flag is used to run experiments of different variations +// of MICE on Android. +const base::Feature kMobileIdentityConsistencyVar{ + "MobileIdentityConsistencyVar", base::FEATURE_DISABLED_BY_DEFAULT}; #endif #if defined(OS_IOS)
diff --git a/components/signin/public/base/account_consistency_method.h b/components/signin/public/base/account_consistency_method.h index 4fa6a7d5..8a4d6e6 100644 --- a/components/signin/public/base/account_consistency_method.h +++ b/components/signin/public/base/account_consistency_method.h
@@ -18,6 +18,9 @@ // Mice is similar to Mirror but also works when the user is not opted into // Sync. extern const base::Feature kMobileIdentityConsistency; +// This feature flag is used to run experiments of different variations +// of MICE on Android. +extern const base::Feature kMobileIdentityConsistencyVar; #endif enum class AccountConsistencyMethod : int {
diff --git a/components/sync/BUILD.gn b/components/sync/BUILD.gn index 6e8b16c..59cf7a7 100644 --- a/components/sync/BUILD.gn +++ b/components/sync/BUILD.gn
@@ -482,6 +482,7 @@ "trusted_vault/standalone_trusted_vault_backend_unittest.cc", "trusted_vault/trusted_vault_access_token_fetcher_frontend_unittest.cc", "trusted_vault/trusted_vault_connection_impl_unittest.cc", + "trusted_vault/trusted_vault_crypto_unittest.cc", "trusted_vault/trusted_vault_request_unittest.cc", ]
diff --git a/components/sync/driver/data_type_manager_impl.cc b/components/sync/driver/data_type_manager_impl.cc index 79329f6..935c083 100644 --- a/components/sync/driver/data_type_manager_impl.cc +++ b/components/sync/driver/data_type_manager_impl.cc
@@ -327,7 +327,7 @@ NotifyStart(); download_types_queue_ = PrioritizeTypes(last_enabled_types_); - association_types_queue_ = base::queue<AssociationTypesInfo>(); + association_types_info_.reset(); download_started_ = false; model_load_manager_.Initialize( @@ -439,7 +439,7 @@ return; } - association_types_queue_ = base::queue<AssociationTypesInfo>(); + association_types_info_.reset(); // An attempt was made to reconfigure while we were already configuring. // This can be because a passphrase was accepted or the user changed the @@ -489,15 +489,15 @@ // Those types that were already downloaded (non first sync/error types) // are already done. Just finalize the newly downloaded types if necessary. - if (!association_types_queue_.empty()) { - association_types_queue_.back().first_sync_types = first_sync_types; - association_types_queue_.back().download_ready_time = base::Time::Now(); + if (association_types_info_) { + // A non-empty |association_types_info_| means there were actually types + // downloading. Finalize those. + association_types_info_->first_sync_types = first_sync_types; + association_types_info_->download_ready_time = base::Time::Now(); StartNextAssociation(UNREADY_AT_CONFIG); } else if (download_types_queue_.empty()) { // There's nothing more to download or associate (implying either there were // no types to associate or they associated as part of |ready_types|). - // If the model association manager is also finished, then we're done - // configuring. state_ = CONFIGURED; ConfigureResult result(OK, last_requested_types_); NotifyDone(result); @@ -528,12 +528,13 @@ // configure request until the current request succeeds. configurer_->ConfigureDataTypes(std::move(config_params)); - AssociationTypesInfo association_info; - association_info.types = download_types_queue_.front(); - association_info.ready_types = ready_types; - association_info.download_start_time = base::Time::Now(); - association_info.high_priority_types_before = high_priority_types_before; - association_types_queue_.push(association_info); + DCHECK(!association_types_info_); + association_types_info_ = AssociationTypesInfo(); + association_types_info_->types = download_types_queue_.front(); + association_types_info_->ready_types = ready_types; + association_types_info_->download_start_time = base::Time::Now(); + association_types_info_->high_priority_types_before = + high_priority_types_before; // Start associating those types that are already downloaded. StartNextAssociation(READY_AT_CONFIG); @@ -642,21 +643,19 @@ } void DataTypeManagerImpl::StartNextAssociation(AssociationGroup group) { - DCHECK(!association_types_queue_.empty()); + DCHECK(association_types_info_); + DCHECK(state_ == STOPPING || state_ == CONFIGURING); ModelTypeSet types_to_associate; if (group == READY_AT_CONFIG) { - types_to_associate = association_types_queue_.front().ready_types; + types_to_associate = association_types_info_->ready_types; } else { DCHECK_EQ(UNREADY_AT_CONFIG, group); - // Only start associating the rest of the types if they have all finished - // downloading. - if (association_types_queue_.front().download_ready_time.is_null()) - return; + DCHECK(!association_types_info_->download_ready_time.is_null()); // We request the full set of types here for completeness sake. All types // within the READY_AT_CONFIG set will already be started and should be // no-ops. - types_to_associate = association_types_queue_.front().types; + types_to_associate = association_types_info_->types; } for (ModelType type : types_to_associate) { @@ -665,8 +664,6 @@ } } - DCHECK(state_ == STOPPING || state_ == CONFIGURING); - if (state_ == STOPPING) return; @@ -678,18 +675,17 @@ // If this model association was for the full set of types, then this priority // set is done. Otherwise it was just the ready types and the unready types // still need to be associated. - if (types_to_associate == association_types_queue_.front().types) { - association_types_queue_.pop(); - if (!association_types_queue_.empty()) { - StartNextAssociation(READY_AT_CONFIG); - } else if (download_types_queue_.empty()) { + if (types_to_associate == association_types_info_->types) { + association_types_info_.reset(); + if (download_types_queue_.empty()) { state_ = CONFIGURED; NotifyDone(ConfigureResult(OK, types_to_associate)); } } else { - DCHECK_EQ(association_types_queue_.front().ready_types, types_to_associate); - // Will do nothing if the types are still downloading. - StartNextAssociation(UNREADY_AT_CONFIG); + DCHECK_EQ(association_types_info_->ready_types, types_to_associate); + // The remaining types are still downloading; this method will get called + // again (with UNREADY_AT_CONFIG) once the download finishes. + DCHECK(association_types_info_->download_ready_time.is_null()); } } @@ -715,7 +711,7 @@ } void DataTypeManagerImpl::RecordConfigurationStats(ModelType type) { - DCHECK(!association_types_queue_.empty()); + DCHECK(association_types_info_); if (!debug_info_listener_.IsInitialized()) return; @@ -723,7 +719,7 @@ if (configuration_stats_.count(type) > 0) return; - AssociationTypesInfo& info = association_types_queue_.front(); + AssociationTypesInfo& info = *association_types_info_; configuration_stats_[type].model_type = type; if (info.types.Has(type)) { // Times in |info| only apply to non-slow types.
diff --git a/components/sync/driver/data_type_manager_impl.h b/components/sync/driver/data_type_manager_impl.h index ef9ff21..a72089e 100644 --- a/components/sync/driver/data_type_manager_impl.h +++ b/components/sync/driver/data_type_manager_impl.h
@@ -15,6 +15,7 @@ #include "base/containers/queue.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/optional.h" #include "base/time/time.h" #include "components/sync/base/weak_handle.h" #include "components/sync/driver/configure_context.h" @@ -235,19 +236,19 @@ // and had to be purged/unapplied from the sync db. // This is a subset of |types|. ModelTypeSet first_sync_types; - // Types that were already ready for association at configuration time. + // Types that were already already downloaded at configuration time. ModelTypeSet ready_types; // Time at which |types| began downloading. base::Time download_start_time; // Time at which |types| finished downloading. base::Time download_ready_time; - // The set of types that are higher priority (and were therefore blocking) - // the association of |types|. + // The set of types that are higher priority, and were therefore blocking + // the download of |types|. ModelTypeSet high_priority_types_before; // The subset of |types| that were successfully configured. ModelTypeSet configured_types; }; - base::queue<AssociationTypesInfo> association_types_queue_; + base::Optional<AssociationTypesInfo> association_types_info_; // The encryption handler lets the DataTypeManager know the state of sync // datatype encryption.
diff --git a/components/sync/trusted_vault/BUILD.gn b/components/sync/trusted_vault/BUILD.gn index 718d164e..8e04a73b8 100644 --- a/components/sync/trusted_vault/BUILD.gn +++ b/components/sync/trusted_vault/BUILD.gn
@@ -22,6 +22,8 @@ "trusted_vault_connection.h", "trusted_vault_connection_impl.cc", "trusted_vault_connection_impl.h", + "trusted_vault_crypto.cc", + "trusted_vault_crypto.h", "trusted_vault_request.cc", "trusted_vault_request.h", ]
diff --git a/components/sync/trusted_vault/download_keys_response_handler.cc b/components/sync/trusted_vault/download_keys_response_handler.cc index ffc72ac..a4277f2 100644 --- a/components/sync/trusted_vault/download_keys_response_handler.cc +++ b/components/sync/trusted_vault/download_keys_response_handler.cc
@@ -10,17 +10,12 @@ #include "components/sync/protocol/vault.pb.h" #include "components/sync/trusted_vault/proto_string_bytes_conversion.h" #include "components/sync/trusted_vault/securebox.h" -#include "crypto/hmac.h" +#include "components/sync/trusted_vault/trusted_vault_crypto.h" namespace syncer { namespace { -// TODO(crbug.com/1113598): move these constants to a dedicated header, since -// they are used in multiple places already. -const size_t kKeyProofLength = 32; -const uint8_t kWrappedKeyHeader[] = {'V', '1', ' ', 's', 'h', 'a', 'r', - 'e', 'd', '_', 'k', 'e', 'y'}; const char kSecurityDomainName[] = "chromesync"; struct ExtractedSharedKey { @@ -73,9 +68,8 @@ std::vector<ExtractedSharedKey> result; for (const sync_pb::SharedKey& shared_key : member.keys()) { base::Optional<std::vector<uint8_t>> decrypted_key = - member_private_key.Decrypt( - base::span<const uint8_t>(), kWrappedKeyHeader, - /*encrypted_payload=*/ProtoStringToBytes(shared_key.wrapped_key())); + DecryptTrustedVaultWrappedKey( + member_private_key, ProtoStringToBytes(shared_key.wrapped_key())); if (!decrypted_key.has_value()) { // Decryption failed. return std::vector<ExtractedSharedKey>(); @@ -115,14 +109,12 @@ return false; } - crypto::HMAC hmac(crypto::HMAC::SHA256); - CHECK(hmac.Init(last_valid_key)); - - std::vector<uint8_t> digest_bytes(kKeyProofLength); - if (!hmac.Verify(next_key.trusted_vault_key, next_key.key_proof)) { + if (!VerifyTrustedVaultHMAC(last_valid_key, next_key.trusted_vault_key, + next_key.key_proof)) { // |key_proof| isn't valid. return false; } + last_valid_key_version = next_key.version; last_valid_key = next_key.trusted_vault_key; }
diff --git a/components/sync/trusted_vault/download_keys_response_handler_unittest.cc b/components/sync/trusted_vault/download_keys_response_handler_unittest.cc index 6a1f229..f61ec4a 100644 --- a/components/sync/trusted_vault/download_keys_response_handler_unittest.cc +++ b/components/sync/trusted_vault/download_keys_response_handler_unittest.cc
@@ -10,7 +10,7 @@ #include "components/sync/protocol/vault.pb.h" #include "components/sync/trusted_vault/proto_string_bytes_conversion.h" #include "components/sync/trusted_vault/securebox.h" -#include "crypto/hmac.h" +#include "components/sync/trusted_vault/trusted_vault_crypto.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -22,11 +22,8 @@ using testing::Eq; using testing::IsEmpty; -const size_t kKeyProofLength = 32; const char kEncodedPrivateKey[] = "49e052293c29b5a50b0013eec9d030ac2ad70a42fe093be084264647cb04e16f"; -const uint8_t kWrappedKeyHeader[] = {'V', '1', ' ', 's', 'h', 'a', 'r', - 'e', 'd', '_', 'k', 'e', 'y'}; const char kSecurityDomainName[] = "chromesync"; std::unique_ptr<SecureBoxKeyPair> MakeTestKeyPair() { @@ -53,19 +50,13 @@ sync_pb::SharedKey* shared_key = member->add_keys(); shared_key->set_epoch(trusted_vault_keys_versions[i]); AssignBytesToProtoString( - public_key.Encrypt( - /*shared_secret=*/base::span<const uint8_t>(), kWrappedKeyHeader, - /*payload=*/trusted_vault_keys[i]), + ComputeTrustedVaultWrappedKey(public_key, trusted_vault_keys[i]), shared_key->mutable_wrapped_key()); if (!signing_keys[i].empty()) { - crypto::HMAC hmac(crypto::HMAC::SHA256); - CHECK(hmac.Init(signing_keys[i])); - - std::vector<uint8_t> key_proof_bytes(kKeyProofLength); - CHECK(hmac.Sign(trusted_vault_keys[i], key_proof_bytes)); - AssignBytesToProtoString(key_proof_bytes, - shared_key->mutable_key_proof()); + AssignBytesToProtoString( + ComputeTrustedVaultHMAC(signing_keys[i], trusted_vault_keys[i]), + shared_key->mutable_key_proof()); } } }
diff --git a/components/sync/trusted_vault/trusted_vault_connection_impl.cc b/components/sync/trusted_vault/trusted_vault_connection_impl.cc index 2d4f4e3..20037a8 100644 --- a/components/sync/trusted_vault/trusted_vault_connection_impl.cc +++ b/components/sync/trusted_vault/trusted_vault_connection_impl.cc
@@ -13,17 +13,14 @@ #include "components/sync/trusted_vault/proto_string_bytes_conversion.h" #include "components/sync/trusted_vault/securebox.h" #include "components/sync/trusted_vault/trusted_vault_access_token_fetcher.h" +#include "components/sync/trusted_vault/trusted_vault_crypto.h" #include "components/sync/trusted_vault/trusted_vault_request.h" -#include "crypto/hmac.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace syncer { namespace { -const size_t kMemberProofLength = 32; -const uint8_t kWrappedKeyHeader[] = {'V', '1', ' ', 's', 'h', 'a', 'r', - 'e', 'd', '_', 'k', 'e', 'y'}; const char kJoinSecurityDomainsURLPath[] = "/domain:join"; const char kListSecurityDomainsURLPathAndQuery[] = "/domain:list?view=1"; const char kSecurityDomainName[] = "chromesync"; @@ -48,36 +45,19 @@ std::move(callback).Run(registration_status); } -std::vector<uint8_t> ComputeWrappedKey( - const SecureBoxPublicKey& public_key, - const std::vector<uint8_t>& trusted_vault_key) { - return public_key.Encrypt( - /*shared_secret=*/base::span<const uint8_t>(), kWrappedKeyHeader, - /*payload=*/trusted_vault_key); -} - -std::vector<uint8_t> ComputeMemberProof( - const SecureBoxPublicKey& public_key, - const std::vector<uint8_t>& trusted_vault_key) { - crypto::HMAC hmac(crypto::HMAC::SHA256); - CHECK(hmac.Init(trusted_vault_key)); - - std::vector<uint8_t> digest_bytes(kMemberProofLength); - CHECK(hmac.Sign(public_key.ExportToBytes(), digest_bytes)); - - return digest_bytes; -} - sync_pb::SharedKey CreateMemberSharedKey( int trusted_vault_key_version, const std::vector<uint8_t>& trusted_vault_key, const SecureBoxPublicKey& public_key) { sync_pb::SharedKey shared_key; shared_key.set_epoch(trusted_vault_key_version); - AssignBytesToProtoString(ComputeWrappedKey(public_key, trusted_vault_key), - shared_key.mutable_wrapped_key()); - AssignBytesToProtoString(ComputeMemberProof(public_key, trusted_vault_key), - shared_key.mutable_member_proof()); + AssignBytesToProtoString( + ComputeTrustedVaultWrappedKey(public_key, trusted_vault_key), + shared_key.mutable_wrapped_key()); + AssignBytesToProtoString( + ComputeTrustedVaultHMAC(/*key=*/trusted_vault_key, + /*data=*/public_key.ExportToBytes()), + shared_key.mutable_member_proof()); return shared_key; }
diff --git a/components/sync/trusted_vault/trusted_vault_connection_impl_unittest.cc b/components/sync/trusted_vault/trusted_vault_connection_impl_unittest.cc index edaea6c..a5e7a2b 100644 --- a/components/sync/trusted_vault/trusted_vault_connection_impl_unittest.cc +++ b/components/sync/trusted_vault/trusted_vault_connection_impl_unittest.cc
@@ -17,6 +17,7 @@ #include "components/sync/trusted_vault/proto_string_bytes_conversion.h" #include "components/sync/trusted_vault/securebox.h" #include "components/sync/trusted_vault/trusted_vault_access_token_fetcher.h" +#include "components/sync/trusted_vault/trusted_vault_crypto.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" @@ -42,8 +43,6 @@ "https://test.com/test/domain:join?alt=proto"; const char kTestListSecurityDomainsURL[] = "https://test.com/test/domain:list?view=1&alt=proto"; -const uint8_t kWrappedKeyHeader[] = {'V', '1', ' ', 's', 'h', 'a', 'r', - 'e', 'd', '_', 'k', 'e', 'y'}; std::unique_ptr<SecureBoxKeyPair> MakeTestKeyPair() { std::vector<uint8_t> private_key_bytes; @@ -178,9 +177,9 @@ EXPECT_THAT(shared_key.epoch(), Eq(kLastKeyVersion)); base::Optional<std::vector<uint8_t>> decrypted_trusted_vault_key = - key_pair->private_key().Decrypt( - /*shared_key=*/base::span<const uint8_t>(), kWrappedKeyHeader, - /*encrypted_payload=*/ProtoStringToBytes(shared_key.wrapped_key())); + DecryptTrustedVaultWrappedKey( + key_pair->private_key(), + /*wrapped_key=*/ProtoStringToBytes(shared_key.wrapped_key())); ASSERT_THAT(decrypted_trusted_vault_key, Ne(base::nullopt)); EXPECT_THAT(*decrypted_trusted_vault_key, Eq(kTrustedVaultKey));
diff --git a/components/sync/trusted_vault/trusted_vault_crypto.cc b/components/sync/trusted_vault/trusted_vault_crypto.cc new file mode 100644 index 0000000..b124939 --- /dev/null +++ b/components/sync/trusted_vault/trusted_vault_crypto.cc
@@ -0,0 +1,54 @@ +// 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/sync/trusted_vault/trusted_vault_crypto.h" + +#include "components/sync/trusted_vault/securebox.h" +#include "crypto/hmac.h" + +namespace syncer { + +namespace { + +const size_t kHMACDigestLength = 32; +const uint8_t kWrappedKeyHeader[] = {'V', '1', ' ', 's', 'h', 'a', 'r', + 'e', 'd', '_', 'k', 'e', 'y'}; + +} // namespace + +base::Optional<std::vector<uint8_t>> DecryptTrustedVaultWrappedKey( + const SecureBoxPrivateKey& private_key, + base::span<const uint8_t> wrapped_key) { + return private_key.Decrypt( + /*shared_secret=*/base::span<const uint8_t>(), kWrappedKeyHeader, + /*encrypted_payload=*/wrapped_key); +} + +std::vector<uint8_t> ComputeTrustedVaultWrappedKey( + const SecureBoxPublicKey& public_key, + base::span<const uint8_t> trusted_vault_key) { + return public_key.Encrypt( + /*shared_secret=*/base::span<const uint8_t>(), kWrappedKeyHeader, + /*payload=*/trusted_vault_key); +} + +std::vector<uint8_t> ComputeTrustedVaultHMAC(base::span<const uint8_t> key, + base::span<const uint8_t> data) { + crypto::HMAC hmac(crypto::HMAC::SHA256); + CHECK(hmac.Init(key)); + + std::vector<uint8_t> digest(kHMACDigestLength); + CHECK(hmac.Sign(data, digest)); + return digest; +} + +bool VerifyTrustedVaultHMAC(base::span<const uint8_t> key, + base::span<const uint8_t> data, + base::span<const uint8_t> digest) { + crypto::HMAC hmac(crypto::HMAC::SHA256); + CHECK(hmac.Init(key)); + return hmac.Verify(data, digest); +} + +} // namespace syncer
diff --git a/components/sync/trusted_vault/trusted_vault_crypto.h b/components/sync/trusted_vault/trusted_vault_crypto.h new file mode 100644 index 0000000..a6bbd59 --- /dev/null +++ b/components/sync/trusted_vault/trusted_vault_crypto.h
@@ -0,0 +1,40 @@ +// 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_SYNC_TRUSTED_VAULT_TRUSTED_VAULT_CRYPTO_H_ +#define COMPONENTS_SYNC_TRUSTED_VAULT_TRUSTED_VAULT_CRYPTO_H_ + +#include <vector> + +#include "base/containers/span.h" +#include "base/optional.h" + +namespace syncer { + +class SecureBoxPrivateKey; +class SecureBoxPublicKey; + +// Decrypts |wrapped_key| using securebox. Returns decrypted key if successful +// and base::nullopt otherwise. +base::Optional<std::vector<uint8_t>> DecryptTrustedVaultWrappedKey( + const SecureBoxPrivateKey& private_key, + base::span<const uint8_t> wrapped_key); + +// Encrypts |trusted_vault_key| using securebox. +std::vector<uint8_t> ComputeTrustedVaultWrappedKey( + const SecureBoxPublicKey& public_key, + base::span<const uint8_t> trusted_vault_key); + +// Computes HMAC digest using SHA-256. +std::vector<uint8_t> ComputeTrustedVaultHMAC(base::span<const uint8_t> key, + base::span<const uint8_t> data); + +// Returns true if |digest| is a valid HMAC SHA-256 digest of |data| and |key|. +bool VerifyTrustedVaultHMAC(base::span<const uint8_t> key, + base::span<const uint8_t> data, + base::span<const uint8_t> digest); + +} // namespace syncer + +#endif // COMPONENTS_SYNC_TRUSTED_VAULT_TRUSTED_VAULT_CRYPTO_H_
diff --git a/components/sync/trusted_vault/trusted_vault_crypto_unittest.cc b/components/sync/trusted_vault/trusted_vault_crypto_unittest.cc new file mode 100644 index 0000000..21f365c8 --- /dev/null +++ b/components/sync/trusted_vault/trusted_vault_crypto_unittest.cc
@@ -0,0 +1,69 @@ +// 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/sync/trusted_vault/trusted_vault_crypto.h" + +#include <memory> + +#include "base/strings/string_number_conversions.h" +#include "components/sync/trusted_vault/securebox.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace syncer { + +namespace { + +using testing::Eq; +using testing::Ne; + +const char kEncodedPrivateKey[] = + "49e052293c29b5a50b0013eec9d030ac2ad70a42fe093be084264647cb04e16f"; + +std::unique_ptr<SecureBoxKeyPair> MakeTestKeyPair() { + std::vector<uint8_t> private_key_bytes; + bool success = base::HexStringToBytes(kEncodedPrivateKey, &private_key_bytes); + DCHECK(success); + return SecureBoxKeyPair::CreateByPrivateKeyImport(private_key_bytes); +} + +TEST(TrustedVaultCrypto, ShouldHandleDecryptionFailure) { + EXPECT_THAT(DecryptTrustedVaultWrappedKey( + MakeTestKeyPair()->private_key(), + /*wrapped_key=*/std::vector<uint8_t>{1, 2, 3, 4}), + Eq(base::nullopt)); +} + +TEST(TrustedVaultCrypto, ShouldEncryptAndDecryptWrappedKey) { + const std::vector<uint8_t> trusted_vault_key = {1, 2, 3, 4}; + const std::unique_ptr<SecureBoxKeyPair> key_pair = MakeTestKeyPair(); + base::Optional<std::vector<uint8_t>> decrypted_trusted_vault_key = + DecryptTrustedVaultWrappedKey( + key_pair->private_key(), + /*wrapped_key=*/ComputeTrustedVaultWrappedKey(key_pair->public_key(), + trusted_vault_key)); + ASSERT_THAT(decrypted_trusted_vault_key, Ne(base::nullopt)); + EXPECT_THAT(*decrypted_trusted_vault_key, Eq(trusted_vault_key)); +} + +TEST(TrustedVaultCrypto, ShouldComputeAndVerifyHMAC) { + const std::vector<uint8_t> key = {1, 2, 3, 4}; + const std::vector<uint8_t> data = {1, 2, 3, 5}; + EXPECT_TRUE( + VerifyTrustedVaultHMAC(key, data, + /*digest=*/ComputeTrustedVaultHMAC(key, data))); +} + +TEST(TrustedVaultCrypto, ShouldDetectIncorrectHMAC) { + const std::vector<uint8_t> correct_key = {1, 2, 3, 4}; + const std::vector<uint8_t> incorrect_key = {1, 2, 3, 5}; + const std::vector<uint8_t> data = {1, 2, 3, 6}; + EXPECT_FALSE(VerifyTrustedVaultHMAC( + correct_key, data, + /*digest=*/ComputeTrustedVaultHMAC(incorrect_key, data))); +} + +} // namespace + +} // namespace syncer
diff --git a/components/test/data/autofill_assistant/html/autofill_assistant_target_website.html b/components/test/data/autofill_assistant/html/autofill_assistant_target_website.html index a4bdc9b6..4affaa19 100644 --- a/components/test/data/autofill_assistant/html/autofill_assistant_target_website.html +++ b/components/test/data/autofill_assistant/html/autofill_assistant_target_website.html
@@ -65,6 +65,10 @@ } } } + + var onChangeIncrement = function(event) { + event.target.value = parseInt(event.target.value) + 1; + } </script> <style> @@ -257,6 +261,9 @@ <div> <input id="input7" type="text" value="" /> </div> + <div> + <input id="input_with_onchange" type="text" value="0" onchange="onChangeIncrement(event)" /> + </div> <div> <input id="input_js_event_listener" type="text">
diff --git a/content/browser/accessibility/dump_accessibility_events_browsertest.cc b/content/browser/accessibility/dump_accessibility_events_browsertest.cc index 4a4a631..d28a6888 100644 --- a/content/browser/accessibility/dump_accessibility_events_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_events_browsertest.cc
@@ -259,8 +259,7 @@ RunEventTest(FILE_PATH_LITERAL("aria-busy-changed.html")); } -#if defined(OS_LINUX) && \ - (defined(THREAD_SANITIZER) || defined(MEMORY_SANITIZER)) +#if defined(OS_LINUX) #define DISABLED_ON_LINUX_TSAN_MSAN(name) DISABLED_##name #else #define DISABLED_ON_LINUX_TSAN_MSAN(name) name
diff --git a/content/browser/android/background_sync_network_observer_android.cc b/content/browser/android/background_sync_network_observer_android.cc index 5f627e0e..0b34b1d4 100644 --- a/content/browser/android/background_sync_network_observer_android.cc +++ b/content/browser/android/background_sync_network_observer_android.cc
@@ -78,14 +78,7 @@ observer_ = Observer::Create(base::BindRepeating( &BackgroundSyncNetworkObserverAndroid::OnConnectionChanged, weak_ptr_factory_.GetWeakPtr())); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - observer_->Init(); - } else { - RunOrPostTaskOnThread( - FROM_HERE, BrowserThread::UI, - base::BindOnce(&BackgroundSyncNetworkObserverAndroid::Observer::Init, - observer_)); - } + observer_->Init(); } void BackgroundSyncNetworkObserverAndroid::RegisterWithNetworkConnectionTracker(
diff --git a/content/browser/back_forward_cache_browsertest.cc b/content/browser/back_forward_cache_browsertest.cc index b39d68d9..fee3b57 100644 --- a/content/browser/back_forward_cache_browsertest.cc +++ b/content/browser/back_forward_cache_browsertest.cc
@@ -2437,8 +2437,9 @@ static_cast<SiteInstanceImpl*>(rfh_a->GetSiteInstance()); RenderFrameDeletedObserver rfh_a_deleted(rfh_a); - // 2) Use WebRTC (non-sticky) and KeyboardLock (sticky) blocklisted features. - EXPECT_TRUE(ExecJs(rfh_a, "new RTCPeerConnection()")); + // 2) Use BroadcastChannel (non-sticky) and KeyboardLock (sticky) blocklisted + // features. + EXPECT_TRUE(ExecJs(rfh_a, "window.foo = new BroadcastChannel('foo');")); EXPECT_TRUE(ExecJs(rfh_a, R"( new Promise(resolve => { navigator.keyboard.lock(); @@ -2468,7 +2469,7 @@ // All features (sticky and non-sticky) will be tracked, because they're // tracked in RenderFrameHostManager::UnloadOldFrame. ExpectBlocklistedFeatures( - {blink::scheduler::WebSchedulerTrackedFeature::kWebRTC, + {blink::scheduler::WebSchedulerTrackedFeature::kBroadcastChannel, blink::scheduler::WebSchedulerTrackedFeature::kKeyboardLock}, FROM_HERE); } @@ -2491,9 +2492,9 @@ scoped_refptr<SiteInstanceImpl> site_instance_a = static_cast<SiteInstanceImpl*>(rfh_a->GetSiteInstance()); - // 2) Use WebRTC (non-sticky) and KeyboardLock (sticky) blocklisted + // 2) Use BroadcastChannel (non-sticky) and KeyboardLock (sticky) blocklisted // features. - EXPECT_TRUE(ExecJs(rfh_a, "new RTCPeerConnection()")); + EXPECT_TRUE(ExecJs(rfh_a, "window.foo = new BroadcastChannel('foo');")); EXPECT_TRUE(ExecJs(rfh_a, R"( new Promise(resolve => { navigator.keyboard.lock(); @@ -2523,7 +2524,7 @@ // All features (sticky and non-sticky) will be tracked, because they're // tracked in RenderFrameHostManager::UnloadOldFrame. ExpectBlocklistedFeatures( - {blink::scheduler::WebSchedulerTrackedFeature::kWebRTC, + {blink::scheduler::WebSchedulerTrackedFeature::kBroadcastChannel, blink::scheduler::WebSchedulerTrackedFeature::kKeyboardLock}, FROM_HERE); ExpectBrowsingInstanceNotSwappedReason( @@ -2574,8 +2575,9 @@ scoped_refptr<SiteInstanceImpl> site_instance_1 = static_cast<SiteInstanceImpl*>(rfh_1->GetSiteInstance()); - // 2) Use WebRTC (non-sticky) and KeyboardLock (sticky) blocklisted features. - EXPECT_TRUE(ExecJs(rfh_1, "new RTCPeerConnection()")); + // 2) Use BroadcastChannel (non-sticky) and KeyboardLock (sticky) blocklisted + // features. + EXPECT_TRUE(ExecJs(rfh_1, "window.foo = new BroadcastChannel('foo');")); EXPECT_TRUE(ExecJs(rfh_1, R"( new Promise(resolve => { navigator.keyboard.lock(); @@ -2621,8 +2623,8 @@ EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); RenderFrameHostImpl* rfh_a = current_frame_host(); - // 2) Use WebRTC (a non-sticky blocklisted feature). - EXPECT_TRUE(ExecJs(rfh_a, "new RTCPeerConnection()")); + // 2) Use BroadcastChannel (a non-sticky blocklisted feature). + EXPECT_TRUE(ExecJs(rfh_a, "window.foo = new BroadcastChannel('foo');")); scoped_refptr<SiteInstanceImpl> site_instance_a = static_cast<SiteInstanceImpl*>( web_contents()->GetMainFrame()->GetSiteInstance()); @@ -2647,7 +2649,8 @@ {BackForwardCacheMetrics::NotRestoredReason::kBlocklistedFeatures}, FROM_HERE); ExpectBlocklistedFeature( - blink::scheduler::WebSchedulerTrackedFeature::kWebRTC, FROM_HERE); + blink::scheduler::WebSchedulerTrackedFeature::kBroadcastChannel, + FROM_HERE); } // Tests which blocklisted features are tracked in the metrics when we used a @@ -2665,8 +2668,8 @@ EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); RenderFrameHostImpl* rfh_a = current_frame_host(); - // 2) Use WebRTC (a non-sticky blocklisted feature). - EXPECT_TRUE(ExecJs(rfh_a, "new RTCPeerConnection()")); + // 2) Use BroadcastChannel (a non-sticky blocklisted feature). + EXPECT_TRUE(ExecJs(rfh_a, "window.foo = new BroadcastChannel('foo');")); scoped_refptr<SiteInstanceImpl> site_instance_a = static_cast<SiteInstanceImpl*>( web_contents()->GetMainFrame()->GetSiteInstance()); @@ -2691,7 +2694,8 @@ {BackForwardCacheMetrics::NotRestoredReason::kBlocklistedFeatures}, FROM_HERE); ExpectBlocklistedFeature( - blink::scheduler::WebSchedulerTrackedFeature::kWebRTC, FROM_HERE); + blink::scheduler::WebSchedulerTrackedFeature::kBroadcastChannel, + FROM_HERE); } // Tests which blocklisted features are tracked in the metrics when we used a @@ -2707,8 +2711,8 @@ EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); RenderFrameHostImpl* rfh_1 = current_frame_host(); - // 2) Use WebRTC (a non-sticky blocklisted feature). - EXPECT_TRUE(ExecJs(rfh_1, "new RTCPeerConnection()")); + // 2) Use BroadcastChannel (a non-sticky blocklisted feature). + EXPECT_TRUE(ExecJs(rfh_1, "window.foo = new BroadcastChannel('foo');")); scoped_refptr<SiteInstanceImpl> site_instance_1 = static_cast<SiteInstanceImpl*>( web_contents()->GetMainFrame()->GetSiteInstance()); @@ -2733,7 +2737,8 @@ {BackForwardCacheMetrics::NotRestoredReason::kBlocklistedFeatures}, FROM_HERE); ExpectBlocklistedFeature( - blink::scheduler::WebSchedulerTrackedFeature::kWebRTC, FROM_HERE); + blink::scheduler::WebSchedulerTrackedFeature::kBroadcastChannel, + FROM_HERE); } // Flaky on Android, see crbug.com/1135601. @@ -3344,11 +3349,11 @@ EXPECT_TRUE(NavigateToURL(shell(), url_1)); RenderFrameHostImpl* rfh_1 = current_frame_host(); RenderFrameDeletedObserver delete_observer_rfh_1(rfh_1); - // 2) Use WebRTC (a non-sticky blocklisted feature), so that we would still do - // a RFH swap on same-site navigation and fire the 'pagehide' event during - // commit of the new page with 'persisted' set to true, but the page will not - // be eligible for back-forward cache after commit. - EXPECT_TRUE(ExecJs(rfh_1, "new RTCPeerConnection()")); + // 2) Use BroadcastChannel (a non-sticky blocklisted feature), so that we + // would still do a RFH swap on same-site navigation and fire the 'pagehide' + // event during commit of the new page with 'persisted' set to true, but the + // page will not be eligible for back-forward cache after commit. + EXPECT_TRUE(ExecJs(rfh_1, "window.foo = new BroadcastChannel('foo');")); EXPECT_TRUE(ExecJs(rfh_1, R"( window.onpagehide = (e) => { @@ -3794,7 +3799,7 @@ // cached. EXPECT_TRUE(ExecJs(rfh_a, R"( document.addEventListener('freeze', event => { - new RTCPeerConnection(); + window.foo = new BroadcastChannel('foo'); }); )"));
diff --git a/content/browser/background_fetch/background_fetch_request_info.cc b/content/browser/background_fetch/background_fetch_request_info.cc index d1f54c23..04ef94c 100644 --- a/content/browser/background_fetch/background_fetch_request_info.cc +++ b/content/browser/background_fetch/background_fetch_request_info.cc
@@ -184,21 +184,14 @@ : nullptr; result_->blob_handle.reset(); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - // base::Unretained is safe because |io_blob_data_| is deleted on the IO - // thread in a task that must run after this task. - GetIOThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce(&BlobDataOnIO::CreateBlobDataHandle, - base::Unretained(io_blob_data_.get()), - std::move(blob_storage_context), std::move(handle), - result_->file_path, result_->file_size, response_size_)); - } else { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - io_blob_data_->CreateBlobDataHandle(std::move(blob_storage_context), - std::move(handle), result_->file_path, - result_->file_size, response_size_); - } + // base::Unretained is safe because |io_blob_data_| is deleted on the IO + // thread in a task that must run after this task. + GetIOThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce(&BlobDataOnIO::CreateBlobDataHandle, + base::Unretained(io_blob_data_.get()), + std::move(blob_storage_context), std::move(handle), + result_->file_path, result_->file_size, response_size_)); } std::unique_ptr<storage::BlobDataHandle>
diff --git a/content/browser/background_fetch/storage/mark_request_complete_task.cc b/content/browser/background_fetch/storage/mark_request_complete_task.cc index 161f54e..d33e260 100644 --- a/content/browser/background_fetch/storage/mark_request_complete_task.cc +++ b/content/browser/background_fetch/storage/mark_request_complete_task.cc
@@ -116,14 +116,10 @@ response_->headers.insert(request_info_->GetResponseHeaders().begin(), request_info_->GetResponseHeaders().end()); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - GetIOThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, base::BindOnce(&MakeBlob, request_info_), - base::BindOnce(&MarkRequestCompleteTask::DidMakeBlob, - weak_factory_.GetWeakPtr(), std::move(done_closure))); - } else { - DidMakeBlob(std::move(done_closure), MakeBlob(request_info_)); - } + GetIOThreadTaskRunner({})->PostTaskAndReplyWithResult( + FROM_HERE, base::BindOnce(&MakeBlob, request_info_), + base::BindOnce(&MarkRequestCompleteTask::DidMakeBlob, + weak_factory_.GetWeakPtr(), std::move(done_closure))); } void MarkRequestCompleteTask::DidMakeBlob(
diff --git a/content/browser/background_sync/background_sync_base_browsertest.cc b/content/browser/background_sync/background_sync_base_browsertest.cc index ccaa88ef..6bd301d 100644 --- a/content/browser/background_sync/background_sync_base_browsertest.cc +++ b/content/browser/background_sync/background_sync_base_browsertest.cc
@@ -128,17 +128,6 @@ std::move(callback))); } -void BackgroundSyncBaseBrowserTest::SetTestClockOnCoreThread( - BackgroundSyncContextImpl* sync_context, - base::SimpleTestClock* clock) { - DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); - DCHECK(clock); - - BackgroundSyncManager* background_sync_manager = - sync_context->background_sync_manager(); - background_sync_manager->set_clock(clock); -} - void BackgroundSyncBaseBrowserTest::SetUp() { const char kTrialName[] = "BackgroundSync"; const char kGroupName[] = "BackgroundSync"; @@ -203,24 +192,13 @@ } void BackgroundSyncBaseBrowserTest::SetTestClock(base::SimpleTestClock* clock) { + DCHECK(clock); StoragePartitionImpl* storage = GetStorage(); BackgroundSyncContextImpl* sync_context = storage->GetBackgroundSyncContext(); - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReply() function so - // the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - SetTestClockOnCoreThread(sync_context, clock); - } else { - base::RunLoop run_loop; - base::PostTaskAndReply( - FROM_HERE, ServiceWorkerContext::GetCoreThreadId(), - base::BindOnce(&BackgroundSyncBaseBrowserTest::SetTestClockOnCoreThread, - base::Unretained(this), base::Unretained(sync_context), - clock), - run_loop.QuitClosure()); - run_loop.Run(); - } + BackgroundSyncManager* background_sync_manager = + sync_context->background_sync_manager(); + background_sync_manager->set_clock(clock); } void BackgroundSyncBaseBrowserTest::ClearStoragePartitionData() {
diff --git a/content/browser/background_sync/background_sync_base_browsertest.h b/content/browser/background_sync/background_sync_base_browsertest.h index e2ca38b2..f9304b71 100644 --- a/content/browser/background_sync/background_sync_base_browsertest.h +++ b/content/browser/background_sync/background_sync_base_browsertest.h
@@ -101,8 +101,6 @@ const GURL& url, base::OnceCallback<void(bool)> callback); StoragePartitionImpl* GetStorage(); - void SetTestClockOnCoreThread(BackgroundSyncContextImpl* sync_context, - base::SimpleTestClock* clock); Shell* shell_ = nullptr; std::unique_ptr<net::EmbeddedTestServer> https_server_;
diff --git a/content/browser/background_sync/background_sync_context_impl.cc b/content/browser/background_sync/background_sync_context_impl.cc index 330616a..6ec6065 100644 --- a/content/browser/background_sync/background_sync_context_impl.cc +++ b/content/browser/background_sync/background_sync_context_impl.cc
@@ -154,22 +154,9 @@ base::OnceCallback<void(base::TimeDelta)> callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReplyWithResult() - // function so the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - base::TimeDelta delta = GetSoonestWakeupDeltaOnCoreThread( - sync_type, last_browser_wakeup_for_periodic_sync); - DidGetSoonestWakeupDelta(std::move(callback), delta); - } else { - base::PostTaskAndReplyWithResult( - FROM_HERE, ServiceWorkerContext::GetCoreThreadId(), - base::BindOnce( - &BackgroundSyncContextImpl::GetSoonestWakeupDeltaOnCoreThread, this, - sync_type, last_browser_wakeup_for_periodic_sync), - base::BindOnce(&BackgroundSyncContextImpl::DidGetSoonestWakeupDelta, - this, std::move(callback))); - } + base::TimeDelta delta = GetSoonestWakeupDeltaOnCoreThread( + sync_type, last_browser_wakeup_for_periodic_sync); + std::move(callback).Run(delta); } void BackgroundSyncContextImpl::RevivePeriodicBackgroundSyncRegistrations( @@ -208,14 +195,6 @@ sync_type, last_browser_wakeup_for_periodic_sync); } -void BackgroundSyncContextImpl::DidGetSoonestWakeupDelta( - base::OnceCallback<void(base::TimeDelta)> callback, - base::TimeDelta soonest_wakeup_delta) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - std::move(callback).Run(soonest_wakeup_delta); -} - void BackgroundSyncContextImpl:: RevivePeriodicBackgroundSyncRegistrationsOnCoreThread(url::Origin origin) { DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId());
diff --git a/content/browser/background_sync/background_sync_context_impl.h b/content/browser/background_sync/background_sync_context_impl.h index 09be152..c1306e59 100644 --- a/content/browser/background_sync/background_sync_context_impl.h +++ b/content/browser/background_sync/background_sync_context_impl.h
@@ -119,9 +119,6 @@ base::TimeDelta GetSoonestWakeupDeltaOnCoreThread( blink::mojom::BackgroundSyncType sync_type, base::Time last_browser_wakeup_for_periodic_sync); - void DidGetSoonestWakeupDelta( - base::OnceCallback<void(base::TimeDelta)> callback, - base::TimeDelta soonest_wakeup_delta); void RevivePeriodicBackgroundSyncRegistrationsOnCoreThread( url::Origin origin);
diff --git a/content/browser/background_sync/background_sync_manager.cc b/content/browser/background_sync/background_sync_manager.cc index b196c9b5..2b33846 100644 --- a/content/browser/background_sync/background_sync_manager.cc +++ b/content/browser/background_sync/background_sync_manager.cc
@@ -714,24 +714,11 @@ return; } - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReplyWithResult() - // function so the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - InitDidGetControllerParameters( - std::move(callback), - GetControllerParameters( - service_worker_context_, - std::make_unique<BackgroundSyncParameters>(*parameters_))); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce( - &GetControllerParameters, service_worker_context_, - std::make_unique<BackgroundSyncParameters>(*parameters_)), - base::BindOnce(&BackgroundSyncManager::InitDidGetControllerParameters, - weak_ptr_factory_.GetWeakPtr(), std::move(callback))); - } + InitDidGetControllerParameters( + std::move(callback), + GetControllerParameters( + service_worker_context_, + std::make_unique<BackgroundSyncParameters>(*parameters_))); } void BackgroundSyncManager::InitDidGetControllerParameters( @@ -904,28 +891,12 @@ return; } - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReplyWithResult() - // function so the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - SyncAndNotificationPermissions permission = - GetBackgroundSyncPermissionOnUIThread( - service_worker_context_, - url::Origin::Create(sw_registration->scope().GetOrigin()), - sync_type); - RegisterDidAskForPermission(sw_registration_id, std::move(options), - std::move(callback), permission); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce( - &GetBackgroundSyncPermissionOnUIThread, service_worker_context_, - url::Origin::Create(sw_registration->scope().GetOrigin()), - sync_type), - base::BindOnce(&BackgroundSyncManager::RegisterDidAskForPermission, - weak_ptr_factory_.GetWeakPtr(), sw_registration_id, - std::move(options), std::move(callback))); - } + SyncAndNotificationPermissions permission = + GetBackgroundSyncPermissionOnUIThread( + service_worker_context_, + url::Origin::Create(sw_registration->scope().GetOrigin()), sync_type); + RegisterDidAskForPermission(sw_registration_id, std::move(options), + std::move(callback), permission); } void BackgroundSyncManager::RegisterDidAskForPermission( @@ -1025,29 +996,13 @@ // schedule time of this registration soon anyway, so considering its // schedule time would cause us to calculate incorrect delay. if (registration.sync_type() == BackgroundSyncType::PERIODIC) { - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReplyWithResult() - // function so the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - base::TimeDelta delay = GetNextEventDelay( - service_worker_context_, registration, - std::make_unique<BackgroundSyncParameters>(*parameters_), - GetSmallestPeriodicSyncEventDelayForOrigin( - origin, registration.options()->tag)); - RegisterDidGetDelay(sw_registration_id, registration, std::move(callback), - delay); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce( - &GetNextEventDelay, service_worker_context_, registration, - std::make_unique<BackgroundSyncParameters>(*parameters_), - GetSmallestPeriodicSyncEventDelayForOrigin( - origin, registration.options()->tag)), - base::BindOnce(&BackgroundSyncManager::RegisterDidGetDelay, - weak_ptr_factory_.GetWeakPtr(), sw_registration_id, - registration, std::move(callback))); - } + base::TimeDelta delay = GetNextEventDelay( + service_worker_context_, registration, + std::make_unique<BackgroundSyncParameters>(*parameters_), + GetSmallestPeriodicSyncEventDelayForOrigin( + origin, registration.options()->tag)); + RegisterDidGetDelay(sw_registration_id, registration, std::move(callback), + delay); return; } @@ -1316,22 +1271,9 @@ registration->set_resolved(); - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReplyWithResult() - // function so the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - ResolveRegistrationDidCreateKeepAlive( - id, CreateBackgroundSyncEventKeepAliveOnUIThread( - service_worker_context_, std::move(*registration_info))); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce(&CreateBackgroundSyncEventKeepAliveOnUIThread, - service_worker_context_, std::move(*registration_info)), - base::BindOnce( - &BackgroundSyncManager::ResolveRegistrationDidCreateKeepAlive, - weak_ptr_factory_.GetWeakPtr(), id)); - } + ResolveRegistrationDidCreateKeepAlive( + id, CreateBackgroundSyncEventKeepAliveOnUIThread( + service_worker_context_, std::move(*registration_info))); } void BackgroundSyncManager::ResolveRegistrationDidCreateKeepAlive( @@ -1852,31 +1794,14 @@ weak_ptr_factory_.GetWeakPtr(), std::move(callback))); for (const auto* registration : to_revive) { - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReplyWithResult() - // function so the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - base::TimeDelta delay = GetNextEventDelay( - service_worker_context_, *registration, - std::make_unique<BackgroundSyncParameters>(*parameters_), - GetSmallestPeriodicSyncEventDelayForOrigin( - origin, registration->options()->tag)); - ReviveDidGetNextEventDelay(service_worker_registration_ids[registration], - *registration, received_new_delays_closure, - delay); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce( - &GetNextEventDelay, service_worker_context_, *registration, - std::make_unique<BackgroundSyncParameters>(*parameters_), - GetSmallestPeriodicSyncEventDelayForOrigin( - origin, registration->options()->tag)), - base::BindOnce(&BackgroundSyncManager::ReviveDidGetNextEventDelay, - weak_ptr_factory_.GetWeakPtr(), - service_worker_registration_ids[registration], - *registration, received_new_delays_closure)); - } + base::TimeDelta delay = GetNextEventDelay( + service_worker_context_, *registration, + std::make_unique<BackgroundSyncParameters>(*parameters_), + GetSmallestPeriodicSyncEventDelayForOrigin( + origin, registration->options()->tag)); + ReviveDidGetNextEventDelay(service_worker_registration_ids[registration], + *registration, received_new_delays_closure, + delay); } } @@ -2251,31 +2176,13 @@ if (registration->sync_type() == BackgroundSyncType::PERIODIC || (!succeeded && registration->num_attempts() < registration->max_attempts())) { - // TODO(crbug.com/824858): Remove the else branch after the feature is - // enabled. Also, try to make a RunOrPostTaskOnThreadAndReplyWithResult() - // function so the if/else isn't needed. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - base::TimeDelta delay = GetNextEventDelay( - service_worker_context_, *registration, - std::make_unique<BackgroundSyncParameters>(*parameters_), - GetSmallestPeriodicSyncEventDelayForOrigin( - origin, registration->options()->tag)); - EventCompleteDidGetDelay(std::move(registration_info), status_code, - origin, std::move(callback), delay); - - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce( - &GetNextEventDelay, service_worker_context_, *registration, - std::make_unique<BackgroundSyncParameters>(*parameters_), - GetSmallestPeriodicSyncEventDelayForOrigin( - origin, registration->options()->tag)), - base::BindOnce(&BackgroundSyncManager::EventCompleteDidGetDelay, - weak_ptr_factory_.GetWeakPtr(), - std::move(registration_info), status_code, origin, - std::move(callback))); - } + base::TimeDelta delay = GetNextEventDelay( + service_worker_context_, *registration, + std::make_unique<BackgroundSyncParameters>(*parameters_), + GetSmallestPeriodicSyncEventDelayForOrigin( + origin, registration->options()->tag)); + EventCompleteDidGetDelay(std::move(registration_info), status_code, origin, + std::move(callback), delay); return; }
diff --git a/content/browser/background_sync/background_sync_network_observer.cc b/content/browser/background_sync/background_sync_network_observer.cc index 74133348..397eba88 100644 --- a/content/browser/background_sync/background_sync_network_observer.cc +++ b/content/browser/background_sync/background_sync_network_observer.cc
@@ -31,15 +31,7 @@ DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); DCHECK(connection_changed_callback_); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - RegisterWithNetworkConnectionTracker(GetNetworkConnectionTracker()); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, base::BindOnce(&GetNetworkConnectionTracker), - base::BindOnce(&BackgroundSyncNetworkObserver:: - RegisterWithNetworkConnectionTracker, - weak_ptr_factory_.GetWeakPtr())); - } + RegisterWithNetworkConnectionTracker(GetNetworkConnectionTracker()); } BackgroundSyncNetworkObserver::~BackgroundSyncNetworkObserver() {
diff --git a/content/browser/browser_interface_binders.cc b/content/browser/browser_interface_binders.cc index 91d49b5..0dee92a 100644 --- a/content/browser/browser_interface_binders.cc +++ b/content/browser/browser_interface_binders.cc
@@ -150,6 +150,10 @@ #include "media/mojo/mojom/remoting.mojom-forward.h" #endif +#if BUILDFLAG(ENABLE_REPORTING) +#include "content/browser/net/reporting_service_proxy.h" +#endif + #if defined(OS_MAC) #include "content/browser/renderer_host/text_input_host_impl.h" #include "third_party/blink/public/mojom/input/text_input_host.mojom.h" @@ -594,6 +598,11 @@ map->Add<blink::mojom::QuotaManagerHost>( base::BindRepeating(&BindQuotaManagerHost, base::Unretained(host))); +#if BUILDFLAG(ENABLE_REPORTING) + map->Add<blink::mojom::ReportingServiceProxy>(base::BindRepeating( + &CreateReportingServiceProxyForFrame, base::Unretained(host))); +#endif + map->Add<blink::mojom::SharedWorkerConnector>( base::BindRepeating(&BindSharedWorkerConnector, base::Unretained(host))); @@ -927,6 +936,10 @@ base::Unretained(host))); map->Add<blink::mojom::CacheStorage>(base::BindRepeating( &DedicatedWorkerHost::BindCacheStorage, base::Unretained(host))); +#if BUILDFLAG(ENABLE_REPORTING) + map->Add<blink::mojom::ReportingServiceProxy>(base::BindRepeating( + &CreateReportingServiceProxyForDedicatedWorker, base::Unretained(host))); +#endif #if !defined(OS_ANDROID) map->Add<blink::mojom::SerialService>(base::BindRepeating( &DedicatedWorkerHost::BindSerialService, base::Unretained(host))); @@ -1005,6 +1018,10 @@ &SharedWorkerHost::CreateQuicTransportConnector, base::Unretained(host))); map->Add<blink::mojom::CacheStorage>(base::BindRepeating( &SharedWorkerHost::BindCacheStorage, base::Unretained(host))); +#if BUILDFLAG(ENABLE_REPORTING) + map->Add<blink::mojom::ReportingServiceProxy>(base::BindRepeating( + &CreateReportingServiceProxyForSharedWorker, base::Unretained(host))); +#endif // render process host binders map->Add<media::mojom::VideoDecodePerfHistory>(BindWorkerReceiver( @@ -1082,6 +1099,10 @@ &ServiceWorkerHost::BindCacheStorage, base::Unretained(host))); map->Add<blink::mojom::BadgeService>( base::BindRepeating(&BindBadgeServiceForServiceWorker, host)); +#if BUILDFLAG(ENABLE_REPORTING) + map->Add<blink::mojom::ReportingServiceProxy>(base::BindRepeating( + &CreateReportingServiceProxyForServiceWorker, base::Unretained(host))); +#endif // render process host binders map->Add<media::mojom::VideoDecodePerfHistory>(BindServiceWorkerReceiver( @@ -1102,24 +1123,12 @@ // static binders // Use a task runner if ServiceWorkerHost lives on the IO thread, as // CreateForWorker() needs to be called on the UI thread. - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - map->Add<blink::mojom::BackgroundFetchService>( - base::BindRepeating(&BackgroundFetchServiceImpl::CreateForWorker)); - map->Add<blink::mojom::ContentIndexService>( - base::BindRepeating(&ContentIndexServiceImpl::CreateForWorker)); - map->Add<blink::mojom::CookieStore>( - base::BindRepeating(&CookieStoreContext::CreateServiceForWorker)); - } else { - map->Add<blink::mojom::BackgroundFetchService>( - base::BindRepeating(&BackgroundFetchServiceImpl::CreateForWorker), - GetUIThreadTaskRunner({})); - map->Add<blink::mojom::ContentIndexService>( - base::BindRepeating(&ContentIndexServiceImpl::CreateForWorker), - GetUIThreadTaskRunner({})); - map->Add<blink::mojom::CookieStore>( - base::BindRepeating(&CookieStoreContext::CreateServiceForWorker), - GetUIThreadTaskRunner({})); - } + map->Add<blink::mojom::BackgroundFetchService>( + base::BindRepeating(&BackgroundFetchServiceImpl::CreateForWorker)); + map->Add<blink::mojom::ContentIndexService>( + base::BindRepeating(&ContentIndexServiceImpl::CreateForWorker)); + map->Add<blink::mojom::CookieStore>( + base::BindRepeating(&CookieStoreContext::CreateServiceForWorker)); // render process host binders taking an origin map->Add<payments::mojom::PaymentManager>(BindServiceWorkerReceiverForOrigin(
diff --git a/content/browser/devtools/service_worker_devtools_agent_host.cc b/content/browser/devtools/service_worker_devtools_agent_host.cc index 3289fd0..da581c7 100644 --- a/content/browser/devtools/service_worker_devtools_agent_host.cc +++ b/content/browser/devtools/service_worker_devtools_agent_host.cc
@@ -47,18 +47,6 @@ version->SetDevToolsAttached(attached); } -void UpdateLoaderFactoriesOnCoreThread( - scoped_refptr<ServiceWorkerContextWrapper> context, - int64_t version_id, - std::unique_ptr<blink::PendingURLLoaderFactoryBundle> script_bundle, - std::unique_ptr<blink::PendingURLLoaderFactoryBundle> subresource_bundle) { - auto* version = context->GetLiveVersion(version_id); - if (!version) - return; - version->embedded_worker()->UpdateLoaderFactories( - std::move(script_bundle), std::move(subresource_bundle)); -} - } // namespace ServiceWorkerDevToolsAgentHost::ServiceWorkerDevToolsAgentHost( @@ -241,19 +229,13 @@ std::move(coep_reporter_for_subresource_loader), ContentBrowserClient::URLLoaderFactoryType::kServiceWorkerSubResource); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - UpdateLoaderFactoriesOnCoreThread(context_wrapper_, version_id_, - std::move(script_bundle), - std::move(subresource_bundle)); - std::move(callback).Run(); - } else { - GetIOThreadTaskRunner({})->PostTaskAndReply( - FROM_HERE, - base::BindOnce(&UpdateLoaderFactoriesOnCoreThread, context_wrapper_, - version_id_, std::move(script_bundle), - std::move(subresource_bundle)), - std::move(callback)); - } + auto* version = context_wrapper_->GetLiveVersion(version_id_); + if (!version) + return; + version->embedded_worker()->UpdateLoaderFactories( + std::move(script_bundle), std::move(subresource_bundle)); + + std::move(callback).Run(); } DevToolsAgentHostImpl::NetworkLoaderFactoryParamsAndInfo
diff --git a/content/browser/net/reporting_service_proxy.cc b/content/browser/net/reporting_service_proxy.cc index 4c7efdf2..55d5b2b 100644 --- a/content/browser/net/reporting_service_proxy.cc +++ b/content/browser/net/reporting_service_proxy.cc
@@ -10,12 +10,17 @@ #include "base/memory/ref_counted.h" #include "base/values.h" +#include "content/browser/service_worker/service_worker_host.h" +#include "content/browser/worker_host/dedicated_worker_host.h" +#include "content/browser/worker_host/shared_worker_host.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" +#include "net/base/network_isolation_key.h" #include "net/reporting/reporting_report.h" #include "net/reporting/reporting_service.h" #include "services/network/public/mojom/network_context.mojom.h" @@ -28,8 +33,15 @@ class ReportingServiceProxyImpl : public blink::mojom::ReportingServiceProxy { public: - explicit ReportingServiceProxyImpl(int render_process_id) - : render_process_id_(render_process_id) {} + ReportingServiceProxyImpl( + int render_process_id, + const net::NetworkIsolationKey& network_isolation_key) + : render_process_id_(render_process_id), + network_isolation_key_(network_isolation_key) {} + + ReportingServiceProxyImpl(const ReportingServiceProxyImpl&) = delete; + ReportingServiceProxyImpl& operator=(const ReportingServiceProxyImpl&) = + delete; // blink::mojom::ReportingServiceProxy: @@ -152,6 +164,8 @@ QueueReport(url, group, "document-policy-violation", std::move(body)); } + int render_process_id() const { return render_process_id_; } + private: void QueueReport(const GURL& url, const std::string& group, @@ -161,27 +175,57 @@ if (!rph) return; - // TODO(https://crbug.com/993805): Pass in the appropriate - // NetworkIsolationKey. rph->GetStoragePartition()->GetNetworkContext()->QueueReport( - type, group, url, net::NetworkIsolationKey::Todo(), + type, group, url, network_isolation_key_, /*user_agent=*/base::nullopt, base::Value::FromUniquePtrValue(std::move(body))); } - int render_process_id_; + const int render_process_id_; + const net::NetworkIsolationKey network_isolation_key_; }; } // namespace -// static -void CreateReportingServiceProxy( - int render_process_id, +void CreateReportingServiceProxyForFrame( + RenderFrameHost* render_frame_host, mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + mojo::MakeSelfOwnedReceiver(std::make_unique<ReportingServiceProxyImpl>( + render_frame_host->GetProcess()->GetID(), + render_frame_host->GetNetworkIsolationKey()), + std::move(receiver)); +} +void CreateReportingServiceProxyForServiceWorker( + ServiceWorkerHost* service_worker_host, + mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); mojo::MakeSelfOwnedReceiver( - std::make_unique<ReportingServiceProxyImpl>(render_process_id), + std::make_unique<ReportingServiceProxyImpl>( + service_worker_host->worker_process_id(), + service_worker_host->GetNetworkIsolationKey()), + std::move(receiver)); +} + +void CreateReportingServiceProxyForSharedWorker( + SharedWorkerHost* shared_worker_host, + mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + mojo::MakeSelfOwnedReceiver(std::make_unique<ReportingServiceProxyImpl>( + shared_worker_host->GetProcessHost()->GetID(), + shared_worker_host->GetNetworkIsolationKey()), + std::move(receiver)); +} + +void CreateReportingServiceProxyForDedicatedWorker( + DedicatedWorkerHost* dedicated_worker_host, + mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + mojo::MakeSelfOwnedReceiver( + std::make_unique<ReportingServiceProxyImpl>( + dedicated_worker_host->GetProcessHost()->GetID(), + dedicated_worker_host->GetNetworkIsolationKey()), std::move(receiver)); }
diff --git a/content/browser/net/reporting_service_proxy.h b/content/browser/net/reporting_service_proxy.h index 489f553..324b77c 100644 --- a/content/browser/net/reporting_service_proxy.h +++ b/content/browser/net/reporting_service_proxy.h
@@ -10,10 +10,24 @@ namespace content { -// Binds a mojom::ReportingServiceProxy to |request| that queues reports using -// |render_process_id|'s NetworkContext. This must be called on the UI thread. -void CreateReportingServiceProxy( - int render_process_id, +class DedicatedWorkerHost; +class RenderFrameHost; +class ServiceWorkerHost; +class SharedWorkerHost; + +// These methods method bind a mojom::ReportingServiceProxy for the specified +// object type. They must be called on the UI thread. +void CreateReportingServiceProxyForFrame( + RenderFrameHost* render_frame_host, + mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver); +void CreateReportingServiceProxyForServiceWorker( + ServiceWorkerHost* service_worker_host, + mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver); +void CreateReportingServiceProxyForSharedWorker( + SharedWorkerHost* shared_worker_host, + mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver); +void CreateReportingServiceProxyForDedicatedWorker( + DedicatedWorkerHost* dedicated_worker_host, mojo::PendingReceiver<blink::mojom::ReportingServiceProxy> receiver); } // namespace content
diff --git a/content/browser/notifications/platform_notification_service_proxy.cc b/content/browser/notifications/platform_notification_service_proxy.cc index fe806d8..fa63220 100644 --- a/content/browser/notifications/platform_notification_service_proxy.cc +++ b/content/browser/notifications/platform_notification_service_proxy.cc
@@ -67,19 +67,9 @@ if (status == blink::ServiceWorkerStatusCode::kOk && registration->scope().GetOrigin() == data.origin) { - task = base::BindOnce( - &PlatformNotificationServiceProxy::DoDisplayNotification, AsWeakPtr(), - data, registration->scope(), std::move(callback)); + DoDisplayNotification(data, registration->scope(), std::move(callback)); } else { - task = base::BindOnce(std::move(callback), /* success= */ false, - /* notification_id= */ ""); - } - - if (ServiceWorkerContextWrapper::IsServiceWorkerOnUIEnabled()) { - std::move(task).Run(); - } else { - GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE}) - ->PostTask(FROM_HERE, std::move(task)); + std::move(callback).Run(/* success= */ false, /* notification_id= */ ""); } }
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index e248136..03895b3 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -7754,8 +7754,8 @@ worker_process_id, /*creator_render_frame_host_id=*/GetGlobalFrameRoutingId(), /*ancestor_render_frame_host_id=*/GetGlobalFrameRoutingId(), - last_committed_origin_, cross_origin_embedder_policy_, - std::move(coep_reporter)), + last_committed_origin_, GetNetworkIsolationKey(), + cross_origin_embedder_policy_, std::move(coep_reporter)), std::move(receiver)); }
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 9147b8637..4fe62d5 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -267,10 +267,6 @@ #include "ppapi/shared_impl/ppapi_switches.h" // nogncheck #endif -#if BUILDFLAG(ENABLE_REPORTING) -#include "content/browser/net/reporting_service_proxy.h" -#endif - #if BUILDFLAG(USE_MINIKIN_HYPHENATION) #include "content/browser/hyphenation/hyphenation_impl.h" #endif @@ -2311,20 +2307,10 @@ registry->AddInterface( base::BindRepeating(&device::GamepadHapticsManager::Create)); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - AddUIThreadInterface( - registry.get(), - base::BindRepeating(&RenderProcessHostImpl::BindPushMessagingManager, - weak_factory_.GetWeakPtr())); - } else { - // Note, the base::Unretained() is safe because the target object has an IO - // thread deleter and the callback is also targeting the IO thread. When - // the RPHI is destroyed it also triggers the destruction of the registry - // on the IO thread. - registry->AddInterface( - base::BindRepeating(&PushMessagingManager::AddPushMessagingReceiver, - base::Unretained(push_messaging_manager_.get()))); - } + AddUIThreadInterface( + registry.get(), + base::BindRepeating(&RenderProcessHostImpl::BindPushMessagingManager, + weak_factory_.GetWeakPtr())); file_system_manager_impl_.reset(new FileSystemManagerImpl( GetID(), storage_partition_impl_->GetFileSystemContext(), @@ -2387,12 +2373,6 @@ base::BindRepeating(&RenderProcessHostImpl::CreateCodeCacheHost, weak_factory_.GetWeakPtr())); -#if BUILDFLAG(ENABLE_REPORTING) - AddUIThreadInterface( - registry.get(), - base::BindRepeating(&CreateReportingServiceProxy, GetID())); -#endif // BUILDFLAG(ENABLE_REPORTING) - AddUIThreadInterface( registry.get(), base::BindRepeating(&RenderProcessHostImpl::BindP2PSocketManager,
diff --git a/content/browser/service_worker/embedded_worker_instance.cc b/content/browser/service_worker/embedded_worker_instance.cc index aeabb62..b7d1f5c 100644 --- a/content/browser/service_worker/embedded_worker_instance.cc +++ b/content/browser/service_worker/embedded_worker_instance.cc
@@ -68,17 +68,6 @@ "Service Worker termination by a timeout timer was canceled because " "DevTools is attached."; -void NotifyWorkerReadyForInspectionOnUI( - int worker_process_id, - int worker_route_id, - mojo::PendingRemote<blink::mojom::DevToolsAgent> agent_remote, - mojo::PendingReceiver<blink::mojom::DevToolsAgentHost> host_receiver) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - ServiceWorkerDevToolsManager::GetInstance()->WorkerReadyForInspection( - worker_process_id, worker_route_id, std::move(agent_remote), - std::move(host_receiver)); -} - void NotifyUpdateCrossOriginEmbedderPolicyOnUI( int worker_process_id, int worker_route_id, @@ -91,19 +80,6 @@ std::move(cross_origin_embedder_policy), std::move(coep_reporter)); } -void NotifyWorkerStoppedOnUI(int worker_process_id, int worker_route_id) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - ServiceWorkerDevToolsManager::GetInstance()->WorkerStopped(worker_process_id, - worker_route_id); -} - -void NotifyWorkerVersionInstalledOnUI(int worker_process_id, - int worker_route_id) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - ServiceWorkerDevToolsManager::GetInstance()->WorkerVersionInstalled( - worker_process_id, worker_route_id); -} - void NotifyWorkerVersionDoomedOnUI( int worker_process_id, int worker_route_id, @@ -232,8 +208,6 @@ SetupProcessCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::Optional<base::TimeDelta> thread_hop_time; - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) - thread_hop_time = base::Time::Now() - io_post_time.value(); auto process_info = std::make_unique<ServiceWorkerProcessManager::AllocatedProcessInfo>(); @@ -247,8 +221,6 @@ if (!process_manager) { base::Optional<base::Time> ui_post_time; - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) - ui_post_time = base::Time::Now(); ServiceWorkerContextWrapper::RunOrPostTaskOnCoreThread( FROM_HERE, base::BindOnce(std::move(callback), @@ -270,8 +242,6 @@ can_use_existing_process, process_info.get()); if (status != blink::ServiceWorkerStatusCode::kOk) { base::Optional<base::Time> ui_post_time; - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) - ui_post_time = base::Time::Now(); ServiceWorkerContextWrapper::RunOrPostTaskOnCoreThread( FROM_HERE, @@ -382,8 +352,6 @@ // Continue to OnSetupCompleted on the core thread. base::Optional<base::Time> ui_post_time; - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) - ui_post_time = base::Time::Now(); RunOrPostTaskOnThread( FROM_HERE, ServiceWorkerContext::GetCoreThreadId(), base::BindOnce( @@ -456,42 +424,24 @@ ui_task_runner_(GetUIThreadTaskRunner({})) {} ~DevToolsProxy() { - DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - NotifyWorkerStoppedOnUI(process_id_, agent_route_id_); - } else { - ui_task_runner_->PostTask( - FROM_HERE, base::BindOnce(NotifyWorkerStoppedOnUI, process_id_, - agent_route_id_)); - } + DCHECK_CURRENTLY_ON(BrowserThread::UI); + ServiceWorkerDevToolsManager::GetInstance()->WorkerStopped(process_id_, + agent_route_id_); } void NotifyWorkerReadyForInspection( mojo::PendingRemote<blink::mojom::DevToolsAgent> agent_remote, mojo::PendingReceiver<blink::mojom::DevToolsAgentHost> host_receiver) { - DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - NotifyWorkerReadyForInspectionOnUI(process_id_, agent_route_id_, - std::move(agent_remote), - std::move(host_receiver)); - } else { - ui_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(NotifyWorkerReadyForInspectionOnUI, process_id_, - agent_route_id_, std::move(agent_remote), - std::move(host_receiver))); - } + DCHECK_CURRENTLY_ON(BrowserThread::UI); + ServiceWorkerDevToolsManager::GetInstance()->WorkerReadyForInspection( + process_id_, agent_route_id_, std::move(agent_remote), + std::move(host_receiver)); } void NotifyWorkerVersionInstalled() { - DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - NotifyWorkerVersionInstalledOnUI(process_id_, agent_route_id_); - } else { - ui_task_runner_->PostTask(FROM_HERE, - base::BindOnce(NotifyWorkerVersionInstalledOnUI, - process_id_, agent_route_id_)); - } + DCHECK_CURRENTLY_ON(BrowserThread::UI); + ServiceWorkerDevToolsManager::GetInstance()->WorkerVersionInstalled( + process_id_, agent_route_id_); } bool ShouldNotifyWorkerStopIgnored() const { @@ -552,14 +502,7 @@ ~WorkerProcessHandle() { DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - process_manager_->ReleaseWorkerProcess(embedded_worker_id_); - } else { - ui_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&ServiceWorkerProcessManager::ReleaseWorkerProcess, - process_manager_, embedded_worker_id_)); - } + process_manager_->ReleaseWorkerProcess(embedded_worker_id_); } int process_id() const { return process_id_; } @@ -688,26 +631,13 @@ // Perform process allocation and setup on the UI thread. We will continue // on the core thread in StartTask::OnSetupCompleted(). - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - SetupOnUIThread( - instance_->embedded_worker_id(), process_manager, - can_use_existing_process, cross_origin_embedder_policy, - std::move(params), std::move(receiver_), - base::WrapRefCounted(context->wrapper()), base::nullopt, - base::BindOnce(&StartTask::OnSetupCompleted, - weak_factory_.GetWeakPtr(), process_manager)); - } else { - instance_->ui_task_runner_->PostTask( - FROM_HERE, - base::BindOnce( - &SetupOnUIThread, instance_->embedded_worker_id(), - process_manager, can_use_existing_process, - cross_origin_embedder_policy, std::move(params), - std::move(receiver_), base::WrapRefCounted(context->wrapper()), - base::make_optional<base::Time>(base::Time::Now()), - base::BindOnce(&StartTask::OnSetupCompleted, - weak_factory_.GetWeakPtr(), process_manager))); - } + SetupOnUIThread( + instance_->embedded_worker_id(), process_manager, + can_use_existing_process, cross_origin_embedder_policy, + std::move(params), std::move(receiver_), + base::WrapRefCounted(context->wrapper()), base::nullopt, + base::BindOnce(&StartTask::OnSetupCompleted, weak_factory_.GetWeakPtr(), + process_manager)); } bool is_installed() const { return is_installed_; } @@ -737,10 +667,6 @@ std::move(reporting_observer_receiver)); } - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) - thread_hop_time_ = - thread_hop_time.value() + (base::Time::Now() - ui_post_time.value()); - std::unique_ptr<WorkerProcessHandle> process_handle; if (status == blink::ServiceWorkerStatusCode::kOk) { // If we allocated a process, WorkerProcessHandle has to be created before @@ -1062,18 +988,9 @@ } void EmbeddedWorkerInstance::OnWorkerVersionDoomed() { - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - NotifyWorkerVersionDoomedOnUI(process_id(), - worker_devtools_agent_route_id(), - base::WrapRefCounted(context_->wrapper()), - owner_version_->version_id()); - } else { - ui_task_runner_->PostTask( - FROM_HERE, base::BindOnce(NotifyWorkerVersionDoomedOnUI, process_id(), - worker_devtools_agent_route_id(), - base::WrapRefCounted(context_->wrapper()), - owner_version_->version_id())); - } + NotifyWorkerVersionDoomedOnUI(process_id(), worker_devtools_agent_route_id(), + base::WrapRefCounted(context_->wrapper()), + owner_version_->version_id()); } void EmbeddedWorkerInstance::OnScriptEvaluationStart() { @@ -1439,13 +1356,7 @@ foreground_notified_ = true; - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - NotifyForegroundServiceWorkerOnUIThread(true /* added */, process_id()); - } else { - ui_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&NotifyForegroundServiceWorkerOnUIThread, - true /* added */, process_id())); - } + NotifyForegroundServiceWorkerOnUIThread(true /* added */, process_id()); } void EmbeddedWorkerInstance::NotifyForegroundServiceWorkerRemoved() { @@ -1456,13 +1367,7 @@ foreground_notified_ = false; - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - NotifyForegroundServiceWorkerOnUIThread(false /* added */, process_id()); - } else { - ui_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&NotifyForegroundServiceWorkerOnUIThread, - false /* added */, process_id())); - } + NotifyForegroundServiceWorkerOnUIThread(false /* added */, process_id()); } mojo::PendingRemote<network::mojom::URLLoaderFactory>
diff --git a/content/browser/service_worker/embedded_worker_instance_unittest.cc b/content/browser/service_worker/embedded_worker_instance_unittest.cc index 74873f0a..9169024 100644 --- a/content/browser/service_worker/embedded_worker_instance_unittest.cc +++ b/content/browser/service_worker/embedded_worker_instance_unittest.cc
@@ -336,42 +336,6 @@ EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status()); } -TEST_F(EmbeddedWorkerInstanceTest, DetachDuringProcessAllocation) { - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - // This test calls Start() then Detach() to test detaching during process - // allocation. But when ServiceWorkerOnUI is enabled, Start() synchronously - // reaches the SetupOnUIThread() step, so process allocation occurs before - // Detach() is called, so this test doesn't make sense. - return; - } - - const GURL scope("http://example.com/"); - const GURL url("http://example.com/worker.js"); - - RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url); - auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get()); - worker->AddObserver(this); - - // Run the start worker sequence and detach during process allocation. - base::Optional<blink::ServiceWorkerStatusCode> status; - blink::mojom::EmbeddedWorkerStartParamsPtr params = - CreateStartParams(pair.second); - worker->Start(std::move(params), ReceiveStatus(&status, base::DoNothing())); - worker->Detach(); - base::RunLoop().RunUntilIdle(); - // The start callback should not be aborted by detach (see a comment on the - // dtor of EmbeddedWorkerInstance::StartTask). - EXPECT_FALSE(status); - - EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status()); - EXPECT_EQ(ChildProcessHost::kInvalidUniqueID, worker->process_id()); - - // "PROCESS_ALLOCATED" event should not be recorded. - ASSERT_EQ(1u, events_.size()); - EXPECT_EQ(DETACHED, events_[0].type); - EXPECT_EQ(EmbeddedWorkerStatus::STARTING, events_[0].status.value()); -} - TEST_F(EmbeddedWorkerInstanceTest, DetachAfterSendingStartWorkerMessage) { const GURL scope("http://example.com/"); const GURL url("http://example.com/worker.js"); @@ -401,55 +365,6 @@ EXPECT_EQ(EmbeddedWorkerStatus::STARTING, events_[0].status.value()); } -TEST_F(EmbeddedWorkerInstanceTest, StopDuringProcessAllocation) { - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - // This test calls Start() then Stop() to test stopping during process - // allocation. But when ServiceWorkerOnUI is enabled, Start() synchronously - // reaches the SetupOnUIThread() step, so process allocation occurs before - // Stop() is called, so this test doesn't make sense. - return; - } - - const GURL scope("http://example.com/"); - const GURL url("http://example.com/worker.js"); - - RegistrationAndVersionPair pair = PrepareRegistrationAndVersion(scope, url); - auto worker = std::make_unique<EmbeddedWorkerInstance>(pair.second.get()); - worker->AddObserver(this); - - // Stop the start worker sequence before a process is allocated. - base::Optional<blink::ServiceWorkerStatusCode> status; - - worker->Start(CreateStartParams(pair.second), - ReceiveStatus(&status, base::DoNothing())); - worker->Stop(); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(EmbeddedWorkerStatus::STOPPED, worker->status()); - EXPECT_EQ(ChildProcessHost::kInvalidUniqueID, worker->process_id()); - - // The start callback should not be aborted by stop (see a comment on the dtor - // of EmbeddedWorkerInstance::StartTask). - EXPECT_FALSE(status); - - // "PROCESS_ALLOCATED" event should not be recorded. - ASSERT_EQ(1u, events_.size()); - EXPECT_EQ(STOPPED, events_[0].type); - EXPECT_EQ(EmbeddedWorkerStatus::STARTING, events_[0].status.value()); - events_.clear(); - - // Restart the worker. - StartWorker(worker.get(), CreateStartParams(pair.second)); - - ASSERT_EQ(3u, events_.size()); - EXPECT_EQ(PROCESS_ALLOCATED, events_[0].type); - EXPECT_EQ(START_WORKER_MESSAGE_SENT, events_[1].type); - EXPECT_EQ(STARTED, events_[2].type); - - // Tear down the worker. - worker->Stop(); -} - TEST_F(EmbeddedWorkerInstanceTest, StopAfterSendingStartWorkerMessage) { const GURL scope("http://example.com/"); const GURL url("http://example.com/worker.js");
diff --git a/content/browser/service_worker/service_worker_browsertest.cc b/content/browser/service_worker/service_worker_browsertest.cc index 26f761e..2d16df1 100644 --- a/content/browser/service_worker/service_worker_browsertest.cc +++ b/content/browser/service_worker/service_worker_browsertest.cc
@@ -987,9 +987,6 @@ DispatchFetchEventToStoppedWorkerSynchronously) { // Setup the server so that the test doesn't crash when tearing down. StartServerAndNavigateToSetup(); - // This test is meaningful only when ServiceWorkerOnUI is enabled. - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) - return; WorkerRunningStatusObserver observer(public_context()); EXPECT_TRUE(NavigateToURL(shell(), @@ -1060,9 +1057,6 @@ DispatchFetchEventToBrokenWorker) { // Setup the server so that the test doesn't crash when tearing down. StartServerAndNavigateToSetup(); - // This test is meaningful only when ServiceWorkerOnUI is enabled. - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) - return; WorkerRunningStatusObserver observer(public_context()); EXPECT_TRUE(NavigateToURL(shell(),
diff --git a/content/browser/service_worker/service_worker_client_utils.cc b/content/browser/service_worker/service_worker_client_utils.cc index fb4afb8..e6a4948 100644 --- a/content/browser/service_worker/service_worker_client_utils.cc +++ b/content/browser/service_worker/service_worker_client_utils.cc
@@ -525,23 +525,10 @@ CHECK_EQ(container_host->url().GetOrigin(), sane_origin); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfoOnUI( - container_host->process_id(), container_host->frame_id(), - container_host->create_time(), container_host->client_uuid()); - std::move(callback).Run(blink::ServiceWorkerStatusCode::kOk, - std::move(info)); - - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce(&GetWindowClientInfoOnUI, container_host->process_id(), - container_host->frame_id(), - container_host->create_time(), - container_host->client_uuid()), - base::BindOnce(std::move(callback), - blink::ServiceWorkerStatusCode::kOk)); - } + blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfoOnUI( + container_host->process_id(), container_host->frame_id(), + container_host->create_time(), container_host->client_uuid()); + std::move(callback).Run(blink::ServiceWorkerStatusCode::kOk, std::move(info)); } } // namespace @@ -551,20 +538,10 @@ DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); DCHECK(container_host->IsContainerForWindowClient()); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - blink::mojom::ServiceWorkerClientInfoPtr info = - FocusOnUI(container_host->process_id(), container_host->frame_id(), - container_host->create_time(), container_host->client_uuid()); - std::move(callback).Run(std::move(info)); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce(&FocusOnUI, container_host->process_id(), - container_host->frame_id(), - container_host->create_time(), - container_host->client_uuid()), - std::move(callback)); - } + blink::mojom::ServiceWorkerClientInfoPtr info = + FocusOnUI(container_host->process_id(), container_host->frame_id(), + container_host->create_time(), container_host->client_uuid()); + std::move(callback).Run(std::move(info)); } void OpenWindow(const GURL& url, @@ -608,21 +585,11 @@ blink::mojom::ServiceWorkerClientType host_client_type = container_host->GetClientType(); if (host_client_type == blink::mojom::ServiceWorkerClientType::kWindow) { - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfoOnUI( - container_host->process_id(), container_host->frame_id(), - container_host->create_time(), container_host->client_uuid()); - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), std::move(info))); - return; - } - base::PostTaskAndReplyWithResult( - FROM_HERE, BrowserThread::UI, - base::BindOnce(&GetWindowClientInfoOnUI, container_host->process_id(), - container_host->frame_id(), - container_host->create_time(), - container_host->client_uuid()), - std::move(callback)); + blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfoOnUI( + container_host->process_id(), container_host->frame_id(), + container_host->create_time(), container_host->client_uuid()); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), std::move(info))); return; }
diff --git a/content/browser/service_worker/service_worker_container_host_unittest.cc b/content/browser/service_worker/service_worker_container_host_unittest.cc index 7113927..003f153f 100644 --- a/content/browser/service_worker/service_worker_container_host_unittest.cc +++ b/content/browser/service_worker/service_worker_container_host_unittest.cc
@@ -1178,7 +1178,6 @@ TEST_F(ServiceWorkerContainerHostTestWithBackForwardCache, SkipBackForwardCachedServiceWorker) { ASSERT_TRUE(IsBackForwardCacheEnabled()); - ASSERT_TRUE(ServiceWorkerContext::IsServiceWorkerOnUIEnabled()); TestBackForwardCachedClientsAreNotExposed( GURL("https://www.example.com/sw.js"));
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index 29e0b45fa..7b088cf 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -383,17 +383,9 @@ container_host_iterator->Advance(); } - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - bool result = FrameListContainsMainFrameOnUI(std::move(render_frames)); - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), result)); - } else { - GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( - FROM_HERE, - base::BindOnce(&FrameListContainsMainFrameOnUI, - std::move(render_frames)), - std::move(callback)); - } + bool result = FrameListContainsMainFrameOnUI(std::move(render_frames)); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), result)); } base::WeakPtr<ServiceWorkerContainerHost>
diff --git a/content/browser/service_worker/service_worker_context_wrapper.cc b/content/browser/service_worker/service_worker_context_wrapper.cc index f26042ce..ea1a4a31 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.cc +++ b/content/browser/service_worker/service_worker_context_wrapper.cc
@@ -311,13 +311,8 @@ } // static -bool ServiceWorkerContext::IsServiceWorkerOnUIEnabled() { - return true; -} - -// static BrowserThread::ID ServiceWorkerContext::GetCoreThreadId() { - return IsServiceWorkerOnUIEnabled() ? BrowserThread::UI : BrowserThread::IO; + return BrowserThread::UI; } void ServiceWorkerContextWrapper::OnRegistrationCompleted( @@ -1967,15 +1962,10 @@ // Set up a Mojo connection to the network loader factory if it's not been // created yet. if (pending_receiver) { - if (IsServiceWorkerOnUIEnabled()) { - DCHECK(storage_partition()); - scoped_refptr<network::SharedURLLoaderFactory> network_factory = - storage_partition_->GetURLLoaderFactoryForBrowserProcess(); - network_factory->Clone(std::move(pending_receiver)); - } else { - context()->loader_factory_getter()->CloneNetworkFactory( - std::move(pending_receiver)); - } + DCHECK(storage_partition()); + scoped_refptr<network::SharedURLLoaderFactory> network_factory = + storage_partition_->GetURLLoaderFactoryForBrowserProcess(); + network_factory->Clone(std::move(pending_receiver)); } // Clone context()->loader_factory_bundle_for_update_check() and set up the
diff --git a/content/browser/service_worker/service_worker_fetch_dispatcher.cc b/content/browser/service_worker/service_worker_fetch_dispatcher.cc index d3f73bac..e2a0c89e 100644 --- a/content/browser/service_worker/service_worker_fetch_dispatcher.cc +++ b/content/browser/service_worker/service_worker_fetch_dispatcher.cc
@@ -538,8 +538,7 @@ base::BindOnce(&ServiceWorkerFetchDispatcher::DidStartWorker, weak_factory_.GetWeakPtr())); - if (ServiceWorkerContext::IsServiceWorkerOnUIEnabled() && - version_->is_endpoint_ready()) { + if (version_->is_endpoint_ready()) { // For an active service worker, the endpoint becomes ready synchronously // with StartWorker(). In that case, we can dispatch FetchEvent immediately. DispatchFetchEvent();
diff --git a/content/browser/service_worker/service_worker_host.cc b/content/browser/service_worker/service_worker_host.cc index 664b30d5..a487d57c 100644 --- a/content/browser/service_worker/service_worker_host.cc +++ b/content/browser/service_worker/service_worker_host.cc
@@ -32,16 +32,17 @@ void CreateQuicTransportConnectorImpl( int process_id, const url::Origin& origin, + const net::NetworkIsolationKey& network_isolation_key, mojo::PendingReceiver<blink::mojom::QuicTransportConnector> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI); auto* process = RenderProcessHost::FromID(process_id); if (!process) return; - mojo::MakeSelfOwnedReceiver(std::make_unique<QuicTransportConnectorImpl>( - process_id, /*frame=*/nullptr, origin, - net::NetworkIsolationKey(origin, origin)), - std::move(receiver)); + mojo::MakeSelfOwnedReceiver( + std::make_unique<QuicTransportConnectorImpl>( + process_id, /*frame=*/nullptr, origin, network_isolation_key), + std::move(receiver)); } } // anonymous namespace @@ -94,7 +95,8 @@ RunOrPostTaskOnThread( FROM_HERE, BrowserThread::UI, base::BindOnce(&CreateQuicTransportConnectorImpl, worker_process_id_, - version_->origin(), std::move(receiver))); + version_->origin(), GetNetworkIsolationKey(), + std::move(receiver))); } void ServiceWorkerHost::BindCacheStorage( @@ -105,6 +107,14 @@ version_->embedded_worker()->BindCacheStorage(std::move(receiver)); } +net::NetworkIsolationKey ServiceWorkerHost::GetNetworkIsolationKey() const { + // TODO(https://crbug.com/1147281): This is the NetworkIsolationKey of a + // top-level browsing context, which shouldn't be use for ServiceWorkers used + // in iframes. + return net::NetworkIsolationKey::ToDoUseTopFrameOriginAsWell( + version_->origin()); +} + base::WeakPtr<ServiceWorkerHost> ServiceWorkerHost::GetWeakPtr() { DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); return weak_factory_.GetWeakPtr();
diff --git a/content/browser/service_worker/service_worker_host.h b/content/browser/service_worker/service_worker_host.h index 166a9b0..6620981 100644 --- a/content/browser/service_worker/service_worker_host.h +++ b/content/browser/service_worker/service_worker_host.h
@@ -22,6 +22,7 @@ #include "mojo/public/cpp/bindings/pending_associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "net/base/network_isolation_key.h" #include "services/network/public/mojom/fetch_api.mojom.h" #include "services/network/public/mojom/network_context.mojom.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" @@ -72,6 +73,8 @@ return container_host_.get(); } + net::NetworkIsolationKey GetNetworkIsolationKey() const; + base::WeakPtr<ServiceWorkerHost> GetWeakPtr(); void ReportNoBinderForInterface(const std::string& error);
diff --git a/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc b/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc index db83af4..4ae606fb 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc +++ b/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc
@@ -309,18 +309,6 @@ bool initialize_container_host_only = false; LoaderCallback original_callback; - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled() && - !handle_->context_wrapper()->MaybeHasRegistrationForOrigin( - url::Origin::Create(tentative_resource_request.url))) { - // We have no registrations, so it's safe to continue the request now - // without blocking on the IO thread. Give a dummy callback to the - // IO thread interceptor, and we'll run the original callback immediately - // after starting it. - original_callback = std::move(loader_callback); - loader_callback = - base::BindOnce([](scoped_refptr<network::SharedURLLoaderFactory>) {}); - initialize_container_host_only = true; - } // Start the inner interceptor on the core thread. It will call back to // LoaderCallbackWrapper() on the UI thread.
diff --git a/content/browser/service_worker/service_worker_metrics.cc b/content/browser/service_worker/service_worker_metrics.cc index 7285414..bc69de06 100644 --- a/content/browser/service_worker/service_worker_metrics.cc +++ b/content/browser/service_worker/service_worker_metrics.cc
@@ -444,16 +444,6 @@ void ServiceWorkerMetrics::RecordStartWorkerTiming(const StartTimes& times, StartSituation situation) { - if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - // This is in-process timing, so process consistency doesn't matter. - constexpr base::TimeDelta kMinTime = base::TimeDelta::FromMicroseconds(1); - constexpr base::TimeDelta kMaxTime = base::TimeDelta::FromMilliseconds(100); - constexpr int kBuckets = 50; - UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES( - "ServiceWorker.StartTiming.BrowserThreadHopTime", times.thread_hop_time, - kMinTime, kMaxTime, kBuckets); - } - // Bail if the timings across processes weren't consistent. if (!base::TimeTicks::IsHighResolution() || !base::TimeTicks::IsConsistentAcrossProcesses()) {
diff --git a/content/browser/worker_host/dedicated_worker_host.cc b/content/browser/worker_host/dedicated_worker_host.cc index eb09cf9..a4f72e1 100644 --- a/content/browser/worker_host/dedicated_worker_host.cc +++ b/content/browser/worker_host/dedicated_worker_host.cc
@@ -46,6 +46,7 @@ base::Optional<GlobalFrameRoutingId> creator_render_frame_host_id, GlobalFrameRoutingId ancestor_render_frame_host_id, const url::Origin& creator_origin, + const net::NetworkIsolationKey& network_isolation_key, const network::CrossOriginEmbedderPolicy& cross_origin_embedder_policy, mojo::PendingRemote<network::mojom::CrossOriginEmbedderPolicyReporter> coep_reporter) @@ -58,6 +59,7 @@ // TODO(https://crbug.com/1058759): Calculate the worker origin based on // the worker script URL. worker_origin_(creator_origin), + network_isolation_key_(network_isolation_key), cross_origin_embedder_policy_(cross_origin_embedder_policy), coep_reporter_(std::move(coep_reporter)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -391,18 +393,10 @@ void DedicatedWorkerHost::CreateQuicTransportConnector( mojo::PendingReceiver<blink::mojom::QuicTransportConnector> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - RenderFrameHostImpl* ancestor_render_frame_host = - RenderFrameHostImpl::FromID(ancestor_render_frame_host_id_); - if (!ancestor_render_frame_host) { - // The ancestor frame may have already been closed. In that case, the worker - // will soon be terminated too, so abort the connection. - return; - } mojo::MakeSelfOwnedReceiver( std::make_unique<QuicTransportConnectorImpl>( worker_process_host_->GetID(), /*frame=*/nullptr, worker_origin_, - ancestor_render_frame_host->GetIsolationInfoForSubresources() - .network_isolation_key()), + network_isolation_key_), std::move(receiver)); } @@ -440,7 +434,8 @@ worker_process_host_->GetID(), /*creator_render_frame_host_id_=*/base::nullopt, ancestor_render_frame_host_id_, worker_origin_, - cross_origin_embedder_policy_, std::move(coep_reporter)), + network_isolation_key_, cross_origin_embedder_policy_, + std::move(coep_reporter)), std::move(receiver)); }
diff --git a/content/browser/worker_host/dedicated_worker_host.h b/content/browser/worker_host/dedicated_worker_host.h index 83b718e..df88959 100644 --- a/content/browser/worker_host/dedicated_worker_host.h +++ b/content/browser/worker_host/dedicated_worker_host.h
@@ -18,6 +18,7 @@ #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" +#include "net/base/network_isolation_key.h" #include "services/network/public/cpp/cross_origin_embedder_policy.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/mojom/idle/idle_manager.mojom-forward.h" @@ -55,6 +56,7 @@ base::Optional<GlobalFrameRoutingId> creator_render_frame_host_id, GlobalFrameRoutingId ancestor_render_frame_host_id, const url::Origin& creator_origin, + const net::NetworkIsolationKey& network_isolation_key, const network::CrossOriginEmbedderPolicy& cross_origin_embedder_policy, mojo::PendingRemote<network::mojom::CrossOriginEmbedderPolicyReporter> coep_reporter); @@ -108,6 +110,10 @@ void ReportNoBinderForInterface(const std::string& error); + const net::NetworkIsolationKey& GetNetworkIsolationKey() const { + return network_isolation_key_; + } + const network::CrossOriginEmbedderPolicy& cross_origin_embedder_policy() const { return cross_origin_embedder_policy_; @@ -192,6 +198,10 @@ // https://html.spec.whatwg.org/C/#concept-settings-object-origin const url::Origin worker_origin_; + // The NetworkIsolationKey associated with this worker. Same as that of the + // frame or the worker that created this worker. + const net::NetworkIsolationKey network_isolation_key_; + // The DedicatedWorker's Cross-Origin-Embedder-Policy(COEP). It is equals to // the nearest ancestor frame host's COEP: // https://mikewest.github.io/corpp/#initialize-embedder-policy-for-global
diff --git a/content/browser/worker_host/dedicated_worker_host_factory_impl.cc b/content/browser/worker_host/dedicated_worker_host_factory_impl.cc index b5c108f..c15d4df 100644 --- a/content/browser/worker_host/dedicated_worker_host_factory_impl.cc +++ b/content/browser/worker_host/dedicated_worker_host_factory_impl.cc
@@ -40,6 +40,7 @@ base::Optional<GlobalFrameRoutingId> creator_render_frame_host_id, GlobalFrameRoutingId ancestor_render_frame_host_id, const url::Origin& creator_origin, + const net::NetworkIsolationKey& network_isolation_key, const network::CrossOriginEmbedderPolicy& cross_origin_embedder_policy, mojo::PendingRemote<network::mojom::CrossOriginEmbedderPolicyReporter> coep_reporter) @@ -47,6 +48,7 @@ creator_render_frame_host_id_(creator_render_frame_host_id), ancestor_render_frame_host_id_(ancestor_render_frame_host_id), creator_origin_(creator_origin), + network_isolation_key_(network_isolation_key), cross_origin_embedder_policy_(cross_origin_embedder_policy), coep_reporter_(std::move(coep_reporter)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -90,7 +92,7 @@ auto* host = new DedicatedWorkerHost( service, token, worker_process_host, creator_render_frame_host_id_, - ancestor_render_frame_host_id_, creator_origin_, + ancestor_render_frame_host_id_, creator_origin_, network_isolation_key_, cross_origin_embedder_policy_, std::move(coep_reporter)); host->BindBrowserInterfaceBrokerReceiver(std::move(broker_receiver)); } @@ -132,7 +134,7 @@ auto* host = new DedicatedWorkerHost( service, token, worker_process_host, creator_render_frame_host_id_, - ancestor_render_frame_host_id_, creator_origin_, + ancestor_render_frame_host_id_, creator_origin_, network_isolation_key_, cross_origin_embedder_policy_, std::move(coep_reporter)); mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker; host->BindBrowserInterfaceBrokerReceiver(
diff --git a/content/browser/worker_host/dedicated_worker_host_factory_impl.h b/content/browser/worker_host/dedicated_worker_host_factory_impl.h index 5cb4f226..f296bc1 100644 --- a/content/browser/worker_host/dedicated_worker_host_factory_impl.h +++ b/content/browser/worker_host/dedicated_worker_host_factory_impl.h
@@ -10,6 +10,7 @@ #include "content/public/browser/global_routing_id.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" +#include "net/base/network_isolation_key.h" #include "services/network/public/cpp/cross_origin_embedder_policy.h" #include "services/network/public/mojom/cross_origin_embedder_policy.mojom.h" #include "third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom.h" @@ -27,6 +28,7 @@ base::Optional<GlobalFrameRoutingId> creator_render_frame_host_id, GlobalFrameRoutingId ancestor_render_frame_host_id, const url::Origin& creator_origin, + const net::NetworkIsolationKey& network_isolation_key, const network::CrossOriginEmbedderPolicy& cross_origin_embedder_policy, mojo::PendingRemote<network::mojom::CrossOriginEmbedderPolicyReporter> coep_reporter); @@ -60,6 +62,7 @@ const GlobalFrameRoutingId ancestor_render_frame_host_id_; const url::Origin creator_origin_; + const net::NetworkIsolationKey network_isolation_key_; const network::CrossOriginEmbedderPolicy cross_origin_embedder_policy_; mojo::Remote<network::mojom::CrossOriginEmbedderPolicyReporter> coep_reporter_;
diff --git a/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc b/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc index b9ac189..9538f2a 100644 --- a/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc +++ b/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc
@@ -19,6 +19,7 @@ #include "content/test/test_web_contents.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" +#include "net/base/network_isolation_key.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/tokens/tokens_mojom_traits.h" @@ -42,7 +43,8 @@ mojo::MakeSelfOwnedReceiver( std::make_unique<DedicatedWorkerHostFactoryImpl>( worker_process_id, render_frame_host_id, render_frame_host_id, - url::Origin(), network::CrossOriginEmbedderPolicy(), + url::Origin(), net::NetworkIsolationKey::CreateTransient(), + network::CrossOriginEmbedderPolicy(), std::move(coep_reporter_remote)), factory_.BindNewPipeAndPassReceiver());
diff --git a/content/browser/worker_host/shared_worker_host.cc b/content/browser/worker_host/shared_worker_host.cc index be8d622..dc559bca 100644 --- a/content/browser/worker_host/shared_worker_host.cc +++ b/content/browser/worker_host/shared_worker_host.cc
@@ -371,11 +371,10 @@ mojo::PendingReceiver<blink::mojom::QuicTransportConnector> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const url::Origin origin = url::Origin::Create(instance().url()); - mojo::MakeSelfOwnedReceiver( - std::make_unique<QuicTransportConnectorImpl>( - GetProcessHost()->GetID(), /*frame=*/nullptr, origin, - net::NetworkIsolationKey(origin, origin)), - std::move(receiver)); + mojo::MakeSelfOwnedReceiver(std::make_unique<QuicTransportConnectorImpl>( + GetProcessHost()->GetID(), /*frame=*/nullptr, + origin, GetNetworkIsolationKey()), + std::move(receiver)); } void SharedWorkerHost::BindCacheStorage( @@ -468,6 +467,14 @@ return weak_factory_.GetWeakPtr(); } +net::NetworkIsolationKey SharedWorkerHost::GetNetworkIsolationKey() const { + const url::Origin origin = url::Origin::Create(instance().url()); + // TODO(https://crbug.com/1147281): This is the NetworkIsolationKey of a + // top-level browsing context, which shouldn't be use for SharedWorkers used + // in iframes. + return net::NetworkIsolationKey::ToDoUseTopFrameOriginAsWell(origin); +} + void SharedWorkerHost::ReportNoBinderForInterface(const std::string& error) { broker_receiver_.ReportBadMessage(error + " for the shared worker scope"); }
diff --git a/content/browser/worker_host/shared_worker_host.h b/content/browser/worker_host/shared_worker_host.h index ce80de4..c6df40bc 100644 --- a/content/browser/worker_host/shared_worker_host.h +++ b/content/browser/worker_host/shared_worker_host.h
@@ -27,6 +27,7 @@ #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" +#include "net/base/network_isolation_key.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "services/network/public/mojom/url_loader_factory.mojom-forward.h" #include "third_party/blink/public/common/tokens/tokens.h" @@ -156,6 +157,8 @@ base::WeakPtr<SharedWorkerHost> AsWeakPtr(); + net::NetworkIsolationKey GetNetworkIsolationKey() const; + void ReportNoBinderForInterface(const std::string& error); // Creates a network factory params for subresource requests from this worker.
diff --git a/content/dev_ui_content_resources.grd b/content/dev_ui_content_resources.grd index d59286d..39e1eef 100644 --- a/content/dev_ui_content_resources.grd +++ b/content/dev_ui_content_resources.grd
@@ -35,7 +35,7 @@ <include name="IDR_NETWORK_ERROR_LISTING_CSS" file="browser/resources/net/network_errors_listing.css" type="BINDATA" /> <include name="IDR_PROCESS_INTERNALS_HTML" file="browser/resources/process/process_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> <include name="IDR_PROCESS_INTERNALS_MOJO_JS" file="${root_gen_dir}/mojom-webui/content/browser/process_internals/process_internals.mojom-webui.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_PROCESS_INTERNALS_CSS" file="browser/resources/process/process_internals.css" flattenhtml="true" type="BINDATA" /> + <include name="IDR_PROCESS_INTERNALS_CSS" file="browser/resources/process/process_internals.css" type="BINDATA" /> <include name="IDR_PROCESS_INTERNALS_JS" file="browser/resources/process/process_internals.js" type="BINDATA" /> <include name="IDR_SERVICE_WORKER_INTERNALS_HTML" file="browser/resources/service_worker/serviceworker_internals.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> <include name="IDR_SERVICE_WORKER_INTERNALS_JS" file="browser/resources/service_worker/serviceworker_internals.js" type="BINDATA" />
diff --git a/content/public/browser/service_worker_context.h b/content/public/browser/service_worker_context.h index 557fe427..37bbafe 100644 --- a/content/public/browser/service_worker_context.h +++ b/content/public/browser/service_worker_context.h
@@ -89,8 +89,6 @@ using StartWorkerCallback = base::OnceCallback< void(int64_t version_id, int process_id, int thread_id)>; - // Temporary for crbug.com/824858. The thread the context core lives on. - static bool IsServiceWorkerOnUIEnabled(); static content::BrowserThread::ID GetCoreThreadId(); // Returns true if |url| is within the service worker |scope|.
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index ce8905d0..f69bc5c 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -901,8 +901,8 @@ base::FEATURE_DISABLED_BY_DEFAULT}; // Kill switch for the WebNFC feature. This feature can be enabled for all sites -// using the kEnableExperimentalWebPlatformFeatures flag or by a particular site -// if it includes an Origin Trial key. https://w3c.github.io/web-nfc/ +// using the kEnableExperimentalWebPlatformFeatures flag. +// https://w3c.github.io/web-nfc/ const base::Feature kWebNfc{"WebNFC", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // defined(OS_ANDROID)
diff --git a/content/renderer/content_security_policy_util.cc b/content/renderer/content_security_policy_util.cc index 1fbb0302..c933b66 100644 --- a/content/renderer/content_security_policy_util.cc +++ b/content/renderer/content_security_policy_util.cc
@@ -40,6 +40,10 @@ policy_in.header.Utf8(), policy_in.disposition, policy_in.source); policy->use_reporting_api = policy_in.use_reporting_api; + for (const auto& directive : policy_in.raw_directives) { + auto name = network::ToCSPDirectiveName(directive.name.Utf8()); + policy->raw_directives[name] = directive.value.Utf8(); + } for (const auto& directive : policy_in.directives) { auto name = network::ToCSPDirectiveName(directive.name.Utf8()); policy->directives[name] = BuildCSPSourceList(directive.source_list);
diff --git a/extensions/browser/events/event_ack_data.cc b/extensions/browser/events/event_ack_data.cc index cc6fbfb..2c82eab 100644 --- a/extensions/browser/events/event_ack_data.cc +++ b/extensions/browser/events/event_ack_data.cc
@@ -50,14 +50,16 @@ DISALLOW_COPY_AND_ASSIGN(CoreThreadEventInfo); }; -// static -void EventAckData::StartExternalRequestOnCoreThread( +EventAckData::EventAckData() + : unacked_events_(base::MakeRefCounted<CoreThreadEventInfo>()) {} +EventAckData::~EventAckData() = default; + +void EventAckData::IncrementInflightEvent( content::ServiceWorkerContext* context, int render_process_id, int64_t version_id, - int event_id, - scoped_refptr<CoreThreadEventInfo> unacked_events) { - DCHECK_CURRENTLY_ON(content::ServiceWorkerContext::GetCoreThreadId()); + int event_id) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string request_uuid = base::GenerateGUID(); bool start_ok = true; @@ -71,24 +73,22 @@ // TODO(lazyboy): Clean up |unacked_events_| if RenderProcessHost died before // it got a chance to ack |event_id|. This shouldn't happen in common cases. - std::map<int, EventInfo>& unacked_events_map = unacked_events->event_map; + std::map<int, EventInfo>& unacked_events_map = unacked_events_->event_map; auto insert_result = unacked_events_map.insert(std::make_pair( event_id, EventInfo{request_uuid, render_process_id, start_ok})); DCHECK(insert_result.second) << "EventAckData: Duplicate event_id."; } -// static -void EventAckData::FinishExternalRequestOnCoreThread( +void EventAckData::DecrementInflightEvent( content::ServiceWorkerContext* context, int render_process_id, int64_t version_id, int event_id, bool worker_stopped, - scoped_refptr<CoreThreadEventInfo> unacked_events, base::OnceClosure failure_callback) { - DCHECK_CURRENTLY_ON(content::ServiceWorkerContext::GetCoreThreadId()); + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::map<int, EventInfo>& unacked_events_map = unacked_events->event_map; + std::map<int, EventInfo>& unacked_events_map = unacked_events_->event_map; auto request_info_iter = unacked_events_map.find(event_id); if (request_info_iter == unacked_events_map.end() || request_info_iter->second.render_process_id != render_process_id) { @@ -113,50 +113,4 @@ } } -EventAckData::EventAckData() - : unacked_events_(base::MakeRefCounted<CoreThreadEventInfo>()) {} -EventAckData::~EventAckData() = default; - -void EventAckData::IncrementInflightEvent( - content::ServiceWorkerContext* context, - int render_process_id, - int64_t version_id, - int event_id) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - StartExternalRequestOnCoreThread(context, render_process_id, version_id, - event_id, unacked_events_); - } else { - content::ServiceWorkerContext::RunTask( - content::GetIOThreadTaskRunner({}), FROM_HERE, context, - base::BindOnce(&EventAckData::StartExternalRequestOnCoreThread, context, - render_process_id, version_id, event_id, - unacked_events_)); - } -} - -void EventAckData::DecrementInflightEvent( - content::ServiceWorkerContext* context, - int render_process_id, - int64_t version_id, - int event_id, - bool worker_stopped, - base::OnceClosure failure_callback) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - FinishExternalRequestOnCoreThread(context, render_process_id, version_id, - event_id, worker_stopped, unacked_events_, - std::move(failure_callback)); - } else { - content::ServiceWorkerContext::RunTask( - content::GetIOThreadTaskRunner({}), FROM_HERE, context, - base::BindOnce(&EventAckData::FinishExternalRequestOnCoreThread, - context, render_process_id, version_id, event_id, - worker_stopped, unacked_events_, - std::move(failure_callback))); - } -} - } // namespace extensions
diff --git a/extensions/browser/extension_service_worker_message_filter.cc b/extensions/browser/extension_service_worker_message_filter.cc index ce99b8e..52485bc 100644 --- a/extensions/browser/extension_service_worker_message_filter.cc +++ b/extensions/browser/extension_service_worker_message_filter.cc
@@ -45,9 +45,8 @@ *thread = content::BrowserThread::UI; } - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled() && - (message.type() == ExtensionHostMsg_IncrementServiceWorkerActivity::ID || - message.type() == ExtensionHostMsg_DecrementServiceWorkerActivity::ID)) { + if (message.type() == ExtensionHostMsg_IncrementServiceWorkerActivity::ID || + message.type() == ExtensionHostMsg_DecrementServiceWorkerActivity::ID) { *thread = content::BrowserThread::UI; } }
diff --git a/extensions/browser/process_manager.cc b/extensions/browser/process_manager.cc index f41d442..33792184 100644 --- a/extensions/browser/process_manager.cc +++ b/extensions/browser/process_manager.cc
@@ -153,22 +153,6 @@ std::move(callback).Run(context_info != nullptr); } -void StartServiceWorkerExternalRequest(content::ServiceWorkerContext* context, - int64_t service_worker_version_id, - const std::string& request_uuid) { - DCHECK_CURRENTLY_ON(content::ServiceWorkerContext::GetCoreThreadId()); - context->StartingExternalRequest(service_worker_version_id, request_uuid); -} - -void FinishServiceWorkerExternalRequest(content::ServiceWorkerContext* context, - int64_t service_worker_version_id, - const std::string& request_uuid) { - DCHECK_CURRENTLY_ON(content::ServiceWorkerContext::GetCoreThreadId()); - content::ServiceWorkerExternalRequestResult result = - context->FinishedExternalRequest(service_worker_version_id, request_uuid); - DCHECK_EQ(result, content::ServiceWorkerExternalRequestResult::kOk); -} - } // namespace struct ProcessManager::BackgroundPageData { @@ -800,16 +784,8 @@ util::GetStoragePartitionForExtensionId(extension->id(), browser_context_) ->GetServiceWorkerContext(); - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - StartServiceWorkerExternalRequest(service_worker_context, - service_worker_version_id, request_uuid); - } else { - content::ServiceWorkerContext::RunTask( - worker_task_runner_, FROM_HERE, service_worker_context, - base::BindOnce(&StartServiceWorkerExternalRequest, - service_worker_context, service_worker_version_id, - request_uuid)); - } + service_worker_context->StartingExternalRequest(service_worker_version_id, + request_uuid); return request_uuid; } @@ -865,16 +841,10 @@ util::GetStoragePartitionForExtensionId(extension->id(), browser_context_) ->GetServiceWorkerContext(); - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - FinishServiceWorkerExternalRequest(service_worker_context, - service_worker_version_id, request_uuid); - } else { - content::ServiceWorkerContext::RunTask( - worker_task_runner_, FROM_HERE, service_worker_context, - base::BindOnce(&FinishServiceWorkerExternalRequest, - service_worker_context, service_worker_version_id, - request_uuid)); - } + content::ServiceWorkerExternalRequestResult result = + service_worker_context->FinishedExternalRequest(service_worker_version_id, + request_uuid); + DCHECK_EQ(result, content::ServiceWorkerExternalRequestResult::kOk); } void ProcessManager::OnLazyBackgroundPageIdle(const std::string& extension_id,
diff --git a/extensions/browser/service_worker_task_queue.cc b/extensions/browser/service_worker_task_queue.cc index 5116dc6c..e3d1c89 100644 --- a/extensions/browser/service_worker_task_queue.cc +++ b/extensions/browser/service_worker_task_queue.cc
@@ -91,59 +91,6 @@ return ServiceWorkerTaskQueueFactory::GetForBrowserContext(context); } -// static -void ServiceWorkerTaskQueue::DidStartWorkerForScopeOnCoreThread( - const SequencedContextId& context_id, - base::Time start_time, - base::WeakPtr<ServiceWorkerTaskQueue> task_queue, - int64_t version_id, - int process_id, - int thread_id) { - DCHECK_CURRENTLY_ON(content::ServiceWorkerContext::GetCoreThreadId()); - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - if (task_queue) { - task_queue->DidStartWorkerForScope(context_id, start_time, version_id, - process_id, thread_id); - } - } else { - content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce(&ServiceWorkerTaskQueue::DidStartWorkerForScope, - task_queue, context_id, start_time, version_id, - process_id, thread_id)); - } -} - -// static -void ServiceWorkerTaskQueue::DidStartWorkerFailOnCoreThread( - const SequencedContextId& context_id, - base::WeakPtr<ServiceWorkerTaskQueue> task_queue) { - DCHECK_CURRENTLY_ON(content::ServiceWorkerContext::GetCoreThreadId()); - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - if (task_queue) - task_queue->DidStartWorkerFail(context_id); - } else { - content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, base::BindOnce(&ServiceWorkerTaskQueue::DidStartWorkerFail, - task_queue, context_id)); - } -} - -// static -void ServiceWorkerTaskQueue::StartServiceWorkerOnCoreThreadToRunTasks( - base::WeakPtr<ServiceWorkerTaskQueue> task_queue_weak, - const SequencedContextId& context_id, - content::ServiceWorkerContext* service_worker_context) { - DCHECK_CURRENTLY_ON(content::ServiceWorkerContext::GetCoreThreadId()); - service_worker_context->StartWorkerForScope( - context_id.first.service_worker_scope(), - base::BindOnce( - &ServiceWorkerTaskQueue::DidStartWorkerForScopeOnCoreThread, - context_id, base::Time::Now(), task_queue_weak), - base::BindOnce(&ServiceWorkerTaskQueue::DidStartWorkerFailOnCoreThread, - context_id, task_queue_weak)); -} - // The current worker related state of an activated extension. class ServiceWorkerTaskQueue::WorkerState { public: @@ -464,16 +411,12 @@ content::ServiceWorkerContext* service_worker_context = partition->GetServiceWorkerContext(); - if (content::ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) { - StartServiceWorkerOnCoreThreadToRunTasks( - weak_factory_.GetWeakPtr(), context_id, service_worker_context); - } else { - content::ServiceWorkerContext::RunTask( - content::GetIOThreadTaskRunner({}), FROM_HERE, service_worker_context, - base::BindOnce( - &ServiceWorkerTaskQueue::StartServiceWorkerOnCoreThreadToRunTasks, - weak_factory_.GetWeakPtr(), context_id, service_worker_context)); - } + service_worker_context->StartWorkerForScope( + context_id.first.service_worker_scope(), + base::BindOnce(&ServiceWorkerTaskQueue::DidStartWorkerForScope, + weak_factory_.GetWeakPtr(), context_id, base::Time::Now()), + base::BindOnce(&ServiceWorkerTaskQueue::DidStartWorkerFail, + weak_factory_.GetWeakPtr(), context_id)); } void ServiceWorkerTaskQueue::DidRegisterServiceWorker(
diff --git a/extensions/browser/service_worker_task_queue.h b/extensions/browser/service_worker_task_queue.h index ec74dd9e1..4c00c37 100644 --- a/extensions/browser/service_worker_task_queue.h +++ b/extensions/browser/service_worker_task_queue.h
@@ -23,7 +23,6 @@ namespace content { class BrowserContext; -class ServiceWorkerContext; } namespace extensions { @@ -148,21 +147,6 @@ class WorkerState; - static void DidStartWorkerForScopeOnCoreThread( - const SequencedContextId& context_id, - base::Time start_time, - base::WeakPtr<ServiceWorkerTaskQueue> task_queue, - int64_t version_id, - int process_id, - int thread_id); - static void DidStartWorkerFailOnCoreThread( - const SequencedContextId& context_id, - base::WeakPtr<ServiceWorkerTaskQueue> task_queue); - static void StartServiceWorkerOnCoreThreadToRunTasks( - base::WeakPtr<ServiceWorkerTaskQueue> task_queue_weak, - const SequencedContextId& context_id, - content::ServiceWorkerContext* service_worker_context); - void RunTasksAfterStartWorker(const SequencedContextId& context_id); void DidRegisterServiceWorker(const SequencedContextId& context_id,
diff --git a/google_apis/google_api_keys.cc b/google_apis/google_api_keys.cc index 917edc5..327f894b 100644 --- a/google_apis/google_api_keys.cc +++ b/google_apis/google_api_keys.cc
@@ -95,12 +95,6 @@ #define GOOGLE_API_KEY_SODA DUMMY_API_TOKEN #endif -// API key for the DevTools frontend to use for surveys. Note there is no -// public API to replace this functionality. -#if !defined(GOOGLE_API_KEY_DEVTOOLS_SURVEYS) -#define GOOGLE_API_KEY_DEVTOOLS_SURVEYS DUMMY_API_TOKEN -#endif - // These are used as shortcuts for developers and users providing // OAuth credentials via preprocessor defines or environment // variables. If set, they will be used to replace any of the client @@ -153,11 +147,6 @@ GOOGLE_API_KEY_SODA, STRINGIZE_NO_EXPANSION(GOOGLE_API_KEY_SODA), nullptr, std::string(), environment.get(), command_line, gaia_config); - api_key_devtools_surveys_ = CalculateKeyValue( - GOOGLE_API_KEY_DEVTOOLS_SURVEYS, - STRINGIZE_NO_EXPANSION(GOOGLE_API_KEY_DEVTOOLS_SURVEYS), nullptr, - std::string(), environment.get(), command_line, gaia_config); - metrics_key_ = CalculateKeyValue( GOOGLE_METRICS_SIGNING_KEY, STRINGIZE_NO_EXPANSION(GOOGLE_METRICS_SIGNING_KEY), nullptr, @@ -224,9 +213,6 @@ std::string api_key_remoting() const { return api_key_remoting_; } std::string api_key_sharing() const { return api_key_sharing_; } std::string api_key_soda() const { return api_key_soda_; } - std::string api_key_devtools_surveys() const { - return api_key_devtools_surveys_; - } std::string metrics_key() const { return metrics_key_; } @@ -338,7 +324,6 @@ std::string api_key_remoting_; std::string api_key_sharing_; std::string api_key_soda_; - std::string api_key_devtools_surveys_; std::string metrics_key_; std::string client_ids_[CLIENT_NUM_ITEMS]; std::string client_secrets_[CLIENT_NUM_ITEMS]; @@ -371,10 +356,6 @@ return g_api_key_cache.Get().api_key_soda(); } -std::string GetDevtoolsSurveysAPIKey() { - return g_api_key_cache.Get().api_key_devtools_surveys(); -} - #if defined(OS_IOS) void SetAPIKey(const std::string& api_key) { g_api_key_cache.Get().set_api_key(api_key);
diff --git a/google_apis/google_api_keys.h b/google_apis/google_api_keys.h index 5297c066..6d999abb 100644 --- a/google_apis/google_api_keys.h +++ b/google_apis/google_api_keys.h
@@ -83,10 +83,6 @@ // Retrieves the Speech On-Device API (SODA) API Key. std::string GetSodaAPIKey(); -// Retrieves the DevTools Survey API Key. Note there is no public API to replace -// this functionality. -std::string GetDevtoolsSurveysAPIKey(); - #if defined(OS_IOS) // Sets the API key. This should be called as early as possible before this // API key is even accessed.
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 index 25b9cec3..18d016c 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -6b7a9692bc33bedc15533079334b599400500eaf \ No newline at end of file +e11e59276ce8a8c59ad646af554313f86bfc64b4 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 index a64873a0..4ddc362 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -689858e0c9d6bdb615c7858d99da089e61da06ca \ No newline at end of file +073bc8891296f54d16e0742ef079b28bda7cc728 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 index f71857f0..f3db25d 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -e14990ba78a86c3accc947b67547c9cbc78f9f29 \ No newline at end of file +9a660eec87d200def784b977a493cd7008f44610 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 index 456b9d1..6ac033f 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -dc323cb02c478f98bc2fafe4f11eeb3c19878579 \ No newline at end of file +9eab555b97d82614875a8738db58b071e6bd4194 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 index d287bf9..480c46e 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -1205be38d8c585ede7f8dfc70f75af303ac4fe4c \ No newline at end of file +2a7ff295021b58ad5ee4c0f85de64ec280cf09ba \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 index e5a881f..82c189f 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -e73f0b349d9032691076df9f2b61729e8b59f197 \ No newline at end of file +224fd50c65d9d481f265c067288e34bb6d80fbe6 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 index 0b0edcc..d03f4d1 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.arm64.zip.sha1
@@ -1 +1 @@ -6e0cfe13cdef814ec4de941e5091616dbda6eb78 \ No newline at end of file +0e5adc7c1ead334464f9ed1d179fac69c0cbfdb0 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 index b7b1566..2393638 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.x64.zip.sha1
@@ -1 +1 @@ -6900d2d5ffa6f77dab48de6f9a756dc3337c80d5 \ No newline at end of file +b34284f5ab02fabd0d10ad852f3bd6909dfb2bf2 \ No newline at end of file
diff --git a/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc b/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc index 9b01b096..81beec4 100644 --- a/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc +++ b/media/capture/video/chromeos/camera_hal_dispatcher_impl.cc
@@ -3,7 +3,6 @@ // found in the LICENSE file. #include "media/capture/video/chromeos/camera_hal_dispatcher_impl.h" - #include <fcntl.h> #include <grp.h> #include <poll.h> @@ -195,6 +194,16 @@ observer_removed_event.Wait(); } +void CameraHalDispatcherImpl::RegisterPluginVmToken( + const base::UnguessableToken& token) { + token_manager_.RegisterPluginVmToken(token); +} + +void CameraHalDispatcherImpl::UnregisterPluginVmToken( + const base::UnguessableToken& token) { + token_manager_.UnregisterPluginVmToken(token); +} + CameraHalDispatcherImpl::CameraHalDispatcherImpl() : proxy_thread_("CameraProxyThread"), blocking_io_thread_("CameraBlockingIOThread"),
diff --git a/media/capture/video/chromeos/camera_hal_dispatcher_impl.h b/media/capture/video/chromeos/camera_hal_dispatcher_impl.h index f65227f0..df5a5d4 100644 --- a/media/capture/video/chromeos/camera_hal_dispatcher_impl.h +++ b/media/capture/video/chromeos/camera_hal_dispatcher_impl.h
@@ -99,6 +99,10 @@ // being destroyed. void RemoveActiveClientObserver(CameraActiveClientObserver* observer); + // Called by vm_permission_service to register the token used for pluginvm. + void RegisterPluginVmToken(const base::UnguessableToken& token); + void UnregisterPluginVmToken(const base::UnguessableToken& token); + // CameraHalDispatcher implementations. void RegisterServer( mojo::PendingRemote<cros::mojom::CameraHalServer> server) final;
diff --git a/media/capture/video/chromeos/token_manager.cc b/media/capture/video/chromeos/token_manager.cc index 6c124a31..fc933e0 100644 --- a/media/capture/video/chromeos/token_manager.cc +++ b/media/capture/video/chromeos/token_manager.cc
@@ -86,24 +86,45 @@ base::UnguessableToken TokenManager::GetTokenForTrustedClient( cros::mojom::CameraClientType type) { + base::AutoLock l(client_token_map_lock_); // pluginvm's token should be generated by vm_permission_service. CHECK_NE(type, cros::mojom::CameraClientType::PLUGINVM); - auto& token = client_token_map_[type]; - if (token.is_empty()) { - token = base::UnguessableToken::Create(); + auto& token_set = client_token_map_[type]; + if (token_set.empty()) { + token_set.insert(base::UnguessableToken::Create()); } - return token; + return *token_set.begin(); +} + +void TokenManager::RegisterPluginVmToken(const base::UnguessableToken& token) { + base::AutoLock l(client_token_map_lock_); + auto result = + client_token_map_[cros::mojom::CameraClientType::PLUGINVM].insert(token); + if (!result.second) { + LOG(WARNING) << "The same token is already registered"; + } +} + +void TokenManager::UnregisterPluginVmToken( + const base::UnguessableToken& token) { + base::AutoLock l(client_token_map_lock_); + auto num_removed = + client_token_map_[cros::mojom::CameraClientType::PLUGINVM].erase(token); + if (num_removed != 1) { + LOG(WARNING) << "The token wasn't registered previously"; + } } bool TokenManager::AuthenticateClient(cros::mojom::CameraClientType type, const base::UnguessableToken& token) { + base::AutoLock l(client_token_map_lock_); // TODO(b/170075468): Check other clients after they have been migrated to // CameraHalDispatcher::RegisterClientWithToken. if (type != cros::mojom::CameraClientType::CHROME) { return true; } - auto it = client_token_map_.find(type); - return it != client_token_map_.end() && it->second == token; + auto& token_set = client_token_map_[type]; + return token_set.find(token) != token_set.end(); } } // namespace media
diff --git a/media/capture/video/chromeos/token_manager.h b/media/capture/video/chromeos/token_manager.h index d2f727e..3531a0b 100644 --- a/media/capture/video/chromeos/token_manager.h +++ b/media/capture/video/chromeos/token_manager.h
@@ -6,6 +6,8 @@ #define MEDIA_CAPTURE_VIDEO_CHROMEOS_TOKEN_MANAGER_H_ #include "base/containers/flat_map.h" +#include "base/containers/flat_set.h" +#include "base/thread_annotations.h" #include "base/unguessable_token.h" #include "media/capture/video/chromeos/mojom/cros_camera_service.mojom.h" @@ -23,13 +25,19 @@ base::UnguessableToken GetTokenForTrustedClient( cros::mojom::CameraClientType type); + void RegisterPluginVmToken(const base::UnguessableToken& token); + void UnregisterPluginVmToken(const base::UnguessableToken& token); + bool AuthenticateClient(cros::mojom::CameraClientType type, const base::UnguessableToken& token); private: base::UnguessableToken server_token_; - base::flat_map<cros::mojom::CameraClientType, base::UnguessableToken> - client_token_map_; + + base::Lock client_token_map_lock_; + base::flat_map<cros::mojom::CameraClientType, + base::flat_set<base::UnguessableToken>> + client_token_map_ GUARDED_BY(client_token_map_lock_); }; } // namespace media
diff --git a/media/gpu/vaapi/vaapi_jpeg_encode_accelerator.cc b/media/gpu/vaapi/vaapi_jpeg_encode_accelerator.cc index 7e9bf64..d94c070 100644 --- a/media/gpu/vaapi/vaapi_jpeg_encode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_jpeg_encode_accelerator.cc
@@ -312,7 +312,7 @@ notify_error_cb_.Run(task_id, PLATFORM_FAILURE); return; } - DCHECK_LE(encoded_size, max_frame_size); + CHECK_LE(encoded_size, max_frame_size); if (exif_buffer_size > 0) { // Check the output header is 2+2+14 bytes APP0 as expected. @@ -340,7 +340,7 @@ static_cast<uint8_t>((exif_buffer_size + 2) / 256), static_cast<uint8_t>((exif_buffer_size + 2) % 256), }; - DCHECK_GE(output_size, base::size(jpeg_soi_and_app1_header)); + CHECK_GE(output_size, base::size(jpeg_soi_and_app1_header)); if (exif_buffer_size > output_size - base::size(jpeg_soi_and_app1_header)) { VLOGF(1) << "Insufficient buffer size reserved for JPEG APP1 data"; notify_error_cb_.Run(task_id, PLATFORM_FAILURE);
diff --git a/mojo/core/mojo_core_unittest.cc b/mojo/core/mojo_core_unittest.cc index 79e3132..e97172c7 100644 --- a/mojo/core/mojo_core_unittest.cc +++ b/mojo/core/mojo_core_unittest.cc
@@ -28,6 +28,11 @@ namespace { +// TODO(https://crbug.com/902135): Re-enable this on MSAN. Currently hangs +// because of an apparent deadlock in MSAN's fork() in multithreaded +// environments. +#if !defined(MEMORY_SANITIZER) + uint64_t kTestPipeName = 0; const char kTestMessage[] = "hai"; const char kTestReply[] = "bai"; @@ -136,4 +141,6 @@ InitializationMode::kLoadBeforeInit), ::testing::Values(LoadPathSpec::kImplicit, LoadPathSpec::kExplicit))); +#endif // !defined(MEMORY_SANITIZER) + } // namespace
diff --git a/net/base/network_isolation_key.h b/net/base/network_isolation_key.h index acd43a7..3736f56 100644 --- a/net/base/network_isolation_key.h +++ b/net/base/network_isolation_key.h
@@ -89,6 +89,17 @@ // NetworkIsolationKey filled in. static NetworkIsolationKey Todo() { return NetworkIsolationKey(); } + // Intended for temporary use in locations that should be using main frame and + // frame origin, but are currently only using frame origin, because the + // creating object may be shared across main frame objects. Having a special + // constructor for these methods makes it easier to keep track of locating + // callsites that need to have their NetworkIsolationKey filled in. + static NetworkIsolationKey ToDoUseTopFrameOriginAsWell( + const url::Origin& incorrectly_used_frame_origin) { + return NetworkIsolationKey(incorrectly_used_frame_origin, + incorrectly_used_frame_origin); + } + // Compare keys for equality, true if all enabled fields are equal. bool operator==(const NetworkIsolationKey& other) const { return std::tie(top_frame_site_, frame_site_, opaque_and_non_transient_) ==
diff --git a/services/device/nfc/README.md b/services/device/nfc/README.md index 23d6ca58..5bcfb8e 100644 --- a/services/device/nfc/README.md +++ b/services/device/nfc/README.md
@@ -10,15 +10,16 @@ the `services/device/public/mojom/nfc.mojom` file and implemented by the `services/device/nfc` module. -NDEFWriter and NDEFReader are the two primary interfaces of the Web NFC APIs. +NDEFReader is the primary interface of the Web NFC APIs. +The NDEFReader interface has both, write and scan methods. -The NDEFWriter interface has the write method for writing data to NFC tags. +The write method is for writing data to the NFC tag. This method will return a promise, which will be resolved when the message is successfully written to a NFC tag or be rejected when errors happened or the process is aborted by setting the AbortSignal in the NDEFWriteOptions. -The NDEFReader interface has the scan method to try to read data from any NFC tag +The scan method tries to read data from any NFC tag that comes within proximity. Once there is some data found an NDEFReadingEvent carrying the data will be dispatched to the NDEFReader.
diff --git a/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java b/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java index 67eba4c7..aafea515 100644 --- a/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java +++ b/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java
@@ -204,21 +204,11 @@ /** * Cancels pending push operation. - * - * @param callback that is used to notify caller when cancelPush() is completed. */ @Override - public void cancelPush(CancelPushResponse callback) { - if (!checkIfReady(callback)) return; - - if (mPendingPushOperation == null) { - callback.call(createError( - NdefErrorType.CANNOT_CANCEL, "No pending push operation to cancel.")); - } else { - completePendingPushOperation(createError( - NdefErrorType.OPERATION_CANCELLED, "The push operation is already cancelled.")); - callback.call(null); - } + public void cancelPush() { + completePendingPushOperation(createError( + NdefErrorType.OPERATION_CANCELLED, "The push operation is already cancelled.")); } /** @@ -250,37 +240,11 @@ * Cancels NFC watch operation. * * @param id of watch operation. - * @param callback that is used to notify caller when cancelWatch() is completed. */ @Override - public void cancelWatch(int id, CancelWatchResponse callback) { - if (!checkIfReady(callback)) return; - - if (!mWatchIds.contains(id)) { - callback.call( - createError(NdefErrorType.NOT_FOUND, "No pending scan operation to cancel.")); - } else { + public void cancelWatch(int id) { + if (mWatchIds.contains(id)) { mWatchIds.remove(mWatchIds.indexOf(id)); - callback.call(null); - disableReaderModeIfNeeded(); - } - } - - /** - * Cancels all NFC watch operations. - * - * @param callback that is used to notify caller when cancelAllWatches() is completed. - */ - @Override - public void cancelAllWatches(CancelAllWatchesResponse callback) { - if (!checkIfReady(callback)) return; - - if (mWatchIds.size() == 0) { - callback.call( - createError(NdefErrorType.NOT_FOUND, "No pending scan operation to cancel.")); - } else { - mWatchIds.clear(); - callback.call(null); disableReaderModeIfNeeded(); } } @@ -368,22 +332,7 @@ /** * Uses checkIfReady() method and if NFC cannot be used, calls mojo callback with NdefError. * - * @param WatchResponse Callback that is provided to watch() method. - * @return boolean true if NFC functionality can be used, false otherwise. - */ - private boolean checkIfReady(WatchResponse callback) { - NdefError error = checkIfReady(); - if (error == null) return true; - - callback.call(error); - return false; - } - - /** - * Uses checkIfReady() method and if NFC cannot be used, calls mojo callback with NdefError. - * - * @param callback Generic callback that is provided to push(), cancelPush(), - * cancelWatch() and cancelAllWatches() methods. + * @param callback Generic callback that is provided to watch() and push() methods. * @return boolean true if NFC functionality can be used, false otherwise. */ private boolean checkIfReady(Callbacks.Callback1<NdefError> callback) { @@ -560,9 +509,7 @@ * Notify all active watchers that an error happened when trying to read the tag coming nearby. */ private void notifyErrorToAllWatchers(NdefError error) { - for (int i = 0; i < mWatchIds.size(); i++) { - mClient.onError(error); - } + if (mWatchIds.size() != 0) mClient.onError(error); } /**
diff --git a/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java b/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java index cc29884d..c7b729cd 100644 --- a/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java +++ b/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java
@@ -50,9 +50,6 @@ import org.chromium.device.mojom.NdefRecord; import org.chromium.device.mojom.NdefRecordTypeCategory; import org.chromium.device.mojom.NdefWriteOptions; -import org.chromium.device.mojom.Nfc.CancelAllWatchesResponse; -import org.chromium.device.mojom.Nfc.CancelPushResponse; -import org.chromium.device.mojom.Nfc.CancelWatchResponse; import org.chromium.device.mojom.Nfc.PushResponse; import org.chromium.device.mojom.Nfc.WatchResponse; import org.chromium.device.mojom.NfcClient; @@ -176,8 +173,8 @@ doReturn(null).when(mNfcManager).getDefaultAdapter(); TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); mDelegate.invokeCallback(); - CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); - nfc.cancelAllWatches(mockCallback); + WatchResponse mockCallback = mock(WatchResponse.class); + nfc.watch(mNextWatchId, mockCallback); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NdefErrorType.NOT_SUPPORTED, mErrorCaptor.getValue().errorType); } @@ -192,8 +189,8 @@ .when(mContext) .checkPermission(anyString(), anyInt(), anyInt()); TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); - CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); - nfc.cancelAllWatches(mockCallback); + WatchResponse mockCallback = mock(WatchResponse.class); + nfc.watch(mNextWatchId, mockCallback); verify(mockCallback).call(mErrorCaptor.capture()); assertEquals(NdefErrorType.NOT_ALLOWED, mErrorCaptor.getValue().errorType); } @@ -1140,7 +1137,7 @@ } /** - * Test that Nfc.cancelPush() cancels pending push opration and completes successfully. + * Test that Nfc.cancelPush() cancels pending push operation. */ @Test @Feature({"NFCTest"}) @@ -1148,17 +1145,12 @@ TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); mDelegate.invokeCallback(); PushResponse mockPushCallback = mock(PushResponse.class); - CancelPushResponse mockCancelPushCallback = mock(CancelPushResponse.class); nfc.push(createMojoNdefMessage(), createNdefWriteOptions(), mockPushCallback); - nfc.cancelPush(mockCancelPushCallback); + nfc.cancelPush(); // Check that push request was cancelled with OPERATION_CANCELLED. verify(mockPushCallback).call(mErrorCaptor.capture()); assertEquals(NdefErrorType.OPERATION_CANCELLED, mErrorCaptor.getValue().errorType); - - // Check that cancel request was successfuly completed. - verify(mockCancelPushCallback).call(mErrorCaptor.capture()); - assertNull(mErrorCaptor.getValue()); } /** @@ -1235,12 +1227,7 @@ verify(mockWatchCallback).call(mErrorCaptor.capture()); assertNull(mErrorCaptor.getValue()); - CancelWatchResponse mockCancelWatchCallback = mock(CancelWatchResponse.class); - nfc.cancelWatch(mNextWatchId, mockCancelWatchCallback); - - // Check that cancel request was successfuly completed. - verify(mockCancelWatchCallback).call(mErrorCaptor.capture()); - assertNull(mErrorCaptor.getValue()); + nfc.cancelWatch(mNextWatchId); // Check that watch is not triggered when NFC tag is in proximity. nfc.processPendingOperationsForTesting(mNfcTagHandler); @@ -1249,69 +1236,6 @@ } /** - * Test that Nfc.cancelAllWatches() cancels all pending watch operations. - */ - @Test - @Feature({"NFCTest"}) - public void testCancelAllWatches() { - TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); - mDelegate.invokeCallback(); - WatchResponse mockWatchCallback1 = mock(WatchResponse.class); - WatchResponse mockWatchCallback2 = mock(WatchResponse.class); - nfc.watch(mNextWatchId++, mockWatchCallback1); - verify(mockWatchCallback1).call(mErrorCaptor.capture()); - assertNull(mErrorCaptor.getValue()); - - nfc.watch(mNextWatchId++, mockWatchCallback2); - verify(mockWatchCallback2).call(mErrorCaptor.capture()); - assertNull(mErrorCaptor.getValue()); - - CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); - nfc.cancelAllWatches(mockCallback); - - // Check that cancel request was successfuly completed. - verify(mockCallback).call(mErrorCaptor.capture()); - assertNull(mErrorCaptor.getValue()); - } - - /** - * Test that Nfc.cancelWatch() with invalid id is failing with NOT_FOUND error. - */ - @Test - @Feature({"NFCTest"}) - public void testCancelWatchInvalidId() { - TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); - mDelegate.invokeCallback(); - WatchResponse mockWatchCallback = mock(WatchResponse.class); - nfc.watch(mNextWatchId, mockWatchCallback); - - verify(mockWatchCallback).call(mErrorCaptor.capture()); - assertNull(mErrorCaptor.getValue()); - - CancelWatchResponse mockCancelWatchCallback = mock(CancelWatchResponse.class); - nfc.cancelWatch(mNextWatchId + 1, mockCancelWatchCallback); - - verify(mockCancelWatchCallback).call(mErrorCaptor.capture()); - assertEquals(NdefErrorType.NOT_FOUND, mErrorCaptor.getValue().errorType); - } - - /** - * Test that Nfc.cancelAllWatches() is failing with NOT_FOUND error if there are no active - * watch opeartions. - */ - @Test - @Feature({"NFCTest"}) - public void testCancelAllWatchesWithNoWathcers() { - TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); - mDelegate.invokeCallback(); - CancelAllWatchesResponse mockCallback = mock(CancelAllWatchesResponse.class); - nfc.cancelAllWatches(mockCallback); - - verify(mockCallback).call(mErrorCaptor.capture()); - assertEquals(NdefErrorType.NOT_FOUND, mErrorCaptor.getValue().errorType); - } - - /** * Test that when the tag in proximity is found to be not NDEF compatible, an error event will * be dispatched to the client and the pending push operation will also be ended with an error. */ @@ -1496,8 +1420,7 @@ .enableReaderMode(any(Activity.class), any(ReaderCallback.class), anyInt(), (Bundle) isNull()); - CancelPushResponse mockCancelPushCallback = mock(CancelPushResponse.class); - nfc.cancelPush(mockCancelPushCallback); + nfc.cancelPush(); // Reader mode is disabled. verify(mNfcAdapter, times(1)).disableReaderMode(mActivity); @@ -1533,8 +1456,7 @@ assertEquals(NdefErrorType.OPERATION_CANCELLED, mErrorCaptor.getValue().errorType); // Cancel the second push. - CancelPushResponse mockCancelPushCallback = mock(CancelPushResponse.class); - nfc.cancelPush(mockCancelPushCallback); + nfc.cancelPush(); // Reader mode is disabled after cancelPush is invoked. verify(mNfcAdapter, times(1)).disableReaderMode(mActivity); @@ -1564,8 +1486,7 @@ .enableReaderMode(any(Activity.class), any(ReaderCallback.class), anyInt(), (Bundle) isNull()); - CancelPushResponse mockCancelPushCallback = mock(CancelPushResponse.class); - nfc.cancelPush(mockCancelPushCallback); + nfc.cancelPush(); // Push was cancelled with OPERATION_CANCELLED. verify(mockPushCallback).call(mErrorCaptor.capture()); @@ -1574,12 +1495,7 @@ verify(mNfcAdapter, times(0)).disableReaderMode(mActivity); - CancelAllWatchesResponse mockCancelCallback = mock(CancelAllWatchesResponse.class); - nfc.cancelAllWatches(mockCancelCallback); - - // Check that cancel request was successfuly completed. - verify(mockCancelCallback).call(mErrorCaptor.capture()); - assertNull(mErrorCaptor.getValue()); + nfc.cancelWatch(mNextWatchId); // Reader mode is disabled when there are no pending push / watch operations. verify(mNfcAdapter, times(1)).disableReaderMode(mActivity);
diff --git a/services/device/public/mojom/nfc.mojom b/services/device/public/mojom/nfc.mojom index 0eff58a..059b27c 100644 --- a/services/device/public/mojom/nfc.mojom +++ b/services/device/public/mojom/nfc.mojom
@@ -5,17 +5,15 @@ module device.mojom; enum NDEFErrorType { - // No permssion. + // No permission. NOT_ALLOWED, // No hardware support, no NFC adapter, the connection cannot be established, // or operation is not supported by the NFC Adapter. NOT_SUPPORTED, // NFC adapter is disabled. NOT_READABLE, - NOT_FOUND, INVALID_MESSAGE, OPERATION_CANCELLED, - CANNOT_CANCEL, // Transfer data error. IO_ERROR }; @@ -103,9 +101,11 @@ bool overwrite; }; +// Interface used by Web NFC to push data to NFC devices and get notified of +// nearby NFC devices. interface NFC { - // NFCClient interface is used to notify |client| when NDEFMessage matches one - // or more pending watch operations. + // NFCClient interface is used to notify |client| when watching for nearby + // NFC devices. SetClient(pending_remote<NFCClient> client); // Pushes data to NFC device. @@ -113,19 +113,18 @@ Push(NDEFMessage message, NDEFWriteOptions? options) => (NDEFError? error); // Cancels pending push request. - CancelPush() => (NDEFError? error); + CancelPush(); // Starts watching for nearby NFC devices. |id| identifies each watch request // on the current Mojo connection. Watch(uint32 id) => (NDEFError? error); // Cancels watch operation with provided id. - CancelWatch (uint32 id) => (NDEFError? error); - - // Cancels all watch operations. - CancelAllWatches () => (NDEFError? error); + CancelWatch(uint32 id); }; +// Interface that client of the NFC interface must implement to get notified of +// nearby NFC devices. interface NFCClient { // Sends |message| to those readers that have registered |watch_ids| via // NFC.Watch(), i.e. |message| matches their filtering criteria.
diff --git a/services/network/public/cpp/content_security_policy/content_security_policy.cc b/services/network/public/cpp/content_security_policy/content_security_policy.cc index 28997ca..3e0d759a 100644 --- a/services/network/public/cpp/content_security_policy/content_security_policy.cc +++ b/services/network/public/cpp/content_security_policy/content_security_policy.cc
@@ -302,8 +302,10 @@ // 5. Let directive value be the result of splitting token on ASCII // whitespace. base::StringPiece value; - if (pos != std::string::npos) - value = directive.substr(pos + 1); + if (pos != std::string::npos) { + value = base::TrimString(directive.substr(pos + 1), + base::kWhitespaceASCII, base::TRIM_ALL); + } // 6. Let directive be a new directive whose name is directive name, // and value is directive value. @@ -858,6 +860,27 @@ continue; } + CSPDirectiveName directive_name = + ToCSPDirectiveName(directive.first.as_string()); + + if (directive_name == CSPDirectiveName::Unknown) { + out->parsing_errors.emplace_back(base::StringPrintf( + "Unrecognized Content-Security-Policy directive '%s'.", + directive.first.as_string().c_str())); + continue; + } + + // A directive with this name has already been parsed. Skip further + // directives per + // https://www.w3.org/TR/CSP3/#parse-serialized-policy. + if (out->raw_directives.count(directive_name)) { + out->parsing_errors.emplace_back(base::StringPrintf( + "Ignoring duplicate Content-Security-Policy directive '%s'.", + directive.first.as_string().c_str())); + continue; + } + out->raw_directives[directive_name] = directive.second.as_string(); + if (!base::ranges::all_of(directive.second, IsDirectiveValueCharacter)) { out->parsing_errors.emplace_back(base::StringPrintf( "The value for the Content-Security-Policy directive '%s' contains " @@ -868,19 +891,6 @@ continue; } - CSPDirectiveName directive_name = - ToCSPDirectiveName(directive.first.as_string()); - - // A directive with this name has already been parsed. Skip further - // directives per - // https://www.w3.org/TR/CSP3/#parse-serialized-policy. - if (out->directives.count(directive_name)) { - out->parsing_errors.emplace_back(base::StringPrintf( - "Ignoring duplicate Content-Security-Policy directive '%s'.", - directive.first.as_string().c_str())); - continue; - } - if (type == mojom::ContentSecurityPolicyType::kReport && !SupportedInReportOnly(directive_name)) { out->parsing_errors.emplace_back( @@ -969,9 +979,6 @@ &(out->report_endpoints)); break; case CSPDirectiveName::Unknown: - out->parsing_errors.emplace_back(base::StringPrintf( - "Unrecognized Content-Security-Policy directive '%s'.", - directive.first.as_string().c_str())); break; } }
diff --git a/services/network/public/cpp/content_security_policy/content_security_policy_unittest.cc b/services/network/public/cpp/content_security_policy/content_security_policy_unittest.cc index 5e332928..5fd66f4 100644 --- a/services/network/public/cpp/content_security_policy/content_security_policy_unittest.cc +++ b/services/network/public/cpp/content_security_policy/content_security_policy_unittest.cc
@@ -5,6 +5,7 @@ #include "services/network/public/cpp/content_security_policy/content_security_policy.h" #include "base/stl_util.h" +#include "base/strings/stringprintf.h" #include "net/http/http_response_headers.h" #include "services/network/public/cpp/content_security_policy/csp_context.h" #include "services/network/public/cpp/web_sandbox_flags.h" @@ -62,6 +63,9 @@ policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; EXPECT_EQ(frame_ancestors->sources.size(), expected_result->parsed_sources.size()); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + header); for (size_t i = 0; i < expected_result->parsed_sources.size(); i++) { EXPECT_EQ(frame_ancestors->sources[i]->scheme, expected_result->parsed_sources[i].scheme); @@ -267,7 +271,11 @@ AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); EXPECT_EQ(2U, policies[0]->directives.size()); + EXPECT_EQ(2U, policies[0]->raw_directives.size()); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.com"); auto& frame_ancestors = policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; EXPECT_EQ(frame_ancestors->sources.size(), 1U); @@ -279,6 +287,8 @@ EXPECT_EQ(frame_ancestors->sources[0]->is_port_wildcard, false); EXPECT_EQ(frame_ancestors->allow_self, false); + EXPECT_EQ(policies[0]->raw_directives[mojom::CSPDirectiveName::ScriptSrc], + "example2.com"); auto& script_src = policies[0]->directives[mojom::CSPDirectiveName::ScriptSrc]; EXPECT_EQ(script_src->sources.size(), 1U); @@ -308,7 +318,11 @@ AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); EXPECT_EQ(1U, policies[0]->directives.size()); + EXPECT_EQ(1U, policies[0]->raw_directives.size()); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.org"); auto& frame_ancestors = policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; EXPECT_EQ(frame_ancestors->sources.size(), 1U); @@ -337,6 +351,7 @@ AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); EXPECT_TRUE(policies[0]->directives.empty()); + EXPECT_TRUE(policies[0]->raw_directives.empty()); EXPECT_EQ(1U, policies[0]->parsing_errors.size()); EXPECT_EQ( @@ -374,7 +389,11 @@ AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); EXPECT_EQ(1U, policies[0]->directives.size()); + EXPECT_EQ(1U, policies[0]->raw_directives.size()); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "object-src"); auto& frame_ancestors = policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; EXPECT_EQ(frame_ancestors->sources.size(), 1U); @@ -405,7 +424,11 @@ AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); EXPECT_EQ(1U, policies[0]->directives.size()); + EXPECT_EQ(1U, policies[0]->raw_directives.size()); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "http://example.org/index.html?a=b"); auto& frame_ancestors = policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; EXPECT_EQ(frame_ancestors->sources.size(), 1U); @@ -437,7 +460,11 @@ AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); EXPECT_EQ(1U, policies[0]->directives.size()); + EXPECT_EQ(1U, policies[0]->raw_directives.size()); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "http://example.org/index.html#a"); auto& frame_ancestors = policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; EXPECT_EQ(frame_ancestors->sources.size(), 1U); @@ -473,6 +500,14 @@ &policies); EXPECT_EQ(2U, policies.size()); + + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.com"); + EXPECT_EQ( + policies[1]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.org"); + auto& frame_ancestors0 = policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; auto& frame_ancestors1 = @@ -509,6 +544,10 @@ &policies); EXPECT_EQ(2U, policies.size()); + EXPECT_EQ( + policies[1]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.org"); + auto& frame_ancestors1 = policies[1]->directives[mojom::CSPDirectiveName::FrameAncestors]; EXPECT_EQ(frame_ancestors1->sources.size(), 1U); @@ -535,6 +574,14 @@ &policies); EXPECT_EQ(2U, policies.size()); + + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.com"); + EXPECT_EQ( + policies[1]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.org"); + auto& frame_ancestors0 = policies[0]->directives[mojom::CSPDirectiveName::FrameAncestors]; auto& frame_ancestors1 = @@ -571,6 +618,10 @@ AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::FrameAncestors], + "example.com"); + auto& report_endpoints = policies[0]->report_endpoints; EXPECT_EQ(report_endpoints.size(), 1U); EXPECT_EQ(report_endpoints[0], "http://example.com/report"); @@ -594,6 +645,8 @@ { std::vector<mojom::ContentSecurityPolicyPtr> policies = ParseCSP("plugin-types application/pdf text/plain invalid a/a/a"); + EXPECT_EQ(policies[0]->raw_directives[mojom::CSPDirectiveName::PluginTypes], + "application/pdf text/plain invalid a/a/a"); EXPECT_EQ(policies[0]->directives.size(), 0u); EXPECT_TRUE(policies[0]->plugin_types.has_value()); EXPECT_EQ(policies[0]->plugin_types.value().size(), 2u); @@ -611,6 +664,8 @@ { std::vector<mojom::ContentSecurityPolicyPtr> policies = ParseCSP("plugin-types ; default-src 'self'"); + EXPECT_EQ(policies[0]->raw_directives[mojom::CSPDirectiveName::PluginTypes], + ""); EXPECT_TRUE(policies[0]->plugin_types.has_value()); EXPECT_EQ(policies[0]->plugin_types.value().size(), 0u); EXPECT_EQ(policies[0]->parsing_errors.size(), 0u); @@ -619,6 +674,8 @@ { std::vector<mojom::ContentSecurityPolicyPtr> policies = ParseCSP("plugin-types 'self' ; default-src 'self'"); + EXPECT_EQ(policies[0]->raw_directives[mojom::CSPDirectiveName::PluginTypes], + "'self'"); EXPECT_TRUE(policies[0]->plugin_types.has_value()); EXPECT_EQ(policies[0]->plugin_types.value().size(), 0u); EXPECT_EQ(policies[0]->parsing_errors.size(), 1u); @@ -641,30 +698,34 @@ network::mojom::CSPRequireTrustedTypesFor expected; } cases[]{ { - "require-trusted-types-for", + "", network::mojom::CSPRequireTrustedTypesFor::None, }, { - "require-trusted-types-for 'script'", + "'script'", network::mojom::CSPRequireTrustedTypesFor::Script, }, { - "require-trusted-types-for 'wasm' 'script'", + "'wasm' 'script'", network::mojom::CSPRequireTrustedTypesFor::Script, }, { - "require-trusted-types-for 'script' 'wasm' 'script'", + "'script' 'wasm' 'script'", network::mojom::CSPRequireTrustedTypesFor::Script, }, { - "require-trusted-types-for 'wasm'", + "'wasm'", network::mojom::CSPRequireTrustedTypesFor::None, }, }; for (const auto& testCase : cases) { - std::vector<mojom::ContentSecurityPolicyPtr> policies = - ParseCSP(testCase.input); + std::vector<mojom::ContentSecurityPolicyPtr> policies = ParseCSP( + base::StringPrintf("require-trusted-types-for %s", testCase.input)); + EXPECT_EQ( + policies[0] + ->raw_directives[mojom::CSPDirectiveName::RequireTrustedTypesFor], + testCase.input); EXPECT_EQ(policies[0]->directives.size(), 0u); EXPECT_EQ(policies[0]->parsing_errors.size(), 0u); EXPECT_EQ(policies[0]->require_trusted_types_for, testCase.expected); @@ -682,6 +743,9 @@ { std::vector<mojom::ContentSecurityPolicyPtr> policies = ParseCSP("trusted-types 'none'"); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::TrustedTypes], + "'none'"); EXPECT_EQ(policies[0]->directives.size(), 0u); EXPECT_TRUE(policies[0]->trusted_types); EXPECT_EQ(policies[0]->trusted_types->list.size(), 0u); @@ -694,6 +758,9 @@ { std::vector<mojom::ContentSecurityPolicyPtr> policies = ParseCSP("trusted-types policy 'none' other_policy@ invalid~policy"); + EXPECT_EQ( + policies[0]->raw_directives[mojom::CSPDirectiveName::TrustedTypes], + "policy 'none' other_policy@ invalid~policy"); EXPECT_EQ(policies[0]->directives.size(), 0u); EXPECT_TRUE(policies[0]->trusted_types); EXPECT_EQ(policies[0]->trusted_types->list.size(), 2u); @@ -1134,6 +1201,8 @@ std::vector<mojom::ContentSecurityPolicyPtr> policies; AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"), &policies); + EXPECT_EQ(policies[0]->raw_directives[mojom::CSPDirectiveName::Sandbox], + "allow-downloads allow-scripts"); EXPECT_EQ(policies[0]->sandbox, ~mojom::WebSandboxFlags::kDownloads & ~mojom::WebSandboxFlags::kScripts & @@ -1306,6 +1375,10 @@ EXPECT_TRUE(test.expected.Run().Equals( policies[0]->directives[mojom::CSPDirectiveName::ScriptSrc])); + EXPECT_EQ(policies[0]->raw_directives[mojom::CSPDirectiveName::ScriptSrc], + base::TrimString(test.directive_value, " ", base::TRIM_ALL) + .as_string()); + if (!test.expected_error.empty()) EXPECT_EQ(test.expected_error, policies[0]->parsing_errors[0]); }
diff --git a/services/network/public/mojom/content_security_policy.mojom b/services/network/public/mojom/content_security_policy.mojom index d8eb9a2..03e4c4c 100644 --- a/services/network/public/mojom/content_security_policy.mojom +++ b/services/network/public/mojom/content_security_policy.mojom
@@ -148,6 +148,10 @@ }; struct ContentSecurityPolicy { + // The raw, unparsed values of the specified CSP directives. Needed for + // reporting. + map<CSPDirectiveName, string> raw_directives; + map<CSPDirectiveName, CSPSourceList> directives; // Spec: https://www.w3.org/TR/upgrade-insecure-requests/
diff --git a/services/network/public/mojom/quic_transport.mojom b/services/network/public/mojom/quic_transport.mojom index e8b4de15..6a62953 100644 --- a/services/network/public/mojom/quic_transport.mojom +++ b/services/network/public/mojom/quic_transport.mojom
@@ -5,6 +5,7 @@ module network.mojom; import "mojo/public/mojom/base/read_only_buffer.mojom"; +import "mojo/public/mojom/base/time.mojom"; import "url/mojom/url.mojom"; // Represents a QuicTransport error. @@ -65,6 +66,10 @@ // Aborts the stream for |stream_id|. AbortStream(uint32 stream_id, uint64 code); + + // Sets the duration which determines whether an outgoing datagram should be + // discarded due to being in the queue for too long. + SetOutgoingDatagramExpirationDuration(mojo_base.mojom.TimeDelta duration); }; // A mojo interface for the client of QuicTransport.
diff --git a/services/network/quic_transport.cc b/services/network/quic_transport.cc index 1b66fce..b752ccb 100644 --- a/services/network/quic_transport.cc +++ b/services/network/quic_transport.cc
@@ -7,9 +7,11 @@ #include "base/auto_reset.h" #include "base/bind.h" #include "base/threading/sequenced_task_runner_handle.h" +#include "base/time/time.h" #include "net/base/io_buffer.h" #include "net/quic/platform/impl/quic_mem_slice_impl.h" #include "net/third_party/quiche/src/quic/core/quic_session.h" +#include "net/third_party/quiche/src/quic/core/quic_time.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice.h" #include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice_span.h" @@ -350,14 +352,14 @@ base::OnceCallback<void(bool)> callback) { DCHECK(!torn_down_); + datagram_callbacks_.emplace(std::move(callback)); + auto buffer = base::MakeRefCounted<net::IOBuffer>(data.size()); memcpy(buffer->data(), data.data(), data.size()); quic::QuicMemSlice slice( quic::QuicMemSliceImpl(std::move(buffer), data.size())); - const quic::MessageStatus status = - transport_->session()->datagram_queue()->SendOrQueueDatagram( - std::move(slice)); - std::move(callback).Run(status == quic::MESSAGE_STATUS_SUCCESS); + transport_->session()->datagram_queue()->SendOrQueueDatagram( + std::move(slice)); } void QuicTransport::CreateStream( @@ -445,6 +447,16 @@ it->second->Abort(code_to_pass); } +void QuicTransport::SetOutgoingDatagramExpirationDuration( + base::TimeDelta duration) { + if (torn_down_) { + return; + } + + transport_->session()->datagram_queue()->SetMaxTimeInQueue( + quic::QuicTime::Delta::FromMicroseconds(duration.InMicroseconds())); +} + void QuicTransport::OnConnected() { if (torn_down_) { return; @@ -588,7 +600,11 @@ void QuicTransport::OnDatagramProcessed( base::Optional<quic::MessageStatus> status) { - // TODO(yhirano): Implement this. + DCHECK(!datagram_callbacks_.empty()); + + std::move(datagram_callbacks_.front()) + .Run(status == quic::MESSAGE_STATUS_SUCCESS); + datagram_callbacks_.pop(); } void QuicTransport::TearDown() {
diff --git a/services/network/quic_transport.h b/services/network/quic_transport.h index 5f630b14..50cbbaa 100644 --- a/services/network/quic_transport.h +++ b/services/network/quic_transport.h
@@ -66,6 +66,7 @@ UnidirectionalStreamAcceptanceCallback callback) override; void SendFin(uint32_t stream_id) override; void AbortStream(uint32_t stream_id, uint64_t code) override; + void SetOutgoingDatagramExpirationDuration(base::TimeDelta duration) override; // net::QuicTransportClient::Visitor implementation: void OnConnected() override; @@ -100,6 +101,7 @@ mojo::Receiver<mojom::QuicTransport> receiver_; mojo::Remote<mojom::QuicTransportHandshakeClient> handshake_client_; mojo::Remote<mojom::QuicTransportClient> client_; + base::queue<base::OnceCallback<void(bool)>> datagram_callbacks_; bool torn_down_ = false;
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 6d8ab83..356eb02 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -5189,6 +5189,27 @@ ] } ], + "PartitionAllocGigaCage32bit": [ + { + "platforms": [ + "android", + "android_webview", + "chromeos", + "ios", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "PartitionAllocGigaCage32bit" + ] + } + ] + } + ], "PartitionConnectionsByNetworkIsolationKey": [ { "platforms": [ @@ -7313,6 +7334,26 @@ ] } ], + "VerifyHTMLFetchedFromAppCacheBeforeDelay": [ + { + "platforms": [ + "windows", + "mac", + "chromeos", + "linux", + "ios", + "android" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "VerifyHTMLFetchedFromAppCacheBeforeDelay" + ] + } + ] + } + ], "VideoToolboxVp9Decoding": [ { "platforms": [
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index 3551de5..d38b552 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -2453,7 +2453,7 @@ kWebkitBoxPackCenterDoesSomething = 3124, kWebkitBoxPackEndDoesSomething = 3125, kV8KeyframeEffect_Constructor = 3126, - kWebNfcAPI = 3127, + kOBSOLETE_WebNfcAPI = 3127, kHostCandidateAttributeGetter = 3128, kCSPWithReasonableObjectRestrictions = 3129, kCSPWithReasonableBaseRestrictions = 3130,
diff --git a/third_party/blink/public/platform/web_content_security_policy_struct.h b/third_party/blink/public/platform/web_content_security_policy_struct.h index 7a63177..d4d20a59 100644 --- a/third_party/blink/public/platform/web_content_security_policy_struct.h +++ b/third_party/blink/public/platform/web_content_security_policy_struct.h
@@ -73,6 +73,13 @@ // TODO(arthursonzogni): Remove this when BeginNavigation will be sent directly // from blink. +struct WebContentSecurityPolicyRawDirective { + WebString name; + WebString value; +}; + +// TODO(arthursonzogni): Remove this when BeginNavigation will be sent directly +// from blink. struct WebCSPTrustedTypes { WebVector<WebString> list; bool allow_any; @@ -84,6 +91,7 @@ struct WebContentSecurityPolicy { network::mojom::ContentSecurityPolicyType disposition; network::mojom::ContentSecurityPolicySource source; + WebVector<WebContentSecurityPolicyRawDirective> raw_directives; WebVector<WebContentSecurityPolicyDirective> directives; bool upgrade_insecure_requests; bool block_all_mixed_content;
diff --git a/third_party/blink/renderer/bindings/generated_in_modules.gni b/third_party/blink/renderer/bindings/generated_in_modules.gni index 60a061c..b2e36a7 100644 --- a/third_party/blink/renderer/bindings/generated_in_modules.gni +++ b/third_party/blink/renderer/bindings/generated_in_modules.gni
@@ -1741,8 +1741,6 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_ndef_reading_event.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_ndef_record.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_ndef_record.h", - "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_ndef_writer.cc", - "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_ndef_writer.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_network_information.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_network_information.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_notification.cc",
diff --git a/third_party/blink/renderer/bindings/idl_in_modules.gni b/third_party/blink/renderer/bindings/idl_in_modules.gni index 035f30a7..520b3df 100644 --- a/third_party/blink/renderer/bindings/idl_in_modules.gni +++ b/third_party/blink/renderer/bindings/idl_in_modules.gni
@@ -415,7 +415,6 @@ "//third_party/blink/renderer/modules/nfc/ndef_record_init.idl", "//third_party/blink/renderer/modules/nfc/ndef_scan_options.idl", "//third_party/blink/renderer/modules/nfc/ndef_write_options.idl", - "//third_party/blink/renderer/modules/nfc/ndef_writer.idl", "//third_party/blink/renderer/modules/notifications/get_notification_options.idl", "//third_party/blink/renderer/modules/notifications/notification.idl", "//third_party/blink/renderer/modules/notifications/notification_action.idl",
diff --git a/third_party/blink/renderer/bindings/scripts/bind_gen/blink_v8_bridge.py b/third_party/blink/renderer/bindings/scripts/bind_gen/blink_v8_bridge.py index e190f71..147e2d13 100644 --- a/third_party/blink/renderer/bindings/scripts/bind_gen/blink_v8_bridge.py +++ b/third_party/blink/renderer/bindings/scripts/bind_gen/blink_v8_bridge.py
@@ -49,17 +49,19 @@ return "V8{}".format(idl_definition.identifier) -def blink_type_info(idl_type): +def blink_type_info(idl_type, use_new_union=False): """ Returns the types of Blink implementation corresponding to the given IDL type. The returned object has the following attributes. - member_t: The type of a member variable. E.g. T => Member<T> ref_t: The type of a local variable that references to an already-existing value. E.g. String => String& const_ref_t: A const-qualified reference type. value_t: The type of a variable that behaves as a value. E.g. String => String + member_t: The type of a member variable. E.g. T => Member<T> + member_ref_t: The type used for input to and output from a member + variable. E.g. T* for Member<T> and const String& for String. has_null_value: True if the Blink implementation type can represent IDL null value by itself without use of base::Optional<T>. """ @@ -72,28 +74,38 @@ ref_fmt="{}", const_ref_fmt="const {}", value_fmt="{}", - has_null_value=False): + has_null_value=False, + clear_member_var_fmt="{}.Clear()"): self.typename = typename - self.member_t = member_fmt.format(typename) + self.is_gc_type = is_gc_type(idl_type) self.ref_t = ref_fmt.format(typename) self.const_ref_t = const_ref_fmt.format(typename) self.value_t = value_fmt.format(typename) - # Whether Blink impl type can represent IDL null or not. + self.member_t = member_fmt.format(typename) + self.member_ref_t = (self.ref_t + if self.is_gc_type else self.const_ref_t) self.has_null_value = has_null_value + self._clear_member_var_fmt = clear_member_var_fmt + + def clear_member_var_expr(self, var_name): + """Returns an expression to reset the given member variable.""" + return self._clear_member_var_fmt.format(var_name) def is_gc_type(idl_type): idl_type = idl_type.unwrap() - return bool(idl_type.type_definition_object - and not idl_type.is_enumeration) + return bool( + idl_type.is_buffer_source_type or + (idl_type.type_definition_object and not idl_type.is_enumeration) + or (idl_type.new_union_definition_object and use_new_union)) def vector_element_type(idl_type): - # Add |Member<T>| explicitly so that the complete type definition of + # Use |Member<T>| explicitly so that the complete type definition of # |T| will not be required. - typename = blink_type_info(idl_type).typename - if is_gc_type(idl_type): - return "Member<{}>".format(typename) + type_info = blink_type_info(idl_type) + if type_info.is_gc_type: + return type_info.member_t else: - return typename + return type_info.typename real_type = idl_type.unwrap(typedef=True) @@ -113,15 +125,16 @@ "double": "double", "unrestricted double": "double", } - return TypeInfo( - cxx_type[real_type.keyword_typename], const_ref_fmt="{}") + return TypeInfo(cxx_type[real_type.keyword_typename], + const_ref_fmt="{}", + clear_member_var_fmt="{} = 0") if real_type.is_string: - return TypeInfo( - "String", - ref_fmt="{}&", - const_ref_fmt="const {}&", - has_null_value=True) + return TypeInfo("String", + ref_fmt="{}&", + const_ref_fmt="const {}&", + has_null_value=True, + clear_member_var_fmt="{} = String()") if real_type.is_array_buffer: assert "AllowShared" not in real_type.extended_attributes @@ -168,7 +181,7 @@ if real_type.type_definition_object: blink_impl_type = blink_class_name(real_type.type_definition_object) if real_type.is_enumeration: - return TypeInfo(blink_impl_type) + return TypeInfo(blink_impl_type, clear_member_var_fmt="") return TypeInfo( blink_impl_type, member_fmt="Member<{}>", @@ -181,18 +194,34 @@ or real_type.is_variadic): typename = "VectorOf<{}>".format( vector_element_type(real_type.element_type)) - return TypeInfo(typename, ref_fmt="{}&", const_ref_fmt="const {}&") + return TypeInfo(typename, + ref_fmt="{}&", + const_ref_fmt="const {}&", + clear_member_var_fmt="{}.clear()") if real_type.is_record: typename = "VectorOfPairs<{}, {}>".format( vector_element_type(real_type.key_type), vector_element_type(real_type.value_type)) - return TypeInfo(typename, ref_fmt="{}&", const_ref_fmt="const {}&") + return TypeInfo(typename, + ref_fmt="{}&", + const_ref_fmt="const {}&", + clear_member_var_fmt="{}.clear()") if real_type.is_promise: return TypeInfo( "ScriptPromise", ref_fmt="{}&", const_ref_fmt="const {}&") + if real_type.is_union and use_new_union: + blink_impl_type = blink_class_name( + real_type.new_union_definition_object) + return TypeInfo(blink_impl_type, + member_fmt="Member<{}>", + ref_fmt="{}*", + const_ref_fmt="const {}*", + value_fmt="{}*", + has_null_value=False) + if real_type.is_union: blink_impl_type = blink_class_name(real_type.union_definition_object) return TypeInfo( @@ -205,10 +234,10 @@ inner_type = blink_type_info(real_type.inner_type) if inner_type.has_null_value: return inner_type - return TypeInfo( - "base::Optional<{}>".format(inner_type.value_t), - ref_fmt="{}&", - const_ref_fmt="const {}&") + return TypeInfo("base::Optional<{}>".format(inner_type.value_t), + ref_fmt="{}&", + const_ref_fmt="const {}&", + clear_member_var_fmt="{}.reset()") assert False, "Unknown type: {}".format(idl_type.syntactic_form)
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_type.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_type.py index 5776c2c..a11a473 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/idl_type.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_type.py
@@ -562,6 +562,10 @@ return None @property + def new_union_definition_object(self): + return None + + @property def union_definition_object(self): """ Returns an object that represents an union or None. @@ -1149,6 +1153,7 @@ debug_info=debug_info, pass_key=pass_key) self._member_types = tuple(member_types) + self._new_union_definition_object = None self._union_definition_object = None def __eq__(self, other): @@ -1223,6 +1228,17 @@ return set(flatten(self)) @property + def new_union_definition_object(self): + return self._new_union_definition_object + + def set_new_union_definition_object(self, union_definition_object): + # In Python2, we need to avoid circular imports. + from .union import NewUnion + assert isinstance(union_definition_object, NewUnion) + assert self._new_union_definition_object is None + self._new_union_definition_object = union_definition_object + + @property def union_definition_object(self): return self._union_definition_object
diff --git a/third_party/blink/renderer/core/css/css_font_selector.cc b/third_party/blink/renderer/core/css/css_font_selector.cc index 3269f58e..7701420 100644 --- a/third_party/blink/renderer/core/css/css_font_selector.cc +++ b/third_party/blink/renderer/core/css/css_font_selector.cc
@@ -46,18 +46,18 @@ namespace blink { -CSSFontSelector::CSSFontSelector(Document* document) - : document_(document), - generic_font_family_settings_( - document->GetFrame()->GetSettings()->GetGenericFontFamilySettings()) { - // FIXME: An old comment used to say there was no need to hold a reference to - // document_ because "we are guaranteed to be destroyed before the document". - // But there does not seem to be any such guarantee. - DCHECK(document_); - DCHECK(document_->GetFrame()); +CSSFontSelector::CSSFontSelector(const TreeScope& tree_scope) + : tree_scope_(&tree_scope), + generic_font_family_settings_(tree_scope.GetDocument() + .GetFrame() + ->GetSettings() + ->GetGenericFontFamilySettings()) { + DCHECK(tree_scope.GetDocument().GetFrame()); FontCache::GetFontCache()->AddClient(this); - FontFaceSetDocument::From(*document)->AddFontFacesToFontFaceCache( - &font_face_cache_); + if (tree_scope.RootNode().IsDocumentNode()) { + FontFaceSetDocument::From(tree_scope.GetDocument()) + ->AddFontFacesToFontFaceCache(&font_face_cache_); + } } CSSFontSelector::~CSSFontSelector() = default; @@ -97,13 +97,14 @@ scoped_refptr<FontData> CSSFontSelector::GetFontData( const FontDescription& font_description, const AtomicString& family_name) { + Document& document = GetTreeScope()->GetDocument(); if (CSSSegmentedFontFace* face = font_face_cache_.Get(font_description, family_name)) { - document_->GetFontMatchingMetrics()->ReportWebFontFamily(family_name); + document.GetFontMatchingMetrics()->ReportWebFontFamily(family_name); return face->GetFontData(font_description); } - document_->GetFontMatchingMetrics()->ReportSystemFontFamily(family_name); + document.GetFontMatchingMetrics()->ReportSystemFontFamily(family_name); // Try to return the correct font based off our settings, in case we were // handed the generic font family name. @@ -112,7 +113,7 @@ if (settings_family_name.IsEmpty()) return nullptr; - document_->GetFontMatchingMetrics()->ReportFontFamilyLookupByGenericFamily( + document.GetFontMatchingMetrics()->ReportFontFamilyLookupByGenericFamily( family_name, font_description.GetScript(), font_description.GenericFamily(), settings_family_name); @@ -120,7 +121,7 @@ FontCache::GetFontCache()->GetFontData(font_description, settings_family_name); - document_->GetFontMatchingMetrics()->ReportFontLookupByUniqueOrFamilyName( + document.GetFontMatchingMetrics()->ReportFontLookupByUniqueOrFamilyName( settings_family_name, font_description, font_data.get()); return font_data; @@ -162,43 +163,37 @@ } void CSSFontSelector::ReportNotDefGlyph() const { - DCHECK(document_); - UseCounter::Count(document_, WebFeature::kFontShapingNotDefGlyphObserved); + UseCounter::Count(GetDocument(), WebFeature::kFontShapingNotDefGlyphObserved); } void CSSFontSelector::ReportSuccessfulFontFamilyMatch( const AtomicString& font_family_name) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportSuccessfulFontFamilyMatch( + GetDocument().GetFontMatchingMetrics()->ReportSuccessfulFontFamilyMatch( font_family_name); } void CSSFontSelector::ReportFailedFontFamilyMatch( const AtomicString& font_family_name) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportFailedFontFamilyMatch( + GetDocument().GetFontMatchingMetrics()->ReportFailedFontFamilyMatch( font_family_name); } void CSSFontSelector::ReportSuccessfulLocalFontMatch( const AtomicString& font_name) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportSuccessfulLocalFontMatch( + GetDocument().GetFontMatchingMetrics()->ReportSuccessfulLocalFontMatch( font_name); } void CSSFontSelector::ReportFailedLocalFontMatch( const AtomicString& font_name) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportFailedLocalFontMatch(font_name); + GetDocument().GetFontMatchingMetrics()->ReportFailedLocalFontMatch(font_name); } void CSSFontSelector::ReportFontLookupByUniqueOrFamilyName( const AtomicString& name, const FontDescription& font_description, SimpleFontData* resulting_font_data) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportFontLookupByUniqueOrFamilyName( + GetDocument().GetFontMatchingMetrics()->ReportFontLookupByUniqueOrFamilyName( name, font_description, resulting_font_data); } @@ -207,8 +202,7 @@ const FontDescription& font_description, SimpleFontData* resulting_font_data, bool is_loading_fallback) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportFontLookupByUniqueNameOnly( + GetDocument().GetFontMatchingMetrics()->ReportFontLookupByUniqueNameOnly( name, font_description, resulting_font_data, is_loading_fallback); } @@ -217,8 +211,7 @@ FontFallbackPriority fallback_priority, const FontDescription& font_description, SimpleFontData* resulting_font_data) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportFontLookupByFallbackCharacter( + GetDocument().GetFontMatchingMetrics()->ReportFontLookupByFallbackCharacter( fallback_character, fallback_priority, font_description, resulting_font_data); } @@ -226,13 +219,12 @@ void CSSFontSelector::ReportLastResortFallbackFontLookup( const FontDescription& font_description, SimpleFontData* resulting_font_data) { - DCHECK(document_); - document_->GetFontMatchingMetrics()->ReportLastResortFallbackFontLookup( + GetDocument().GetFontMatchingMetrics()->ReportLastResortFallbackFontLookup( font_description, resulting_font_data); } void CSSFontSelector::Trace(Visitor* visitor) const { - visitor->Trace(document_); + visitor->Trace(tree_scope_); visitor->Trace(font_face_cache_); visitor->Trace(clients_); FontSelector::Trace(visitor);
diff --git a/third_party/blink/renderer/core/css/css_font_selector.h b/third_party/blink/renderer/core/css/css_font_selector.h index 47c57645..0744fce 100644 --- a/third_party/blink/renderer/core/css/css_font_selector.h +++ b/third_party/blink/renderer/core/css/css_font_selector.h
@@ -42,7 +42,7 @@ class CORE_EXPORT CSSFontSelector : public FontSelector { public: - explicit CSSFontSelector(Document*); + explicit CSSFontSelector(const TreeScope&); ~CSSFontSelector() override; unsigned Version() const override { return font_face_cache_.Version(); } @@ -100,7 +100,7 @@ void UnregisterForInvalidationCallbacks(FontSelectorClient*) override; ExecutionContext* GetExecutionContext() const override { - return document_ ? document_->GetExecutionContext() : nullptr; + return tree_scope_ ? GetDocument().GetExecutionContext() : nullptr; } FontFaceCache* GetFontFaceCache() override { return &font_face_cache_; } @@ -109,7 +109,11 @@ } void UpdateGenericFontFamilySettings(Document&); - const TreeScope* GetTreeScope() const { return document_; } + const TreeScope* GetTreeScope() const { return tree_scope_; } + Document& GetDocument() const { + DCHECK(tree_scope_); + return tree_scope_->GetDocument(); + } void Trace(Visitor*) const override; @@ -120,7 +124,7 @@ // TODO(Oilpan): Ideally this should just be a traced Member but that will // currently leak because ComputedStyle and its data are not on the heap. // See crbug.com/383860 for details. - WeakMember<Document> document_; + WeakMember<const TreeScope> tree_scope_; // TODO(futhark): Make this a Member which can be shared between scopes // sharing the same set of @font-faces. FontFaceCache font_face_cache_;
diff --git a/third_party/blink/renderer/core/css/style_engine.cc b/third_party/blink/renderer/core/css/style_engine.cc index 494fb9a..cd498e84 100644 --- a/third_party/blink/renderer/core/css/style_engine.cc +++ b/third_party/blink/renderer/core/css/style_engine.cc
@@ -100,10 +100,9 @@ CSSFontSelector* CreateCSSFontSelectorFor(Document& document) { DCHECK(document.GetFrame()); - if (UNLIKELY(document.GetFrame()->PagePopupOwner())) { + if (UNLIKELY(document.GetFrame()->PagePopupOwner())) return PagePopupController::CreateCSSFontSelector(document); - } - return MakeGarbageCollected<CSSFontSelector>(&document); + return MakeGarbageCollected<CSSFontSelector>(document); } } // namespace
diff --git a/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc b/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc index 9600c06..926510d9 100644 --- a/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc +++ b/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc
@@ -338,15 +338,15 @@ Node* outer_div = GetDocument().getElementById("outer"); Node* span_in_shadow = shadow_root->firstChild(); Position start = Position::FirstPositionInNode(*span_in_shadow); - Position end(outer_div, PositionAnchorType::kAfterChildren); + Position end = Position::LastPositionInNode(*outer_div); EXPECT_EQ( "[ shadow][text][ iterator.]", IteratePartial<DOMTree>(start, end, EntersOpenShadowRootsBehavior())); PositionInFlatTree start_in_flat_tree = PositionInFlatTree::FirstPositionInNode(*span_in_shadow); - PositionInFlatTree end_in_flat_tree(outer_div, - PositionAnchorType::kAfterChildren); + PositionInFlatTree end_in_flat_tree = + PositionInFlatTree::LastPositionInNode(*outer_div); EXPECT_EQ("[text][ shadow][ iterator.]", IteratePartial<FlatTree>(start_in_flat_tree, end_in_flat_tree, EntersOpenShadowRootsBehavior())); @@ -363,15 +363,15 @@ Node* outer_div = GetDocument().getElementById("outer"); Node* span_in_shadow = shadow_root->firstChild(); Position start = Position::FirstPositionInNode(*outer_div); - Position end(span_in_shadow, PositionAnchorType::kAfterChildren); + Position end = Position::LastPositionInNode(*span_in_shadow); EXPECT_EQ( "[Hello, ][ shadow]", IteratePartial<DOMTree>(start, end, EntersOpenShadowRootsBehavior())); PositionInFlatTree start_in_flat_tree = PositionInFlatTree::FirstPositionInNode(*outer_div); - PositionInFlatTree end_in_flat_tree(span_in_shadow, - PositionAnchorType::kAfterChildren); + PositionInFlatTree end_in_flat_tree = + PositionInFlatTree::LastPositionInNode(*span_in_shadow); EXPECT_EQ("[Hello, ][text][ shadow]", IteratePartial<FlatTree>(start_in_flat_tree, end_in_flat_tree, EntersOpenShadowRootsBehavior()));
diff --git a/third_party/blink/renderer/core/editing/local_caret_rect_test.cc b/third_party/blink/renderer/core/editing/local_caret_rect_test.cc index 03a54014..75ea6e41 100644 --- a/third_party/blink/renderer/core/editing/local_caret_rect_test.cc +++ b/third_party/blink/renderer/core/editing/local_caret_rect_test.cc
@@ -782,9 +782,9 @@ // TODO(yoichio): Following should return valid rect: crbug.com/812535. EXPECT_EQ( LocalCaretRect(first_span->GetLayoutObject(), PhysicalRect(0, 0, 0, 0)), - LocalCaretRectOfPosition(PositionWithAffinity( - Position(first_span, PositionAnchorType::kAfterChildren), - TextAffinity::kDownstream))); + LocalCaretRectOfPosition( + PositionWithAffinity(Position::LastPositionInNode(*first_span), + TextAffinity::kDownstream))); EXPECT_EQ(LayoutNGEnabled() ? LocalCaretRect(foo->GetLayoutObject(), PhysicalRect(30, 0, 1, 10)) : LocalCaretRect(white_spaces->GetLayoutObject(), @@ -832,9 +832,8 @@ SetBodyContent("<div>foo<img></div>"); Node* node = GetDocument().QuerySelector("img"); - IntRect rect = - AbsoluteSelectionBoundsOf(VisiblePosition::Create(PositionWithAffinity( - Position(node, PositionAnchorType::kAfterChildren)))); + IntRect rect = AbsoluteSelectionBoundsOf(VisiblePosition::Create( + PositionWithAffinity(Position::LastPositionInNode(*node)))); EXPECT_FALSE(rect.IsEmpty()); }
diff --git a/third_party/blink/renderer/core/editing/position.cc b/third_party/blink/renderer/core/editing/position.cc index ffa65eb4..1a98cb7 100644 --- a/third_party/blink/renderer/core/editing/position.cc +++ b/third_party/blink/renderer/core/editing/position.cc
@@ -600,10 +600,11 @@ int offset = pos.ComputeOffsetInContainerNode(); Node* child = NodeTraversal::ChildAt(*anchor, offset); if (!child) { - if (anchor->IsShadowRoot()) - return PositionInFlatTree(anchor->OwnerShadowHost(), - PositionAnchorType::kAfterChildren); - return PositionInFlatTree(anchor, PositionAnchorType::kAfterChildren); + if (anchor->IsShadowRoot()) { + return PositionInFlatTree::LastPositionInNode( + *anchor->OwnerShadowHost()); + } + return PositionInFlatTree::LastPositionInNode(*anchor); } child->UpdateDistributionForFlatTreeTraversal(); if (!child->CanParticipateInFlatTree()) { @@ -616,10 +617,10 @@ // When |pos| isn't appeared in flat tree, we map |pos| to after // children of shadow host. // e.g. "foo",0 in <progress>foo</progress> - if (anchor->IsShadowRoot()) - return PositionInFlatTree(anchor->OwnerShadowHost(), - PositionAnchorType::kAfterChildren); - return PositionInFlatTree(anchor, PositionAnchorType::kAfterChildren); + if (anchor->IsShadowRoot()) { + return PositionInFlatTree::LastPositionInNode(*anchor->OwnerShadowHost()); + } + return PositionInFlatTree::LastPositionInNode(*anchor); } if (anchor->IsShadowRoot()) @@ -656,7 +657,7 @@ switch (position.AnchorType()) { case PositionAnchorType::kAfterChildren: // FIXME: When anchorNode is <img>, assertion fails in the constructor. - return Position(anchor_node, PositionAnchorType::kAfterChildren); + return Position::LastPositionInNode(*anchor_node); case PositionAnchorType::kAfterAnchor: return Position::AfterNode(*anchor_node); case PositionAnchorType::kBeforeChildren: @@ -675,7 +676,7 @@ // |child| is null when the position is at the end of the children. // <div>foo|</div> - return Position(anchor_node, PositionAnchorType::kAfterChildren); + return Position::LastPositionInNode(*anchor_node); } default: NOTREACHED();
diff --git a/third_party/blink/renderer/core/editing/position_test.cc b/third_party/blink/renderer/core/editing/position_test.cc index 58f0a6f8..cc76c3c 100644 --- a/third_party/blink/renderer/core/editing/position_test.cc +++ b/third_party/blink/renderer/core/editing/position_test.cc
@@ -160,7 +160,7 @@ ToPositionInFlatTree(Position(anchor, 0))); EXPECT_EQ(PositionInFlatTree(anchor, 1), ToPositionInFlatTree(Position(anchor, 1))); - EXPECT_EQ(PositionInFlatTree(anchor, PositionAnchorType::kAfterChildren), + EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*anchor), ToPositionInFlatTree(Position(anchor, 2))); } @@ -171,7 +171,7 @@ EXPECT_EQ(PositionInFlatTree(anchor, 0), ToPositionInFlatTree(Position(anchor, 0))); - EXPECT_EQ(PositionInFlatTree(anchor, PositionAnchorType::kAfterChildren), + EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*anchor), ToPositionInFlatTree(Position(anchor, 1))); } @@ -180,7 +180,7 @@ SetBodyContent("<progress id=sample>foo</progress>"); Element* sample = GetDocument().getElementById("sample"); - EXPECT_EQ(PositionInFlatTree(sample, PositionAnchorType::kAfterChildren), + EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*sample), ToPositionInFlatTree(Position(sample, 0))); } @@ -193,11 +193,10 @@ EXPECT_EQ(PositionInFlatTree(host, 0), ToPositionInFlatTree(Position(shadow_root, 0))); - EXPECT_EQ(PositionInFlatTree(host, PositionAnchorType::kAfterChildren), + EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*host), ToPositionInFlatTree(Position(shadow_root, 1))); - EXPECT_EQ(PositionInFlatTree(host, PositionAnchorType::kAfterChildren), - ToPositionInFlatTree( - Position(shadow_root, PositionAnchorType::kAfterChildren))); + EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*host), + ToPositionInFlatTree(Position::LastPositionInNode(*shadow_root))); EXPECT_EQ(PositionInFlatTree::FirstPositionInNode(*host), ToPositionInFlatTree(Position::FirstPositionInNode(*shadow_root))); } @@ -212,7 +211,7 @@ EXPECT_EQ(PositionInFlatTree(host, 0), ToPositionInFlatTree(Position(shadow_root, 0))); - EXPECT_EQ(PositionInFlatTree(host, PositionAnchorType::kAfterChildren), + EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*host), ToPositionInFlatTree(Position(shadow_root, 1))); } @@ -223,7 +222,7 @@ ShadowRoot* shadow_root = SetShadowContent(shadow_content, "host"); Element* host = GetDocument().getElementById("host"); - EXPECT_EQ(PositionInFlatTree(host, PositionAnchorType::kAfterChildren), + EXPECT_EQ(PositionInFlatTree::LastPositionInNode(*host), ToPositionInFlatTree(Position(shadow_root, 0))); }
diff --git a/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc b/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc index 406d49bce..cb30fb0a 100644 --- a/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc +++ b/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc
@@ -46,8 +46,8 @@ const CreateMarkupOptions& options) { PositionTemplate<Strategy> start = PositionTemplate<Strategy>::FirstPositionInNode(*GetDocument().body()); - PositionTemplate<Strategy> end = PositionTemplate<Strategy>( - GetDocument().body(), PositionAnchorType::kAfterChildren); + PositionTemplate<Strategy> end = + PositionTemplate<Strategy>::LastPositionInNode(*GetDocument().body()); return CreateMarkup(start, end, options).Utf8(); }
diff --git a/third_party/blink/renderer/core/execution_context/execution_context.cc b/third_party/blink/renderer/core/execution_context/execution_context.cc index c7398cb..644537a 100644 --- a/third_party/blink/renderer/core/execution_context/execution_context.cc +++ b/third_party/blink/renderer/core/execution_context/execution_context.cc
@@ -115,6 +115,10 @@ return ToExecutionContext(ctx); } +void ExecutionContext::SetIsInBackForwardCache(bool value) { + is_in_back_forward_cache_ = value; +} + void ExecutionContext::SetLifecycleState(mojom::FrameLifecycleState state) { if (lifecycle_state_ == state) return; @@ -234,9 +238,11 @@ } WebURLLoader::DeferType ExecutionContext::DeferType() const { - if (lifecycle_state_ == mojom::blink::FrameLifecycleState::kFrozen) { + if (is_in_back_forward_cache_) { + DCHECK_EQ(lifecycle_state_, mojom::blink::FrameLifecycleState::kFrozen); return WebURLLoader::DeferType::kDeferredWithBackForwardCache; - } else if (lifecycle_state_ == mojom::blink::FrameLifecycleState::kPaused) { + } else if (lifecycle_state_ == mojom::blink::FrameLifecycleState::kFrozen || + lifecycle_state_ == mojom::blink::FrameLifecycleState::kPaused) { return WebURLLoader::DeferType::kDeferred; } return WebURLLoader::DeferType::kNotDeferred;
diff --git a/third_party/blink/renderer/core/execution_context/execution_context.h b/third_party/blink/renderer/core/execution_context/execution_context.h index c1dcadaf..64c0cf8 100644 --- a/third_party/blink/renderer/core/execution_context/execution_context.h +++ b/third_party/blink/renderer/core/execution_context/execution_context.h
@@ -232,6 +232,7 @@ virtual void RemoveURLFromMemoryCache(const KURL&); + void SetIsInBackForwardCache(bool); void SetLifecycleState(mojom::FrameLifecycleState); void NotifyContextDestroyed(); @@ -450,6 +451,8 @@ mojom::FrameLifecycleState lifecycle_state_; bool is_context_destroyed_; + bool is_in_back_forward_cache_ = false; + Member<PublicURLManager> public_url_manager_; const Member<ContentSecurityPolicyDelegate> csp_delegate_;
diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc index f9be9194..2c39109e 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc
@@ -2209,7 +2209,7 @@ mojom::blink::ReportingServiceProxy* LocalFrame::GetReportingService() { if (!reporting_service_.is_bound()) { - Platform::Current()->GetBrowserInterfaceBroker()->GetInterface( + GetBrowserInterfaceBroker().GetInterface( reporting_service_.BindNewPipeAndPassReceiver( GetTaskRunner(blink::TaskType::kInternalDefault))); } @@ -2398,6 +2398,10 @@ performance_manager::mojom::LifecycleState::kFrozen); } + if (GetPage()->GetPageScheduler()->IsInBackForwardCache()) { + DomWindow()->SetIsInBackForwardCache(true); + } + WebURLLoader::DeferType defer = GetPage()->GetPageScheduler()->IsInBackForwardCache() ? WebURLLoader::DeferType::kDeferredWithBackForwardCache @@ -2425,6 +2429,8 @@ GetDocument()->Fetcher()->SetDefersLoading( WebURLLoader::DeferType::kNotDeferred); Loader().SetDefersLoading(WebURLLoader::DeferType::kNotDeferred); + + DomWindow()->SetIsInBackForwardCache(false); } void LocalFrame::MaybeLogAdClickNavigation() {
diff --git a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc index 28e4f17..d489dbbf 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc +++ b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc
@@ -277,8 +277,17 @@ ConvertToPublic(std::move(directive.value))}; } + WebVector<WebContentSecurityPolicyRawDirective> raw_directives( + policy->raw_directives.size()); + i = 0; + for (auto& directive : policy->raw_directives) { + raw_directives[i++] = {ConvertToPublic(directive.key), + std::move(directive.value)}; + } + return {policy->header->type, policy->header->source, + std::move(raw_directives), std::move(directives), policy->upgrade_insecure_requests, policy->block_all_mixed_content,
diff --git a/third_party/blink/renderer/core/frame/reporting_context.cc b/third_party/blink/renderer/core/frame/reporting_context.cc index 18940eb..53ff9082de2 100644 --- a/third_party/blink/renderer/core/frame/reporting_context.cc +++ b/third_party/blink/renderer/core/frame/reporting_context.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/frame/reporting_context.h" +#include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" @@ -143,7 +144,7 @@ const HeapMojoRemote<mojom::blink::ReportingServiceProxy>& ReportingContext::GetReportingService() const { if (!reporting_service_.is_bound()) { - Platform::Current()->GetBrowserInterfaceBroker()->GetInterface( + execution_context_->GetBrowserInterfaceBroker().GetInterface( reporting_service_.BindNewPipeAndPassReceiver( execution_context_->GetTaskRunner(TaskType::kMiscPlatformAPI))); }
diff --git a/third_party/blink/renderer/core/frame/reporting_context_test.cc b/third_party/blink/renderer/core/frame/reporting_context_test.cc index 7ae687c38..3dc9aaf 100644 --- a/third_party/blink/renderer/core/frame/reporting_context_test.cc +++ b/third_party/blink/renderer/core/frame/reporting_context_test.cc
@@ -5,7 +5,7 @@ #include "third_party/blink/renderer/core/frame/reporting_context.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h" +#include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/renderer/core/frame/deprecation_report_body.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/report.h" @@ -28,7 +28,7 @@ using ReportingServiceProxy = mojom::blink::ReportingServiceProxy; public: - MockReportingServiceProxy(ThreadSafeBrowserInterfaceBrokerProxy& broker, + MockReportingServiceProxy(BrowserInterfaceBrokerProxy& broker, base::OnceClosure reached_callback) : broker_(broker), reached_callback_(std::move(reached_callback)) { broker.SetBinderForTesting( @@ -114,7 +114,7 @@ std::move(reached_callback_).Run(); } - ThreadSafeBrowserInterfaceBrokerProxy& broker_; + BrowserInterfaceBrokerProxy& broker_; mojo::ReceiverSet<ReportingServiceProxy> receivers_; base::OnceClosure reached_callback_; @@ -146,9 +146,8 @@ auto dummy_page_holder = std::make_unique<DummyPageHolder>(); auto* win = dummy_page_holder->GetFrame().DomWindow(); base::RunLoop run_loop; - MockReportingServiceProxy reporting_service( - *Platform::Current()->GetBrowserInterfaceBroker(), - run_loop.QuitClosure()); + MockReportingServiceProxy reporting_service(win->GetBrowserInterfaceBroker(), + run_loop.QuitClosure()); auto* body = MakeGarbageCollected<DeprecationReportBody>( "FeatureId", base::Time::FromJsTime(1000), "Test report");
diff --git a/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc b/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc index ec97640..3c4a5f7 100644 --- a/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc +++ b/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc
@@ -99,7 +99,7 @@ class PopupMenuCSSFontSelector : public CSSFontSelector, private FontSelectorClient { public: - PopupMenuCSSFontSelector(Document*, CSSFontSelector*); + PopupMenuCSSFontSelector(Document&, CSSFontSelector*); ~PopupMenuCSSFontSelector() override; // We don't override willUseFontData() for now because the old PopupListBox @@ -116,7 +116,7 @@ }; PopupMenuCSSFontSelector::PopupMenuCSSFontSelector( - Document* document, + Document& document, CSSFontSelector* owner_font_selector) : CSSFontSelector(document), owner_font_selector_(owner_font_selector) { owner_font_selector_->RegisterForInvalidationCallbacks(this); @@ -510,7 +510,7 @@ Document& popup_document) { Document& owner_document = OwnerElement().GetDocument(); return MakeGarbageCollected<PopupMenuCSSFontSelector>( - &popup_document, owner_document.GetStyleEngine().GetFontSelector()); + popup_document, owner_document.GetStyleEngine().GetFontSelector()); } void InternalPopupMenu::SetValueAndClosePopup(int num_value,
diff --git a/third_party/blink/renderer/core/inspector/inspector_highlight.cc b/third_party/blink/renderer/core/inspector/inspector_highlight.cc index f3de72c..31be97c1 100644 --- a/third_party/blink/renderer/core/inspector/inspector_highlight.cc +++ b/third_party/blink/renderer/core/inspector/inspector_highlight.cc
@@ -526,12 +526,13 @@ float scale) { LayoutObject* layout_object = node->GetLayoutObject(); auto* layout_grid = To<LayoutGrid>(layout_object); - FloatPoint local_in_frame = FramePointToViewport( - node->GetDocument().View(), FloatPoint(local.left, local.top)); - PhysicalOffset abs_number_pos = layout_grid->LocalToAbsolutePoint( - PhysicalOffset::FromFloatPointRound(local_in_frame)); - abs_number_pos.Scale(scale); - return abs_number_pos; + PhysicalOffset abs_point = layout_grid->LocalToAbsolutePoint(local); + FloatPoint abs_point_in_viewport = FramePointToViewport( + node->GetDocument().View(), FloatPoint(abs_point.left, abs_point.top)); + PhysicalOffset scaled_abs_point = + PhysicalOffset::FromFloatPointRound(abs_point_in_viewport); + scaled_abs_point.Scale(scale); + return scaled_abs_point; } std::unique_ptr<protocol::DictionaryValue> BuildPosition( @@ -880,7 +881,8 @@ } Vector<Vector<PhysicalRect>> GetFlexLinesAndItems(LayoutBox* layout_box, - bool is_horizontal) { + bool is_horizontal, + bool is_reverse) { Vector<Vector<PhysicalRect>> flex_lines; // Flex containers can't get fragmented yet, but this may change in the @@ -907,13 +909,14 @@ LayoutUnit item_end = is_horizontal ? item_rect.X() + item_rect.Width() : item_rect.Y() + item_rect.Height(); - if (flex_lines.IsEmpty() || item_start < progression) { + if (flex_lines.IsEmpty() || + (is_reverse ? item_end > progression : item_start < progression)) { flex_lines.emplace_back(); } flex_lines.back().push_back(item_rect); - progression = item_end; + progression = is_reverse ? item_start : item_end; } } @@ -932,6 +935,9 @@ auto* layout_box = To<LayoutBox>(layout_object); DCHECK(layout_object); bool is_horizontal = IsHorizontalFlex(layout_object); + bool is_reverse = + layout_object->StyleRef().ResolvedIsRowReverseFlexDirection() || + layout_object->StyleRef().ResolvedIsColumnReverseFlexDirection(); std::unique_ptr<protocol::DictionaryValue> flex_info = protocol::DictionaryValue::create(); @@ -945,7 +951,7 @@ // Gather all flex items, sorted by flex line. Vector<Vector<PhysicalRect>> flex_lines = - GetFlexLinesAndItems(layout_box, is_horizontal); + GetFlexLinesAndItems(layout_box, is_horizontal, is_reverse); // Send the offset information for each item to the frontend. std::unique_ptr<protocol::ListValue> lines_info =
diff --git a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc index f6f52bd..f7083b0 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc
@@ -150,8 +150,18 @@ NGLayoutInputNode child, base::Optional<NGBreakAppeal> appeal, bool is_forced_break) { - if (appeal) + if (appeal) { break_appeal_ = *appeal; + // If we're violating any orphans / widows or + // break-{after,before,inside}:avoid requests, remember this. If we're + // balancing columns, we may be able to stretch the columns to resolve the + // situation. Note that we should consider handling kBreakAppealLastResort + // as well here, but that's currently causing trouble for large leading + // margins, which would cause taller columns than desirable in some cases. + if (break_appeal_ == kBreakAppealViolatingBreakAvoid || + break_appeal_ == kBreakAppealViolatingOrphansAndWidows) + has_violating_break_ = true; + } if (is_forced_break) { SetHasForcedBreak(); // A forced break is considered to always have perfect appeal; they should @@ -416,6 +426,9 @@ } else { PropagateSpaceShortage(child_layout_result.MinimalSpaceShortage()); } + + if (!is_fragmentation_context_root_) + has_violating_break_ |= child_layout_result.HasViolatingBreak(); } scoped_refptr<const NGLayoutResult> NGBoxFragmentBuilder::ToBoxFragment(
diff --git a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h index faffbd0..1343d93c 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h +++ b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h
@@ -593,6 +593,7 @@ bool is_math_fraction_ = false; bool is_math_operator_ = false; bool is_at_block_end_ = false; + bool has_violating_break_ = false; LayoutUnit consumed_block_size_; LayoutUnit block_offset_for_additional_columns_; unsigned sequence_number_ = 0;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc index 4767ac3..c48534cc1 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
@@ -490,22 +490,11 @@ column_size.block_size = column_size.block_size.ClampNegativeToZero(); } - // We balance if block-size is unconstrained, or when we're explicitly told - // to. Note that the block-size may be constrained by outer fragmentation - // contexts, not just by a block-size specified on this multicol container. - bool balance_columns = Style().GetColumnFill() == EColumnFill::kBalance || - (column_size.block_size == kIndefiniteSize && - !is_constrained_by_outer_fragmentation_context_); - - if (balance_columns) { - column_size.block_size = - CalculateBalancedColumnBlockSize(column_size, next_column_token); - } - - bool needs_more_fragments_in_outer = false; + bool may_resume_in_next_outer_fragmentainer = false; bool zero_outer_space_left = false; + LayoutUnit available_outer_space = kIndefiniteSize; if (is_constrained_by_outer_fragmentation_context_) { - LayoutUnit available_outer_space = + available_outer_space = FragmentainerSpaceAtBfcStart(ConstraintSpace()) - intrinsic_block_size_; if (available_outer_space <= LayoutUnit()) { @@ -521,17 +510,34 @@ zero_outer_space_left = true; } - // Check if we can fit everything (that's remaining), block-wise, within the - // current outer fragmentainer. If we can't, we need to adjust the block - // size, and allow the multicol container to continue in a subsequent outer - // fragmentainer. Note that we also need to handle indefinite block-size, - // because that may happen in a nested multicol container with auto - // block-size and column balancing disabled. + // Determine if we should resume layout in the next outer fragmentation + // context if we run out of space in the current one. This is always the + // thing to do except when block-size is non-auto and short enough to fit in + // the current outer fragmentainer. In such cases we'll allow inner columns + // to overflow its outer fragmentainer (since the inner multicol is too + // short to reach the outer fragmentation line). + if (column_size.block_size == kIndefiniteSize || + column_size.block_size > available_outer_space) + may_resume_in_next_outer_fragmentainer = true; + } + + // We balance if block-size is unconstrained, or when we're explicitly told + // to. Note that the block-size may be constrained by outer fragmentation + // contexts, not just by a block-size specified on this multicol container. + bool balance_columns = Style().GetColumnFill() == EColumnFill::kBalance || + (column_size.block_size == kIndefiniteSize && + !is_constrained_by_outer_fragmentation_context_); + + if (balance_columns) { + column_size.block_size = + CalculateBalancedColumnBlockSize(column_size, next_column_token); + } else if (available_outer_space != kIndefiniteSize) { + // Finally, resolve any remaining auto block-size, and make sure that we + // don't take up more space than there's room for in the outer fragmentation + // context. if (column_size.block_size > available_outer_space || - column_size.block_size == kIndefiniteSize) { + column_size.block_size == kIndefiniteSize) column_size.block_size = available_outer_space; - needs_more_fragments_in_outer = true; - } } DCHECK_GE(column_size.block_size, LayoutUnit()); @@ -563,6 +569,7 @@ bool allow_discard_start_margin = column_break_token && !column_break_token->IsCausedByColumnSpanner(); + bool has_violating_break = false; LayoutUnit column_inline_offset(BorderScrollbarPadding().inline_start); int actual_column_count = 0; @@ -603,6 +610,7 @@ if (result->HasForcedBreak()) forced_break_count++; + has_violating_break |= result->HasViolatingBreak(); column_inline_offset += column_inline_progression_; if (result->ColumnSpanner()) @@ -621,7 +629,7 @@ // multicol container fits block-wise in the current outer fragmentainer. if (ConstraintSpace().HasBlockFragmentation() && column_break_token && actual_column_count >= used_column_count_ && - needs_more_fragments_in_outer) { + may_resume_in_next_outer_fragmentainer) { // We cannot keep any of this if we have zero space left. Then we need // to resume in the next outer fragmentainer. if (zero_outer_space_left) @@ -657,12 +665,16 @@ // We're balancing columns. Check if the column block-size that we laid out // with was satisfactory. If not, stretch and retry, if possible. // - // If we overflowed (actual column count larger than what we have room for), - // see if we're able to stretch them. We can only stretch the columns if we - // have at least one column that could take more content. - // - // If we didn't exceed used column-count, we're done. - if (actual_column_count <= used_column_count_) + // If we didn't break at any undesirable location and actual column count + // wasn't larger than what we have room for, we're done IF we're also out of + // content (no break token; in nested multicol situations there are cases + // where we only allow as many columns as we have room for, as additional + // columns normally need to continue in the next outer fragmentainer). If we + // have made the columns tall enough to bump into a spanner, it also means + // we need to stop to lay out the spanner(s), and resume column layout + // afterwards. + if (!has_violating_break && actual_column_count <= used_column_count_ && + (!column_break_token || result->ColumnSpanner())) break; // We're in a situation where we'd like to stretch the columns, but then we @@ -989,6 +1001,14 @@ // balanced output, for no reason. The only thing we need to worry about here // is to not overflow the multicol container. + if (is_constrained_by_outer_fragmentation_context_) { + // Don't become too tall to fit in the outer fragmentation context. + LayoutUnit available_outer_space = + FragmentainerSpaceAtBfcStart(ConstraintSpace()) - intrinsic_block_size_; + DCHECK_GE(available_outer_space, LayoutUnit()); + size = std::min(size, available_outer_space); + } + // First of all we need to convert the size to a value that can be compared // against the resolved properties on the multicol container. That means that // we have to convert the value from content-box to border-box. @@ -1004,11 +1024,16 @@ extent = ResolveMainBlockLength(ConstraintSpace(), style, BorderPadding(), style.LogicalHeight(), kIndefiniteSize, LengthResolvePhase::kLayout); + // A specified block-size will just constrain the maximum length. + if (extent != kIndefiniteSize) + max = std::min(max, extent); } - if (extent != kIndefiniteSize) { - // A specified height/width will just constrain the maximum length. - max = std::min(max, extent); - } + + // A specified min-block-size may increase the maximum length. + LayoutUnit min = ResolveMinBlockLength( + ConstraintSpace(), style, BorderPadding(), style.LogicalMinHeight(), + LengthResolvePhase::kLayout); + max = std::max(max, min); // If this multicol container is nested inside another fragmentation // context, we need to subtract the space consumed in previous fragments.
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc b/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc index e15108c..fce19442 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc
@@ -95,6 +95,8 @@ rare_data->minimal_space_shortage = builder->minimal_space_shortage_; } + rare_data->has_violating_break = builder->has_violating_break_; + if (builder->column_spanner_) rare_data->column_spanner = builder->column_spanner_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_result.h b/third_party/blink/renderer/core/layout/ng/ng_layout_result.h index 81fd737..1f4ce1e 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_result.h +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_result.h
@@ -204,6 +204,13 @@ return rare_data_->tallest_unbreakable_block_size; } + // Return true if we weren't able to honor all break avoidance hints requested + // by break-{after,before,inside}:avoid or orphans / widows. This is used for + // column balancing. + bool HasViolatingBreak() const { + return HasRareData() && rare_data_->has_violating_break; + } + // Return whether this result is single-use only (true), or if it is allowed // to be involved in cache hits in future layout passes (false). // For example, this happens when a block is fragmented, since we don't yet @@ -425,6 +432,7 @@ LayoutUnit annotation_overflow; LayoutUnit block_end_annotation_space; bool is_single_use = false; + bool has_violating_break = false; int lines_until_clamp = 0; wtf_size_t table_column_count_ = 0; base::Optional<MathData> math_layout_data_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc index 8524a584..a9d61e9 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
@@ -523,7 +523,7 @@ rect.offset.ConvertToLogical(writing_direction, container.Size(), rect.size) + rect.size.ConvertToLogical(writing_direction.GetWritingMode()); - return rect_logical_end.inline_offset > border_inline_start && + return rect_logical_end.inline_offset > border_inline_start || rect_logical_end.block_offset > border_block_start; }
diff --git a/third_party/blink/renderer/core/page/drag_controller.cc b/third_party/blink/renderer/core/page/drag_controller.cc index ce121a5..68c0b0f 100644 --- a/third_party/blink/renderer/core/page/drag_controller.cc +++ b/third_party/blink/renderer/core/page/drag_controller.cc
@@ -906,21 +906,6 @@ return node; } -static ImageResourceContent* GetImageResource(Element* element) { - DCHECK(element); - if (auto* layout_image = DynamicTo<LayoutImage>(element->GetLayoutObject())) - return layout_image->CachedImage(); - return nullptr; -} - -static Image* GetImage(Element* element) { - DCHECK(element); - ImageResourceContent* cached_image = GetImageResource(element); - return (cached_image && !cached_image->ErrorOccurred()) - ? cached_image->GetImage() - : nullptr; -} - static void PrepareDataTransferForImageDrag(LocalFrame* source, DataTransfer* data_transfer, Element* node, @@ -1063,70 +1048,74 @@ return max_size_in_pixels; } +static bool CanDragImage(const Element& element) { + auto* layout_image = DynamicTo<LayoutImage>(element.GetLayoutObject()); + if (!layout_image) + return false; + const ImageResourceContent* image_content = layout_image->CachedImage(); + if (!image_content || image_content->ErrorOccurred() || + image_content->GetImage()->IsNull()) + return false; + scoped_refptr<const SharedBuffer> buffer = image_content->ResourceBuffer(); + if (!buffer || !buffer->size()) + return false; + // We shouldn't be starting a drag for an image that can't provide an + // extension. + // This is an early detection for problems encountered later upon drop. + DCHECK(!image_content->GetImage()->FilenameExtension().IsEmpty()); + return true; +} + static std::unique_ptr<DragImage> DragImageForImage( - Element* element, - Image* image, + const Element& element, float device_scale_factor, - const IntPoint& drag_origin, - const IntPoint& image_element_location, - const IntSize& image_element_size_in_pixels, - IntPoint& drag_location) { - std::unique_ptr<DragImage> drag_image; - IntPoint origin; - - // Substitute an appropriately-sized SVGImageForContainer, to ensure dragged - // SVG images scale seamlessly. - scoped_refptr<SVGImageForContainer> svg_image; - if (auto* svg_img = DynamicTo<SVGImage>(image)) { - KURL url = element->GetDocument().CompleteURL(element->ImageSourceURL()); - svg_image = SVGImageForContainer::Create( - svg_img, FloatSize(image_element_size_in_pixels), 1, url); - image = svg_image.get(); - } - - InterpolationQuality interpolation_quality = kInterpolationDefault; - if (const ComputedStyle* style = element->GetComputedStyle()) { - if (style->ImageRendering() == EImageRendering::kPixelated) - interpolation_quality = kInterpolationNone; - } + const IntSize& image_element_size_in_pixels) { + auto* layout_image = To<LayoutImage>(element.GetLayoutObject()); + const LayoutImageResource& image_resource = *layout_image->ImageResource(); + scoped_refptr<Image> image = + image_resource.GetImage(image_element_size_in_pixels); // Always respect the orientation of opaque origin images to avoid leaking // image data. Otherwise pull orientation from the layout object's style. - ImageResourceContent* image_content = GetImageResource(element); + const ImageResourceContent* image_content = image_resource.CachedImage(); RespectImageOrientationEnum respect_orientation = - LayoutObject::ShouldRespectImageOrientation(element->GetLayoutObject()); - if (image_content) { - respect_orientation = - image_content->ForceOrientationIfNecessary(respect_orientation); - } + LayoutObject::ShouldRespectImageOrientation(layout_image); + respect_orientation = + image_content->ForceOrientationIfNecessary(respect_orientation); IntSize image_size = image->Size(respect_orientation); + if (image_size.Area() > kMaxOriginalImageArea) + return nullptr; + + InterpolationQuality interpolation_quality = kInterpolationDefault; + if (layout_image->StyleRef().ImageRendering() == EImageRendering::kPixelated) + interpolation_quality = kInterpolationNone; + FloatSize image_scale = DragImage::ClampedImageScale(image_size, image_element_size_in_pixels, MaxDragImageSize(device_scale_factor)); - if (image_size.Area() <= kMaxOriginalImageArea && - (drag_image = DragImage::Create( - image, respect_orientation, device_scale_factor, - interpolation_quality, kDragImageAlpha, image_scale))) { - IntSize original_size = image_element_size_in_pixels; - origin = image_element_location; + return DragImage::Create(image.get(), respect_orientation, + device_scale_factor, interpolation_quality, + kDragImageAlpha, image_scale); +} - IntSize new_size = drag_image->Size(); +static IntPoint DragLocationForImage( + const DragImage* drag_image, + const IntPoint& drag_origin, + const IntPoint& image_element_location, + const IntSize& image_element_size_in_pixels) { + if (!drag_image) + return drag_origin; - // Properly orient the drag image and orient it differently if it's smaller - // than the original - float scale = new_size.Width() / (float)original_size.Width(); - float dx = origin.X() - drag_origin.X(); - dx *= scale; - origin.SetX((int)(dx + 0.5)); - float dy = origin.Y() - drag_origin.Y(); - dy *= scale; - origin.SetY((int)(dy + 0.5)); - } + IntSize original_size = image_element_size_in_pixels; + IntSize new_size = drag_image->Size(); - drag_location = drag_origin + origin; - return drag_image; + // Properly orient the drag image and orient it differently if it's smaller + // than the original + float scale = new_size.Width() / static_cast<float>(original_size.Width()); + FloatPoint offset(image_element_location - drag_origin); + return drag_origin + RoundedIntPoint(offset.ScaledBy(scale)); } static std::unique_ptr<DragImage> DragImageForLink(const KURL& link_url, @@ -1244,15 +1233,8 @@ src, false); } else if (state.drag_type_ == kDragSourceActionImage) { auto* element = DynamicTo<Element>(node); - if (image_url.IsEmpty() || !element) + if (image_url.IsEmpty() || !element || !CanDragImage(*element)) return false; - Image* image = GetImage(element); - if (!image || image->IsNull() || !image->Data() || !image->Data()->size()) - return false; - // We shouldn't be starting a drag for an image that can't provide an - // extension. - // This is an early detection for problems encountered later upon drop. - DCHECK(!image->FilenameExtension().IsEmpty()); if (!drag_image) { const IntRect& image_rect = hit_test_result.ImageRect(); IntSize image_size_in_pixels = image_rect.Size(); @@ -1269,9 +1251,11 @@ // TODO(oshima): Currently, the dragged image on high DPI is scaled and // can be blurry because of this. Consider to clip in the screen // coordinates to use high resolution image on high DPI screens. - drag_image = DragImageForImage(element, image, screen_device_scale_factor, - drag_origin, image_rect.Location(), - image_size_in_pixels, drag_location); + drag_image = DragImageForImage(*element, screen_device_scale_factor, + image_size_in_pixels); + drag_location = + DragLocationForImage(drag_image.get(), drag_origin, + image_rect.Location(), image_size_in_pixels); } DoSystemDrag(drag_image.get(), drag_location, drag_origin, data_transfer, src, false);
diff --git a/third_party/blink/renderer/core/page/page_popup_client.cc b/third_party/blink/renderer/core/page/page_popup_client.cc index 3f7596b0e..10d7130 100644 --- a/third_party/blink/renderer/core/page/page_popup_client.cc +++ b/third_party/blink/renderer/core/page/page_popup_client.cc
@@ -166,7 +166,7 @@ CSSFontSelector* PagePopupClient::CreateCSSFontSelector( Document& popup_document) { - return MakeGarbageCollected<CSSFontSelector>(&popup_document); + return MakeGarbageCollected<CSSFontSelector>(popup_document); } PagePopupController* PagePopupClient::CreatePagePopupController(
diff --git a/third_party/blink/renderer/core/page/scrolling/text_fragment_selector_generator_test.cc b/third_party/blink/renderer/core/page/scrolling/text_fragment_selector_generator_test.cc index 3888509..a2affb3 100644 --- a/third_party/blink/renderer/core/page/scrolling/text_fragment_selector_generator_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/text_fragment_selector_generator_test.cc
@@ -768,7 +768,7 @@ GetDocument().View()->UpdateAllLifecyclePhasesForTest(); Node* img = GetDocument().getElementById("link1"); Node* first_paragraph = GetDocument().getElementById("first")->firstChild(); - const auto& start = Position(img, PositionAnchorType::kAfterChildren); + const auto& start = Position::LastPositionInNode(*img); const auto& end = Position(first_paragraph, 5); ASSERT_EQ(" \nFirst", PlainText(EphemeralRange(start, end)));
diff --git a/third_party/blink/renderer/core/testing/internals.cc b/third_party/blink/renderer/core/testing/internals.cc index 07830bd..3d096782 100644 --- a/third_party/blink/renderer/core/testing/internals.cc +++ b/third_party/blink/renderer/core/testing/internals.cc
@@ -3143,6 +3143,15 @@ document->GetFrame()->View()->UpdateAllLifecyclePhasesForTest(); } +void Internals::setForcedColorsAndDarkPreferredColorScheme(Document* document) { + DCHECK(document); + ColorSchemeHelper color_scheme_helper(*document); + color_scheme_helper.SetPreferredColorScheme( + mojom::blink::PreferredColorScheme::kDark); + color_scheme_helper.SetForcedColors(*document, ForcedColors::kActive); + document->GetFrame()->View()->UpdateAllLifecyclePhasesForTest(); +} + void Internals::setShouldRevealPassword(Element* element, bool reveal, ExceptionState& exception_state) {
diff --git a/third_party/blink/renderer/core/testing/internals.h b/third_party/blink/renderer/core/testing/internals.h index a4db2f6..8b03f19 100644 --- a/third_party/blink/renderer/core/testing/internals.h +++ b/third_party/blink/renderer/core/testing/internals.h
@@ -31,6 +31,7 @@ #include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/core/css/css_computed_style_declaration.h" #include "third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h" +#include "third_party/blink/renderer/core/testing/color_scheme_helper.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" @@ -472,6 +473,8 @@ void forceCompositingUpdate(Document*, ExceptionState&); + void setForcedColorsAndDarkPreferredColorScheme(Document* document); + void setShouldRevealPassword(Element*, bool, ExceptionState&); ScriptPromise createResolvedPromise(ScriptState*, ScriptValue);
diff --git a/third_party/blink/renderer/core/testing/internals.idl b/third_party/blink/renderer/core/testing/internals.idl index a731d5c2..b8eb512 100644 --- a/third_party/blink/renderer/core/testing/internals.idl +++ b/third_party/blink/renderer/core/testing/internals.idl
@@ -298,6 +298,8 @@ [RaisesException] void forceCompositingUpdate(Document document); + void setForcedColorsAndDarkPreferredColorScheme(Document document); + [RaisesException] void setShouldRevealPassword(Element element, boolean reveal); [CallWith=ScriptState] Promise<any> createResolvedPromise(any value);
diff --git a/third_party/blink/renderer/core/workers/dedicated_worker_test.cc b/third_party/blink/renderer/core/workers/dedicated_worker_test.cc index 0f7ab8e3..1394c4e6 100644 --- a/third_party/blink/renderer/core/workers/dedicated_worker_test.cc +++ b/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
@@ -43,6 +43,11 @@ WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope( std::unique_ptr<GlobalScopeCreationParams> creation_params) override { + // Needed to avoid calling into an uninitialized broker. + if (!creation_params->browser_interface_broker) { + (void)creation_params->browser_interface_broker + .InitWithNewPipeAndPassReceiver(); + } auto* global_scope = DedicatedWorkerGlobalScope::Create( std::move(creation_params), this, time_origin_, ukm::kInvalidSourceId); // Initializing a global scope with a dummy creation params may emit warning
diff --git a/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc b/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc index a8d8685..456fb4a 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_layout_object.cc
@@ -72,7 +72,6 @@ #include "third_party/blink/renderer/core/layout/layout_table_cell.h" #include "third_party/blink/renderer/core/layout/layout_table_row.h" #include "third_party/blink/renderer/core/layout/layout_table_section.h" -#include "third_party/blink/renderer/core/layout/layout_text_fragment.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/layout/list_marker.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h" @@ -1112,7 +1111,7 @@ // // This AXLayoutObject might not be included in the accessibility tree at // all, so "RawNextSibling" needs to be used to walk the layout tree. - result = RawNextSibling(); + result = NextSiblingIncludingIgnored(); } else if (ShouldUseLayoutNG(*GetLayoutObject())) { result = NextOnLineInternalNG(*this); } else { @@ -1168,7 +1167,7 @@ // Note that we can't use AXObject::IndexInParent() to do this, because // for performance reasons we don't define it on objects that are not // included in the accessibility tree at all. - if (parent && !RawNextSibling()) + if (parent && !NextSiblingIncludingIgnored()) result = parent->NextOnLine(); } } @@ -1283,7 +1282,7 @@ // Note that we can't use AXObject::IndexInParent() to do this, because // for performance reasons we don't define it on objects that are not // included in the accessibility tree at all. - if (parent && parent->RawFirstChild() == this) + if (parent && parent->FirstChildIncludingIgnored() == this) result = parent->PreviousOnLine(); } } @@ -1644,89 +1643,6 @@ return layout_object->Parent(); } -// See LAYOUT TREE WALKING ALGORITHM, above, for details. -// Return true if this layout object is the continuation of some other -// layout object. -static bool IsContinuation(LayoutObject* layout_object) { - if (layout_object->IsElementContinuation()) - return true; - - auto* block_flow = DynamicTo<LayoutBlockFlow>(layout_object); - return block_flow && block_flow->IsAnonymousBlock() && - block_flow->Continuation(); -} - -// See LAYOUT TREE WALKING ALGORITHM, above, for details. -// Return the continuation of this layout object, or nullptr if it doesn't -// have one. -LayoutObject* GetContinuation(LayoutObject* layout_object) { - if (layout_object->IsLayoutInline()) - return To<LayoutInline>(layout_object)->Continuation(); - - if (auto* block_flow = DynamicTo<LayoutBlockFlow>(layout_object)) - return block_flow->Continuation(); - - return nullptr; -} - -// See LAYOUT TREE WALKING ALGORITHM, above, for details. -AXObject* AXLayoutObject::RawFirstChild() const { - if (!layout_object_) - return nullptr; - - LayoutObject* first_child = layout_object_->SlowFirstChild(); - - // CSS first-letter pseudo element is handled as continuation. Returning it - // will result in duplicated elements. - auto* fragment = DynamicTo<LayoutTextFragment>(first_child); - if (fragment && fragment->GetFirstLetterPseudoElement()) - return nullptr; - - // Skip over continuations. - while (first_child && IsContinuation(first_child)) - first_child = first_child->NextSibling(); - - // If there's a first child that's not a continuation, return that. - if (first_child) - return AXObjectCache().GetOrCreate(first_child); - - // Finally check if this object has no children but it has a continuation - // itself - and if so, it's the first child. - LayoutObject* continuation = GetContinuation(layout_object_); - if (continuation) - return AXObjectCache().GetOrCreate(continuation); - - return nullptr; -} - -// See LAYOUT TREE WALKING ALGORITHM, above, for details. -AXObject* AXLayoutObject::RawNextSibling() const { - if (!layout_object_) - return nullptr; - - // If it's not a continuation, just get the next sibling from the - // layout tree, skipping over continuations. - if (!IsContinuation(layout_object_)) { - LayoutObject* next_sibling = layout_object_->NextSibling(); - while (next_sibling && IsContinuation(next_sibling)) - next_sibling = next_sibling->NextSibling(); - - if (next_sibling) - return AXObjectCache().GetOrCreate(next_sibling); - } - - // If we've run out of siblings, check to see if the parent of this - // object has a continuation, and if so, follow it. - LayoutObject* parent = layout_object_->Parent(); - if (parent) { - LayoutObject* continuation = GetContinuation(parent); - if (continuation) - return AXObjectCache().GetOrCreate(continuation); - } - - return nullptr; -} - // // High-level accessibility tree access. //
diff --git a/third_party/blink/renderer/modules/accessibility/ax_layout_object.h b/third_party/blink/renderer/modules/accessibility/ax_layout_object.h index b00fde5..799fb9a 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_layout_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_layout_object.h
@@ -142,10 +142,6 @@ AXObject* ComputeParent() const override; AXObject* ComputeParentIfExists() const override; - // Low-level accessibility tree exploration, only for use within the - // accessibility module. - AXObject* RawFirstChild() const override; - AXObject* RawNextSibling() const override; bool CanHaveChildren() const override; // Notifications that this object may have changed.
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc index 171849f..4c7c1453 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -3001,29 +3001,6 @@ return nullptr; } -AXObject* AXNodeObject::RawFirstChild() const { - if (!GetNode()) - return nullptr; - - Node* first_child = LayoutTreeBuilderTraversal::FirstChild(*GetNode()); - - if (!first_child) - return nullptr; - - return AXObjectCache().GetOrCreate(first_child); -} - -AXObject* AXNodeObject::RawNextSibling() const { - if (!GetNode()) - return nullptr; - - Node* next_sibling = LayoutTreeBuilderTraversal::NextSibling(*GetNode()); - if (!next_sibling) - return nullptr; - - return AXObjectCache().GetOrCreate(next_sibling); -} - bool AXNodeObject::IsHtmlTable() const { return IsTableLikeRole() && GetLayoutObject() && GetLayoutObject()->IsTable() && IsA<HTMLTableElement>(GetNode()); @@ -3225,13 +3202,8 @@ AddChild(html_input_element->PopupRootAXObject()); } -void AXNodeObject::AddPseudoElementChildren() { - // Pseudo elements often have text and image children that are not - // visited by the LayoutTreeBuilderTraversal class used in DOM traversal. - Element* element = GetElement(); - if (!element || !element->IsPseudoElement() || !GetLayoutObject()) - return; - +void AXNodeObject::AddLayoutChildren() { + DCHECK(GetLayoutObject()); LayoutObject* child = GetLayoutObject()->SlowFirstChild(); while (child) { AddChild(AXObjectCache().GetOrCreate(child)); @@ -3251,6 +3223,8 @@ } void AXNodeObject::AddNodeChildren() { + if (!node_) + return; for (Node* child = LayoutTreeBuilderTraversal::FirstChild(*node_); child; child = LayoutTreeBuilderTraversal::NextSibling(*child)) { if (child->IsMarkerPseudoElement() && AccessibilityIsIgnored()) @@ -3267,17 +3241,6 @@ } } -void AXNodeObject::AddLayoutChildren() { - for (AXObject* obj = RawFirstChild(); obj; obj = obj->RawNextSibling()) { - if (RuntimeEnabledFeatures::AccessibilityExposeIgnoredNodesEnabled() && - obj && obj->RoleValue() == ax::mojom::blink::Role::kStaticText && - obj->CanIgnoreTextAsEmpty()) - continue; - - AddChild(obj); - } -} - void AXNodeObject::AddChildren() { if (IsDetached()) return; @@ -3293,15 +3256,14 @@ if (IsHtmlTable()) AddTableChildren(); - else if (ShouldUseLayoutBuilderTraversal()) - AddNodeChildren(); - else + else if (ShouldUseLayoutObjectTraversalForChildren()) AddLayoutChildren(); + else + AddNodeChildren(); AddPopupChildren(); AddRemoteSVGChildren(); AddImageMapChildren(); - AddPseudoElementChildren(); AddInlineTextBoxChildren(false); AddValidationMessageChild(); AddAccessibleNodeChildren(); @@ -3781,14 +3743,10 @@ return; } - // If the combobox or listbox is a descendant of a label element for another - // widget, it may be ignored and Children() won't return all its children. - // As a result, we need to use RawFirstChild and RawNextSibling to iterate - // over the children in search of the selected option(s). - + const AXObjectVector& children = ChildrenIncludingIgnored(); if (RoleValue() == ax::mojom::blink::Role::kComboBoxGrouping || RoleValue() == ax::mojom::blink::Role::kComboBoxMenuButton) { - for (AXObject* obj = RawFirstChild(); obj; obj = obj->RawNextSibling()) { + for (const auto& obj : children) { if (obj->RoleValue() == ax::mojom::blink::Role::kListBox) { obj->SelectedOptions(options); return; @@ -3796,7 +3754,7 @@ } } - for (AXObject* obj = RawFirstChild(); obj; obj = obj->RawNextSibling()) { + for (const auto& obj : children) { if (obj->IsSelected() == kSelectedStateTrue) options.push_back(obj); }
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.h b/third_party/blink/renderer/modules/accessibility/ax_node_object.h index 793b466..18b97cc 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.h
@@ -215,9 +215,6 @@ AXObject* ComputeParent() const override; AXObject* ComputeParentIfExists() const override; - // Low-level accessibility tree exploration. - AXObject* RawFirstChild() const override; - AXObject* RawNextSibling() const override; void AddChildren() override; bool CanHaveChildren() const override; @@ -312,7 +309,6 @@ bool IsDescendantOfElementType(HashSet<QualifiedName>& tag_names) const; String PlaceholderFromNativeAttribute() const; - void AddPseudoElementChildren(); void AddNodeChildren(); void AddLayoutChildren(); void AddInlineTextBoxChildren(bool force);
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index 31a08cf..b0f5f63 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -3519,6 +3519,22 @@ return ancestor; } +bool AXObject::ShouldUseLayoutObjectTraversalForChildren() const { + if (!GetLayoutObject()) + return false; + + // If no node, this may be an anonymous layout object, e.g. an anonymous block + // that is inserted to enforce the rule that all children are blocks or all + // children are inlines. Anonymous blocks have a layout object but no node. + if (!GetNode()) + return true; + + // The only other case for using layout builder traversal is for a pseudo + // element, such as ::before. Pseudo element child text and images are not + // visibited by LayoutBuilderTraversal. + return GetNode()->IsPseudoElement(); +} + void AXObject::UpdateChildrenIfNecessary() { if (!HasChildren()) AddChildren();
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.h b/third_party/blink/renderer/modules/accessibility/ax_object.h index b336448..4c8a0fd8 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object.h
@@ -1063,34 +1063,14 @@ AXObject* ContainerWidget() const; bool IsContainerWidget() const; - // Low-level accessibility tree exploration, only for use within the - // accessibility module. - - // Returns the AXObject's first child, skipping over any children that - // represent continuations in the layout tree. If the AXObject has no - // children, returns the AXObject representing the next in pre-order - // continuation in the layout tree, if any. - // - // In the accessibility tree, this results in continuations becoming - // descendants of the nodes they "continue". - virtual AXObject* RawFirstChild() const { return nullptr; } - - // Returns the AXObject's next sibling, skipping over any siblings that - // represent continuations in the layout tree. If this is the last child, - // returns the AXObject representing the next in pre-order continuation in the - // layout tree, if any. - // - // In the accessibility tree, this results in continuations becoming - // descendants of the nodes they "continue". - virtual AXObject* RawNextSibling() const { return nullptr; } - virtual void AddChildren() {} - // If there is a DOM node, use LayoutBuilderTraversal, which visits DOM - // children and pseudo element nodes, otherwise this may be an anonymous node, - // such as an anonymous block that is inserted to enforce the rule that all - // children are blocks or all children are inlines. Anonymous blocks have a - // layout object but no DOM node. - virtual bool ShouldUseLayoutBuilderTraversal() const { return GetNode(); } + // There are two types of traversal for obtaining children: + // 1. LayoutTreeBuilderTraversal. Despite the name, this traverses a flattened + // DOM tree that includes pseudo element children such as ::before, and where + // shadow DOM slotting has been run. + // 2. LayoutObject traversal. This is necessary if there is no parent node, + // or if the parent node is a pseudo element. + bool ShouldUseLayoutObjectTraversalForChildren() const; virtual bool CanHaveChildren() const { return true; } bool HasChildren() const { return have_children_; } virtual void UpdateChildrenIfNecessary();
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc index 070abe0..e54dd8ec 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.cc
@@ -1406,14 +1406,14 @@ continue; } - bool did_use_layout_builder_traversal = - object->ShouldUseLayoutBuilderTraversal(); + bool did_use_layout_object_traversal = + object->ShouldUseLayoutObjectTraversalForChildren(); AXObject* parent = object->ParentObjectIncludedInTree(); AXObject* new_object = refresh(object); // Children might change because child traversal style changed. - if (new_object->ShouldUseLayoutBuilderTraversal() != - did_use_layout_builder_traversal) { + if (new_object->ShouldUseLayoutObjectTraversalForChildren() != + did_use_layout_object_traversal) { // TODO(accessibility) Need test for this, e.g. for continuations. pending_children_changed_ids.insert(ax_id); }
diff --git a/third_party/blink/renderer/modules/manifest/manifest_parser.cc b/third_party/blink/renderer/modules/manifest/manifest_parser.cc index d464159..4bb876a 100644 --- a/third_party/blink/renderer/modules/manifest/manifest_parser.cc +++ b/third_party/blink/renderer/modules/manifest/manifest_parser.cc
@@ -455,12 +455,12 @@ if (keyword.IsEmpty()) continue; - if (!CodeUnitCompareIgnoringASCIICase(keyword, "any")) { + if (EqualIgnoringASCIICase(keyword, "any")) { purposes.push_back(mojom::blink::ManifestImageResource::Purpose::ANY); - } else if (!CodeUnitCompareIgnoringASCIICase(keyword, "monochrome")) { + } else if (EqualIgnoringASCIICase(keyword, "monochrome")) { purposes.push_back( mojom::blink::ManifestImageResource::Purpose::MONOCHROME); - } else if (!CodeUnitCompareIgnoringASCIICase(keyword, "maskable")) { + } else if (EqualIgnoringASCIICase(keyword, "maskable")) { purposes.push_back( mojom::blink::ManifestImageResource::Purpose::MASKABLE); } else {
diff --git a/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.cc b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.cc index 3bfae67..9da735e1 100644 --- a/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.cc +++ b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.cc
@@ -161,11 +161,9 @@ if (type.IsEmpty()) return true; - const bool video = - !CodeUnitCompareIgnoringASCIICase(type, "video/webm") || - !CodeUnitCompareIgnoringASCIICase(type, "video/x-matroska"); - const bool audio = - video ? false : (!CodeUnitCompareIgnoringASCIICase(type, "audio/webm")); + const bool video = EqualIgnoringASCIICase(type, "video/webm") || + EqualIgnoringASCIICase(type, "video/x-matroska"); + const bool audio = !video && EqualIgnoringASCIICase(type, "audio/webm"); if (!video && !audio) return false; @@ -195,7 +193,7 @@ String codec_string = String::FromUTF8(codec); auto* const* found = std::find_if( &codecs[0], &codecs[codecs_count], [&codec_string](const char* name) { - return !CodeUnitCompareIgnoringASCIICase(codec_string, name); + return EqualIgnoringASCIICase(codec_string, name); }); if (found == &codecs[codecs_count]) return false;
diff --git a/third_party/blink/renderer/modules/nfc/BUILD.gn b/third_party/blink/renderer/modules/nfc/BUILD.gn index 06dcd3e..803cbd15 100644 --- a/third_party/blink/renderer/modules/nfc/BUILD.gn +++ b/third_party/blink/renderer/modules/nfc/BUILD.gn
@@ -14,8 +14,6 @@ "ndef_reading_event.h", "ndef_record.cc", "ndef_record.h", - "ndef_writer.cc", - "ndef_writer.h", "nfc_proxy.cc", "nfc_proxy.h", "nfc_type_converters.cc",
diff --git a/third_party/blink/renderer/modules/nfc/idls.gni b/third_party/blink/renderer/modules/nfc/idls.gni index 3426634..87158dc 100644 --- a/third_party/blink/renderer/modules/nfc/idls.gni +++ b/third_party/blink/renderer/modules/nfc/idls.gni
@@ -7,7 +7,6 @@ "ndef_record.idl", "ndef_reader.idl", "ndef_reading_event.idl", - "ndef_writer.idl", ] modules_dictionary_idl_files = [
diff --git a/third_party/blink/renderer/modules/nfc/ndef_reader.cc b/third_party/blink/renderer/modules/nfc/ndef_reader.cc index da91ed8..089f76c8 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_reader.cc +++ b/third_party/blink/renderer/modules/nfc/ndef_reader.cc
@@ -6,9 +6,12 @@ #include <utility> +#include "mojo/public/cpp/bindings/callback_helpers.h" #include "services/device/public/mojom/nfc.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/bindings/modules/v8/string_or_array_buffer_or_array_buffer_view_or_ndef_message_init.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_ndef_scan_options.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_ndef_write_options.h" #include "third_party/blink/renderer/core/dom/abort_signal.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" @@ -18,6 +21,7 @@ #include "third_party/blink/renderer/modules/nfc/ndef_message.h" #include "third_party/blink/renderer/modules/nfc/ndef_reading_event.h" #include "third_party/blink/renderer/modules/nfc/nfc_proxy.h" +#include "third_party/blink/renderer/modules/nfc/nfc_type_converters.h" #include "third_party/blink/renderer/modules/nfc/nfc_utils.h" #include "third_party/blink/renderer/modules/permissions/permission_utils.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" @@ -34,7 +38,10 @@ namespace { constexpr char kNotSupportedOrPermissionDenied[] = - "WebNFC feature is unavailable or permission denied."; + "Web NFC is unavailable or permission denied."; + +constexpr char kChildFrameErrorMessage[] = + "Web NFC can only be accessed in a top-level browsing context."; constexpr char kInvalidStateErrorMessage[] = "A scan() operation is ongoing."; } // namespace @@ -73,15 +80,11 @@ ScriptPromise NDEFReader::scan(ScriptState* script_state, const NDEFScanOptions* options, ExceptionState& exception_state) { - LocalFrame* frame = script_state->ContextIsValid() - ? LocalDOMWindow::From(script_state)->GetFrame() - : nullptr; // https://w3c.github.io/web-nfc/#security-policies // WebNFC API must be only accessible from top level browsing context. - if (!frame || !frame->IsMainFrame()) { - exception_state.ThrowDOMException(DOMExceptionCode::kNotAllowedError, - "NFC interfaces are only avaliable " - "in a top-level browsing context"); + if (!DomWindow() || !DomWindow()->GetFrame()->IsMainFrame()) { + exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, + kChildFrameErrorMessage); return ScriptPromise(); } @@ -89,7 +92,7 @@ // "AbortError" DOMException and return p. if (options->hasSignal() && options->signal()->aborted()) { exception_state.ThrowDOMException(DOMExceptionCode::kAbortError, - "The NFC operation was cancelled."); + "The NFC scan operation was cancelled."); return ScriptPromise(); } @@ -108,85 +111,64 @@ return ScriptPromise(); } - resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state); - // 8. If reader.[[Signal]] is not null, then add the following abort steps - // to reader.[[Signal]]: + scan_resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + // 8. If |signal| is not null, then add the following abort steps + // to |signal|: if (options->hasSignal()) { options->signal()->AddAlgorithm( - WTF::Bind(&NDEFReader::Abort, WrapPersistent(this))); + WTF::Bind(&NDEFReader::ReadAbort, WrapPersistent(this))); } GetPermissionService()->RequestPermission( CreatePermissionDescriptor(PermissionName::NFC), - LocalFrame::HasTransientUserActivation(frame), - WTF::Bind(&NDEFReader::OnRequestPermission, WrapPersistent(this), + LocalFrame::HasTransientUserActivation(DomWindow()->GetFrame()), + WTF::Bind(&NDEFReader::ReadOnRequestPermission, WrapPersistent(this), WrapPersistent(options))); - return resolver_->Promise(); + return scan_resolver_->Promise(); } -PermissionService* NDEFReader::GetPermissionService() { - if (!permission_service_.is_bound()) { - ConnectToPermissionService( - GetExecutionContext(), - permission_service_.BindNewPipeAndPassReceiver( - GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI))); - } - return permission_service_.get(); -} - -void NDEFReader::OnRequestPermission(const NDEFScanOptions* options, - PermissionStatus status) { - if (!resolver_) { +void NDEFReader::ReadOnRequestPermission(const NDEFScanOptions* options, + PermissionStatus status) { + if (!scan_resolver_) { has_pending_scan_request_ = false; return; } if (status != PermissionStatus::GRANTED) { has_pending_scan_request_ = false; - resolver_->Reject(MakeGarbageCollected<DOMException>( + scan_resolver_->Reject(MakeGarbageCollected<DOMException>( DOMExceptionCode::kNotAllowedError, "NFC permission request denied.")); - resolver_.Clear(); + scan_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(); + scan_resolver_->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kAbortError, + "The NFC scan operation was cancelled.")); + scan_resolver_.Clear(); return; } - UseCounter::Count(GetExecutionContext(), WebFeature::kWebNfcNdefReaderScan); - // TODO(https://crbug.com/994936) remove when origin trial is complete. - UseCounter::Count(GetExecutionContext(), WebFeature::kWebNfcAPI); - GetNfcProxy()->StartReading( this, - WTF::Bind(&NDEFReader::OnScanRequestCompleted, WrapPersistent(this))); + WTF::Bind(&NDEFReader::ReadOnRequestCompleted, WrapPersistent(this))); } -void NDEFReader::OnScanRequestCompleted( +void NDEFReader::ReadOnRequestCompleted( device::mojom::blink::NDEFErrorPtr error) { has_pending_scan_request_ = false; - if (!resolver_) + if (!scan_resolver_) return; if (error) { - resolver_->Reject( + scan_resolver_->Reject( NDEFErrorTypeToDOMException(error->error_type, error->error_message)); } else { - resolver_->Resolve(); + scan_resolver_->Resolve(); } - resolver_.Clear(); -} - -void NDEFReader::Trace(Visitor* visitor) const { - visitor->Trace(permission_service_); - visitor->Trace(resolver_); - EventTargetWithInlineData::Trace(visitor); - ActiveScriptWrappable::Trace(visitor); - ExecutionContextLifecycleObserver::Trace(visitor); + scan_resolver_.Clear(); } void NDEFReader::OnReading(const String& serial_number, @@ -204,40 +186,172 @@ mojom::blink::ConsoleMessageLevel::kInfo, message)); } -void NDEFReader::OnMojoConnectionError() { - // If |resolver_| has already settled this rejection is silently ignored. - if (resolver_) { - resolver_->Reject(NDEFErrorTypeToDOMException( - device::mojom::blink::NDEFErrorType::NOT_SUPPORTED, - kNotSupportedOrPermissionDenied)); - resolver_.Clear(); - } -} - void NDEFReader::ContextDestroyed() { - // If |resolver_| has already settled this rejection is silently ignored. - if (resolver_) { - resolver_->Reject(MakeGarbageCollected<DOMException>( - DOMExceptionCode::kAbortError, - "The execution context is going to be gone.")); - resolver_.Clear(); - } GetNfcProxy()->StopReading(this); } -void NDEFReader::Abort() { - if (resolver_) { - resolver_->Reject(MakeGarbageCollected<DOMException>( - DOMExceptionCode::kAbortError, "The NFC operation was cancelled.")); - resolver_.Clear(); +void NDEFReader::ReadAbort() { + if (scan_resolver_) { + scan_resolver_->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kAbortError, + "The NFC scan operation was cancelled.")); + scan_resolver_.Clear(); } GetNfcProxy()->StopReading(this); } +// https://w3c.github.io/web-nfc/#writing-content +// https://w3c.github.io/web-nfc/#the-write-method +ScriptPromise NDEFReader::write(ScriptState* script_state, + const NDEFMessageSource& write_message, + const NDEFWriteOptions* options, + ExceptionState& exception_state) { + // https://w3c.github.io/web-nfc/#security-policies + // WebNFC API must be only accessible from top level browsing context. + if (!DomWindow() || !DomWindow()->GetFrame()->IsMainFrame()) { + exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, + kChildFrameErrorMessage); + return ScriptPromise(); + } + + if (options->hasSignal() && options->signal()->aborted()) { + // If signal’s aborted flag is set, then reject p with an "AbortError" + // DOMException and return p. + exception_state.ThrowDOMException(DOMExceptionCode::kAbortError, + "The NFC write operation was cancelled."); + return ScriptPromise(); + } + + // Step 11.2: Run "create NDEF message", if this throws an exception, + // reject p with that exception and abort these steps. + NDEFMessage* ndef_message = + NDEFMessage::Create(DomWindow(), write_message, exception_state); + if (exception_state.HadException()) { + return ScriptPromise(); + } + + auto message = device::mojom::blink::NDEFMessage::From(ndef_message); + DCHECK(message); + + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + write_requests_.insert(resolver); + + // Add the writer to proxy's writer list for Mojo connection error + // notification. + GetNfcProxy()->AddWriter(this); + + GetPermissionService()->RequestPermission( + CreatePermissionDescriptor(PermissionName::NFC), + LocalFrame::HasTransientUserActivation(DomWindow()->GetFrame()), + WTF::Bind(&NDEFReader::WriteOnRequestPermission, WrapPersistent(this), + WrapPersistent(resolver), WrapPersistent(options), + std::move(message))); + + return resolver->Promise(); +} + +void NDEFReader::WriteOnRequestPermission( + ScriptPromiseResolver* resolver, + const NDEFWriteOptions* options, + device::mojom::blink::NDEFMessagePtr message, + PermissionStatus status) { + if (status != PermissionStatus::GRANTED) { + resolver->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kNotAllowedError, "NFC permission request denied.")); + return; + } + + if (options->hasSignal() && options->signal()->aborted()) { + resolver->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kAbortError, + "The NFC write operation was cancelled.")); + return; + } + + // If signal is not null, then add the abort steps to signal. + if (options->hasSignal() && !options->signal()->aborted()) { + options->signal()->AddAlgorithm(WTF::Bind(&NDEFReader::WriteAbort, + WrapPersistent(this), + WrapPersistent(resolver))); + } + + auto callback = WTF::Bind(&NDEFReader::WriteOnRequestCompleted, + WrapPersistent(this), WrapPersistent(resolver)); + GetNfcProxy()->Push(std::move(message), + device::mojom::blink::NDEFWriteOptions::From(options), + std::move(callback)); +} + +void NDEFReader::WriteOnRequestCompleted( + ScriptPromiseResolver* resolver, + device::mojom::blink::NDEFErrorPtr error) { + DCHECK(write_requests_.Contains(resolver)); + + write_requests_.erase(resolver); + + if (error.is_null()) { + resolver->Resolve(); + } else { + resolver->Reject( + NDEFErrorTypeToDOMException(error->error_type, error->error_message)); + } +} + +void NDEFReader::WriteAbort(ScriptPromiseResolver* resolver) { + // WriteOnRequestCompleted() should always be called whether the push + // operation is cancelled successfully or not. + GetNfcProxy()->CancelPush(); +} + NFCProxy* NDEFReader::GetNfcProxy() const { - DCHECK(GetExecutionContext()); - return NFCProxy::From(*To<LocalDOMWindow>(GetExecutionContext())); + DCHECK(DomWindow()); + return NFCProxy::From(*DomWindow()); +} + +void NDEFReader::Trace(Visitor* visitor) const { + visitor->Trace(permission_service_); + visitor->Trace(scan_resolver_); + visitor->Trace(write_requests_); + EventTargetWithInlineData::Trace(visitor); + ActiveScriptWrappable::Trace(visitor); + ExecutionContextLifecycleObserver::Trace(visitor); +} + +PermissionService* NDEFReader::GetPermissionService() { + if (!permission_service_.is_bound()) { + ConnectToPermissionService( + GetExecutionContext(), + permission_service_.BindNewPipeAndPassReceiver( + GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI))); + } + return permission_service_.get(); +} + +void NDEFReader::ReadOnMojoConnectionError() { + // If |scan_resolver_| has already settled this rejection is silently ignored. + if (scan_resolver_) { + scan_resolver_->Reject(NDEFErrorTypeToDOMException( + device::mojom::blink::NDEFErrorType::NOT_SUPPORTED, + kNotSupportedOrPermissionDenied)); + scan_resolver_.Clear(); + } +} + +void NDEFReader::WriteOnMojoConnectionError() { + // If the mojo connection breaks, All push requests will be rejected with a + // default error. + + // Script may execute during a call to Resolve(). Swap these sets to prevent + // concurrent modification. + HeapHashSet<Member<ScriptPromiseResolver>> write_requests; + write_requests_.swap(write_requests); + write_requests_.clear(); + for (ScriptPromiseResolver* resolver : write_requests) { + resolver->Reject(NDEFErrorTypeToDOMException( + device::mojom::blink::NDEFErrorType::NOT_SUPPORTED, + kNotSupportedOrPermissionDenied)); + } } } // namespace blink
diff --git a/third_party/blink/renderer/modules/nfc/ndef_reader.h b/third_party/blink/renderer/modules/nfc/ndef_reader.h index cf3edc51..377e0b6 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_reader.h +++ b/third_party/blink/renderer/modules/nfc/ndef_reader.h
@@ -18,10 +18,13 @@ namespace blink { -class ExecutionContext; -class NFCProxy; class NDEFScanOptions; +class NDEFWriteOptions; +class NFCProxy; class ScriptPromiseResolver; +class StringOrArrayBufferOrArrayBufferViewOrNDEFMessageInit; + +using NDEFMessageSource = StringOrArrayBufferOrArrayBufferViewOrNDEFMessageInit; class MODULES_EXPORT NDEFReader : public EventTargetWithInlineData, public ActiveScriptWrappable<NDEFReader>, @@ -43,7 +46,17 @@ DEFINE_ATTRIBUTE_EVENT_LISTENER(reading, kReading) DEFINE_ATTRIBUTE_EVENT_LISTENER(readingerror, kReadingerror) - ScriptPromise scan(ScriptState*, const NDEFScanOptions*, ExceptionState&); + + // Scan from an NFC tag. + ScriptPromise scan(ScriptState* script_state, + const NDEFScanOptions* options, + ExceptionState& exception_state); + + // Write NDEFMessageSource asynchronously to NFC tag. + ScriptPromise write(ScriptState* script_state, + const NDEFMessageSource& write_message, + const NDEFWriteOptions* options, + ExceptionState& exception_state); void Trace(Visitor*) const override; @@ -53,32 +66,50 @@ virtual void OnReadingError(const String& message); // Called by NFCProxy for notification about connection error. - void OnMojoConnectionError(); + void ReadOnMojoConnectionError(); + void WriteOnMojoConnectionError(); private: // ExecutionContextLifecycleObserver overrides. void ContextDestroyed() override; - void Abort(); - NFCProxy* GetNfcProxy() const; - void OnScanRequestCompleted(device::mojom::blink::NDEFErrorPtr error); + void ReadAbort(); + void ReadOnRequestCompleted(device::mojom::blink::NDEFErrorPtr error); - // Permission handling - void OnRequestPermission(const NDEFScanOptions* options, - mojom::blink::PermissionStatus status); - mojom::blink::PermissionService* GetPermissionService(); + void WriteAbort(ScriptPromiseResolver* resolver); + void WriteOnRequestCompleted(ScriptPromiseResolver* resolver, + device::mojom::blink::NDEFErrorPtr error); + + // Read Permission handling + void ReadOnRequestPermission(const NDEFScanOptions* options, + mojom::blink::PermissionStatus status); + + // Write Permission handling + void WriteOnRequestPermission( + ScriptPromiseResolver* resolver, + const NDEFWriteOptions* options, + device::mojom::blink::NDEFMessagePtr ndef_message, + mojom::blink::PermissionStatus status); + + // |scan_resolver_| is kept here to handle Mojo connection failures because in + // that case the callback passed to Watch() won't be called and + // mojo::WrapCallbackWithDefaultInvokeIfNotRun() is forbidden in Blink. + Member<ScriptPromiseResolver> scan_resolver_; + // To reject if there is already an ongoing scan. + bool has_pending_scan_request_ = false; + HeapMojoRemote<mojom::blink::PermissionService, HeapMojoWrapperMode::kWithoutContextObserver> permission_service_; + mojom::blink::PermissionService* GetPermissionService(); - // |resolver_| is kept here to handle Mojo connection failures because in that - // case the callback passed to Watch() won't be called and + // |write_requests_| are kept here to handle Mojo connection failures because + // in that case the callback passed to Push() won't be called and // mojo::WrapCallbackWithDefaultInvokeIfNotRun() is forbidden in Blink. - Member<ScriptPromiseResolver> resolver_; - // To reject if there is already an ongoing scan. - bool has_pending_scan_request_ = false; + // This list will also be used by AbortSignal. + HeapHashSet<Member<ScriptPromiseResolver>> write_requests_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/nfc/ndef_reader.idl b/third_party/blink/renderer/modules/nfc/ndef_reader.idl index 2359a7a..63575c5e 100644 --- a/third_party/blink/renderer/modules/nfc/ndef_reader.idl +++ b/third_party/blink/renderer/modules/nfc/ndef_reader.idl
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// https://w3c.github.io/web-nfc/#dom-ndefmessagesource +typedef (DOMString or BufferSource or NDEFMessageInit) NDEFMessageSource; + // http://w3c.github.io/web-nfc/#dom-ndefreader [ @@ -14,6 +17,10 @@ attribute EventHandler onreading; attribute EventHandler onreadingerror; - [CallWith=ScriptState, RaisesException] Promise<void> scan( + [CallWith=ScriptState, RaisesException, MeasureAs=WebNfcNdefReaderScan] Promise<void> scan( optional NDEFScanOptions options={}); + + [CallWith=ScriptState, RaisesException, MeasureAs=WebNfcNdefWriterWrite] Promise<void> write( + NDEFMessageSource message, + optional NDEFWriteOptions options={}); };
diff --git a/third_party/blink/renderer/modules/nfc/ndef_writer.cc b/third_party/blink/renderer/modules/nfc/ndef_writer.cc deleted file mode 100644 index 56a7315..0000000 --- a/third_party/blink/renderer/modules/nfc/ndef_writer.cc +++ /dev/null
@@ -1,197 +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. - -#include "third_party/blink/renderer/modules/nfc/ndef_writer.h" - -#include <utility> - -#include "mojo/public/cpp/bindings/callback_helpers.h" -#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" -#include "third_party/blink/renderer/bindings/modules/v8/string_or_array_buffer_or_array_buffer_view_or_ndef_message_init.h" -#include "third_party/blink/renderer/bindings/modules/v8/v8_ndef_write_options.h" -#include "third_party/blink/renderer/core/dom/abort_signal.h" -#include "third_party/blink/renderer/core/dom/dom_exception.h" -#include "third_party/blink/renderer/core/frame/local_dom_window.h" -#include "third_party/blink/renderer/core/frame/local_frame.h" -#include "third_party/blink/renderer/modules/nfc/ndef_message.h" -#include "third_party/blink/renderer/modules/nfc/nfc_type_converters.h" -#include "third_party/blink/renderer/modules/nfc/nfc_utils.h" -#include "third_party/blink/renderer/modules/permissions/permission_utils.h" -#include "third_party/blink/renderer/platform/bindings/exception_state.h" -#include "third_party/blink/renderer/platform/instrumentation/use_counter.h" -#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h" -#include "third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h" -#include "third_party/blink/renderer/platform/weborigin/security_origin.h" - -namespace blink { - -using mojom::blink::PermissionName; -using mojom::blink::PermissionService; -using mojom::blink::PermissionStatus; - -// static -NDEFWriter* NDEFWriter::Create(ExecutionContext* context) { - context->GetScheduler()->RegisterStickyFeature( - blink::SchedulingPolicy::Feature::kWebNfc, - {blink::SchedulingPolicy::RecordMetricsForBackForwardCache()}); - return MakeGarbageCollected<NDEFWriter>(context); -} - -NDEFWriter::NDEFWriter(ExecutionContext* context) - : ExecutionContextClient(context), permission_service_(context) {} - -void NDEFWriter::Trace(Visitor* visitor) const { - visitor->Trace(permission_service_); - visitor->Trace(requests_); - visitor->Trace(nfc_proxy_); - ScriptWrappable::Trace(visitor); - ExecutionContextClient::Trace(visitor); -} - -// https://w3c.github.io/web-nfc/#writing-content -// https://w3c.github.io/web-nfc/#the-write-method -ScriptPromise NDEFWriter::write(ScriptState* script_state, - const NDEFMessageSource& write_message, - const NDEFWriteOptions* options, - ExceptionState& exception_state) { - LocalDOMWindow* window = script_state->ContextIsValid() - ? LocalDOMWindow::From(script_state) - : nullptr; - // https://w3c.github.io/web-nfc/#security-policies - // WebNFC API must be only accessible from top level browsing context. - if (!window || !window->GetFrame()->IsMainFrame()) { - exception_state.ThrowDOMException(DOMExceptionCode::kNotAllowedError, - "NFC interfaces are only avaliable " - "in a top-level browsing context"); - return ScriptPromise(); - } - - if (options->hasSignal() && options->signal()->aborted()) { - // If signal’s aborted flag is set, then reject p with an "AbortError" - // DOMException and return p. - exception_state.ThrowDOMException(DOMExceptionCode::kAbortError, - "The NFC operation was cancelled."); - return ScriptPromise(); - } - - // Step 11.2: Run "create NDEF message", if this throws an exception, - // reject p with that exception and abort these steps. - NDEFMessage* ndef_message = - NDEFMessage::Create(window, write_message, exception_state); - if (exception_state.HadException()) { - return ScriptPromise(); - } - - auto message = device::mojom::blink::NDEFMessage::From(ndef_message); - DCHECK(message); - - auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); - requests_.insert(resolver); - InitNfcProxyIfNeeded(); - GetPermissionService()->RequestPermission( - CreatePermissionDescriptor(PermissionName::NFC), - LocalFrame::HasTransientUserActivation(window->GetFrame()), - WTF::Bind(&NDEFWriter::OnRequestPermission, WrapPersistent(this), - WrapPersistent(resolver), WrapPersistent(options), - std::move(message))); - - return resolver->Promise(); -} - -PermissionService* NDEFWriter::GetPermissionService() { - if (!permission_service_.is_bound()) { - ConnectToPermissionService( - GetExecutionContext(), - permission_service_.BindNewPipeAndPassReceiver( - GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI))); - } - return permission_service_.get(); -} - -void NDEFWriter::OnRequestPermission( - ScriptPromiseResolver* resolver, - const NDEFWriteOptions* options, - device::mojom::blink::NDEFMessagePtr message, - PermissionStatus status) { - if (status != PermissionStatus::GRANTED) { - resolver->Reject(MakeGarbageCollected<DOMException>( - DOMExceptionCode::kNotAllowedError, "NFC permission request denied.")); - return; - } - - if (options->hasSignal() && options->signal()->aborted()) { - resolver->Reject(MakeGarbageCollected<DOMException>( - DOMExceptionCode::kAbortError, "The NFC operation was cancelled.")); - return; - } - - // If signal is not null, then add the abort steps to signal. - if (options->hasSignal() && !options->signal()->aborted()) { - options->signal()->AddAlgorithm(WTF::Bind( - &NDEFWriter::Abort, WrapPersistent(this), WrapPersistent(resolver))); - } - - UseCounter::Count(GetExecutionContext(), WebFeature::kWebNfcNdefWriterWrite); - // TODO(https://crbug.com/994936) remove when origin trial is complete. - UseCounter::Count(GetExecutionContext(), WebFeature::kWebNfcAPI); - - auto callback = WTF::Bind(&NDEFWriter::OnRequestCompleted, - WrapPersistent(this), WrapPersistent(resolver)); - nfc_proxy_->Push(std::move(message), - device::mojom::blink::NDEFWriteOptions::From(options), - std::move(callback)); -} - -void NDEFWriter::OnMojoConnectionError() { - nfc_proxy_.Clear(); - - // If the mojo connection breaks, all push requests will be rejected with a - // default error. - for (ScriptPromiseResolver* resolver : requests_) { - resolver->Reject(NDEFErrorTypeToDOMException( - device::mojom::blink::NDEFErrorType::NOT_SUPPORTED, - "WebNFC feature is unavailable or permission denied.")); - } - requests_.clear(); -} - -void NDEFWriter::InitNfcProxyIfNeeded() { - // Init NfcProxy if needed. - if (nfc_proxy_) - return; - - nfc_proxy_ = NFCProxy::From(*To<LocalDOMWindow>(GetExecutionContext())); - DCHECK(nfc_proxy_); - - // Add the writer to proxy's writer list for mojo connection error - // notification. - nfc_proxy_->AddWriter(this); -} - -void NDEFWriter::Abort(ScriptPromiseResolver* resolver) { - // |nfc_proxy_| could be null on Mojo connection failure, simply ignore the - // abort request in this case. - if (!nfc_proxy_) - return; - - // OnRequestCompleted() should always be called whether the push operation is - // cancelled successfully or not. So do nothing for the cancelled callback. - nfc_proxy_->CancelPush(device::mojom::blink::NFC::CancelPushCallback()); -} - -void NDEFWriter::OnRequestCompleted(ScriptPromiseResolver* resolver, - device::mojom::blink::NDEFErrorPtr error) { - DCHECK(requests_.Contains(resolver)); - - requests_.erase(resolver); - - if (error.is_null()) { - resolver->Resolve(); - } else { - resolver->Reject( - NDEFErrorTypeToDOMException(error->error_type, error->error_message)); - } -} - -} // namespace blink
diff --git a/third_party/blink/renderer/modules/nfc/ndef_writer.h b/third_party/blink/renderer/modules/nfc/ndef_writer.h deleted file mode 100644 index 3e0631c..0000000 --- a/third_party/blink/renderer/modules/nfc/ndef_writer.h +++ /dev/null
@@ -1,74 +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. - -#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_WRITER_H_ -#define THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_WRITER_H_ - -#include "third_party/blink/public/mojom/permissions/permission.mojom-blink.h" -#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" -#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" -#include "third_party/blink/renderer/modules/nfc/nfc_proxy.h" -#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" -#include "third_party/blink/renderer/platform/heap/heap_allocator.h" -#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" -#include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h" - -namespace blink { - -class NDEFWriteOptions; -class ExceptionState; -class ExecutionContext; -class ScriptPromise; -class StringOrArrayBufferOrArrayBufferViewOrNDEFMessageInit; - -using NDEFMessageSource = StringOrArrayBufferOrArrayBufferViewOrNDEFMessageInit; - -class NDEFWriter : public ScriptWrappable, public ExecutionContextClient { - DEFINE_WRAPPERTYPEINFO(); - - public: - static NDEFWriter* Create(ExecutionContext*); - - explicit NDEFWriter(ExecutionContext*); - ~NDEFWriter() override = default; - - void Trace(Visitor*) const override; - - // Write NDEFMessageSource asynchronously to NFC tag. - ScriptPromise write(ScriptState*, - const NDEFMessageSource&, - const NDEFWriteOptions*, - ExceptionState&); - - // Called by NFCProxy for notification about connection error. - void OnMojoConnectionError(); - - private: - void InitNfcProxyIfNeeded(); - void Abort(ScriptPromiseResolver* resolver); - void OnRequestCompleted(ScriptPromiseResolver* resolver, - device::mojom::blink::NDEFErrorPtr error); - - // Permission handling - void OnRequestPermission(ScriptPromiseResolver* resolver, - const NDEFWriteOptions* options, - device::mojom::blink::NDEFMessagePtr ndef_message, - mojom::blink::PermissionStatus status); - mojom::blink::PermissionService* GetPermissionService(); - - HeapMojoRemote<mojom::blink::PermissionService, - HeapMojoWrapperMode::kWithoutContextObserver> - permission_service_; - - // |requests_| are kept here to handle Mojo connection failures because - // in that case the callback passed to Push() won't be called and - // mojo::WrapCallbackWithDefaultInvokeIfNotRun() is forbidden in Blink. - // This list will also be used by AbortSignal. - HeapHashSet<Member<ScriptPromiseResolver>> requests_; - Member<NFCProxy> nfc_proxy_; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_NFC_NDEF_WRITER_H_
diff --git a/third_party/blink/renderer/modules/nfc/ndef_writer.idl b/third_party/blink/renderer/modules/nfc/ndef_writer.idl deleted file mode 100644 index 23e2dcc..0000000 --- a/third_party/blink/renderer/modules/nfc/ndef_writer.idl +++ /dev/null
@@ -1,20 +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. - -// https://w3c.github.io/web-nfc/#dom-ndefmessagesource - -typedef (DOMString or BufferSource or NDEFMessageInit) NDEFMessageSource; - -// https://w3c.github.io/web-nfc/#dom-nfcwriter - -[ - RuntimeEnabled=WebNFC, - SecureContext, - Exposed=Window -] interface NDEFWriter { - [CallWith=ExecutionContext] constructor(); - [CallWith=ScriptState, RaisesException] Promise<void> write( - NDEFMessageSource message, - optional NDEFWriteOptions options={}); -};
diff --git a/third_party/blink/renderer/modules/nfc/nfc_proxy.cc b/third_party/blink/renderer/modules/nfc/nfc_proxy.cc index fb380ee..3dd93fb 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_proxy.cc +++ b/third_party/blink/renderer/modules/nfc/nfc_proxy.cc
@@ -10,7 +10,6 @@ #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/modules/nfc/ndef_reader.h" -#include "third_party/blink/renderer/modules/nfc/ndef_writer.h" #include "third_party/blink/renderer/modules/nfc/nfc_type_converters.h" #include "third_party/blink/renderer/modules/nfc/nfc_utils.h" #include "third_party/blink/renderer/platform/mojo/mojo_helper.h" @@ -22,10 +21,6 @@ // static NFCProxy* NFCProxy::From(LocalDOMWindow& window) { - // https://w3c.github.io/web-nfc/#security-policies - // WebNFC API must be only accessible from top level browsing context. - DCHECK(window.GetFrame()->IsMainFrame()); - NFCProxy* nfc_proxy = Supplement<LocalDOMWindow>::From<NFCProxy>(window); if (!nfc_proxy) { nfc_proxy = MakeGarbageCollected<NFCProxy>(window); @@ -66,11 +61,8 @@ DCHECK(reader); auto iter = readers_.find(reader); if (iter != readers_.end()) { - if (nfc_remote_) { - // We do not need to notify |reader| of anything. - nfc_remote_->CancelWatch( - iter->value, device::mojom::blink::NFC::CancelWatchCallback()); - } + if (nfc_remote_) + nfc_remote_->CancelWatch(iter->value); readers_.erase(iter); } } @@ -80,9 +72,9 @@ return readers_.Contains(const_cast<NDEFReader*>(reader)); } -void NFCProxy::AddWriter(NDEFWriter* writer) { - DCHECK(!writers_.Contains(writer)); - writers_.insert(writer); +void NFCProxy::AddWriter(NDEFReader* writer) { + if (!writers_.Contains(writer)) + writers_.insert(writer); } void NFCProxy::Push(device::mojom::blink::NDEFMessagePtr message, @@ -92,10 +84,10 @@ nfc_remote_->Push(std::move(message), std::move(options), std::move(cb)); } -void NFCProxy::CancelPush( - device::mojom::blink::NFC::CancelPushCallback callback) { - DCHECK(nfc_remote_); - nfc_remote_->CancelPush(std::move(callback)); +void NFCProxy::CancelPush() { + if (!nfc_remote_) + return; + nfc_remote_->CancelPush(); } // device::mojom::blink::NFCClient implementation. @@ -180,21 +172,20 @@ nfc_remote_.reset(); client_receiver_.reset(); - // Notify all active readers about the connection error and clear the list. + // Notify all active readers about the connection error. ReaderMap readers = std::move(readers_); for (auto& pair : readers) { - pair.key->OnMojoConnectionError(); + pair.key->ReadOnMojoConnectionError(); } // Each connection maintains its own watch ID numbering, so reset to 1 on // connection error. next_watch_id_ = 1; - // Notify all writers about the connection error. + // Notify all writers about the connection error and clear the list. for (auto& writer : writers_) { - writer->OnMojoConnectionError(); + writer->WriteOnMojoConnectionError(); } - // Clear the reader list. writers_.clear(); }
diff --git a/third_party/blink/renderer/modules/nfc/nfc_proxy.h b/third_party/blink/renderer/modules/nfc/nfc_proxy.h index 2054198..751dcd9 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_proxy.h +++ b/third_party/blink/renderer/modules/nfc/nfc_proxy.h
@@ -18,9 +18,8 @@ class LocalDOMWindow; class NDEFReader; -class NDEFWriter; -// This is a proxy class used by NDEFWriter(s) and NDEFReader(s) to connect +// This is a proxy class used by NDEFReader(s) to connect // to implementation of device::mojom::blink::NFC interface. class MODULES_EXPORT NFCProxy final : public GarbageCollected<NFCProxy>, public Supplement<LocalDOMWindow>, @@ -37,7 +36,7 @@ // There is no matching RemoveWriter() method because writers are // automatically removed from the weak hash set when they are garbage // collected. - void AddWriter(NDEFWriter*); + void AddWriter(NDEFReader*); void StartReading(NDEFReader*, device::mojom::blink::NFC::WatchCallback); @@ -46,7 +45,7 @@ void Push(device::mojom::blink::NDEFMessagePtr, device::mojom::blink::NDEFWriteOptionsPtr, device::mojom::blink::NFC::PushCallback); - void CancelPush(device::mojom::blink::NFC::CancelPushCallback); + void CancelPush(); private: // Implementation of device::mojom::blink::NFCClient. @@ -74,7 +73,7 @@ using ReaderMap = HeapHashMap<WeakMember<NDEFReader>, uint32_t>; ReaderMap readers_; - using WriterSet = HeapHashSet<WeakMember<NDEFWriter>>; + using WriterSet = HeapHashSet<WeakMember<NDEFReader>>; WriterSet writers_; mojo::Remote<device::mojom::blink::NFC> nfc_remote_;
diff --git a/third_party/blink/renderer/modules/nfc/nfc_proxy_test.cc b/third_party/blink/renderer/modules/nfc/nfc_proxy_test.cc index 2f65ec3..5f08d0a2 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_proxy_test.cc +++ b/third_party/blink/renderer/modules/nfc/nfc_proxy_test.cc
@@ -105,9 +105,7 @@ set_tag_message(std::move(message)); std::move(callback).Run(nullptr); } - void CancelPush(CancelPushCallback callback) override { - std::move(callback).Run(nullptr); - } + void CancelPush() override {} void Watch(uint32_t id, WatchCallback callback) override { if (watch_error_) { std::move(callback).Run(watch_error_.Clone()); @@ -117,19 +115,10 @@ watchIDs_.push_back(id); std::move(callback).Run(nullptr); } - void CancelWatch(uint32_t id, CancelWatchCallback callback) override { + void CancelWatch(uint32_t id) override { size_t index = watchIDs_.Find(id); - if (index == kNotFound) { - std::move(callback).Run(device::mojom::blink::NDEFError::New( - device::mojom::blink::NDEFErrorType::NOT_FOUND, "")); - } else { + if (index != kNotFound) watchIDs_.EraseAt(index); - std::move(callback).Run(nullptr); - } - } - void CancelAllWatches(CancelAllWatchesCallback callback) override { - watchIDs_.clear(); - std::move(callback).Run(nullptr); } device::mojom::blink::NDEFErrorPtr watch_error_;
diff --git a/third_party/blink/renderer/modules/nfc/nfc_utils.cc b/third_party/blink/renderer/modules/nfc/nfc_utils.cc index 9e01de92..599bdb2 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_utils.cc +++ b/third_party/blink/renderer/modules/nfc/nfc_utils.cc
@@ -25,18 +25,12 @@ case device::mojom::blink::NDEFErrorType::NOT_READABLE: return MakeGarbageCollected<DOMException>( DOMExceptionCode::kNotReadableError, error_message); - case device::mojom::blink::NDEFErrorType::NOT_FOUND: - return MakeGarbageCollected<DOMException>( - DOMExceptionCode::kNotFoundError, error_message); case device::mojom::blink::NDEFErrorType::INVALID_MESSAGE: return MakeGarbageCollected<DOMException>(DOMExceptionCode::kSyntaxError, error_message); case device::mojom::blink::NDEFErrorType::OPERATION_CANCELLED: return MakeGarbageCollected<DOMException>(DOMExceptionCode::kAbortError, error_message); - case device::mojom::blink::NDEFErrorType::CANNOT_CANCEL: - return MakeGarbageCollected<DOMException>( - DOMExceptionCode::kNoModificationAllowedError, error_message); case device::mojom::blink::NDEFErrorType::IO_ERROR: return MakeGarbageCollected<DOMException>(DOMExceptionCode::kNetworkError, error_message);
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc index 509ea0f..117f331 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc +++ b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.cc
@@ -392,7 +392,8 @@ MockPeerConnectionDependencyFactory::CreatePeerConnection( const webrtc::PeerConnectionInterface::RTCConfiguration& config, blink::WebLocalFrame* frame, - webrtc::PeerConnectionObserver* observer) { + webrtc::PeerConnectionObserver* observer, + ExceptionState& exception_state) { return new rtc::RefCountedObject<MockPeerConnectionImpl>(this, observer); }
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.h b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.h index 0d583f46..64f84a8 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.h +++ b/third_party/blink/renderer/modules/peerconnection/mock_peer_connection_dependency_factory.h
@@ -171,7 +171,8 @@ scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection( const webrtc::PeerConnectionInterface::RTCConfiguration& config, blink::WebLocalFrame* frame, - webrtc::PeerConnectionObserver* observer) override; + webrtc::PeerConnectionObserver* observer, + ExceptionState& exception_state) override; scoped_refptr<webrtc::VideoTrackSourceInterface> CreateVideoTrackSourceProxy( webrtc::VideoTrackSourceInterface* source) override; scoped_refptr<webrtc::MediaStreamInterface> CreateLocalMediaStream(
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc index da6d4bb..098c1c5a 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc +++ b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc
@@ -251,7 +251,8 @@ bool MockRTCPeerConnectionHandlerPlatform::Initialize( const webrtc::PeerConnectionInterface::RTCConfiguration&, const MediaConstraints&, - WebLocalFrame*) { + WebLocalFrame*, + ExceptionState&) { return true; }
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h index 1a9cb0f..a2f93c4 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h +++ b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h
@@ -29,7 +29,8 @@ bool Initialize(const webrtc::PeerConnectionInterface::RTCConfiguration&, const MediaConstraints&, - WebLocalFrame*) override; + WebLocalFrame*, + ExceptionState&) override; void Stop() override; void StopAndUnregister() override;
diff --git a/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc b/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc index d765ec0..6c13b869 100644 --- a/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc +++ b/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc
@@ -32,6 +32,7 @@ #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_local_frame_client.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_error_util.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h" #include "third_party/blink/renderer/modules/webrtc/webrtc_audio_device_impl.h" #include "third_party/blink/renderer/platform/mediastream/media_constraints.h" @@ -346,7 +347,8 @@ PeerConnectionDependencyFactory::CreatePeerConnection( const webrtc::PeerConnectionInterface::RTCConfiguration& config, blink::WebLocalFrame* web_frame, - webrtc::PeerConnectionObserver* observer) { + webrtc::PeerConnectionObserver* observer, + ExceptionState& exception_state) { CHECK(web_frame); CHECK(observer); if (!GetPcFactory().get()) @@ -357,9 +359,16 @@ webrtc::PeerConnectionDependencies dependencies(observer); dependencies.allocator = CreatePortAllocator(web_frame); dependencies.async_resolver_factory = CreateAsyncResolverFactory(); - return GetPcFactory() - ->CreatePeerConnection(config, std::move(dependencies)) - .get(); + auto pc_or_error = GetPcFactory()->CreatePeerConnectionOrError( + config, std::move(dependencies)); + if (pc_or_error.ok()) { + // Convert from rtc::scoped_refptr to scoped_refptr + return pc_or_error.value().get(); + } else { + // Convert error + ThrowExceptionFromRTCError(pc_or_error.error(), exception_state); + return nullptr; + } } std::unique_ptr<cricket::PortAllocator>
diff --git a/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.h b/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.h index 7092f910..e0ab47c 100644 --- a/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.h +++ b/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.h
@@ -11,6 +11,7 @@ #include "base/threading/thread.h" #include "base/threading/thread_checker.h" #include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/webrtc/api/peer_connection_interface.h" #include "third_party/webrtc/p2p/stunprober/stun_prober.h" @@ -78,7 +79,8 @@ virtual scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection( const webrtc::PeerConnectionInterface::RTCConfiguration& config, blink::WebLocalFrame* web_frame, - webrtc::PeerConnectionObserver* observer); + webrtc::PeerConnectionObserver* observer, + ExceptionState& exception_state); // Creates a PortAllocator that uses Chrome IPC sockets and enforces privacy // controls according to the permissions granted on the page.
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index b38cf32b..e007497 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -805,10 +805,9 @@ auto* web_frame = static_cast<WebLocalFrame*>(WebFrame::FromFrame(window->GetFrame())); - if (!peer_handler_->Initialize(configuration, constraints, web_frame)) { - exception_state.ThrowDOMException( - DOMExceptionCode::kNotSupportedError, - "Failed to initialize native PeerConnection."); + if (!peer_handler_->Initialize(configuration, constraints, web_frame, + exception_state)) { + DCHECK(exception_state.HadException()); return; } // The RTCPeerConnection was successfully constructed.
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc index 2531921..b068300 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc
@@ -1106,7 +1106,8 @@ const webrtc::PeerConnectionInterface::RTCConfiguration& server_configuration, const MediaConstraints& options, - WebLocalFrame* frame) { + WebLocalFrame* frame, + ExceptionState& exception_state) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); DCHECK(frame); frame_ = frame; @@ -1140,7 +1141,7 @@ peer_connection_observer_ = MakeGarbageCollected<Observer>(weak_factory_.GetWeakPtr(), task_runner_); native_peer_connection_ = dependency_factory_->CreatePeerConnection( - configuration_, frame_, peer_connection_observer_); + configuration_, frame_, peer_connection_observer_, exception_state); if (!native_peer_connection_.get()) { LOG(ERROR) << "Failed to initialize native PeerConnection."; return false; @@ -1159,7 +1160,8 @@ const webrtc::PeerConnectionInterface::RTCConfiguration& server_configuration, const MediaConstraints& options, - const base::WeakPtr<PeerConnectionTracker>& peer_connection_tracker) { + const base::WeakPtr<PeerConnectionTracker>& peer_connection_tracker, + ExceptionState& exception_state) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); CHECK(!initialize_called_); @@ -1172,7 +1174,7 @@ CopyConstraintsIntoRtcConfiguration(options, &configuration_); native_peer_connection_ = dependency_factory_->CreatePeerConnection( - configuration_, nullptr, peer_connection_observer_); + configuration_, nullptr, peer_connection_observer_, exception_state); if (!native_peer_connection_.get()) { LOG(ERROR) << "Failed to initialize native PeerConnection."; return false;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h index 3b1b9f60..cbf6bd1 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h
@@ -25,6 +25,7 @@ #include "third_party/blink/renderer/modules/peerconnection/thermal_uma_listener.h" #include "third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer.h" #include "third_party/blink/renderer/modules/peerconnection/webrtc_media_stream_track_adapter_map.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/member.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/mediastream/media_stream_component.h" @@ -124,14 +125,16 @@ const webrtc::PeerConnectionInterface::RTCConfiguration& server_configuration, const MediaConstraints& options, - const base::WeakPtr<PeerConnectionTracker>& peer_connection_tracker); + const base::WeakPtr<PeerConnectionTracker>& peer_connection_tracker, + ExceptionState& exception_state); // RTCPeerConnectionHandlerPlatform implementation virtual bool Initialize( const webrtc::PeerConnectionInterface::RTCConfiguration& server_configuration, const MediaConstraints& options, - WebLocalFrame* web_frame); + WebLocalFrame* web_frame, + ExceptionState& exception_state); virtual void Stop(); virtual void StopAndUnregister();
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc index baf1dfbd..e321466f 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc
@@ -295,9 +295,10 @@ webrtc::PeerConnectionInterface::RTCConfiguration config; config.sdp_semantics = webrtc::SdpSemantics::kPlanB; MediaConstraints constraints; - EXPECT_TRUE(pc_handler_->InitializeForTest( - config, constraints, mock_tracker_.get()->AsWeakPtr())); - + DummyExceptionStateForTesting exception_state; + EXPECT_TRUE(pc_handler_->InitializeForTest(config, constraints, + mock_tracker_.get()->AsWeakPtr(), + exception_state)); mock_peer_connection_ = pc_handler_->native_peer_connection(); ASSERT_TRUE(mock_peer_connection_); EXPECT_CALL(*mock_peer_connection_, Close());
diff --git a/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc b/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc index adc1f71..3fa8c41 100644 --- a/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/transceiver_state_surfacer_test.cc
@@ -50,8 +50,10 @@ dependency_factory_.get(), main_task_runner_); surfacer_.reset(new TransceiverStateSurfacer(main_task_runner_, signaling_task_runner())); + DummyExceptionStateForTesting exception_state; peer_connection_ = dependency_factory_->CreatePeerConnection( - webrtc::PeerConnectionInterface::RTCConfiguration(), nullptr, nullptr); + webrtc::PeerConnectionInterface::RTCConfiguration(), nullptr, nullptr, + exception_state); EXPECT_CALL( *(static_cast<blink::MockPeerConnectionImpl*>(peer_connection_.get())), GetSctpTransport())
diff --git a/third_party/blink/renderer/modules/webtransport/bidirectional_stream_test.cc b/third_party/blink/renderer/modules/webtransport/bidirectional_stream_test.cc index ef587aa8..804e719 100644 --- a/third_party/blink/renderer/modules/webtransport/bidirectional_stream_test.cc +++ b/third_party/blink/renderer/modules/webtransport/bidirectional_stream_test.cc
@@ -154,6 +154,8 @@ was_abort_stream_called_ = true; } + void SetOutgoingDatagramExpirationDuration(base::TimeDelta) override {} + private: base::OnceCallback<void(uint32_t, mojo::ScopedDataPipeConsumerHandle,
diff --git a/third_party/blink/renderer/modules/webtransport/quic_transport.cc b/third_party/blink/renderer/modules/webtransport/quic_transport.cc index 5d5cf42..56597d9 100644 --- a/third_party/blink/renderer/modules/webtransport/quic_transport.cc +++ b/third_party/blink/renderer/modules/webtransport/quic_transport.cc
@@ -76,8 +76,8 @@ // Sends a datagram on write(). class QuicTransport::DatagramUnderlyingSink final : public UnderlyingSinkBase { public: - explicit DatagramUnderlyingSink(QuicTransport* quic_transport) - : quic_transport_(quic_transport) {} + DatagramUnderlyingSink(QuicTransport* quic_transport, int high_water_mark) + : quic_transport_(quic_transport), high_water_mark_(high_water_mark) {} ScriptPromise start(ScriptState* script_state, WritableStreamDefaultController*, @@ -131,6 +131,7 @@ void Trace(Visitor* visitor) const override { visitor->Trace(quic_transport_); + visitor->Trace(pending_datagrams_); UnderlyingSinkBase::Trace(visitor); } @@ -145,18 +146,31 @@ auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>( quic_transport_->script_state_); + pending_datagrams_.push_back(resolver); + quic_transport_->quic_transport_->SendDatagram( - data, WTF::Bind(&DatagramSent, WrapPersistent(resolver))); + data, WTF::Bind(&DatagramUnderlyingSink::OnDatagramProcessed, + WrapWeakPersistent(this))); + if (pending_datagrams_.size() < static_cast<wtf_size_t>(high_water_mark_)) { + // In this case we pretend that the datagram is processed immediately, to + // get more requests from the stream. + return ScriptPromise::CastUndefined(quic_transport_->script_state_); + } return resolver->Promise(); } - // |sent| indicates whether the datagram was sent or dropped. Currently we - // |don't do anything with this information. - static void DatagramSent(ScriptPromiseResolver* resolver, bool sent) { + void OnDatagramProcessed(bool sent) { + DCHECK(!pending_datagrams_.empty()); + + ScriptPromiseResolver* resolver = pending_datagrams_.front(); + pending_datagrams_.pop_front(); + resolver->Resolve(); } Member<QuicTransport> quic_transport_; + const int high_water_mark_; + HeapDeque<Member<ScriptPromiseResolver>> pending_datagrams_; }; // Captures a pointer to the ReadableStreamDefaultControllerWithScriptScope in @@ -607,6 +621,11 @@ stream_map_.erase(stream_id); } +void QuicTransport::SetDatagramWritableQueueExpirationDuration( + base::TimeDelta duration) { + quic_transport_->SetOutgoingDatagramExpirationDuration(duration); +} + void QuicTransport::Trace(Visitor* visitor) const { visitor->Trace(received_datagrams_); visitor->Trace(received_datagrams_controller_); @@ -713,8 +732,25 @@ received_datagrams_ = ReadableStream::CreateWithCountQueueingStrategy( script_state_, MakeGarbageCollected<DatagramUnderlyingSource>(script_state_, this), 1); + int outgoing_datagrams_high_water_mark = 1; + if (options.hasDatagramWritableHighWaterMark()) { + outgoing_datagrams_high_water_mark = + options.datagramWritableHighWaterMark(); + } + + // We create a WritableStream with high water mark 1 and try to mimic the + // given high water mark in the Sink, from two reasons: + // 1. This is better because we can hide the RTT between the renderer and the + // network service. + // 2. Keeping datagrams in the renderer would be confusing for the timer for + // the datagram + // queue in the network service, because the timestamp is taken when the + // datagram is added to the queue. outgoing_datagrams_ = WritableStream::CreateWithCountQueueingStrategy( - script_state_, MakeGarbageCollected<DatagramUnderlyingSink>(this), 1); + script_state_, + MakeGarbageCollected<DatagramUnderlyingSink>( + this, outgoing_datagrams_high_water_mark), + 1); received_streams_underlying_source_ = StreamVendingUnderlyingSource::CreateWithVendor<ReceiveStreamVendor>(
diff --git a/third_party/blink/renderer/modules/webtransport/quic_transport.h b/third_party/blink/renderer/modules/webtransport/quic_transport.h index 6c847d56..9ecbdb63 100644 --- a/third_party/blink/renderer/modules/webtransport/quic_transport.h +++ b/third_party/blink/renderer/modules/webtransport/quic_transport.h
@@ -97,6 +97,8 @@ // Removes the reference to a stream. void ForgetStream(uint32_t stream_id); + void SetDatagramWritableQueueExpirationDuration(base::TimeDelta duration); + // ScriptWrappable implementation void Trace(Visitor* visitor) const override;
diff --git a/third_party/blink/renderer/modules/webtransport/quic_transport_options.idl b/third_party/blink/renderer/modules/webtransport/quic_transport_options.idl index cb20475..4c7daba2 100644 --- a/third_party/blink/renderer/modules/webtransport/quic_transport_options.idl +++ b/third_party/blink/renderer/modules/webtransport/quic_transport_options.idl
@@ -6,4 +6,9 @@ dictionary QuicTransportOptions { sequence<RTCDtlsFingerprint> serverCertificateFingerprints; + + // This is an experimental and non-standard parameter. This controls the high + // water mark (https://streams.spec.whatwg.org/#high-water-mark) for the + // datagramWritable stream. + long datagramWritableHighWaterMark; };
diff --git a/third_party/blink/renderer/modules/webtransport/quic_transport_test.cc b/third_party/blink/renderer/modules/webtransport/quic_transport_test.cc index 650e668..7a711c0 100644 --- a/third_party/blink/renderer/modules/webtransport/quic_transport_test.cc +++ b/third_party/blink/renderer/modules/webtransport/quic_transport_test.cc
@@ -130,6 +130,8 @@ void(base::OnceCallback< void(uint32_t, mojo::ScopedDataPipeConsumerHandle)>)); + MOCK_METHOD1(SetOutgoingDatagramExpirationDuration, void(base::TimeDelta)); + void SendFin(uint32_t stream_id) override {} void AbortStream(uint32_t stream_id, uint64_t code) override {} @@ -160,9 +162,11 @@ } // Creates a QuicTransport object with the given |url|. - QuicTransport* Create(const V8TestingScope& scope, const String& url) { + QuicTransport* Create(const V8TestingScope& scope, + const String& url, + QuicTransportOptions* options) { AddBinder(scope); - return QuicTransport::Create(scope.GetScriptState(), url, EmptyOptions(), + return QuicTransport::Create(scope.GetScriptState(), url, options, ASSERT_NO_EXCEPTION); } @@ -212,9 +216,11 @@ // Creates, connects and returns a QuicTransport object with the given |url|. // Runs the event loop. - QuicTransport* CreateAndConnectSuccessfully(const V8TestingScope& scope, - const String& url) { - auto* quic_transport = Create(scope, url); + QuicTransport* CreateAndConnectSuccessfully( + const V8TestingScope& scope, + const String& url, + QuicTransportOptions* options = EmptyOptions()) { + auto* quic_transport = Create(scope, url, options); ConnectSuccessfully(quic_transport); return quic_transport; } @@ -617,9 +623,77 @@ EXPECT_TRUE(tester.Value().IsUndefined()); } +TEST_F(QuicTransportTest, BackpressureForOutgoingDatagrams) { + V8TestingScope scope; + auto* const options = MakeGarbageCollected<QuicTransportOptions>(); + options->setDatagramWritableHighWaterMark(3); + auto* quic_transport = CreateAndConnectSuccessfully( + scope, "quic-transport://example.com", options); + + EXPECT_CALL(*mock_quic_transport_, SendDatagram(_, _)) + .Times(4) + .WillRepeatedly( + Invoke([](base::span<const uint8_t>, + MockQuicTransport::SendDatagramCallback callback) { + std::move(callback).Run(true); + })); + + auto* writable = quic_transport->sendDatagrams(); + auto* script_state = scope.GetScriptState(); + auto* writer = writable->getWriter(script_state, ASSERT_NO_EXCEPTION); + + ScriptPromise promise1; + ScriptPromise promise2; + ScriptPromise promise3; + ScriptPromise promise4; + + { + auto* chunk = DOMUint8Array::Create(1); + *chunk->Data() = 'A'; + promise1 = + writer->write(script_state, ScriptValue::From(script_state, chunk), + ASSERT_NO_EXCEPTION); + } + { + auto* chunk = DOMUint8Array::Create(1); + *chunk->Data() = 'B'; + promise2 = + writer->write(script_state, ScriptValue::From(script_state, chunk), + ASSERT_NO_EXCEPTION); + } + { + auto* chunk = DOMUint8Array::Create(1); + *chunk->Data() = 'C'; + promise3 = + writer->write(script_state, ScriptValue::From(script_state, chunk), + ASSERT_NO_EXCEPTION); + } + { + auto* chunk = DOMUint8Array::Create(1); + *chunk->Data() = 'D'; + promise4 = + writer->write(script_state, ScriptValue::From(script_state, chunk), + ASSERT_NO_EXCEPTION); + } + + // The first two promises are resolved immediately. + v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate()); + EXPECT_EQ(promise1.V8Promise()->State(), v8::Promise::kFulfilled); + EXPECT_EQ(promise2.V8Promise()->State(), v8::Promise::kFulfilled); + EXPECT_EQ(promise3.V8Promise()->State(), v8::Promise::kPending); + EXPECT_EQ(promise4.V8Promise()->State(), v8::Promise::kPending); + + // The rest are resolved by the callback. + test::RunPendingTasks(); + v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate()); + EXPECT_EQ(promise3.V8Promise()->State(), v8::Promise::kFulfilled); + EXPECT_EQ(promise4.V8Promise()->State(), v8::Promise::kFulfilled); +} + TEST_F(QuicTransportTest, SendDatagramBeforeConnect) { V8TestingScope scope; - auto* quic_transport = Create(scope, "quic-transport://example.com"); + auto* quic_transport = + Create(scope, "quic-transport://example.com", EmptyOptions()); auto* writable = quic_transport->sendDatagrams(); auto* script_state = scope.GetScriptState(); @@ -1268,6 +1342,21 @@ EXPECT_TRUE(bidirectional_stream); } +TEST_F(QuicTransportTest, SetDatagramWritableQueueExpirationDuration) { + V8TestingScope scope; + + auto* quic_transport = + CreateAndConnectSuccessfully(scope, "quic-transport://example.com"); + + constexpr base::TimeDelta duration = base::TimeDelta::FromMilliseconds(40); + EXPECT_CALL(*mock_quic_transport_, + SetOutgoingDatagramExpirationDuration(duration)); + + quic_transport->SetDatagramWritableQueueExpirationDuration(duration); + + test::RunPendingTasks(); +} + } // namespace } // namespace blink
diff --git a/third_party/blink/renderer/modules/webtransport/web_transport.h b/third_party/blink/renderer/modules/webtransport/web_transport.h index ea7ccad..025ffc62 100644 --- a/third_party/blink/renderer/modules/webtransport/web_transport.h +++ b/third_party/blink/renderer/modules/webtransport/web_transport.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBTRANSPORT_WEB_TRANSPORT_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBTRANSPORT_WEB_TRANSPORT_H_ +#include "base/time/time.h" #include "base/types/pass_key.h" #include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" @@ -74,6 +75,11 @@ return quic_transport_->GetExecutionContext(); } + void setDatagramWritableQueueExpirationDuration(double ms) { + return quic_transport_->SetDatagramWritableQueueExpirationDuration( + base::TimeDelta::FromMillisecondsD(ms)); + } + private: const Member<QuicTransport> quic_transport_; };
diff --git a/third_party/blink/renderer/modules/webtransport/web_transport.idl b/third_party/blink/renderer/modules/webtransport/web_transport.idl index 16df63a..d619d615 100644 --- a/third_party/blink/renderer/modules/webtransport/web_transport.idl +++ b/third_party/blink/renderer/modules/webtransport/web_transport.idl
@@ -23,4 +23,9 @@ void close(optional WebTransportCloseInfo closeInfo = {}); readonly attribute Promise<void> ready; readonly attribute Promise<WebTransportCloseInfo> closed; + + // This is an experimental and non-standard function. Sets the duration + // which determines whether an outgoing datagram should be discarded due to + // being in the queue for too long, in milliseconds. + void setDatagramWritableQueueExpirationDuration(double ms); };
diff --git a/third_party/blink/renderer/platform/heap/BUILD.gn b/third_party/blink/renderer/platform/heap/BUILD.gn index a69520a..503522b0 100644 --- a/third_party/blink/renderer/platform/heap/BUILD.gn +++ b/third_party/blink/renderer/platform/heap/BUILD.gn
@@ -101,6 +101,7 @@ "v8_wrapper/member.h", "v8_wrapper/persistent.h", "v8_wrapper/process_heap.h", + "v8_wrapper/thread_state.cc", "v8_wrapper/thread_state.h", "v8_wrapper/thread_state_scopes.h", "v8_wrapper/unified_heap_controller.h", @@ -108,7 +109,8 @@ "v8_wrapper/visitor.h", ] - deps += [ "//v8:cppgc" ] + # Dependency on V8 which transitively depends on cppgc but exposes JS-related C++ heap through V8's Isolate. + deps += [ "//v8" ] } else { sources += [ "impl/atomic_entry_flag.h",
diff --git a/third_party/blink/renderer/platform/heap/self_keep_alive.h b/third_party/blink/renderer/platform/heap/self_keep_alive.h index 3eaff5d5..70b36f1 100644 --- a/third_party/blink/renderer/platform/heap/self_keep_alive.h +++ b/third_party/blink/renderer/platform/heap/self_keep_alive.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_SELF_KEEP_ALIVE_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_SELF_KEEP_ALIVE_H_ +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/assertions.h"
diff --git a/third_party/blink/renderer/platform/heap/v8_wrapper/garbage_collected.h b/third_party/blink/renderer/platform/heap/v8_wrapper/garbage_collected.h index 5867016..94cabcd 100644 --- a/third_party/blink/renderer/platform/heap/v8_wrapper/garbage_collected.h +++ b/third_party/blink/renderer/platform/heap/v8_wrapper/garbage_collected.h
@@ -4,6 +4,16 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_GARBAGE_COLLECTED_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_GARBAGE_COLLECTED_H_ -// TODO(chromium:1056170): Implement wrapper. + +// GC_PLUGIN_IGNORE is used to make the plugin ignore a particular class or +// field when checking for proper usage. When using GC_PLUGIN_IGNORE +// a bug-number should be provided as an argument where the bug describes +// what needs to happen to remove the GC_PLUGIN_IGNORE again. +#if defined(__clang__) +#define GC_PLUGIN_IGNORE(bug) \ + __attribute__((annotate("blink_gc_plugin_ignore"))) +#else +#define GC_PLUGIN_IGNORE(bug) +#endif #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_GARBAGE_COLLECTED_H_
diff --git a/third_party/blink/renderer/platform/heap/v8_wrapper/heap.h b/third_party/blink/renderer/platform/heap/v8_wrapper/heap.h index 5aecfbbb..30dc9f55 100644 --- a/third_party/blink/renderer/platform/heap/v8_wrapper/heap.h +++ b/third_party/blink/renderer/platform/heap/v8_wrapper/heap.h
@@ -5,6 +5,8 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_HEAP_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_HEAP_H_ +#include "third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h" +#include "v8/include/cppgc/allocation.h" #include "v8/include/cppgc/garbage-collected.h" namespace blink { @@ -14,6 +16,29 @@ using GarbageCollectedMixin = cppgc::GarbageCollectedMixin; +// Default MakeGarbageCollected: Constructs an instance of T, which is a garbage +// collected type. +template <typename T, typename... Args> +T* MakeGarbageCollected(Args&&... args) { + return cppgc::MakeGarbageCollected<T>( + ThreadStateFor<ThreadingTrait<T>::kAffinity>::GetState() + ->allocation_handle(), + std::forward<Args>(args)...); +} + +using AdditionalBytes = cppgc::AdditionalBytes; + +// Constructs an instance of T, which is a garbage collected type. This special +// version takes size which enables constructing inline objects. +template <typename T, typename... Args> +T* MakeGarbageCollected(AdditionalBytes additional_bytes, Args&&... args) { + return cppgc::MakeGarbageCollected<T>( + ThreadStateFor<ThreadingTrait<T>::kAffinity>::GetState() + ->allocation_handle(), + std::forward<AdditionalBytes>(additional_bytes), + std::forward<args>(args)...); +} + } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_HEAP_H_
diff --git a/third_party/blink/renderer/platform/heap/v8_wrapper/persistent.h b/third_party/blink/renderer/platform/heap/v8_wrapper/persistent.h index 98bf0ac2..dd0b82dc 100644 --- a/third_party/blink/renderer/platform/heap/v8_wrapper/persistent.h +++ b/third_party/blink/renderer/platform/heap/v8_wrapper/persistent.h
@@ -25,6 +25,8 @@ template <typename T> using CrossThreadWeakPersistent = cppgc::subtle::WeakCrossThreadPersistent<T>; +using PersistentLocation = cppgc::SourceLocation; + template <typename T> Persistent<T> WrapPersistent( T* value,
diff --git a/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.cc b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.cc new file mode 100644 index 0000000..8aec303 --- /dev/null +++ b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.cc
@@ -0,0 +1,45 @@ +// 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/platform/heap/v8_wrapper/thread_state.h" + +#include "v8/include/v8-cppgc.h" + +namespace blink { + +// static +base::LazyInstance<WTF::ThreadSpecific<ThreadState*>>::Leaky + ThreadState::thread_specific_ = LAZY_INSTANCE_INITIALIZER; + +// static +uint8_t ThreadState::main_thread_state_storage_[sizeof(ThreadState)]; + +// static +ThreadState* ThreadState::AttachMainThread(v8::CppHeap& cpp_heap) { + return new (main_thread_state_storage_) ThreadState(cpp_heap); +} + +// static +ThreadState* ThreadState::AttachCurrentThread(v8::CppHeap& cpp_heap) { + return new ThreadState(cpp_heap); +} + +// static +void ThreadState::DetachCurrentThread() { + auto* state = ThreadState::Current(); + DCHECK(state); + delete state; +} + +ThreadState::ThreadState(v8::CppHeap& cpp_heap) + : cpp_heap_(cpp_heap), + allocation_handle_(cpp_heap.GetAllocationHandle()) + thread_id_(CurrentThread()) {} + +ThreadState::~ThreadState() { + DCHECK(!IsMainThread()); + DCHECK(IsCreationThread()); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h index eea17788..25289ae4 100644 --- a/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h +++ b/third_party/blink/renderer/platform/heap/v8_wrapper/thread_state.h
@@ -5,13 +5,108 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_THREAD_STATE_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_THREAD_STATE_H_ +#include "base/lazy_instance.h" +#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" +#include "third_party/blink/renderer/platform/wtf/thread_specific.h" +#include "third_party/blink/renderer/platform/wtf/threading.h" #include "v8/include/cppgc/prefinalizer.h" +#include "v8/include/v8.h" + +namespace v8 { +class CppHeap; +} // namespace v8 + +namespace cppgc { +class AllocationHandle; +} // namespace cppgc namespace blink { #define USING_PRE_FINALIZER(Class, PreFinalizer) \ CPPGC_USING_PRE_FINALIZER(Class, PreFinalizer) +// ThreadAffinity indicates which threads objects can be used on. We +// distinguish between objects that can be used on the main thread +// only and objects that can be used on any thread. +// +// For objects that can only be used on the main thread, we avoid going +// through thread-local storage to get to the thread state. This is +// important for performance. +enum ThreadAffinity { + kAnyThread, + kMainThreadOnly, +}; + +// TODO(mlippautz): Provide specializations. +template <typename T> +struct ThreadingTrait { + STATIC_ONLY(ThreadingTrait); + static constexpr ThreadAffinity kAffinity = kAnyThread; +}; + +template <ThreadAffinity> +class ThreadStateFor; + +class ThreadState final { + public: + static ALWAYS_INLINE ThreadState* Current() { + return *(thread_specific_.Get()); + } + + static ALWAYS_INLINE ThreadState* MainThreadState() { + DCHECK(Current()->IsMainThread()); + return reinterpret_cast<ThreadState*>(main_thread_state_storage_); + } + + // Attaches a ThreadState to the main-thread. + static ThreadState* AttachMainThread(v8::CppHeap&); + // Attaches a ThreadState to the currently running thread. Must not be the + // main thread and must be called after AttachMainThread(). + static ThreadState* AttachCurrentThread(v8::CppHeap&); + static void DetachCurrentThread(); + + ALWAYS_INLINE cppgc::AllocationHandle& allocation_handle() const { + return allocation_handle_; + } + + private: + // Main-thread ThreadState avoids TLS completely by using a regular global. + // The object is manually managed and should not rely on global ctor/dtor. + static uint8_t main_thread_state_storage_[] alignas(ThreadState); + // Storage for all ThreadState objects. This includes the main-thread + // ThreadState as well. + static base::LazyInstance<WTF::ThreadSpecific<ThreadState*>>::Leaky + thread_specific_; + + explicit ThreadState(v8::CppHeap&); + ~ThreadState(); + + bool IsMainThread() const { return this == MainThreadState(); } + bool IsCreationThread() const { return thread_id_ == CurrentThread(); } + + // Handle is the most frequently accessed field as it is required for + // MakeGarbageCollected(). + cppgc::AllocationHandle& allocation_handle_; + v8::CppHeap& cpp_heap_; + base::PlatformThreadId thread_id_; +}; + +template <> +class ThreadStateFor<kMainThreadOnly> { + STATIC_ONLY(ThreadStateFor); + + public: + static ThreadState* GetState() { return ThreadState::MainThreadState(); } +}; + +template <> +class ThreadStateFor<kAnyThread> { + STATIC_ONLY(ThreadStateFor); + + public: + static ThreadState* GetState() { return ThreadState::Current(); } +}; + } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_V8_WRAPPER_THREAD_STATE_H_
diff --git a/third_party/blink/renderer/platform/network/http_parsers.cc b/third_party/blink/renderer/platform/network/http_parsers.cc index 0178dde1..0038044c 100644 --- a/third_party/blink/renderer/platform/network/http_parsers.cc +++ b/third_party/blink/renderer/platform/network/http_parsers.cc
@@ -114,6 +114,18 @@ return out; } +WTF::HashMap<blink::CSPDirectiveName, String> ConvertToBlink( + base::flat_map<CSPDirectiveName, std::string> directives) { + WTF::HashMap<blink::CSPDirectiveName, String> out; + + for (auto& list : directives) { + out.insert(ConvertToBlink(list.first), + String::FromUTF8(std::move(list.second))); + } + + return out; +} + WTF::Vector<WTF::String> ConvertToBlink(std::vector<std::string> in) { WTF::Vector<WTF::String> out; for (auto& el : in) @@ -132,6 +144,7 @@ blink::ContentSecurityPolicyPtr ConvertToBlink( ContentSecurityPolicyPtr policy_in) { return blink::ContentSecurityPolicy::New( + ConvertToBlink(std::move(policy_in->raw_directives)), ConvertToBlink(std::move(policy_in->directives)), policy_in->upgrade_insecure_requests, policy_in->treat_as_public_address, policy_in->block_all_mixed_content, policy_in->sandbox,
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index f35fb4c..be7aa465 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -2176,8 +2176,6 @@ }, { name: "WebNFC", - origin_trial_feature_name: "WebNFC", - origin_trial_os: ["android"], status: "experimental", }, {
diff --git a/third_party/blink/renderer/platform/text/locale_to_script_mapping.cc b/third_party/blink/renderer/platform/text/locale_to_script_mapping.cc index b940c8f..289f26c3 100644 --- a/third_party/blink/renderer/platform/text/locale_to_script_mapping.cc +++ b/third_party/blink/renderer/platform/text/locale_to_script_mapping.cc
@@ -155,7 +155,7 @@ {"zxxx", USCRIPT_UNWRITTEN_LANGUAGES}, {"zzzz", USCRIPT_UNKNOWN}}; for (const auto& kv : kScriptNameCodeList) { - if (CodeUnitCompareIgnoringASCIICase(script_name, kv.subtag) == 0) + if (EqualIgnoringASCIICase(script_name, kv.subtag)) return kv.script; } return USCRIPT_INVALID_CODE; @@ -447,7 +447,7 @@ while (!canonical_locale.IsEmpty()) { for (const auto& kv : kLocaleScriptList) { - if (CodeUnitCompareIgnoringASCIICase(canonical_locale, kv.subtag) == 0) + if (EqualIgnoringASCIICase(canonical_locale, kv.subtag)) return kv.script; } @@ -472,7 +472,7 @@ {"tw", USCRIPT_TRADITIONAL_HAN}, }; for (const auto& kv : kRegionScriptList) { - if (CodeUnitCompareIgnoringASCIICase(region, kv.subtag) == 0) + if (EqualIgnoringASCIICase(region, kv.subtag)) return kv.script; } return USCRIPT_COMMON;
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index ef5b3cd..c0ee6b2 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -1860,9 +1860,9 @@ external/wpt/visual-viewport/viewport-scale-manual.html [ Skip ] external/wpt/visual-viewport/viewport-scroll-event-manual.html [ Skip ] external/wpt/visual-viewport/viewport-url-bar-changes-height-manual.html [ Skip ] +external/wpt/web-nfc/NDEFReader-read-document-hidden-manual.https.html [ Skip ] +external/wpt/web-nfc/NDEFReader-write-document-hidden-manual.https.html [ Skip ] external/wpt/screen-wake-lock/wakelock-document-hidden-manual.https.html [ Skip ] -external/wpt/web-nfc/NDEFReader-document-hidden-manual.https.html [ Skip ] -external/wpt/web-nfc/NDEFWriter-document-hidden-manual.https.html [ Skip ] external/wpt/web-share/share-cancel-manual.https.html [ Skip ] external/wpt/web-share/share-extra-argument-manual.https.html [ Skip ] external/wpt/web-share/share-extra-field-manual.https.html [ Skip ] @@ -2038,11 +2038,6 @@ crbug.com/626703 [ Mac ] external/wpt/payment-method-basic-card/billing-address-is-null-manual.https.html [ Skip ] crbug.com/626703 [ Win ] external/wpt/payment-method-basic-card/billing-address-is-null-manual.https.html [ Skip ] -# Chrome Win/Linux/Mac don't support WebNFC origin trial -[ Win ] virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/web-nfc-origin-trial-interfaces.html [ Skip ] -[ Linux ] virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/web-nfc-origin-trial-interfaces.html [ Skip ] -[ Mac ] virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/web-nfc-origin-trial-interfaces.html [ Skip ] - crbug.com/626703 [ Win7 ] external/wpt/pointerevents/pointerevent_fractional_coordinates-manual.html [ Skip ] crbug.com/626703 [ Linux ] external/wpt/payment-request/dynamically-change-shipping-options-manual.https.html [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 5549499..8227144 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1005,6 +1005,8 @@ virtual/layout_ng_block_frag/external/wpt/css/css-break/tall-line-in-short-fragmentainer-002.html [ Pass ] virtual/layout_ng_block_frag/external/wpt/css/css-break/trailing-child-margin-000.html [ Pass ] virtual/layout_ng_block_frag/external/wpt/css/css-break/trailing-child-margin-002.html [ Pass ] +virtual/layout_ng_block_frag/external/wpt/css/css-multicol/balance-break-avoidance-001.html [ Pass ] +virtual/layout_ng_block_frag/external/wpt/css/css-multicol/balance-orphans-widows-000.html [ Pass ] virtual/layout_ng_block_frag/external/wpt/css/css-multicol/baseline-001.html [ Pass ] virtual/layout_ng_block_frag/external/wpt/css/css-multicol/baseline-007.html [ Pass ] virtual/layout_ng_block_frag/external/wpt/css/css-multicol/baseline-008.html [ Pass ] @@ -1044,8 +1046,6 @@ crbug.com/1079031 virtual/layout_ng_block_frag/external/wpt/css/css-break/block-end-aligned-abspos-with-overflow.html [ Failure ] crbug.com/1113911 virtual/layout_ng_block_frag/external/wpt/css/css-break/fieldset-001.html [ Failure ] crbug.com/1146973 virtual/layout_ng_block_frag/external/wpt/css/css-break/out-of-flow-in-multicolumn-009.html [ Failure ] -crbug.com/1066380 virtual/layout_ng_block_frag/external/wpt/css/css-break/widows-orphans-002.html [ Failure ] -crbug.com/1066380 virtual/layout_ng_block_frag/external/wpt/css/css-break/widows-orphans-004.html [ Failure ] crbug.com/1079031 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/change-out-of-flow-type-and-remove-inner-multicol-crash.html [ Crash Failure ] crbug.com/1058792 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/composited-under-clip-under-multicol.html [ Failure Crash ] crbug.com/996655 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/going-out-of-flow-after-spanner.html [ Crash Failure Pass ] @@ -1111,7 +1111,6 @@ crbug.com/829028 virtual/layout_ng_block_frag/fast/multicol/nested-with-padding.html [ Failure ] crbug.com/1131125 virtual/layout_ng_block_frag/fast/multicol/newmulticol/breaks-3-columns-3.html [ Failure ] crbug.com/1066616 virtual/layout_ng_block_frag/fast/multicol/newmulticol/clipping-overflow-hidden.html [ Failure ] -crbug.com/1066380 virtual/layout_ng_block_frag/fast/multicol/newmulticol/orphans-and-widows-balance.html [ Failure ] crbug.com/1079031 virtual/layout_ng_block_frag/fast/multicol/out-of-flow/abspos-auto-position-on-line-at-boundary.html [ Failure ] crbug.com/1079031 virtual/layout_ng_block_frag/fast/multicol/out-of-flow/abspos-auto-position.html [ Failure ] crbug.com/1079031 virtual/layout_ng_block_frag/fast/multicol/out-of-flow/abspos-auto-position-on-line.html [ Failure ] @@ -2005,9 +2004,6 @@ crbug.com/332189 external/wpt/css/css-transitions/no-transition-from-ua-to-blocking-stylesheet.html [ Pass Failure ] -# Awaiting DevTools changes. -crbug.com/1152391 http/tests/devtools/elements/copy-styles.js [ Pass Failure ] - # Some control characters still not visible crbug.com/893490 [ Mac ] external/wpt/css/css-text/white-space/control-chars-001.html [ Failure ] crbug.com/893490 [ Mac ] external/wpt/css/css-text/white-space/control-chars-002.html [ Failure ] @@ -3223,6 +3219,8 @@ crbug.com/829028 external/wpt/css/css-break/trailing-child-margin-002.html [ Failure ] crbug.com/967329 external/wpt/css/css-multicol/columnfill-auto-max-height-001.html [ Failure ] crbug.com/967329 external/wpt/css/css-multicol/columnfill-auto-max-height-002.html [ Failure ] +crbug.com/829028 external/wpt/css/css-multicol/balance-break-avoidance-001.html [ Failure ] +crbug.com/829028 external/wpt/css/css-multicol/balance-orphans-widows-000.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/baseline-001.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/baseline-007.html [ Failure ] crbug.com/829028 external/wpt/css/css-multicol/baseline-008.html [ Failure ]
diff --git a/third_party/blink/web_tests/android/ChromiumWPTExpectations b/third_party/blink/web_tests/android/ChromiumWPTExpectations index b96d70e..6072b851 100644 --- a/third_party/blink/web_tests/android/ChromiumWPTExpectations +++ b/third_party/blink/web_tests/android/ChromiumWPTExpectations
@@ -4494,9 +4494,9 @@ crbug.com/1050754 external/wpt/web-nfc/NDEFMessage_constructor.https.html [ Failure Pass ] crbug.com/1050754 external/wpt/web-nfc/NDEFReader_scan.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFReader_scan_iframe.https.html [ Failure ] +crbug.com/1050754 external/wpt/web-nfc/NDEFReader_write.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFReadingEvent_constructor.https.html [ Failure Pass ] crbug.com/1050754 external/wpt/web-nfc/NDEFRecord_constructor.https.html [ Failure Pass ] -crbug.com/1050754 external/wpt/web-nfc/NDEFWriter_write.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/idlharness.https.window.html [ Failure Pass ] crbug.com/1050754 external/wpt/web-nfc/nfc_permission.https.html [ Crash Failure ] crbug.com/1050754 external/wpt/web-share/share-sharePromise-internal-slot.https.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/android/WeblayerWPTExpectations b/third_party/blink/web_tests/android/WeblayerWPTExpectations index 59454e16..6833b93 100644 --- a/third_party/blink/web_tests/android/WeblayerWPTExpectations +++ b/third_party/blink/web_tests/android/WeblayerWPTExpectations
@@ -4548,9 +4548,9 @@ crbug.com/1050754 external/wpt/web-nfc/NDEFMessage_constructor.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFReader_scan.https.html [ Failure Timeout ] crbug.com/1050754 external/wpt/web-nfc/NDEFReader_scan_iframe.https.html [ Failure Timeout ] +crbug.com/1050754 external/wpt/web-nfc/NDEFReader_write.https.html [ Failure Timeout ] crbug.com/1050754 external/wpt/web-nfc/NDEFReadingEvent_constructor.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFRecord_constructor.https.html [ Failure ] -crbug.com/1050754 external/wpt/web-nfc/NDEFWriter_write.https.html [ Failure Timeout ] crbug.com/1050754 external/wpt/web-nfc/idlharness.https.window.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/nfc_permission.https.html [ Crash Failure ] crbug.com/1050754 external/wpt/web-otp/idlharness.https.window.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/android/WebviewWPTExpectations b/third_party/blink/web_tests/android/WebviewWPTExpectations index b09d9d4..df00ddf 100644 --- a/third_party/blink/web_tests/android/WebviewWPTExpectations +++ b/third_party/blink/web_tests/android/WebviewWPTExpectations
@@ -5055,9 +5055,9 @@ crbug.com/1050754 external/wpt/web-nfc/NDEFMessage_constructor.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFReader_scan.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFReader_scan_iframe.https.html [ Failure ] +crbug.com/1050754 external/wpt/web-nfc/NDEFReader_write.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFReadingEvent_constructor.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/NDEFRecord_constructor.https.html [ Failure ] -crbug.com/1050754 external/wpt/web-nfc/NDEFWriter_write.https.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/idlharness.https.window.html [ Failure ] crbug.com/1050754 external/wpt/web-nfc/nfc_permission.https.html [ Crash Failure ] crbug.com/1050754 external/wpt/web-otp/idlharness.https.window.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-break-avoidance-000.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-break-avoidance-000.html new file mode 100644 index 0000000..f6540e4a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-break-avoidance-000.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://www.w3.org/TR/css-multicol-1/#filling-columns"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-between"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-within"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="width:100px; height:100px; background:red;"> + <div style="columns:4; background:green;"> + <div style="break-inside:avoid; height:100px;"></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-break-avoidance-001.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-break-avoidance-001.html new file mode 100644 index 0000000..1449110 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-break-avoidance-001.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://www.w3.org/TR/css-multicol-1/#filling-columns"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-between"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-within"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="width:100px; height:100px; background:red;"> + <div style="columns:4; background:green;"> + <div style="break-inside:avoid; break-after:avoid; height:50px;"></div> + <div style="break-inside:avoid; height:50px;"></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-orphans-widows-000.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-orphans-widows-000.html new file mode 100644 index 0000000..97f2d0c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/balance-orphans-widows-000.html
@@ -0,0 +1,37 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://www.w3.org/TR/css-multicol-1/#filling-columns"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#widows-orphans"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<style> + .multicol { + columns: 2; + orphans: 4; + widows: 4; + width: 100px; + column-gap: 80px; + column-rule: 80px solid green; + line-height: 0; + background: red; + } + span { + display: inline-block; + width: 100%; + height: 10px; + background: green; + } + span.tall { + height: 40px; + } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div class="multicol"> + <span></span><br> + <span></span><br> + <span class="tall"></span><br> + <span class="tall"></span><br> + <span class="tall"></span><br> + <span class="tall"></span><br> + <span></span><br> + <span></span><br> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-fill-balance-005.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-fill-balance-005.html new file mode 100644 index 0000000..ad9a592 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-fill-balance-005.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://www.w3.org/TR/css-multicol-1/#filling-columns"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div style="columns:2; column-gap:0; width:100px; height:20px; max-height:40px; min-height:100px; background:red;"> + <div style="height:200px; background:green;"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-fill-balance-nested-000.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-fill-balance-nested-000.html new file mode 100644 index 0000000..5e466df --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/multicol-fill-balance-nested-000.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://www.w3.org/TR/css-multicol-1/#the-multi-column-model"> +<link rel="help" href="https://www.w3.org/TR/css-multicol-1/#filling-columns"> +<link rel="help" href="https://www.w3.org/TR/css-break-3/#break-within"> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht"> +<style> + #outer, #outer div { background: green; } + #inner * { break-inside: avoid; } +</style> +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> +<div id="outer" style="columns:2; column-gap:0; column-fill:auto; width:100px; height:100px;"> + <div id="inner" style="columns:2; column-gap:0;"> + <div style="height:50px;"></div> + <div style="height:100px;"> + <div style="margin-left:100%; width:100%; height:50px; background:red;"></div> + </div> + <div style="height:50px;"></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js b/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js index aa94257e..2665f3d 100644 --- a/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js +++ b/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js
@@ -214,23 +214,11 @@ return createNDEFError(null); } - async cancelWatch(id) { + cancelWatch(id) { let index = this.watchers_.findIndex(value => value.id === id); - if (index === -1) { - return createNDEFError(device.mojom.NDEFErrorType.NOT_FOUND); + if (index !== -1) { + this.watchers_.splice(index, 1); } - - this.watchers_.splice(index, 1); - return createNDEFError(null); - } - - async cancelAllWatches() { - if (this.watchers_.length === 0) { - return createNDEFError(device.mojom.NDEFErrorType.NOT_FOUND); - } - - this.watchers_.splice(0, this.watchers_.length); - return createNDEFError(null); } getHWError() {
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-document-hidden-manual.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-read-document-hidden-manual.https.html similarity index 80% rename from third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-document-hidden-manual.https.html rename to third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-read-document-hidden-manual.https.html index ffbd7ebc..47c1332 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-document-hidden-manual.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-read-document-hidden-manual.https.html
@@ -9,15 +9,15 @@ <script> nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); + const ndef = new NDEFReader(); + const ndefWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); const promise = new Promise((resolve, reject) => { - readerWatcher.wait_for("reading").then(event => { + ndefWatcher.wait_for("reading").then(event => { if (document.hidden) reject(); else resolve(); }); }); - await reader.scan(); + await ndef.scan(); await promise; }, "Test NDEFReader.onreading is not fired when document is hidden");
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter-document-hidden-manual.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-write-document-hidden-manual.https.html similarity index 79% rename from third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter-document-hidden-manual.https.html rename to third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-write-document-hidden-manual.https.html index 1a28398..150e5a2 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter-document-hidden-manual.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader-write-document-hidden-manual.https.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <meta charset="utf-8"> <meta name="timeout" content="long"> -<title>NDEFWriter.write respect page visibility changes</title> +<title>NDEFReader.write respect page visibility changes</title> <link rel="help" href="https://w3c.github.io/web-nfc/#visible-document"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -9,7 +9,7 @@ <script> promise_test(async t => { - const writer = new NDEFWriter(); + const writer = new NDEFReader(); const p1 = writer.write(test_text_data); return await new Promise((resolve, reject) => { @@ -20,7 +20,7 @@ reject(); }); }); -}, "Test NDEFWriter.write operation should be suspend when document is not visible"); +}, "Test NDEFReader.write operation should be suspended when document is not visible"); </script>
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 b551af0..ba101d6 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
@@ -21,104 +21,122 @@ ]; function waitSyntaxErrorPromise(t, scan_options) { - const reader = new NDEFReader(); - return promise_rejects_dom(t, 'SyntaxError', reader.scan(scan_options)); + const ndef = new NDEFReader(); + return promise_rejects_dom(t, 'SyntaxError', ndef.scan(scan_options)); } nfc_test(async t => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const promises = []; invalid_signals.forEach(invalid_signal => { promises.push(promise_rejects_js(t, TypeError, - reader.scan({ signal: invalid_signal }))); + ndef.scan({ signal: invalid_signal }))); }); await Promise.all(promises); }, "Test that NDEFReader.scan rejects if signal is not an AbortSignal."); nfc_test(async t => { await test_driver.set_permission({ name: 'nfc' }, 'denied', false); - const reader = new NDEFReader(); - await promise_rejects_dom(t, 'NotAllowedError', reader.scan()); + const ndef = new NDEFReader(); + await promise_rejects_dom(t, 'NotAllowedError', ndef.scan()); }, "NDEFReader.scan should fail if user permission is not granted."); // We do not provide NFC mock here to simulate that there has no available // implementation for NFC Mojo interface. nfc_test(async (t, mockNFC) => { mockNFC.simulateClosedPipe(); - const reader = new NDEFReader(); - await promise_rejects_dom(t, 'NotSupportedError', reader.scan()); -}, "NDEFReader.scan should faild if no implementation for NFC Mojo interface."); + const ndef = new NDEFReader(); + await promise_rejects_dom(t, 'NotSupportedError', ndef.scan()); +}, "NDEFReader.scan should fail if no implementation for NFC Mojo interface."); nfc_test(async (t, mockNFC) => { mockNFC.setHWStatus(NFCHWStatus.DISABLED); - const reader = new NDEFReader(); - await promise_rejects_dom(t, 'NotReadableError', reader.scan()); + const ndef = new NDEFReader(); + await promise_rejects_dom(t, 'NotReadableError', ndef.scan()); }, "NDEFReader.scan should fail if NFC HW is disabled."); nfc_test(async (t, mockNFC) => { mockNFC.setHWStatus(NFCHWStatus.NOT_SUPPORTED); - const reader = new NDEFReader(); - await promise_rejects_dom(t, 'NotSupportedError', reader.scan()); + const ndef = new NDEFReader(); + await promise_rejects_dom(t, 'NotSupportedError', ndef.scan()); }, "NDEFReader.scan should fail if NFC HW is not supported."); +nfc_test(async () => { + await new Promise((resolve,reject) => { + const iframe = document.createElement('iframe'); + iframe.srcdoc = `<script> + window.onmessage = async (message) => { + if (message.data === "Ready") { + try { + const ndef = new NDEFReader(); + await ndef.scan(); + parent.postMessage("Failure", "*"); + } catch (error) { + if (error.name == "InvalidStateError") { + parent.postMessage("Success", "*"); + } else { + parent.postMessage("Failure", "*"); + } + } + } + }; + <\/script>`; + iframe.onload = () => iframe.contentWindow.postMessage('Ready', '*'); + document.body.appendChild(iframe); + window.onmessage = message => { + if (message.data == 'Success') { + resolve(); + } else if (message.data == 'Failure') { + reject(); + } + } + }); +}, 'Test that WebNFC API is not accessible from iframe context.'); + nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); + const promise = ndefWatcher.wait_for("reading").then(event => { assert_true(event instanceof NDEFReadingEvent); controller.abort(); }); - await reader.scan({signal : controller.signal}); + await ndef.scan({signal : controller.signal}); mockNFC.setReadingMessage(createMessage([createTextRecord(test_text_data)])); await promise; }, "Test that nfc watch success if NFC HW is enabled."); nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); - const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { - assert_true(event instanceof NDEFReadingEvent); - controller.abort(); - }); - await reader.scan({signal : controller.signal}); - - mockNFC.setReadingMessage(createMessage([createTextRecord(test_text_data)])); - await promise; -}, "Test that NDEFReader.scan matches any ids if NDEFScanOptions.id is undefined."); - -nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); controller.abort(); - await promise_rejects_dom(t, 'AbortError', reader.scan({signal: controller.signal})); + await promise_rejects_dom(t, 'AbortError', ndef.scan({signal: controller.signal})); }, "Test that NDEFReader.scan rejects if NDEFScanOptions.signal is already aborted."); nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const promise = reader.scan({signal: controller.signal}); + const promise = ndef.scan({signal: controller.signal}); controller.abort(); await promise_rejects_dom(t, 'AbortError', promise); }, "Test that NDEFReader.scan rejects if NDEFScanOptions.signal aborts right after \ the scan invocation."); nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); const message = createMessage([createTextRecord(test_text_data)]); - const promise = readerWatcher.wait_for("reading").then(event => { + const promise = ndefWatcher.wait_for("reading").then(event => { assert_true(event instanceof NDEFReadingEvent); }); - await reader.scan({signal : controller.signal}); + await ndef.scan({signal : controller.signal}); mockNFC.setReadingMessage(message); await promise; - reader.onreading = t.unreached_func("reading event should not be fired."); + ndef.onreading = t.unreached_func("reading event should not be fired."); mockNFC.setReadingMessage(message); controller.abort(); await new Promise((resolve, reject) => { @@ -127,10 +145,10 @@ }, "Test that NDEFReader can not get any reading events once the signal aborts."); nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); + const promise = ndefWatcher.wait_for("reading").then(event => { controller.abort(); assert_true(event instanceof NDEFReadingEvent); @@ -151,7 +169,7 @@ assert_equals(decoder.decode(event.message.records[0].toRecords()[0].toRecords()[0].data), test_text_data, 'data has the same content with the original dictionary'); }); - await reader.scan({signal : controller.signal}); + await ndef.scan({signal : controller.signal}); // An external type record --contains-> a local type record --contains-> a text record. const messageContainText = createMessage([createTextRecord(test_text_data)]); @@ -164,10 +182,10 @@ }, "NDEFRecord.toRecords returns its embedded records correctly."); nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); + const promise = ndefWatcher.wait_for("reading").then(event => { controller.abort(); assert_true(event instanceof NDEFReadingEvent); @@ -203,7 +221,7 @@ assert_array_equals(embedded_record_types.sort(), ['text', 'url'], 'smart-poster record\'s contained record types'); }); - await reader.scan({signal : controller.signal}); + await ndef.scan({signal : controller.signal}); // A smart-poster record contains a uri record, text record. const uri_record = createUrlRecord(test_url_data); @@ -218,17 +236,17 @@ nfc_test(async (t, mockNFC) => { const promises = []; - const reader1 = new NDEFReader(); - const readerWatcher1 = new EventWatcher(t, reader1, ["reading", "readingerror"]); - const promise1 = readerWatcher1.wait_for("readingerror"); + const ndef1 = new NDEFReader(); + const ndefWatcher1 = new EventWatcher(t, ndef1, ["reading", "readingerror"]); + const promise1 = ndefWatcher1.wait_for("readingerror"); promises.push(promise1); - await reader1.scan(); + await ndef1.scan(); - const reader2 = new NDEFReader(); - const readerWatcher2 = new EventWatcher(t, reader2, ["reading", "readingerror"]); - const promise2 = readerWatcher2.wait_for("readingerror"); + const ndef2 = new NDEFReader(); + const ndefWatcher2 = new EventWatcher(t, ndef2, ["reading", "readingerror"]); + const promise2 = ndefWatcher2.wait_for("readingerror"); promises.push(promise2); - await reader2.scan(); + await ndef2.scan(); mockNFC.simulateNonNDEFTagDiscovered(); await Promise.all(promises); @@ -236,15 +254,15 @@ expose NDEF technology."); nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); + const promise = ndefWatcher.wait_for("reading").then(event => { assert_equals(event.serialNumber, fake_tag_serial_number); assert_equals(event.message.records.length, 0); controller.abort(); }); - await reader.scan({signal : controller.signal}); + await ndef.scan({signal : controller.signal}); mockNFC.setReadingMessage({ records: [] }); await promise; @@ -252,7 +270,7 @@ with empty records array for NDEFMessage."); nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); const message = createMessage([createTextRecord(test_text_data), createMimeRecordFromJson(test_json_data), @@ -262,31 +280,31 @@ createUrlRecord(test_url_data, true), createRecord('w3.org:xyz', test_buffer_data)], test_message_origin); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); + const promise = ndefWatcher.wait_for("reading").then(event => { assert_equals(event.serialNumber, fake_tag_serial_number); assertWebNDEFMessagesEqual(event.message, new NDEFMessage(message)); controller.abort(); }); - await reader.scan({signal : controller.signal}); + await ndef.scan({signal : controller.signal}); mockNFC.setReadingMessage(message); 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()); + const ndef = new NDEFReader(); + const promise1 = ndef.scan(); + const promise2 = promise_rejects_dom(t, 'InvalidStateError', ndef.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 ndef = new NDEFReader(); const controller = new AbortController(); - await reader.scan({signal : controller.signal}); + await ndef.scan({signal : controller.signal}); controller.abort(); - await reader.scan(); + await ndef.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_iframe.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan_iframe.https.html index 8803c25fb..6967c76 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan_iframe.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_scan_iframe.https.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <meta charset=utf-8> -<title>NDEFWriter.scan with an focused iframe</title> +<title>NDEFReader.scan with an focused iframe</title> <link rel="help" href="https://w3c.github.io/web-nfc/"/> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -9,15 +9,15 @@ <script> nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const promise = ndefWatcher.wait_for("reading").then(event => { assert_true(event instanceof NDEFReadingEvent); controller.abort(); }); - await reader.scan({ signal: controller.signal }); + await ndef.scan({ signal: controller.signal }); const iframe = document.createElement('iframe'); iframe.src = 'resources/support-iframe.html'; @@ -37,7 +37,7 @@ // Remove iframe from main document. iframe.parentNode.removeChild(iframe); -}, 'Test that NDEFWriter.scan is not suspended if iframe gains focus.'); +}, 'Test that NDEFReader.scan is not suspended if iframe gains focus.'); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_write.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_write.https.html similarity index 75% rename from third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_write.https.html rename to third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_write.https.html index 57fd300..35e6dd372 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/NDEFWriter_write.https.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/NDEFReader_write.https.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <meta charset=utf-8> -<title>Web NFC: NDEFWriter.write Tests</title> +<title>Web NFC: NDEFReader.write Tests</title> <link rel="author" title="Intel" href="http://www.intel.com"/> <link rel="help" href="https://w3c.github.io/web-nfc/"/> <script src="/resources/testharness.js"></script> @@ -124,21 +124,21 @@ ]; nfc_test(async t => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); const promises = []; invalid_type_messages.forEach(message => { promises.push( - promise_rejects_js(t, TypeError, writer.write(message))); + promise_rejects_js(t, TypeError, ndef.write(message))); }); await Promise.all(promises); }, "Test that promise is rejected with TypeError if NDEFMessageSource is invalid."); nfc_test(async t => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); const promises = []; invalid_syntax_messages.forEach(message => { promises.push( - promise_rejects_dom(t, 'SyntaxError', writer.write(message))); + promise_rejects_dom(t, 'SyntaxError', ndef.write(message))); }); await Promise.all(promises); }, "Test that promise is rejected with SyntaxError if NDEFMessageSource contains\ @@ -146,25 +146,25 @@ nfc_test(async t => { await test_driver.set_permission({ name: 'nfc' }, 'denied', false); - const writer = new NDEFWriter(); - await promise_rejects_dom(t, 'NotAllowedError', writer.write(test_text_data)); -}, 'NDEFWriter.write should fail if user permission is not granted.'); + const ndef = new NDEFReader(); + await promise_rejects_dom(t, 'NotAllowedError', ndef.write(test_text_data)); +}, 'NDEFReader.write should fail if user permission is not granted.'); // We do not provide NFC mock here to simulate that there has no available // implementation for NFC Mojo interface. nfc_test(async (t, mockNFC) => { mockNFC.simulateClosedPipe(); - const writer = new NDEFWriter(); - await promise_rejects_dom(t, 'NotSupportedError', writer.write(test_text_data)); -}, 'NDEFWriter.write should fail if no implementation for NFC Mojo interface is available.'); + const ndef = new NDEFReader(); + await promise_rejects_dom(t, 'NotSupportedError', ndef.write(test_text_data)); +}, 'NDEFReader.write should fail if no implementation for NFC Mojo interface is available.'); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); const controller = new AbortController(); //Make sure push is pending mockNFC.setPendingPushCompleted(false); - const p = writer.write(test_text_data, { signal: controller.signal }); + const p = ndef.write(test_text_data, { signal: controller.signal }); const rejected = promise_rejects_dom(t, 'AbortError', p); let callback_called = false; await new Promise(resolve => { @@ -176,76 +176,71 @@ }); await rejected; assert_true(callback_called, 'timeout should have caused the abort'); -}, "NDEFWriter.write should fail if abort write request before write happends."); +}, "NDEFReader.write should fail if abort write request before write happends."); nfc_test(async t => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); const controller = new AbortController(); assert_false(controller.signal.aborted); controller.abort(); assert_true(controller.signal.aborted); await promise_rejects_dom(t, 'AbortError', - writer.write(test_text_data, { signal: controller.signal })); -}, "NDEFWriter.write should fail if signal's aborted flag is set."); + ndef.write(test_text_data, { signal: controller.signal })); +}, "NDEFReader.write should fail if signal's aborted flag is set."); nfc_test(async t => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); const promises = []; invalid_signals.forEach(invalid_signal => { promises.push(promise_rejects_js(t, TypeError, - writer.write(test_text_data, { signal: invalid_signal }))); + ndef.write(test_text_data, { signal: invalid_signal }))); }); await Promise.all(promises); -}, "NDEFWriter.write should fail if signal is not an AbortSignal."); +}, "NDEFReader.write should fail if signal is not an AbortSignal."); nfc_test(async (t, mockNFC) => { - const writer1 = new NDEFWriter(); - const writer2 = new NDEFWriter(); + const ndef1 = new NDEFReader(); + const ndef2 = new NDEFReader(); const controller = new AbortController(); - const p1 = writer1.write(test_text_data, { signal: controller.signal }); + const p1 = ndef1.write(test_text_data, { signal: controller.signal }); // Even though write request is grantable, // this abort should be processed synchronously. controller.abort(); await promise_rejects_dom(t, 'AbortError', p1); - await writer2.write(test_text_data); + await ndef2.write(test_text_data); assertNDEFMessagesEqual(test_text_data, mockNFC.pushedMessage()); }, "Synchronously signaled abort."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); mockNFC.setHWStatus(NFCHWStatus.DISABLED); - await promise_rejects_dom(t, 'NotReadableError', writer.write(test_text_data)); -}, "NDEFWriter.write should fail when NFC HW is disabled."); + await promise_rejects_dom(t, 'NotReadableError', ndef.write(test_text_data)); +}, "NDEFReader.write should fail when NFC HW is disabled."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); mockNFC.setHWStatus(NFCHWStatus.NOT_SUPPORTED); - await promise_rejects_dom(t, 'NotSupportedError', writer.write(test_text_data)); -}, "NDEFWriter.write should fail when NFC HW is not supported."); + await promise_rejects_dom(t, 'NotSupportedError', ndef.write(test_text_data)); +}, "NDEFReader.write should fail when NFC HW is not supported."); nfc_test(async () => { await new Promise((resolve,reject) => { const iframe = document.createElement('iframe'); iframe.srcdoc = `<script> - window.onmessage = message => { + window.onmessage = async (message) => { if (message.data === "Ready") { - const onSuccess = () => { + try { + const ndef = new NDEFReader(); + await ndef.write("Test"); parent.postMessage("Failure", "*"); - }; - const onError = error => { - if (error.name == "NotAllowedError") { + } catch (error) { + if (error.name == "InvalidStateError") { parent.postMessage("Success", "*"); } else { parent.postMessage("Failure", "*"); } - }; - try { - const writer = new NDEFWriter(); - writer.write("Test").then(onSuccess, onError); - } catch(e) { - parent.postMessage("Failure", "*"); } } }; @@ -263,12 +258,12 @@ }, 'Test that WebNFC API is not accessible from iframe context.'); nfc_test(async () => { - const writer = new NDEFWriter(); - await writer.write(test_text_data); -}, 'NDEFWriter.write should succeed when NFC HW is enabled'); + const ndef = new NDEFReader(); + await ndef.write(test_text_data); +}, 'NDEFReader.write should succeed when NFC HW is enabled'); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); const message = createMessage([createTextRecord(test_text_data), createMimeRecordFromJson(test_json_data), createMimeRecord(test_buffer_data), @@ -277,9 +272,9 @@ createUrlRecord(test_url_data, true), createRecord('w3.org:xyz', test_buffer_data)], test_message_origin); - await writer.write(message); + await ndef.write(message); assertNDEFMessagesEqual(message, mockNFC.pushedMessage()); -}, "NDEFWriter.write NDEFMessage containing text, mime, unknown, url, absolute-url \ +}, "NDEFReader.write NDEFMessage containing text, mime, unknown, url, absolute-url \ and external records with default NDEFWriteOptions."); nfc_test(async (t, mockNFC) => { @@ -291,8 +286,8 @@ // Prepare an external type record that uses |messageContainLocal| as its payload. const message = createMessage([createRecord('example.com:containsLocalRecord', messageContainLocal)]); - const writer = new NDEFWriter(); - await writer.write(message); + const ndef = new NDEFReader(); + await ndef.write(message); const pushed_message = mockNFC.pushedMessage(); // The mojom message received by mock nfc contains only the external type record. @@ -311,7 +306,7 @@ assert_array_equals(pushed_message.data[0].payloadMessage.data[0].data, new Uint8Array(0), 'payloadMessage is used instead'); assertNDEFMessagesEqual(messageContainText, pushed_message.data[0].payloadMessage.data[0].payloadMessage); -}, "NDEFWriter.write NDEFMessage containing embedded records."); +}, "NDEFReader.write NDEFMessage containing embedded records."); nfc_test(async (t, mockNFC) => { // A smart-poster record contains a uri record, text record. @@ -321,8 +316,8 @@ const message = createMessage([createRecord( 'smart-poster', payload_message, "dummy_record_id")]); - const writer = new NDEFWriter(); - await writer.write(message); + const ndef = new NDEFReader(); + await ndef.write(message); const pushed_message = mockNFC.pushedMessage(); // The mojom message received by mock nfc contains only the smart-poster record. @@ -350,53 +345,53 @@ } assert_array_equals(embedded_record_types.sort(), ['text', 'url'], 'smart-poster record\'s contained record types'); -}, "NDEFWriter.write NDEFMessage containing smart-poster record."); +}, "NDEFReader.write NDEFMessage containing smart-poster record."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write(test_text_data); + const ndef = new NDEFReader(); + await ndef.write(test_text_data); assertNDEFMessagesEqual(test_text_data, mockNFC.pushedMessage()); -}, "Test that NDEFWriter.write succeeds when message is DOMString."); +}, "Test that NDEFReader.write succeeds when message is DOMString."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write(test_buffer_data); + const ndef = new NDEFReader(); + await ndef.write(test_buffer_data); assertNDEFMessagesEqual(test_buffer_data, mockNFC.pushedMessage()); -}, "Test that NDEFWriter.write succeeds when message is ArrayBuffer."); +}, "Test that NDEFReader.write succeeds when message is ArrayBuffer."); nfc_test(async (t, mockNFC) => { let buffer_view = new Uint8Array(test_buffer_data, 2, 5); - const writer = new NDEFWriter(); - await writer.write(buffer_view); + const ndef = new NDEFReader(); + await ndef.write(buffer_view); assertNDEFMessagesEqual(buffer_view, mockNFC.pushedMessage()); -}, "Test that NDEFWriter.write succeeds when message is ArrayBufferView."); +}, "Test that NDEFReader.write succeeds when message is ArrayBufferView."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write(createMessage([createRecord('empty')])); + const ndef = new NDEFReader(); + await ndef.write(createMessage([createRecord('empty')])); const receivedMessage = mockNFC.pushedMessage(); assert_equals(receivedMessage.data.length, 1); assert_equals(receivedMessage.data[0].recordType, 'empty', 'recordType'); -}, "NDEFWriter.write with 'empty' record should succeed."); +}, "NDEFReader.write with 'empty' record should succeed."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write(test_text_data); + const ndef = new NDEFReader(); + await ndef.write(test_text_data); assertNDEFWriteOptionsEqual({overwrite: true}, mockNFC.writeOptions()); }, "Check that default NDEFWriteOptions values are correctly set."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write(test_text_data, {overwrite: false}); + const ndef = new NDEFReader(); + await ndef.write(test_text_data, {overwrite: false}); assertNDEFWriteOptionsEqual({overwrite: false}, mockNFC.writeOptions()); }, "Check that provided NDEFWriteOptions values are correctly converted."); nfc_test(async (t, mockNFC) => { - const writer1 = new NDEFWriter(); - const writer2 = new NDEFWriter(); + const ndef1 = new NDEFReader(); + const ndef2 = new NDEFReader(); - const p1 = writer1.write(test_text_data, {overwrite: false}); - const p2 = writer2.write(test_url_data, {overwrite: true}); + const p1 = ndef1.write(test_text_data, {overwrite: false}); + const p2 = ndef2.write(test_url_data, {overwrite: true}); await new Promise((resolve, reject) => { // Make first push pending @@ -414,11 +409,11 @@ resolve(); }); }); -}, "NDEFWriter.write should replace all previously configured write operations."); +}, "NDEFReader.write should replace all previously configured write operations."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write({ records: [{ recordType: "mime", data: test_buffer_data }] }); + const ndef = new NDEFReader(); + await ndef.write({ records: [{ recordType: "mime", data: test_buffer_data }] }); assertNDEFMessagesEqual(test_buffer_data, mockNFC.pushedMessage()); }, "Test that mediaType should be set to 'application/octet-stream' if \ NDEFRecordInit.record's recordType is 'mime' and NDEFRecordInit.record's \ @@ -428,46 +423,46 @@ // Make sure the push will be pending in the mock. mockNFC.setPendingPushCompleted(false); - const writer = new NDEFWriter(); - const promise = writer.write(test_text_data); + const ndef1 = new NDEFReader(); + const promise = ndef1.write(test_text_data); // Just to make sure the write() request has already reached to the mock. - const reader = new NDEFReader(); - await reader.scan(); + const ndef2 = new NDEFReader(); + await ndef2.scan(); mockNFC.simulateNonNDEFTagDiscovered(); await promise_rejects_dom(t, 'NotSupportedError', promise); -}, "NDEFWriter.write should fail when the NFC device coming up does not expose \ +}, "NDEFReader.write should fail when the NFC device coming up does not expose \ NDEF technology."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write(test_text_data, {overwrite: false}); + const ndef = new NDEFReader(); + await ndef.write(test_text_data, {overwrite: false}); assertNDEFMessagesEqual(test_text_data, mockNFC.pushedMessage()); -}, "NDEFWriter.write should succeed to write data to an unformatted NFC device \ +}, "NDEFReader.write should succeed to write data to an unformatted NFC device \ when the NDEFWriteOptions.overwrite is false."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - await writer.write(test_buffer_data); + const ndef = new NDEFReader(); + await ndef.write(test_buffer_data); assertNDEFMessagesEqual(test_buffer_data, mockNFC.pushedMessage()); - await writer.write(test_text_data, {overwrite: true}); + await ndef.write(test_text_data, {overwrite: true}); assertNDEFMessagesEqual(test_text_data, mockNFC.pushedMessage()); -}, "NDEFWriter.write should succeed to overwrite the existing data \ +}, "NDEFReader.write should succeed to overwrite the existing data \ when the NDEFWriteOptions.overwrite is true."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); - const p = writer.write(test_text_data, {overwrite: false}); + const ndef = new NDEFReader(); + const p = ndef.write(test_text_data, {overwrite: false}); mockNFC.setIsFormattedTag(true); await promise_rejects_dom(t, 'NotAllowedError', p); -}, "NDEFWriter.write should fail when there are NDEF records on the NFC device \ +}, "NDEFReader.write should fail when there are NDEF records on the NFC device \ and NDEFWriteOptions.overwrite is false."); nfc_test(async (t, mockNFC) => { - const writer = new NDEFWriter(); + const ndef = new NDEFReader(); mockNFC.simulateDataTransferFails(); - await promise_rejects_dom(t, 'NetworkError', writer.write(test_text_data)); -}, "NDEFWriter.write should fail with NetworkError when NFC data transfer fails."); + await promise_rejects_dom(t, 'NetworkError', ndef.write(test_text_data)); +}, "NDEFReader.write should fail with NetworkError when NFC data transfer fails."); </script>
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt deleted file mode 100644 index c64b15a..0000000 --- a/third_party/blink/web_tests/external/wpt/web-nfc/idlharness.https.window-expected.txt +++ /dev/null
@@ -1,68 +0,0 @@ -This is a testharness.js-based test. -Found 64 tests; 61 PASS, 3 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS idl_test setup -PASS idl_test validation -PASS NDEFMessage interface: existence and properties of interface object -PASS NDEFMessage interface object length -PASS NDEFMessage interface object name -PASS NDEFMessage interface: existence and properties of interface prototype object -PASS NDEFMessage interface: existence and properties of interface prototype object's "constructor" property -PASS NDEFMessage interface: existence and properties of interface prototype object's @@unscopables property -PASS NDEFMessage interface: attribute records -PASS NDEFMessage must be primary interface of new NDEFMessage({"url":"/custom/path","records":[{"recordType":"text","data":"Hello World","id":"/custom/path"}]}); -PASS Stringification of new NDEFMessage({"url":"/custom/path","records":[{"recordType":"text","data":"Hello World","id":"/custom/path"}]}); -PASS NDEFMessage interface: new NDEFMessage({"url":"/custom/path","records":[{"recordType":"text","data":"Hello World","id":"/custom/path"}]}); must inherit property "records" with the proper type -PASS NDEFRecord interface: existence and properties of interface object -PASS NDEFRecord interface object length -PASS NDEFRecord interface object name -PASS NDEFRecord interface: existence and properties of interface prototype object -PASS NDEFRecord interface: existence and properties of interface prototype object's "constructor" property -PASS NDEFRecord interface: existence and properties of interface prototype object's @@unscopables property -PASS NDEFRecord interface: attribute recordType -PASS NDEFRecord interface: attribute mediaType -PASS NDEFRecord interface: attribute id -PASS NDEFRecord interface: attribute data -PASS NDEFRecord interface: attribute encoding -PASS NDEFRecord interface: attribute lang -PASS NDEFRecord interface: operation toRecords() -PASS NDEFRecord must be primary interface of new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); -PASS Stringification of new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); -PASS NDEFRecord interface: new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); must inherit property "recordType" with the proper type -PASS NDEFRecord interface: new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); must inherit property "mediaType" with the proper type -PASS NDEFRecord interface: new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); must inherit property "id" with the proper type -PASS NDEFRecord interface: new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); must inherit property "data" with the proper type -PASS NDEFRecord interface: new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); must inherit property "encoding" with the proper type -PASS NDEFRecord interface: new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); must inherit property "lang" with the proper type -PASS NDEFRecord interface: new NDEFRecord({"recordType":"text","data":"Hello World","id":"/custom/path"}); must inherit property "toRecords()" with the proper type -PASS NDEFReader interface: existence and properties of interface object -PASS NDEFReader interface object length -PASS NDEFReader interface object name -PASS NDEFReader interface: existence and properties of interface prototype object -PASS NDEFReader interface: existence and properties of interface prototype object's "constructor" property -PASS NDEFReader interface: existence and properties of interface prototype object's @@unscopables property -PASS NDEFReader interface: attribute onreading -PASS NDEFReader interface: attribute onreadingerror -PASS NDEFReader interface: operation scan(optional NDEFScanOptions) -FAIL NDEFReader interface: operation write(NDEFMessageSource, optional NDEFWriteOptions) assert_own_property: interface prototype object missing non-static operation expected property "write" missing -PASS NDEFReader must be primary interface of new NDEFReader(); -PASS Stringification of new NDEFReader(); -PASS NDEFReader interface: new NDEFReader(); must inherit property "onreading" with the proper type -PASS NDEFReader interface: new NDEFReader(); must inherit property "onreadingerror" with the proper type -PASS NDEFReader interface: new NDEFReader(); must inherit property "scan(optional NDEFScanOptions)" with the proper type -PASS NDEFReader interface: calling scan(optional NDEFScanOptions) on new NDEFReader(); with too few arguments must throw TypeError -FAIL NDEFReader interface: new NDEFReader(); must inherit property "write(NDEFMessageSource, optional NDEFWriteOptions)" with the proper type assert_inherits: property "write" not found in prototype chain -FAIL NDEFReader interface: calling write(NDEFMessageSource, optional NDEFWriteOptions) on new NDEFReader(); with too few arguments must throw TypeError assert_inherits: property "write" not found in prototype chain -PASS NDEFReadingEvent interface: existence and properties of interface object -PASS NDEFReadingEvent interface object length -PASS NDEFReadingEvent interface object name -PASS NDEFReadingEvent interface: existence and properties of interface prototype object -PASS NDEFReadingEvent interface: existence and properties of interface prototype object's "constructor" property -PASS NDEFReadingEvent interface: existence and properties of interface prototype object's @@unscopables property -PASS NDEFReadingEvent interface: attribute serialNumber -PASS NDEFReadingEvent interface: attribute message -PASS NDEFReadingEvent must be primary interface of new NDEFReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World","id":"/custom/path"}]} }) -PASS Stringification of new NDEFReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World","id":"/custom/path"}]} }) -PASS NDEFReadingEvent interface: new NDEFReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World","id":"/custom/path"}]} }) must inherit property "serialNumber" with the proper type -PASS NDEFReadingEvent interface: new NDEFReadingEvent("reading", { message: {"url":"/custom/path","records":[{"recordType":"text","data":"Hello World","id":"/custom/path"}]} }) must inherit property "message" with the proper type -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/nfc_insecure_context.html b/third_party/blink/web_tests/external/wpt/web-nfc/nfc_insecure_context.html index 9a8e58c..8c2eb5a 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/nfc_insecure_context.html +++ b/third_party/blink/web_tests/external/wpt/web-nfc/nfc_insecure_context.html
@@ -17,11 +17,6 @@ test(t => { assert_false(isSecureContext); - assert_false('NDEFWriter' in window); -}, 'NDEFWriter requires a secure context'); - -test(t => { - assert_false(isSecureContext); assert_false('NDEFReader' in window); }, 'NDEFReader requires a secure context');
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc-helpers.js b/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc-helpers.js index 0b26d09..659f74e 100644 --- a/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc-helpers.js +++ b/third_party/blink/web_tests/external/wpt/web-nfc/resources/nfc-helpers.js
@@ -150,7 +150,7 @@ } // Compares NDEFMessageSource that was provided to the API -// (e.g. NDEFWriter.write), and NDEFMessage that was received by the +// (e.g. NDEFReader.write), and NDEFMessage that was received by the // mock NFC service. function assertNDEFMessagesEqual(providedMessage, receivedMessage) { // If simple data type is passed, e.g. String or ArrayBuffer or @@ -174,7 +174,7 @@ } // Used to compare two NDEFMessage, one that is received from -// NDEFWriter.onreading() EventHandler and another that is provided to mock NFC +// NDEFReader.onreading() EventHandler and another that is provided to mock NFC // service. function assertWebNDEFMessagesEqual(message, expectedMessage) { assert_equals(message.records.length, expectedMessage.records.length); @@ -195,22 +195,22 @@ function testMultiScanOptions(message, scanOptions, unmatchedScanOptions, desc) { nfc_test(async (t, mockNFC) => { - const reader1 = new NDEFReader(); - const reader2 = new NDEFReader(); + const ndef1 = new NDEFReader(); + const ndef2 = new NDEFReader(); const controller = new AbortController(); - // Reading from unmatched reader will not be triggered - reader1.onreading = t.unreached_func("reading event should not be fired."); + // Reading from unmatched ndef will not be triggered + ndef1.onreading = t.unreached_func("reading event should not be fired."); unmatchedScanOptions.signal = controller.signal; - await reader1.scan(unmatchedScanOptions); + await ndef1.scan(unmatchedScanOptions); - const readerWatcher = new EventWatcher(t, reader2, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const ndefWatcher = new EventWatcher(t, ndef2, ["reading", "readingerror"]); + const promise = ndefWatcher.wait_for("reading").then(event => { controller.abort(); assertWebNDEFMessagesEqual(event.message, new NDEFMessage(message)); }); scanOptions.signal = controller.signal; - await reader2.scan(scanOptions); + await ndef2.scan(scanOptions); mockNFC.setReadingMessage(message); await promise; @@ -219,15 +219,15 @@ function testMultiMessages(message, scanOptions, unmatchedMessage, desc) { nfc_test(async (t, mockNFC) => { - const reader = new NDEFReader(); + const ndef = new NDEFReader(); const controller = new AbortController(); - const readerWatcher = new EventWatcher(t, reader, ["reading", "readingerror"]); - const promise = readerWatcher.wait_for("reading").then(event => { + const ndefWatcher = new EventWatcher(t, ndef, ["reading", "readingerror"]); + const promise = ndefWatcher.wait_for("reading").then(event => { controller.abort(); assertWebNDEFMessagesEqual(event.message, new NDEFMessage(message)); }); scanOptions.signal = controller.signal; - await reader.scan(scanOptions); + await ndef.scan(scanOptions); // Unmatched message will not be read mockNFC.setReadingMessage(unmatchedMessage);
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCConfiguration-iceServers-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCConfiguration-iceServers-expected.txt index 301d7e6..33430edd 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCConfiguration-iceServers-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCConfiguration-iceServers-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 67 tests; 32 PASS, 35 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 67 tests; 33 PASS, 34 FAIL, 0 TIMEOUT, 0 NOTRUN. FAIL new RTCPeerConnection() should have default configuration.iceServers of undefined assert_equals: expected (undefined) undefined but got (object) [] PASS new RTCPeerConnection(config) - {} should succeed PASS setConfiguration(config) - {} should succeed @@ -23,9 +23,9 @@ FAIL setConfiguration(config) - with 2 stun servers should succeed assert_equals: expected 1 but got 2 FAIL new RTCPeerConnection(config) - with turn server, username, credential should succeed assert_equals: expected (string) "password" but got (undefined) undefined FAIL setConfiguration(config) - with turn server, username, credential should succeed assert_equals: expected (string) "password" but got (undefined) undefined -FAIL new RTCPeerConnection(config) - with turns server and empty string username, credential should succeed Failed to construct 'RTCPeerConnection': Failed to initialize native PeerConnection. +FAIL new RTCPeerConnection(config) - with turns server and empty string username, credential should succeed Failed to construct 'RTCPeerConnection': ICE server parse failed FAIL setConfiguration(config) - with turns server and empty string username, credential should succeed Failed to execute 'setConfiguration' on 'RTCPeerConnection': Could not update the PeerConnection with the given configuration. -FAIL new RTCPeerConnection(config) - with turn server and empty string username, credential should succeed Failed to construct 'RTCPeerConnection': Failed to initialize native PeerConnection. +FAIL new RTCPeerConnection(config) - with turn server and empty string username, credential should succeed Failed to construct 'RTCPeerConnection': ICE server parse failed FAIL setConfiguration(config) - with turn server and empty string username, credential should succeed Failed to execute 'setConfiguration' on 'RTCPeerConnection': Could not update the PeerConnection with the given configuration. FAIL new RTCPeerConnection(config) - with one turns server, one turn server, username, credential should succeed assert_equals: expected 1 but got 2 FAIL setConfiguration(config) - with one turns server, one turn server, username, credential should succeed assert_equals: expected 1 but got 2 @@ -59,10 +59,7 @@ makePc({ iceServers: [{ urls: 'turn://example.org/foo?x=y' }] })" threw object "InvalidAccessError: Failed to execute 'setConfiguration' on 'RTCPeerConnection': Both username and credential are required when the URL scheme is "turn" or "turns"." that is not a DOMException SyntaxError: property "code" is equal to 15, expected 12 -FAIL new RTCPeerConnection(config) - with invalid stun url should throw SyntaxError assert_throws_dom: function "() => - makePc({ iceServers: [{ - urls: 'stun://example.org/foo?x=y' - }] })" threw object "NotSupportedError: Failed to construct 'RTCPeerConnection': Failed to initialize native PeerConnection." that is not a DOMException SyntaxError: property "code" is equal to 9, expected 12 +PASS new RTCPeerConnection(config) - with invalid stun url should throw SyntaxError FAIL setConfiguration(config) - with invalid stun url should throw SyntaxError assert_throws_dom: function "() => makePc({ iceServers: [{ urls: 'stun://example.org/foo?x=y'
diff --git a/third_party/blink/web_tests/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change.html b/third_party/blink/web_tests/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change.html new file mode 100644 index 0000000..777a53e --- /dev/null +++ b/third_party/blink/web_tests/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change.html
@@ -0,0 +1,25 @@ +<!DOCTYPE html> + +<head> + <meta name="color-scheme" content="light dark"> + <script src="../../../../resources/run-after-layout-and-paint.js"></script> + <script> + + function endTest() { + if (window.testRunner) + testRunner.notifyDone(); + } + + function doTest() { + window.internals.setForcedColorsAndDarkPreferredColorScheme(document); + runAfterLayoutAndPaint(endTest); + } + + runAfterLayoutAndPaint(doTest); + + if (window.testRunner) + testRunner.waitUntilDone(); + </script> +</head> + +<body style='height:5000px; width:5000px'></body> \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/copy-styles-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/copy-styles-expected.txt index 5afb8ef5..19dceda 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/copy-styles-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/copy-styles-expected.txt
@@ -24,19 +24,19 @@ <body>​ InspectorFrontendHost.copyText: -border: 1px solid black; -font-weight: bold; + border: 1px solid black; + font-weight: bold; <div style=​"padding:​ 5px">​ Hello ​</div>​ InspectorFrontendHost.copyText: -font-weight: bold; -padding: 5px; + font-weight: bold; + padding: 5px; <button>​ A red button ​</button>​ InspectorFrontendHost.copyText: -color: red; + color: red; <button style=​"color:​ green">​ A green button ​</button>​ InspectorFrontendHost.copyText: -color: green; + color: green;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-reverse-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-reverse-expected.txt new file mode 100644 index 0000000..f1ec94cf --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-reverse-expected.txt
@@ -0,0 +1,405 @@ +This test verifies that the flex overlay creates the right lines and items for reverse direction flex containers. See crbug.com/1153272. + +test-1{ + "paths": [ + { + "path": [ + "M", + 8, + 8, + "L", + 108, + 8, + "L", + 108, + 108, + "L", + 8, + 108, + "Z" + ], + "fillColor": "rgba(255, 0, 0, 0)", + "outlineColor": "rgba(128, 0, 0, 0)", + "name": "content" + }, + { + "path": [ + "M", + 8, + 8, + "L", + 108, + 8, + "L", + 108, + 108, + "L", + 8, + 108, + "Z" + ], + "fillColor": "rgba(0, 255, 0, 0)", + "name": "padding" + }, + { + "path": [ + "M", + 8, + 8, + "L", + 108, + 8, + "L", + 108, + 108, + "L", + 8, + 108, + "Z" + ], + "fillColor": "rgba(0, 0, 255, 0)", + "name": "border" + }, + { + "path": [ + "M", + 8, + 8, + "L", + 792, + 8, + "L", + 792, + 108, + "L", + 8, + 108, + "Z" + ], + "fillColor": "rgba(255, 255, 255, 0)", + "name": "margin" + } + ], + "showRulers": true, + "showExtensionLines": true, + "showAccessibilityInfo": true, + "colorFormat": "hex", + "elementInfo": { + "tagName": "div", + "idValue": "test-1", + "className": ".container", + "nodeWidth": "100", + "nodeHeight": "100", + "isKeyboardFocusable": false, + "accessibleName": "", + "accessibleRole": "generic", + "layoutObjectName": "LayoutNGFlexibleBox", + "showAccessibilityInfo": true + }, + "flexInfo": [ + { + "containerBorder": [ + "M", + 8, + 8, + "L", + 108, + 8, + "L", + 108, + 108, + "L", + 8, + 108, + "Z" + ], + "lines": [ + [ + [ + "M", + 78, + 8, + "L", + 98, + 8, + "L", + 98, + 28, + "L", + 78, + 28, + "Z" + ], + [ + "M", + 48, + 88, + "L", + 68, + 88, + "L", + 68, + 108, + "L", + 48, + 108, + "Z" + ], + [ + "M", + 18, + 8, + "L", + 38, + 8, + "L", + 38, + 28, + "L", + 18, + 28, + "Z" + ] + ] + ], + "isHorizontalFlow": true, + "alignItemsStyle": "flex-start", + "flexContainerHighlightConfig": { + "containerBorder": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + }, + "lineSeparator": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + }, + "itemSeparator": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + }, + "mainDistributedSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "crossDistributedSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "rowGapSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "columnGapSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "crossAlignment": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + } + } + } + ] +} +test-2{ + "paths": [ + { + "path": [ + "M", + 8, + 108, + "L", + 108, + 108, + "L", + 108, + 208, + "L", + 8, + 208, + "Z" + ], + "fillColor": "rgba(255, 0, 0, 0)", + "outlineColor": "rgba(128, 0, 0, 0)", + "name": "content" + }, + { + "path": [ + "M", + 8, + 108, + "L", + 108, + 108, + "L", + 108, + 208, + "L", + 8, + 208, + "Z" + ], + "fillColor": "rgba(0, 255, 0, 0)", + "name": "padding" + }, + { + "path": [ + "M", + 8, + 108, + "L", + 108, + 108, + "L", + 108, + 208, + "L", + 8, + 208, + "Z" + ], + "fillColor": "rgba(0, 0, 255, 0)", + "name": "border" + }, + { + "path": [ + "M", + 8, + 108, + "L", + 792, + 108, + "L", + 792, + 208, + "L", + 8, + 208, + "Z" + ], + "fillColor": "rgba(255, 255, 255, 0)", + "name": "margin" + } + ], + "showRulers": true, + "showExtensionLines": true, + "showAccessibilityInfo": true, + "colorFormat": "hex", + "elementInfo": { + "tagName": "div", + "idValue": "test-2", + "className": ".container", + "nodeWidth": "100", + "nodeHeight": "100", + "isKeyboardFocusable": false, + "accessibleName": "", + "accessibleRole": "generic", + "layoutObjectName": "LayoutNGFlexibleBox", + "showAccessibilityInfo": true + }, + "flexInfo": [ + { + "containerBorder": [ + "M", + 8, + 108, + "L", + 108, + 108, + "L", + 108, + 208, + "L", + 8, + 208, + "Z" + ], + "lines": [ + [ + [ + "M", + 8, + 178, + "L", + 28, + 178, + "L", + 28, + 198, + "L", + 8, + 198, + "Z" + ], + [ + "M", + 88, + 148, + "L", + 108, + 148, + "L", + 108, + 168, + "L", + 88, + 168, + "Z" + ], + [ + "M", + 8, + 118, + "L", + 28, + 118, + "L", + 28, + 138, + "L", + 8, + 138, + "Z" + ] + ] + ], + "isHorizontalFlow": false, + "alignItemsStyle": "flex-start", + "flexContainerHighlightConfig": { + "containerBorder": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + }, + "lineSeparator": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + }, + "itemSeparator": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + }, + "mainDistributedSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "crossDistributedSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "rowGapSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "columnGapSpace": { + "fillColor": "rgba(255, 0, 0, 0)", + "hatchColor": "rgba(255, 0, 0, 0)" + }, + "crossAlignment": { + "color": "rgba(255, 0, 0, 0)", + "pattern": "solid" + } + } + } + ] +} +
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-reverse.js b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-reverse.js new file mode 100644 index 0000000..72cd8b1 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-reverse.js
@@ -0,0 +1,42 @@ +// 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. + +(async function() { + TestRunner.addResult(`This test verifies that the flex overlay creates the right lines and items for reverse direction flex containers. See crbug.com/1153272.\n`); + await TestRunner.loadModule('elements_test_runner'); + await TestRunner.showPanel('elements'); + await TestRunner.loadHTML(` + <style> + .container { + display: flex; + justify-content: center; + width: 100px; + height: 100px; + gap: 10px; + align-items: flex-start; + background: gold; + } + .item { padding: 10px; } + </style> + <div class="container" id="test-1" style="flex-direction:row-reverse;"> + <div class="item"></div> + <div class="item" style="align-self: flex-end;"></div> + <div class="item"></div> + </div> + <div class="container" id="test-2" style="flex-direction:column-reverse;"> + <div class="item"></div> + <div class="item" style="align-self: flex-end;"></div> + <div class="item"></div> + </div> + `); + + function dumFlexHighlight(id) { + return new Promise(resolve => ElementsTestRunner.dumpInspectorHighlightJSON(id, resolve)); + } + + await dumFlexHighlight('test-1'); + await dumFlexHighlight('test-2'); + + TestRunner.completeTest(); +})();
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/web-nfc-origin-trial-interfaces.html b/third_party/blink/web_tests/http/tests/origin_trials/webexposed/web-nfc-origin-trial-interfaces.html deleted file mode 100644 index 0493668..0000000 --- a/third_party/blink/web_tests/http/tests/origin_trials/webexposed/web-nfc-origin-trial-interfaces.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<!-- Generate token with the command: -generate_token.py http://127.0.0.1:8000 WebNFC --expire-timestamp=2000000000 --- --> -<meta http-equiv="origin-trial" content="Aqf7eFO7NmOkdlMoZ/n0ptqFGPH5WMzwB8x9cwISBw1gM6FYOW+YwVuol8dAbAhjdZxPoz43qDsWnqeuAk9rmQgAAABOeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiV2ViTkZDIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9" /> -<title>WebNFC - interfaces exposed by origin trial</title> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> -<script src="../../resources/origin-trials-helper.js"></script> -<script> -test(t => { - OriginTrialsHelper.check_properties_exist(this, - { - 'NDEFMessage': ['records'], - 'NDEFReader': ['scan', 'onreading', 'onreadingerror'], - 'NDEFReadingEvent': ['serialNumber', 'message'], - 'NDEFRecord': ['recordType', 'mediaType', 'id', 'encoding', 'lang', 'data', 'toRecords'], - 'NDEFWriter': ['write'], - }, - ); -}, "WebNFC related interfaces in Origin-Trial enabled document."); - -</script>
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 6bd7187..b919ec7c 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
@@ -2879,6 +2879,7 @@ method constructor method createBidirectionalStream method createUnidirectionalStream + method setDatagramWritableQueueExpirationDuration interface WindowClient : Client attribute @@toStringTag getter focused
diff --git a/third_party/blink/web_tests/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt b/third_party/blink/web_tests/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt new file mode 100644 index 0000000..c91df11 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt
@@ -0,0 +1,28 @@ +Verifies that Overlay.setShowGridOverlays works together with Emulation.setDeviceMetricsOverride. +Expected 3 track size labels; actual: 3 +Positions: +{ + bottom : 27.53125 + height : 18 + left : 382 + right : 418 + top : 9.53125 + width : 36 +} +{ + bottom : 23.6875 + height : 18 + left : 9.53125 + right : 39.53125 + top : 5.6875 + width : 30 +} +{ + bottom : 40.015625 + height : 18 + left : 9.53125 + right : 39.53125 + top : 22.015625 + width : 30 +} +
diff --git a/third_party/blink/web_tests/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation.js b/third_party/blink/web_tests/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation.js new file mode 100644 index 0000000..e2df782 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation.js
@@ -0,0 +1,82 @@ +(async function(testRunner) { + const {page, session, dp} = await testRunner.startHTML(` + <style> + #grid { + display: grid; + } + </style> + <div id="grid"><div>A</div><div>B</div></div> + `, 'Verifies that Overlay.setShowGridOverlays works together with Emulation.setDeviceMetricsOverride.'); + + await dp.DOM.enable(); + await dp.CSS.enable(); + await dp.Emulation.enable(); + await dp.Overlay.enable(); + + await dp.Emulation.setDeviceMetricsOverride({ + width: 0, + height: 0, + deviceScaleFactor: 2, + mobile: true, + scale: 1, + screenWidth: 800, + screenHeight: 600, + positionX: 0, + positionY: 0, + dontSetVisibleSize: true, + screenOrientation: { + type: 'landscapePrimary', + angle: 90 + } + }); + + const CSSHelper = await testRunner.loadScript('../resources/css-helper.js'); + const cssHelper = new CSSHelper(testRunner, dp); + const documentNodeId = await cssHelper.requestDocumentNodeId(); + const nodeId = await cssHelper.requestNodeId(documentNodeId, '#grid'); + await dp.Overlay.setShowGridOverlays({ + gridNodeHighlightConfigs: [{ + nodeId, + gridHighlightConfig: { + showTrackSizes: true, + }, + }] + }); + + // Wait for overlay rendering to finish by requesting an animation frame. + await session.evaluate(() => { + return new Promise(resolve => requestAnimationFrame(resolve)); + }); + + async function getGridLabelPositions() { + return await session.evaluate(() => { + return internals.evaluateInInspectorOverlay(`(function () { + const labels = document.querySelectorAll('.grid-label-content'); + const positions = []; + for (const label of labels) { + const rect = label.getBoundingClientRect(); + positions.push({ + left: rect.left, + right: rect.right, + bottom: rect.bottom, + top: rect.top, + width: rect.width, + height: rect.height, + }); + } + return JSON.stringify(positions); + })()`); + }); + } + + const labelPositions = JSON.parse(await getGridLabelPositions()); + + testRunner.log('Expected 3 track size labels; actual: ' + labelPositions.length); + testRunner.log('Positions: '); + + for (const position of labelPositions) { + testRunner.log(position); + } + + testRunner.completeTest(); +});
diff --git a/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..50e03b4 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/linux/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..1148727f --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac-arm11.0/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt b/third_party/blink/web_tests/platform/mac-mac-arm11.0/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt new file mode 100644 index 0000000..c91df11 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac-arm11.0/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt
@@ -0,0 +1,28 @@ +Verifies that Overlay.setShowGridOverlays works together with Emulation.setDeviceMetricsOverride. +Expected 3 track size labels; actual: 3 +Positions: +{ + bottom : 27.53125 + height : 18 + left : 382 + right : 418 + top : 9.53125 + width : 36 +} +{ + bottom : 23.6875 + height : 18 + left : 9.53125 + right : 39.53125 + top : 5.6875 + width : 30 +} +{ + bottom : 40.015625 + height : 18 + left : 9.53125 + right : 39.53125 + top : 22.015625 + width : 30 +} +
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..454d1fe --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..57a794fd --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..454d1fe --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.13/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.13/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.13/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..57a794fd --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.13/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.14/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.14/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..454d1fe --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.14/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.14/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.14/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..57a794fd --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.14/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..454d1fe --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.15/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..57a794fd --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.15/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..454d1fe --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt b/third_party/blink/web_tests/platform/mac/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt new file mode 100644 index 0000000..4efb669 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/inspector-protocol/overlay/overlay-persistent-overlays-with-emulation-expected.txt
@@ -0,0 +1,28 @@ +Verifies that Overlay.setShowGridOverlays works together with Emulation.setDeviceMetricsOverride. +Expected 3 track size labels; actual: 3 +Positions: +{ + bottom : 26.53125 + height : 17 + left : 381.9375 + right : 418.046875 + top : 9.53125 + width : 36.109375 +} +{ + bottom : 22.375 + height : 17 + left : 9.53125 + right : 39.625 + top : 5.375 + width : 30.09375 +} +{ + bottom : 37.078125 + height : 17 + left : 9.53125 + right : 39.625 + top : 20.078125 + width : 30.09375 +} +
diff --git a/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..454d1fe --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/mac/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..57a794fd --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/win/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..3aad2876 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/win/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..419a8f9 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/win/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..1148727f --- /dev/null +++ b/third_party/blink/web_tests/platform/win/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win7/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/win7/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..419a8f9 --- /dev/null +++ b/third_party/blink/web_tests/platform/win7/virtual/controls-refresh-hc/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win7/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png b/third_party/blink/web_tests/platform/win7/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png new file mode 100644 index 0000000..1148727f --- /dev/null +++ b/third_party/blink/web_tests/platform/win7/virtual/dark-color-scheme/fast/forms/color-scheme/scrollbar/dynamic-color-scheme-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/reporting-observer/reporting-api.html b/third_party/blink/web_tests/reporting-observer/reporting-api.html index 8d97173..9a9158f 100644 --- a/third_party/blink/web_tests/reporting-observer/reporting-api.html +++ b/third_party/blink/web_tests/reporting-observer/reporting-api.html
@@ -42,7 +42,7 @@ // Make an instance and have it receive the request. var proxy = new MockReportingServiceProxy(); -var interceptor = new MojoInterfaceInterceptor(blink.mojom.ReportingServiceProxy.name, "process"); +var interceptor = new MojoInterfaceInterceptor(blink.mojom.ReportingServiceProxy.name); interceptor.oninterfacerequest = e => proxy.bind(e.handle); interceptor.start();
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 391ac21..404d9f32 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
@@ -3053,6 +3053,7 @@ [Worker] method constructor [Worker] method createBidirectionalStream [Worker] method createUnidirectionalStream +[Worker] method setDatagramWritableQueueExpirationDuration [Worker] interface Worker : EventTarget [Worker] attribute @@toStringTag [Worker] getter onerror
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 be751d2..e997058 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
@@ -5382,6 +5382,7 @@ getter onreadingerror method constructor method scan + method write setter onreading setter onreadingerror interface NDEFReadingEvent : Event @@ -5399,10 +5400,6 @@ getter recordType method constructor method toRecords -interface NDEFWriter - attribute @@toStringTag - method constructor - method write interface NamedNodeMap attribute @@toStringTag getter length @@ -10259,6 +10256,7 @@ method constructor method createBidirectionalStream method createUnidirectionalStream + method setDatagramWritableQueueExpirationDuration interface WheelEvent : MouseEvent attribute @@toStringTag attribute DOM_DELTA_LINE
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 b9472a0..1861c9c 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
@@ -2756,6 +2756,7 @@ [Worker] method constructor [Worker] method createBidirectionalStream [Worker] method createUnidirectionalStream +[Worker] method setDatagramWritableQueueExpirationDuration [Worker] interface WorkerGlobalScope : EventTarget [Worker] attribute @@toStringTag [Worker] getter addressSpace
diff --git a/third_party/crashpad/README.chromium b/third_party/crashpad/README.chromium index b269e98c..727a7b9 100644 --- a/third_party/crashpad/README.chromium +++ b/third_party/crashpad/README.chromium
@@ -36,3 +36,6 @@ Local Modifications: - codereview.settings has been excluded. + - MultiprocessExec.MultiprocessExec is disabled when OS_POSIX and + BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) are defined. crbug.com/1153544 + (third_party/crashpad/crashpad/test/multiprocess_exec_test.cc)
diff --git a/third_party/crashpad/crashpad/test/multiprocess_exec_test.cc b/third_party/crashpad/crashpad/test/multiprocess_exec_test.cc index 4f5418ad..76fda30 100644 --- a/third_party/crashpad/crashpad/test/multiprocess_exec_test.cc +++ b/third_party/crashpad/crashpad/test/multiprocess_exec_test.cc
@@ -14,6 +14,7 @@ #include "test/multiprocess_exec.h" +#include "base/allocator/buildflags.h" #include "base/logging.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" @@ -48,7 +49,19 @@ DISALLOW_COPY_AND_ASSIGN(TestMultiprocessExec); }; -TEST(MultiprocessExec, MultiprocessExec) { +// TODO(tasak): enable this test after making address randomization not to +// keep /dev/urandom open. +// PartitionAllocator opens /dev/urandom because of address randomization. +// (c.f. //base/rand_util_posix.cc and +// //base/allocator/partition_allocator/random.cc) So when making +// PartitionAllocator default, multiprocess_exec_test_child will crash because +// of LOG(FATAL) << "close". https://crbug.com/1153544 +#if defined(OS_POSIX) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#define MAYBE_MultiprocessExec DISABLED_MultiprocessExec +#else +#define MAYBE_MultiprocessExec MultiprocessExec +#endif +TEST(MultiprocessExec, MAYBE_MultiprocessExec) { TestMultiprocessExec multiprocess_exec; base::FilePath child_test_executable = TestPaths::BuildArtifact( FILE_PATH_LITERAL("test"),
diff --git a/tools/json_schema_compiler/cc_generator.py b/tools/json_schema_compiler/cc_generator.py index d3dc51a3..f37d805 100644 --- a/tools/json_schema_compiler/cc_generator.py +++ b/tools/json_schema_compiler/cc_generator.py
@@ -39,7 +39,8 @@ c = Code() (c.Append(cpp_util.CHROMIUM_LICENSE) .Append() - .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file) + .Append(cpp_util.GENERATED_FILE_MESSAGE % + cpp_util.ToPosixPath(self._namespace.source_file)) .Append() .Append(self._util_cc_helper.GetIncludePath()) .Append('#include "base/check.h"') @@ -49,7 +50,8 @@ .Append('#include "base/strings/utf_string_conversions.h"') .Append('#include "base/values.h"') .Append('#include "%s/%s.h"' % - (self._namespace.source_file_dir, self._namespace.short_filename)) + (cpp_util.ToPosixPath(self._namespace.source_file_dir), + self._namespace.short_filename)) .Append('#include <set>') .Append('#include <utility>') .Cblock(self._GenerateManifestKeysIncludes())
diff --git a/tools/json_schema_compiler/cpp_bundle_generator.py b/tools/json_schema_compiler/cpp_bundle_generator.py index d874aec3..0f7b683eb 100644 --- a/tools/json_schema_compiler/cpp_bundle_generator.py +++ b/tools/json_schema_compiler/cpp_bundle_generator.py
@@ -122,9 +122,10 @@ c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() - c.Append(cpp_util.GENERATED_BUNDLE_FILE_MESSAGE % self._source_file_dir) + c.Append(cpp_util.GENERATED_BUNDLE_FILE_MESSAGE % + cpp_util.ToPosixPath(self._source_file_dir)) ifndef_name = cpp_util.GenerateIfndefName( - '%s/%s.h' % (self._source_file_dir, file_base)) + '%s/%s.h' % (cpp_util.ToPosixPath(self._source_file_dir), file_base)) c.Append() c.Append('#ifndef %s' % ifndef_name) c.Append('#define %s' % ifndef_name) @@ -256,8 +257,8 @@ c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append('#include "%s"' % ( - os.path.join(self._bundle._impl_dir, - 'generated_api_registration.h'))) + cpp_util.ToPosixPath(os.path.join(self._bundle._impl_dir, + 'generated_api_registration.h')))) c.Append() c.Append('#include "build/build_config.h"') c.Append('#include "build/chromeos_buildflags.h"') @@ -281,7 +282,7 @@ if ifdefs is not None: c.Append("#if %s" % ifdefs, indent_level=0) - c.Append('#include "%s"' % implementation_header) + c.Append('#include "%s"' % cpp_util.ToPosixPath(implementation_header)) if ifdefs is not None: c.Append("#endif // %s" % ifdefs, indent_level=0) @@ -341,8 +342,9 @@ c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() - c.Append('#include "%s"' % (os.path.join(self._bundle._source_file_dir, - 'generated_schemas.h'))) + c.Append('#include "%s"' % ( + cpp_util.ToPosixPath(os.path.join(self._bundle._source_file_dir, + 'generated_schemas.h')))) c.Append() c.Append('#include <algorithm>') c.Append('#include <iterator>')
diff --git a/tools/json_schema_compiler/cpp_type_generator.py b/tools/json_schema_compiler/cpp_type_generator.py index 17772d7..4e394f1d 100644 --- a/tools/json_schema_compiler/cpp_type_generator.py +++ b/tools/json_schema_compiler/cpp_type_generator.py
@@ -178,7 +178,7 @@ path = '%s/%s.h' % (namespace.source_file_dir, namespace.unix_name) if path not in added_paths: added_paths.add(path) - c.Append('#include "%s"' % path) + c.Append('#include "%s"' % cpp_util.ToPosixPath(path)) return c def _FindType(self, full_name):
diff --git a/tools/json_schema_compiler/cpp_util.py b/tools/json_schema_compiler/cpp_util.py index af8ce05..abee9fa 100644 --- a/tools/json_schema_compiler/cpp_util.py +++ b/tools/json_schema_compiler/cpp_util.py
@@ -9,6 +9,7 @@ from datetime import datetime from model import PropertyType import os +import posixpath import re CHROMIUM_LICENSE = ( @@ -165,6 +166,14 @@ """ return all(x.islower() or x == '_' for x in s) and '_' in s +def ToPosixPath(path): + """Returns |path| with separator converted to POSIX style. + + This is needed to generate C++ #include paths. + """ + return path.replace(os.path.sep, posixpath.sep) + + def CamelCase(unix_name): return ''.join(word.capitalize() for word in unix_name.split('_'))
diff --git a/tools/json_schema_compiler/feature_compiler.py b/tools/json_schema_compiler/feature_compiler.py index fe20b20..1618996c 100644 --- a/tools/json_schema_compiler/feature_compiler.py +++ b/tools/json_schema_compiler/feature_compiler.py
@@ -10,6 +10,7 @@ from functools import partial import json import os +import posixpath import re import sys @@ -73,6 +74,13 @@ LEGACY_ALLOWLIST_KEY = 'whitelist' LEGACY_BLOCKLIST_KEY = 'blacklist' +def ToPosixPath(path): + """Returns |path| with separator converted to POSIX style. + + This is needed to generate C++ #include paths. + """ + return path.replace(os.path.sep, posixpath.sep) + # Returns true if the list 'l' only contains strings that are a hex-encoded SHA1 # hashes. def ListContainsOnlySha1Hashes(l): @@ -894,7 +902,7 @@ 'header_guard': (header_file_path.replace('/', '_'). replace('.', '_').upper()), 'method_name': self._method_name, - 'source_files': str(self._source_files), + 'source_files': str([ToPosixPath(f) for f in self._source_files]), 'year': str(datetime.now().year) }) if not os.path.exists(self._out_root):
diff --git a/tools/json_schema_compiler/features_cc_generator.py b/tools/json_schema_compiler/features_cc_generator.py index 3847914..a2172d6 100644 --- a/tools/json_schema_compiler/features_cc_generator.py +++ b/tools/json_schema_compiler/features_cc_generator.py
@@ -29,11 +29,13 @@ c = Code() (c.Append(cpp_util.CHROMIUM_LICENSE) .Append() - .Append(cpp_util.GENERATED_FEATURE_MESSAGE % self._source_file) + .Append(cpp_util.GENERATED_FEATURE_MESSAGE % + cpp_util.ToPosixPath(self._source_file)) .Append() .Append('#include <string>') .Append() - .Append('#include "%s.h"' % self._source_file_filename) + .Append('#include "%s.h"' % + cpp_util.ToPosixPath(self._source_file_filename)) .Append() .Append('#include "base/notreached.h"') .Append()
diff --git a/tools/json_schema_compiler/features_h_generator.py b/tools/json_schema_compiler/features_h_generator.py index eae39c5..5b88d0c 100644 --- a/tools/json_schema_compiler/features_h_generator.py +++ b/tools/json_schema_compiler/features_h_generator.py
@@ -29,7 +29,8 @@ c = Code() (c.Append(cpp_util.CHROMIUM_LICENSE) .Append() - .Append(cpp_util.GENERATED_FEATURE_MESSAGE % self._source_file) + .Append(cpp_util.GENERATED_FEATURE_MESSAGE % + cpp_util.ToPosixPath(self._source_file)) .Append() )
diff --git a/tools/json_schema_compiler/h_generator.py b/tools/json_schema_compiler/h_generator.py index 0fd7e419..9e86bb385 100644 --- a/tools/json_schema_compiler/h_generator.py +++ b/tools/json_schema_compiler/h_generator.py
@@ -32,7 +32,8 @@ c = Code() (c.Append(cpp_util.CHROMIUM_LICENSE) .Append() - .Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file) + .Append(cpp_util.GENERATED_FILE_MESSAGE % + cpp_util.ToPosixPath(self._namespace.source_file)) .Append() )
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index c4faee1b..a6af6634 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -29758,7 +29758,7 @@ <int value="3124" label="WebkitBoxPackCenterDoesSomething"/> <int value="3125" label="WebkitBoxPackEndDoesSomething"/> <int value="3126" label="V8KeyframeEffect_Constructor"/> - <int value="3127" label="WebNfcAPI"/> + <int value="3127" label="OBSOLETE_WebNfcAPI"/> <int value="3128" label="HostCandidateAttributeGetter"/> <int value="3129" label="CSPWithReasonableObjectRestrictions"/> <int value="3130" label="CSPWithReasonableBaseRestrictions"/> @@ -39759,6 +39759,7 @@ <int value="0" label="Completed"/> <int value="1" label="Provider Selection"/> <int value="2" label="Media Feeds Consent"/> + <int value="3" label="Welcome Screen"/> </enum> <enum name="KaleidoscopeNavigation"> @@ -42709,6 +42710,7 @@ <int value="-1159563774" label="enable-accessibility-script-injection"/> <int value="-1159369873" label="TabGroupsUiImprovementsAndroid:disabled"/> <int value="-1159154050" label="FilesSinglePartitionFormat:enabled"/> + <int value="-1159151875" label="RecordWebAppDebugInfo:disabled"/> <int value="-1158993534" label="PrintScaling:enabled"/> <int value="-1156179600" label="OmniboxRichEntitySuggestions:enabled"/> <int value="-1155543191" label="CopylessPaste:disabled"/> @@ -43285,6 +43287,7 @@ <int value="-596337171" label="disable-ash-sidebar"/> <int value="-595819071" label="OmniboxUIExperimentBlueTitlesOnPageSuggestions:disabled"/> + <int value="-595353721" label="RecordWebAppDebugInfo:enabled"/> <int value="-594076614" label="PluginVmShowCameraPermissions:disabled"/> <int value="-593536514" label="ExperimentalTabController:enabled"/> <int value="-591874964" label="LiteVideo:enabled"/> @@ -43910,6 +43913,7 @@ <int value="19629326" label="OmniboxExperimentalKeywordMode:enabled"/> <int value="19815558" label="EnableSettingsShortcutSearch:disabled"/> <int value="21055794" label="OpenXR:enabled"/> + <int value="23121136" label="MobileIdentityConsistencyVar:enabled"/> <int value="23556595" label="MarkHttpAs:enabled"/> <int value="26875005" label="disable-explicit-dma-fences"/> <int value="26945819" label="EnhancedDeskAnimations:disabled"/> @@ -44290,6 +44294,7 @@ <int value="401983950" label="enable-spdy4"/> <int value="402143634" label="enable-search-button-in-omnibox-always"/> <int value="403288255" label="enable-wheel-scroll-latching"/> + <int value="403554154" label="SafetyCheckWeakPasswords:enabled"/> <int value="405329388" label="FramebustingNeedsSameOriginOrUserGesture:enabled"/> <int value="408190863" label="OmniboxDisableInstantExtendedLimit:disabled"/> @@ -44601,6 +44606,7 @@ <int value="699149897" label="ContentSuggestionsDebugLog:disabled"/> <int value="700346797" label="WheelEventRegions:enabled"/> <int value="701766325" label="PerNavigationMojoInterface:enabled"/> + <int value="702060507" label="SafetyCheckWeakPasswords:disabled"/> <int value="703469777" label="AndroidNightModeTabReparenting:enabled"/> <int value="705407202" label="AutofillSaveCardImprovedUserConsent:disabled"/> <int value="705411729" label="AccessiblePDFForm:disabled"/> @@ -45970,6 +45976,7 @@ <int value="2018956925" label="UseAAudioDriver:disabled"/> <int value="2020107447" label="AndroidPayIntegrationV1:enabled"/> <int value="2020898714" label="HudDisplayForPerformanceMetrics:enabled"/> + <int value="2022153130" label="MobileIdentityConsistencyVar:disabled"/> <int value="2022294878" label="WifiSyncAndroid:enabled"/> <int value="2024172900" label="KidsManagementUrlClassification:disabled"/> <int value="2024298022"
diff --git a/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml b/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml index fe03902..862fd27 100644 --- a/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml +++ b/tools/metrics/histograms/histograms_xml/histogram_suffixes_list.xml
@@ -11995,6 +11995,8 @@ <suffix name="Fingerprint-setup.Next" label=""/> <suffix name="Gaia-signin.Back" label=""/> <suffix name="Gaia-signin.CloseDialog" label=""/> + <suffix name="Gaia-signin.EnterpriseEnroll" label=""/> + <suffix name="Gaia-signin.StartConsumerKiosk" label=""/> <suffix name="Gesture-navigation.Next" label=""/> <suffix name="Hid-detection.Next" label=""/> <suffix name="Hid-detection.StartDemo" label=""/>
diff --git a/tools/metrics/histograms/histograms_xml/others/histograms.xml b/tools/metrics/histograms/histograms_xml/others/histograms.xml index 530d85e0..71964a0 100644 --- a/tools/metrics/histograms/histograms_xml/others/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/others/histograms.xml
@@ -16984,17 +16984,6 @@ </summary> </histogram> -<histogram name="WebApp.Preinstalled.UninstallAndReplaceCount" units="apps" - expires_after="2021-04-01"> - <owner>alancutter@chromium.org</owner> - <owner>desktop-pwas-team@google.com</owner> - <summary> - Records how many preinstalled web app installations uninstalled and replaced - an old default app (web app or Chrome app). This corresponds to the - "uninstall_and_replace" field in preinstalled web app configs. - </summary> -</histogram> - <histogram name="WebApp.Shortcuts.Creation.Result" enum="ShortcutsCreationResult" expires_after="M93"> <owner>phillis@chromium.org</owner>
diff --git a/tools/metrics/histograms/histograms_xml/variations/histograms.xml b/tools/metrics/histograms/histograms_xml/variations/histograms.xml index ac7b0ee1..3dcc2fdc 100644 --- a/tools/metrics/histograms/histograms_xml/variations/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/variations/histograms.xml
@@ -212,7 +212,7 @@ </histogram> <histogram name="Variations.PolicyRestriction" - enum="VariationsRestrictionPolicyValues" expires_after="2020-12-31"> + enum="VariationsRestrictionPolicyValues" expires_after="2021-05-31"> <owner>pastarmovj@chromium.org</owner> <owner>ydago@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner>
diff --git a/tools/metrics/histograms/histograms_xml/web_rtc/histograms.xml b/tools/metrics/histograms/histograms_xml/web_rtc/histograms.xml index ee498b6b..795b46ea 100644 --- a/tools/metrics/histograms/histograms_xml/web_rtc/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/web_rtc/histograms.xml
@@ -1209,20 +1209,24 @@ </histogram> <histogram name="WebRTC.PeerConnection.KeyProtocol" - enum="PeerConnectionKeyProtocol" expires_after="M82"> + enum="PeerConnectionKeyProtocol" expires_after="2021-07-01"> <owner>hta@chromium.org</owner> + <owner>webrtc-dev@chromium.org</owner> <summary> What key exchange protocol (DTLS or SDES) is used to establish the crypto - keys for a PeerConnection's RTP transport. + keys for a PeerConnection's RTP transport. Note: This histogram was expired + after M82, and resurrected in M89. </summary> </histogram> <histogram name="WebRTC.PeerConnection.KeyProtocolByMedia" - enum="PeerConnectionKeyProtocolByMedia" expires_after="M82"> + enum="PeerConnectionKeyProtocolByMedia" expires_after="2021-07-01"> <owner>hta@chromium.org</owner> + <owner>webrtc-dev@chromium.org</owner> <summary> What key exchange protocol (DTLS or SDES) is used to establish the crypto - keys for a PeerConnection's RTP transport, specified per media type. + keys for a PeerConnection's RTP transport, specified per media type. Note: + This histogram was expired after M82, and resurrected in M89. </summary> </histogram> @@ -1327,6 +1331,7 @@ enum="PeerConnectionSdpFormatReceived" expires_after="2021-04-04"> <owner>steveanton@chromium.org</owner> <owner>hta@chromium.org</owner> + <owner>webrtc-dev@chromium.org</owner> <summary> What SDP format is received in the remote offer. The value "no tracks" means that no audio or video tracks were received. The value @@ -1343,6 +1348,7 @@ enum="PeerConnectionSdpFormatReceived" expires_after="2021-04-04"> <owner>steveanton@chromium.org</owner> <owner>hta@chromium.org</owner> + <owner>webrtc-dev@chromium.org</owner> <summary> What SDP format is received in the remote answer. See WebRTC.PeerConnection.SdpFormatReceived for the description of the values. @@ -1366,6 +1372,7 @@ <histogram name="WebRTC.PeerConnection.SdpSemanticRequested" enum="PeerConnectionSdpSemanticRequested" expires_after="2021-05-16"> <owner>hta@chromium.org</owner> + <owner>webrtc-dev@chromium.org</owner> <summary> What SDP semantic (Unified Plan, Plan B or "use default") has been asked for by the creator of a PeerConnection.
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 9b4d62fe..91c0f67 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -1,8 +1,8 @@ { "trace_processor_shell": { "win": { - "hash": "f1723fc6dd1f6c07dbcd45546d6531ef20aed428", - "remote_path": "perfetto_binaries/trace_processor_shell/win/f37338cdaa2126eef2a11e1a6f0cb075888c20e6/trace_processor_shell.exe" + "hash": "e8474594069dc7104a150ab3cf1e0545784fec5b", + "remote_path": "perfetto_binaries/trace_processor_shell/win/42433abb9596f1f471251070f7fd7d135c3e9df0/trace_processor_shell.exe" }, "mac": { "hash": "93f80fdc5944e51cabff3dd7cf60c2b5968898a0",
diff --git a/tools/polymer/polymer_test.py b/tools/polymer/polymer_test.py index c38714c..7df09704 100755 --- a/tools/polymer/polymer_test.py +++ b/tools/polymer/polymer_test.py
@@ -54,6 +54,17 @@ 'dom-module', 'dom_module.html', 'dom_module.js', 'dom_module.m.js', 'dom_module_expected.js') + # Test case where a commented out HTML import exists in the original HTML + # file. It is purposefully picked up and converted to a JS module, to address + # a unique use case of the FilesApp where an HTML import does not actually + # exist in the Polymer2 code. + # TODO(crbug.com/1133186): Remove after FilesApp Polymer3 migration is + # completed. + def testDomModuleWithCommentedOutImport(self): + self._run_test('dom-module', 'dom_module_with_commented_out_import.html', + 'dom_module.js', 'dom_module.m.js', + 'dom_module_with_commented_out_import_expected.js') + # Test case where HTML is extracted from a Polymer2 <dom-module> that is # wrapped in an IIFE function. def testDomModuleIife(self):
diff --git a/tools/polymer/tests/dom_module_with_commented_out_import.html b/tools/polymer/tests/dom_module_with_commented_out_import.html new file mode 100644 index 0000000..5989e5b --- /dev/null +++ b/tools/polymer/tests/dom_module_with_commented_out_import.html
@@ -0,0 +1,19 @@ +<link rel="import" href="../../../ui/webui/resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/polymer/v1_0/paper-behaviors/paper-ripple-behavior.html"> +<link rel="import" href="chrome://resources/html/ignore_me.html"> +<link rel="import" href="../shared_vars_css.html"> +<link rel="import" href="foo.html"> +<!-- <link rel="import" href="bar.html"> --> + +<dom-module id="cr-test-foo"> + <template> + <style> + div { + font-size: 2rem; + } + </style> + <div>Hello world</div> + </template> + <script src="dom_module.js"></script> +</dom-module>
diff --git a/tools/polymer/tests/dom_module_with_commented_out_import_expected.js b/tools/polymer/tests/dom_module_with_commented_out_import_expected.js new file mode 100644 index 0000000..f25489e1 --- /dev/null +++ b/tools/polymer/tests/dom_module_with_commented_out_import_expected.js
@@ -0,0 +1,20 @@ +import {Polymer, html} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; + +import {PaperRippleBehavior} from '//resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js'; +import '//resources/js/ignore_me.m.js'; +import '../shared_vars_css.m.js'; +import './foo.m.js'; +import './bar.m.js'; + +Polymer({ + _template: html`<!--_html_template_start_--> + <style> + div { + font-size: 2rem; + } + </style> + <div>Hello world</div> +<!--_html_template_end_-->`, + is: 'cr-test-foo', + behaviors: [PaperRippleBehavior], +});
diff --git a/ui/file_manager/file_manager/foreground/css/common.css b/ui/file_manager/file_manager/foreground/css/common.css index 9586aaf..9a67f31 100644 --- a/ui/file_manager/file_manager/foreground/css/common.css +++ b/ui/file_manager/file_manager/foreground/css/common.css
@@ -475,19 +475,6 @@ padding-top: 32px; } -.cr-dialog-container:not(.files-ng) .cr-dialog-close { - background: -webkit-image-set( - url(../images/files/ui/close_button.png) 1x, - url(../images/files/ui/2x/close_button.png) 2x) center no-repeat; - display: inline-block; - height: 40px; - opacity: 0.7; - position: absolute; - right: 0; - top: 0; - width: 40px; -} - .cr-dialog-container.files-ng .cr-dialog-close { display: none; }
diff --git a/ui/file_manager/file_manager/foreground/css/drive_welcome.css b/ui/file_manager/file_manager/foreground/css/drive_welcome.css index f794151..b3ab0a28f0 100644 --- a/ui/file_manager/file_manager/foreground/css/drive_welcome.css +++ b/ui/file_manager/file_manager/foreground/css/drive_welcome.css
@@ -4,13 +4,6 @@ /* Google Drive welcome banners.*/ -body:not(.files-ng) .drive-welcome-icon { - background-image: -webkit-image-set( - url(../images/files/ui/drive_logo.png) 1x, - url(../images/files/ui/2x/drive_logo.png) 2x); - background-repeat: no-repeat; -} - body.files-ng .drive-welcome-icon { background-image: url(../images/files/ui/drive_logo.svg); background-repeat: no-repeat; @@ -157,16 +150,6 @@ top: 0; } -.drive-welcome.header .banner-people { - background-image: -webkit-image-set( - url(../images/files/ui/drive_banner_people.png) 1x, - url(../images/files/ui/2x/drive_banner_people.png) 2x); - height: 128px; - position: absolute; - top: 0; - width: 106px; -} - html[dir='ltr'] .drive-welcome.header .banner-people { right: 38px; } @@ -175,15 +158,6 @@ left: 38px; } -.drive-welcome.header .banner-cloud-bg { - bottom: 0; - left: 0; - position: absolute; - right: 0; - top: 0; - transform: scaleY(-1); -} - body:not(.files-ng) .drive-welcome.header .plain-link { color: white; font-size: 16px; @@ -215,10 +189,6 @@ .drive-welcome.page .drive-welcome-wrapper { align-items: center; background-color: white; - /* This image looks good in high DPI as is. */ - background-image: url(../images/files/ui/clouds.png); - background-repeat: repeat-x; - background-size: 520px 173px; bottom: 0; color: #333; display: flex;
diff --git a/ui/file_manager/file_manager/foreground/css/file_manager.css b/ui/file_manager/file_manager/foreground/css/file_manager.css index adab168a..33f537e 100644 --- a/ui/file_manager/file_manager/foreground/css/file_manager.css +++ b/ui/file_manager/file_manager/foreground/css/file_manager.css
@@ -758,28 +758,10 @@ width: 0; } -.dialog-header:not(.files-ng) #search-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/search_white.png) 1x, - url(../images/files/ui/2x/search_white.png) 2x); -} - .dialog-header.files-ng #search-button > .icon { -webkit-mask-image: url(../images/files/ui/search.svg); } -body.check-select .dialog-header #search-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/search.png) 1x, - url(../images/files/ui/2x/search.png) 2x); -} - -.dialog-header:not(.files-ng) #share-menu-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/share_white.png) 1x, - url(../images/files/ui/2x/share_white.png) 2x); -} - .dialog-header.files-ng #share-menu-button > .icon { -webkit-mask-image: url(../images/files/ui/share_ng.svg); height: 48px; @@ -790,30 +772,10 @@ width: 48px; } -body.check-select .dialog-header #share-menu-button > .icon { - background-image: url(../images/files/ui/share.svg); -} - -.dialog-header:not(.files-ng) #sharesheet-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/share_white.png) 1x, - url(../images/files/ui/2x/share_white.png) 2x); -} - .dialog-header.files-ng #sharesheet-button > .icon { -webkit-mask-image: url(../images/files/ui/share_ng.svg); } -body.check-select .dialog-header #sharesheet-button > .icon { - background-image: url(../images/files/ui/share.svg); -} - -.dialog-header:not(.files-ng) #delete-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/delete_white.png) 1x, - url(../images/files/ui/2x/delete_white.png) 2x); -} - .dialog-header.files-ng #delete-button > .icon { -webkit-mask-image: url(../images/files/ui/delete_ng.svg); } @@ -822,22 +784,10 @@ background-image: url(../images/files/ui/delete.svg); } -.dialog-header:not(.files-ng) #refresh-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/refresh_white.png) 1x, - url(../images/files/ui/2x/refresh_white.png) 2x); -} - .dialog-header.files-ng #refresh-button > .icon { -webkit-mask-image: url(../images/files/ui/refresh.svg); } -.dialog-header:not(.files-ng) #view-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/view_list_white.png) 1x, - url(../images/files/ui/2x/view_list_white.png) 2x); -} - .dialog-header.files-ng #view-button > .icon { -webkit-mask-image: url(../images/files/ui/view_list.svg); } @@ -846,12 +796,6 @@ display: none; } -.dialog-header:not(.files-ng) #view-button.thumbnail > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/view_thumbnail_white.png) 1x, - url(../images/files/ui/2x/view_thumbnail_white.png) 2x); -} - .dialog-header.files-ng #view-button.thumbnail > .icon { -webkit-mask-image: url(../images/files/ui/view_thumbnail.svg); } @@ -860,10 +804,6 @@ display: none; } -.dialog-header:not(.files-ng) #sort-button > .icon { - background-image: url(../images/files/ui/sorting_white.svg); -} - .dialog-header.files-ng #sort-button > .icon { -webkit-mask-image: url(../images/files/ui/sorting_ng.svg); height: 48px; @@ -878,12 +818,6 @@ display: none; } -.dialog-header:not(.files-ng) #gear-button > .icon { - background-image: -webkit-image-set( - url(../images/files/ui/menu_white.png) 1x, - url(../images/files/ui/2x/menu_white.png) 2x); -} - .dialog-header.files-ng #gear-button > .icon { -webkit-mask-image: url(../images/files/ui/menu_ng.svg); height: 48px; @@ -893,15 +827,10 @@ position: absolute; width: 48px; } - body.check-select #gear-button { display: none; } -.dialog-header:not(.files-ng) #selection-menu-button > .icon { - background-image: url(../images/files/ui/menu.svg); -} - .dialog-header.files-ng #selection-menu-button > .icon { -webkit-mask-image: url(../images/files/ui/menu_ng.svg); height: 48px; @@ -1110,18 +1039,6 @@ display: none; } -body:not(.files-ng) #cancel-selection-button .icon-arrow-back { - background-image: -webkit-image-set( - url(../images/files/ui/back.png) 1x, - url(../images/files/ui/2x/back.png) 2x); - background-position: center; - background-repeat: no-repeat; - flex: none; - height: 16px; - margin-inline-end: 8px; - width: 16px; -} - body.files-ng #cancel-selection-button .icon-arrow-back { -webkit-mask-image: url(../images/files/ui/list_check.svg); -webkit-mask-position: center; @@ -1226,16 +1143,6 @@ visibility: hidden; } -.dialog-header:not(.files-ng) #search-box .clear { - background: -webkit-image-set( - url(../images/files/ui/search_clear.png) 1x, - url(../images/files/ui/2x/search_clear.png) 2x) - no-repeat center; - border: 0; - height: 16px; - width: 16px; -} - .dialog-header.files-ng #search-box .clear { background: none; height: 36px; @@ -1688,21 +1595,10 @@ display: none; } -#read-only-icon { - background-image: url(../images/files/ui/visibility_white.svg); - flex: none; - margin-inline-end: 8px; -} - -.dialog-header:not(.files-ng) #read-only-icon { - background-image: url(../images/files/ui/visibility_white.svg); - height: 16px; - width: 16px; -} - .dialog-header.files-ng #read-only-icon { -webkit-mask-image: url(../images/files/ui/visibility_ng.svg); height: 20px; + margin-inline-end: 8px; width: 20px; } @@ -1822,17 +1718,6 @@ color: var(--google-blue-600); } -body:not(.files-ng) .downloads-warning .warning-icon { - background-image: -webkit-image-set( - url(../images/files/ui/warning_white.png) 1x, - url(../images/files/ui/2x/warning_white.png) 2x); - background-size: 16px 16px; - flex: none; - height: 16px; - margin: 0 14px; - width: 16px; -} - body.files-ng .downloads-warning .warning-icon { -webkit-mask-image: url(../images/files/ui/warning.svg); background-color: var(--google-grey-700); @@ -1923,18 +1808,6 @@ visibility: hidden; } -body:not(.files-ng) .volume-warning .drive-icon { - background: white -webkit-image-set( - url(../images/files/ui/drive_logo.png) 1x, - url(../images/files/ui/2x/drive_logo.png) 2x) no-repeat center; - background-size: 29px 29px; - border-radius: 2px; - flex: none; - height: 36px; - margin: 0 14px; - width: 36px; -} - body.files-ng .volume-warning .drive-icon { background: white url(../images/files/ui/drive_logo.svg) no-repeat center; background-size: 20px 20px; @@ -1991,19 +1864,6 @@ width: 20px; } -body:not(.files-ng) .banner-close { - background: -webkit-image-set( - url(../images/files/ui/close_button_white.png) 1x, - url(../images/files/ui/2x/close_button_white.png) 2x) no-repeat center; - border: 0; - cursor: pointer; - display: inline-block; - height: 40px; - position: absolute; - top: 12px; - width: 40px; -} - body.files-ng .banner-close { border: 0; height: 32px; @@ -2021,14 +1881,6 @@ left: 0; } -body:not(.files-ng) .banner-cloud-bg { - background-image: -webkit-image-set( - url(../images/files/ui/drive_banner_clouds.png) 1x, - url(../images/files/ui/2x/drive_banner_clouds.png) 2x); - background-position: bottom left; - background-repeat: repeat-x; -} - /* The cr.ui.Grid representing the detailed file list. */ .thumbnail-grid { /* On the right side, we have less margin to pack items as long as they are @@ -2182,18 +2034,6 @@ width: 36px; } -.thumbnail-grid .checkmark.inactive { - background-image: -webkit-image-set( - url(../images/files/ui/grid_image_check.png) 1x, - url(../images/files/ui/2x/grid_image_check.png) 2x); -} - -.thumbnail-grid .checkmark.active { - background-image: -webkit-image-set( - url(../images/files/ui/grid_image_check_active.png) 1x, - url(../images/files/ui/2x/grid_image_check_active.png) 2x); -} - body.selecting .thumbnail-grid .checkmark.inactive, .thumbnail-grid .thumbnail-item:hover .checkmark.inactive { opacity: 0.6; @@ -2620,17 +2460,6 @@ } /* Table splitter element */ -.table-header-splitter { - background-image: -webkit-image-set( - url(../images/files/ui/vertical_separator.png) 1x, - url(../images/files/ui/2x/vertical_separator.png) 2x); - background-position: center; - background-repeat: repeat-y; - height: 40px; - top: 0; - width: 5px; -} - .table-header-splitter:last-child { display: none; } @@ -2643,32 +2472,6 @@ height: 40px; } -.table-header-sort-image-desc::after { - background-image: -webkit-image-set( - url(../images/files/ui/sort_desc.png) 1x, - url(../images/files/ui/2x/sort_desc.png) 2x); - background-position: center center; - background-repeat: no-repeat; - color: #888; - content: ' '; - padding-inline-start: 13px; - position: relative; - top: 1px; -} - -.table-header-sort-image-asc::after { - background-image: -webkit-image-set( - url(../images/files/ui/sort_asc.png) 1x, - url(../images/files/ui/2x/sort_asc.png) 2x); - background-position: center center; - background-repeat: no-repeat; - color: #888; - content: ' '; - padding-inline-start: 13px; - position: relative; - top: -1px; -} - /* Text label in a table header. */ .table-header-label { color: rgb(100, 100, 100); @@ -2743,18 +2546,6 @@ width: 28px; } -#list-container list li .detail-checkmark { - background-image: -webkit-image-set( - url(../images/files/ui/list_check.png) 1x, - url(../images/files/ui/2x/list_check.png) 2x); -} - -#list-container grid li .detail-checkmark { - background-image: -webkit-image-set( - url(../images/files/ui/grid_folder_check.png) 1x, - url(../images/files/ui/2x/grid_folder_check.png) 2x); -} - body.check-select #list-container li[selected] .detail-checkmark { opacity: 1; } @@ -3078,37 +2869,10 @@ position: relative; } -#empty-folder { - display: flex; - flex-direction: column; - height: 100%; - justify-content: center; - left: 0; - position: absolute; - top: 0; - width: 100%; -} - -#empty-folder > .image { - background-image: -webkit-image-set( - url(../images/files/ui/empty_folder.png) 1x, - url(../images/files/ui/2x/empty_folder.png) 2x); - height: 145px; - margin: 50px auto 32px auto; - width: 120px; -} - body.files-ng #empty-folder { display: none; } -#empty-folder > .label { - color: rgb(180, 180, 180); - font-size: 16px; - font-weight: bold; - text-align: center; -} - #volume-space-info-contents { align-items: center; display: flex;
diff --git a/ui/file_manager/file_manager/foreground/css/file_types.css b/ui/file_manager/file_manager/foreground/css/file_types.css index ca0b018..36e1bd3 100644 --- a/ui/file_manager/file_manager/foreground/css/file_types.css +++ b/ui/file_manager/file_manager/foreground/css/file_types.css
@@ -8,58 +8,27 @@ noting that file-type-icon is also used in lists and menus ;) */ /* Small icons for file types, used in lists and menus. */ -[file-type-icon] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_generic.png) 1x, - url(../images/filetype/2x/filetype_generic.png) 2x); - background-position: center; - background-repeat: no-repeat; - background-size: 16px 16px; -} - body.files-ng [file-type-icon] { -webkit-mask-position: center; -webkit-mask-repeat: no-repeat; background-image: url(../images/filetype/filetype_generic.svg); + background-position: center; + background-repeat: no-repeat; background-size: 20px 20px; } -[file-type-icon='archive'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_archive.png) 1x, - url(../images/filetype/2x/filetype_archive.png) 2x); -} - body.files-ng [file-type-icon='archive'] { background-image: url(../images/filetype/filetype_archive.svg); } -[file-type-icon='audio'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_audio.png) 1x, - url(../images/filetype/2x/filetype_audio.png) 2x); -} - body.files-ng [file-type-icon='audio'] { background-image: url(../images/filetype/filetype_audio.svg); } -[file-type-icon='excel'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_excel.png) 1x, - url(../images/filetype/2x/filetype_excel.png) 2x); -} - body.files-ng [file-type-icon='excel'] { background-image: url(../images/filetype/filetype_excel.svg); } -[file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_folder.png) 1x, - url(../images/filetype/2x/filetype_folder.png) 2x); -} - body.files-ng [file-type-icon='folder'] { -webkit-mask-image: url(../images/filetype/filetype_folder.svg); background-color: currentColor; @@ -71,243 +40,99 @@ background: none; } -.computers-root[file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/volumes/computer.png) 1x, - url(../images/volumes/2x/computer.png) 2x); -} - body.files-ng .computers-root[file-type-icon='folder'] { -webkit-mask-image: url(../images/volumes/computer.svg); } -.external-media-root[file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/volumes/usb.png) 1x, - url(../images/volumes/2x/usb.png) 2x); -} - body.files-ng .external-media-root[file-type-icon='folder'] { -webkit-mask-image: url(../images/volumes/usb.svg); } -.shared[file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_folder_shared.png) 1x, - url(../images/filetype/2x/filetype_folder_shared.png) 2x); -} - body.files-ng .shared[file-type-icon='folder'] { -webkit-mask-image: url(../images/filetype/filetype_folder_shared.svg); } -.team-drive-root[file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/volumes/hard_drive.png) 1x, - url(../images/volumes/2x/hard_drive.png) 2x); -} - body.files-ng .team-drive-root[file-type-icon='folder'] { -webkit-mask-image: url(../images/volumes/hard_drive.svg); } -.tree-row[selected] > [file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_folder_active.png) 1x, - url(../images/filetype/2x/filetype_folder_active.png) 2x); -} - /* .tree-row > .file-row icon for files-ng. */ .tree-row > .file-row > [file-type-icon='folder'] { -webkit-mask-image: url(../images/filetype/filetype_folder.svg); } -.tree-row[selected] > .shared[file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_folder_shared_active.png) 1x, - url(../images/filetype/2x/filetype_folder_shared_active.png) 2x); -} - .tree-row > .file-row > .shared[file-type-icon='folder'] { -webkit-mask-image: url(../images/filetype/filetype_folder_shared.svg); } -.tree-row[selected] > .team-drive-root[file-type-icon='folder'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_team_drive_active.png) 1x, - url(../images/filetype/2x/filetype_team_drive_active.png) 2x); -} - .tree-row > .file-row > .team-drive-root[file-type-icon='folder'] { -webkit-mask-image: url(../images/filetype/filetype_team_drive.svg); } -[file-type-icon='gdoc'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gdoc.png) 1x, - url(../images/filetype/2x/filetype_gdoc.png) 2x); -} - body.files-ng [file-type-icon='gdoc'] { background-image: url(../images/filetype/filetype_gdoc.svg); } -[file-type-icon='gdraw'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gdraw.png) 1x, - url(../images/filetype/2x/filetype_gdraw.png) 2x); -} - body.files-ng [file-type-icon='gdraw'] { background-image: url(../images/filetype/filetype_gdraw.svg); } -[file-type-icon='glink'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_generic.png) 1x, - url(../images/filetype/2x/filetype_generic.png) 2x); -} - body.files-ng [file-type-icon='glink'] { background-image: url(../images/filetype/filetype_generic.svg); } -[file-type-icon='gsheet'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gsheet.png) 1x, - url(../images/filetype/2x/filetype_gsheet.png) 2x); -} - body.files-ng [file-type-icon='gsheet'] { background-image: url(../images/filetype/filetype_gsheet.svg); } -[file-type-icon='gslides'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gslides.png) 1x, - url(../images/filetype/2x/filetype_gslides.png) 2x); -} - body.files-ng [file-type-icon='gslides'] { background-image: url(../images/filetype/filetype_gslides.svg); } -[file-type-icon='gtable'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gtable.png) 1x, - url(../images/filetype/2x/filetype_gtable.png) 2x); -} - body.files-ng [file-type-icon='gtable'] { background-image: url(../images/filetype/filetype_gtable.svg); } -[file-type-icon='gform'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gform.png) 1x, - url(../images/filetype/2x/filetype_gform.png) 2x); -} - body.files-ng [file-type-icon='gform'] { background-image: url(../images/filetype/filetype_gform.svg); } -[file-type-icon='gmap'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gmap.png) 1x, - url(../images/filetype/2x/filetype_gmap.png) 2x); -} - body.files-ng [file-type-icon='gmap'] { background-image: url(../images/filetype/filetype_gmap.svg); } -[file-type-icon='gsite'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_gsite.png) 1x, - url(../images/filetype/2x/filetype_gsite.png) 2x); -} - body.files-ng [file-type-icon='gsite'] { background-image: url(../images/filetype/filetype_gsite.svg); } -[file-type-icon='image'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_image.png) 1x, - url(../images/filetype/2x/filetype_image.png) 2x); -} - body.files-ng [file-type-icon='image'] { background-image: url(../images/filetype/filetype_image.svg); } -[file-type-icon='pdf'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_pdf.png) 1x, - url(../images/filetype/2x/filetype_pdf.png) 2x); -} - body.files-ng [file-type-icon='pdf'] { background-image: url(../images/filetype/filetype_pdf.svg); } -[file-type-icon='ppt'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_ppt.png) 1x, - url(../images/filetype/2x/filetype_ppt.png) 2x); -} - body.files-ng [file-type-icon='ppt'] { background-image: url(../images/filetype/filetype_ppt.svg); } -[file-type-icon='script'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_script.png) 1x, - url(../images/filetype/2x/filetype_script.png) 2x); -} - body.files-ng [file-type-icon='script'] { background-image: url(../images/filetype/filetype_script.svg); } -[file-type-icon='sites'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_sites.png) 1x, - url(../images/filetype/2x/filetype_sites.png) 2x); -} - body.files-ng [file-type-icon='sites'] { background-image: url(../images/filetype/filetype_sites.svg); } -[file-type-icon='tini'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_tini.png) 1x, - url(../images/filetype/2x/filetype_tini.png) 2x); -} - body.files-ng [file-type-icon='tini'] { background-image: url(../images/filetype/filetype_tini.svg); } -[file-type-icon='video'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_video.png) 1x, - url(../images/filetype/2x/filetype_video.png) 2x); -} - body.files-ng [file-type-icon='video'] { background-image: url(../images/filetype/filetype_video.svg); } -[file-type-icon='word'] { - background-image: -webkit-image-set( - url(../images/filetype/filetype_word.png) 1x, - url(../images/filetype/2x/filetype_word.png) 2x); -} - body.files-ng [file-type-icon='word'] { background-image: url(../images/filetype/filetype_word.svg); } @@ -432,52 +257,14 @@ /* Icons for volume types. A ".tree-row > .file-row" component in any rules means the rule only matches in files-ng. */ -[volume-type-icon='archive'] { - background-image: -webkit-image-set( - url(../images/volumes/archive.png) 1x, - url(../images/volumes/2x/archive.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='archive'] { - background-image: -webkit-image-set( - url(../images/volumes/archive_active.png) 1x, - url(../images/volumes/2x/archive_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='archive'] { -webkit-mask-image: url(../images/volumes/archive.svg); } -[root-type-icon='my_files'] { - background-image: -webkit-image-set( - url(../images/volumes/my_files.png) 1x, - url(../images/volumes/2x/my_files.png) 2x); -} - -.tree-row[selected] > [root-type-icon='my_files'] { - background-image: -webkit-image-set( - url(../images/volumes/my_files_active.png) 1x, - url(../images/volumes/2x/my_files_active.png) 2x); -} - .tree-row > .file-row > [root-type-icon='my_files'] { -webkit-mask-image: url(../images/volumes/my_files.svg); } -[volume-type-icon='downloads'], -[file-type-icon='downloads'] { - background-image: -webkit-image-set( - url(../images/volumes/downloads.png) 1x, - url(../images/volumes/2x/downloads.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='downloads'], -.tree-row[selected] > [file-type-icon='downloads'] { - background-image: -webkit-image-set( - url(../images/volumes/downloads_active.png) 1x, - url(../images/volumes/2x/downloads_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='downloads'], .tree-row > .file-row > [file-type-icon='downloads'] { -webkit-mask-image: url(../images/volumes/downloads.svg); @@ -499,323 +286,89 @@ -webkit-mask-image: url(../images/volumes/camera.svg); } -[volume-type-icon='drive'] { - background-image: -webkit-image-set( - url(../images/volumes/drive.png) 1x, - url(../images/volumes/2x/drive.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='drive'] { - background-image: -webkit-image-set( - url(../images/volumes/drive_active.png) 1x, - url(../images/volumes/2x/drive_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='drive'] { -webkit-mask-image: url(../images/volumes/drive.svg); } -[volume-type-icon='shortcut'] { - background-image: -webkit-image-set( - url(../images/volumes/shortcut.png) 1x, - url(../images/volumes/2x/shortcut.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='shortcut'] { - background-image: -webkit-image-set( - url(../images/volumes/shortcut_active.png) 1x, - url(../images/volumes/2x/shortcut_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='shortcut'] { -webkit-mask-image: url(../images/volumes/shortcut.svg); } -.drive-volume > .tree-row > [volume-type-icon='drive'], -.tree-row > [root-type-icon='drive'] { - background-image: -webkit-image-set( - url(../images/volumes/service_drive.png) 1x, - url(../images/volumes/2x/service_drive.png) 2x); -} - -.drive-volume > .tree-row[selected] > [volume-type-icon='drive'], -.tree-row[selected] > [root-type-icon='drive'] { - background-image: -webkit-image-set( - url(../images/volumes/service_drive_active.png) 1x, - url(../images/volumes/2x/service_drive_active.png) 2x); -} - .drive-volume > .tree-row > .file-row > [volume-type-icon='drive'], .tree-row > .file-row > [root-type-icon='drive'] { -webkit-mask-image: url(../images/volumes/service_drive.svg); } -[volume-type-icon='shared_drives_grand_root'] { - background-image: -webkit-image-set( - url(../images/volumes/team_drive.png) 1x, - url(../images/volumes/2x/team_drive.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='shared_drives_grand_root'] { - background-image: -webkit-image-set( - url(../images/volumes/team_drive_active.png) 1x, - url(../images/volumes/2x/team_drive_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='shared_drives_grand_root'] { -webkit-mask-image: url(../images/volumes/team_drive.svg); } -[volume-type-icon='team_drive'] { - background-image: -webkit-image-set( - url(../images/volumes/hard_drive.png) 1x, - url(../images/volumes/2x/hard_drive.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='team_drive'] { - background-image: -webkit-image-set( - url(../images/volumes/hard_drive_active.png) 1x, - url(../images/volumes/2x/hard_drive_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='team_drive'] { -webkit-mask-image: url(../images/volumes/hard_drive.svg); } -[volume-type-icon='computers_grand_root'] { - background-image: -webkit-image-set( - url(../images/volumes/devices.png) 1x, - url(../images/volumes/2x/devices.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='computers_grand_root'] { - background-image: -webkit-image-set( - url(../images/volumes/devices_active.png) 1x, - url(../images/volumes/2x/devices_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='computers_grand_root'] { -webkit-mask-image: url(../images/volumes/devices.svg); } -[volume-type-icon='computer'] { - background-image: -webkit-image-set( - url(../images/volumes/computer.png) 1x, - url(../images/volumes/2x/computer.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='computer'] { - background-image: -webkit-image-set( - url(../images/volumes/computer_active.png) 1x, - url(../images/volumes/2x/computer_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='computer'] { -webkit-mask-image: url(../images/volumes/computer.svg); } -[volume-type-icon='drive_offline'] { - background-image: -webkit-image-set( - url(../images/volumes/offline.png) 1x, - url(../images/volumes/2x/offline.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='drive_offline'] { - background-image: -webkit-image-set( - url(../images/volumes/offline_active.png) 1x, - url(../images/volumes/2x/offline_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='drive_offline'] { -webkit-mask-image: url(../images/volumes/offline.svg); } -[volume-type-icon='drive_shared_with_me'] { - background-image: -webkit-image-set( - url(../images/volumes/shared.png) 1x, - url(../images/volumes/2x/shared.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='drive_shared_with_me'] { - background-image: -webkit-image-set( - url(../images/volumes/shared_active.png) 1x, - url(../images/volumes/2x/shared_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='drive_shared_with_me'] { -webkit-mask-image: url(../images/volumes/shared.svg); } -[volume-type-icon='drive_recent'] { - background-image: -webkit-image-set( - url(../images/volumes/recent.png) 1x, - url(../images/volumes/2x/recent.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='drive_recent'] { - background-image: -webkit-image-set( - url(../images/volumes/recent_active.png) 1x, - url(../images/volumes/2x/recent_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='drive_recent'] { -webkit-mask-image: url(../images/volumes/recent.svg); } -[volume-type-icon='external_media'], -[volume-type-icon='removable'], -[root-type-icon='removable'] { - background-image: -webkit-image-set( - url(../images/volumes/usb.png) 1x, - url(../images/volumes/2x/usb.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='external_media'], -.tree-row[selected] > [volume-type-icon='removable'], -.tree-row[selected] > [root-type-icon='removable'] { - background-image: -webkit-image-set( - url(../images/volumes/usb_active.png) 1x, - url(../images/volumes/2x/usb_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='external_media'], .tree-row > .file-row > [volume-type-icon='removable'], .tree-row > .file-row > [root-type-icon='removable'] { -webkit-mask-image: url(../images/volumes/usb.svg); } -[volume-type-icon='removable'][volume-subtype='sd'] { - background-image: -webkit-image-set( - url(../images/volumes/sd.png) 1x, - url(../images/volumes/2x/sd.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='removable'][volume-subtype='sd'] { - background-image: -webkit-image-set( - url(../images/volumes/sd_active.png) 1x, - url(../images/volumes/2x/sd_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='removable'][volume-subtype='sd'] { -webkit-mask-image: url(../images/volumes/sd.svg); } -[volume-type-icon='removable'][volume-subtype='optical'] { - background-image: -webkit-image-set( - url(../images/volumes/cd.png) 1x, - url(../images/volumes/2x/cd.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='removable'][volume-subtype='optical'] { - background-image: -webkit-image-set( - url(../images/volumes/cd_active.png) 1x, - url(../images/volumes/2x/cd_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='removable'][volume-subtype='optical'] { -webkit-mask-image: url(../images/volumes/cd.svg); } -[volume-type-icon='media_view'][volume-subtype='images_root'], -[root-type-icon='recent'][recent-file-type='image'] { - background-image: -webkit-image-set( - url(../images/volumes/images.png) 1x, - url(../images/volumes/2x/images.png) 2x); -} - -.tree-row[selected] - > [volume-type-icon='media_view'][volume-subtype='images_root'], -.tree-row[selected] > [root-type-icon='recent'][recent-file-type='image'] { - background-image: -webkit-image-set( - url(../images/volumes/images_active.png) 1x, - url(../images/volumes/2x/images_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='media_view'][volume-subtype='images_root'], .tree-row > .file-row > [root-type-icon='recent'][recent-file-type='image'] { -webkit-mask-image: url(../images/volumes/images.svg); } -[volume-type-icon='media_view'][volume-subtype='videos_root'], -[root-type-icon='recent'][recent-file-type='video'] { - background-image: -webkit-image-set( - url(../images/volumes/videos.png) 1x, - url(../images/volumes/2x/videos.png) 2x); -} - -.tree-row[selected] - > [volume-type-icon='media_view'][volume-subtype='videos_root'], -.tree-row[selected] > [root-type-icon='recent'][recent-file-type='video'] { - background-image: -webkit-image-set( - url(../images/volumes/videos_active.png) 1x, - url(../images/volumes/2x/videos_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='media_view'][volume-subtype='videos_root'], .tree-row > .file-row > [root-type-icon='recent'][recent-file-type='video'] { -webkit-mask-image: url(../images/volumes/videos.svg); } -[volume-type-icon='media_view'][volume-subtype='audio_root'], -[root-type-icon='recent'][recent-file-type='audio'] { - background-image: -webkit-image-set( - url(../images/volumes/audio.png) 1x, - url(../images/volumes/2x/audio.png) 2x); -} - -.tree-row[selected] - > [volume-type-icon='media_view'][volume-subtype='audio_root'], -.tree-row[selected] > [root-type-icon='recent'][recent-file-type='audio'] { - background-image: -webkit-image-set( - url(../images/volumes/audio_active.png) 1x, - url(../images/volumes/2x/audio_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='media_view'][volume-subtype='audio_root'], .tree-row > .file-row > [root-type-icon='recent'][recent-file-type='audio'] { -webkit-mask-image: url(../images/volumes/audio.svg); } -[volume-type-icon='mtp'] { - background-image: -webkit-image-set( - url(../images/volumes/phone.png) 1x, - url(../images/volumes/2x/phone.png) 2x); -} - -.tree-row[selected] > [volume-type-icon='mtp'] { - background-image: -webkit-image-set( - url(../images/volumes/phone_active.png) 1x, - url(../images/volumes/2x/phone_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='mtp'] { -webkit-mask-image: url(../images/volumes/phone.svg); } -[volume-type-icon='removable'][volume-subtype='unknown'], -.tree-item .tree-item > .tree-row > [volume-type-icon='removable'], -[file-type-icon='removable'] { - background-image: -webkit-image-set( - url(../images/volumes/hard_drive.png) 1x, - url(../images/volumes/2x/hard_drive.png) 2x); -} - body.files-ng [file-type-icon='removable'] { -webkit-mask-image: url(../images/volumes/hard_drive.svg); background-color: currentColor; background-image: none; } -.tree-row[selected] > [volume-type-icon='removable'][volume-subtype='unknown'], -.tree-item .tree-item > .tree-row[selected] > [volume-type-icon='removable'] { - background-image: -webkit-image-set( - url(../images/volumes/hard_drive_active.png) 1x, - url(../images/volumes/2x/hard_drive_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='removable'][volume-subtype='unknown'], .tree-item .tree-item > .tree-row > .file-row > [volume-type-icon='removable'] { -webkit-mask-image: url(../images/volumes/hard_drive.svg); @@ -827,93 +380,39 @@ filter: contrast(0) brightness(0.7143); } -[root-type-icon='recent'] { - background-image: -webkit-image-set( - url(../images/volumes/recent.png) 1x, - url(../images/volumes/2x/recent.png) 2x); -} - -.tree-row[selected] > [root-type-icon='recent'] { - background-image: -webkit-image-set( - url(../images/volumes/recent_active.png) 1x, - url(../images/volumes/2x/recent_active.png) 2x); -} - .tree-row > .file-row > [root-type-icon='recent'] { -webkit-mask-image: url(../images/volumes/recent.svg); } -[file-type-icon='crostini'], -[root-type-icon='crostini'], -[volume-type-icon='crostini'] { - background-image: -webkit-image-set( - url(../images/volumes/linux_files.png) 1x, - url(../images/volumes/2x/linux_files.png) 2x); -} - body.files-ng [file-type-icon='crostini'] { background-image: url(../images/volumes/linux_files.svg); } -.tree-row[selected] > [root-type-icon='crostini'], -.tree-row[selected] > [volume-type-icon='crostini'] { - background-image: -webkit-image-set( - url(../images/volumes/linux_files_active.png) 1x, - url(../images/volumes/2x/linux_files_active.png) 2x); -} - .tree-row > .file-row > [root-type-icon='crostini'], .tree-row > .file-row > [volume-type-icon='crostini'] { -webkit-mask-image: url(../images/volumes/linux_files.svg); } -[file-type-icon='android_files'], -[volume-type-icon='android_files'] { - background-image: -webkit-image-set( - url(../images/volumes/android.png) 1x, - url(../images/volumes/2x/android.png) 2x); -} - body.files-ng [file-type-icon='android_files'] { -webkit-mask-image: url(../images/volumes/android.svg); background-color: currentColor; background-image: none; } -.tree-row[selected] > [volume-type-icon='android_files'] { - background-image: -webkit-image-set( - url(../images/volumes/android_active.png) 1x, - url(../images/volumes/2x/android_active.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='android_files'] { -webkit-mask-image: url(../images/volumes/android.svg); } -[file-type-icon='plugin_vm'] { - background-image: url(../images/volumes/plugin_vm.svg); -} - body.files-ng [file-type-icon='plugin_vm'] { -webkit-mask-image: url(../images/volumes/plugin_vm_ng.svg); background-color: currentColor; background-image: none; } -.tree-row[selected] > [file-type-icon='plugin_vm'] { - background-image: url(../images/volumes/plugin_vm_active.svg) -} - .tree-row > .file-row > [file-type-icon='plugin_vm'] { -webkit-mask-image: url(../images/volumes/plugin_vm_ng.svg); } -[volume-type-icon='smb'] { - background-image: -webkit-image-set( - url(../images/volumes/smb.png) 1x, - url(../images/volumes/2x/smb.png) 2x); -} - .tree-row > .file-row > [volume-type-icon='smb'] { -webkit-mask-image: url(../images/volumes/smb.svg); }
diff --git a/ui/file_manager/file_manager/foreground/css/tree.css b/ui/file_manager/file_manager/foreground/css/tree.css index e7115c6..ed9d5de 100644 --- a/ui/file_manager/file_manager/foreground/css/tree.css +++ b/ui/file_manager/file_manager/foreground/css/tree.css
@@ -17,25 +17,6 @@ white-space: nowrap; } -.tree-row > .expand-icon { - background-image: -webkit-image-set( - url(../images/files/ui/expand_more.png) 1x, - url(../images/files/ui/2x/expand_more.png) 2x); - background-position: 50% 50%; - background-repeat: no-repeat; - background-size: 16px 16px; - position: relative; - transform: rotate(-90deg); - transition: all 150ms; - vertical-align: top; -} - -.tree-row[selected] > .expand-icon { - background-image: -webkit-image-set( - url(../images/files/ui/expand_more_active.png) 1x, - url(../images/files/ui/2x/expand_more_active.png) 2x); -} - /* All .tree-row > .file-row > ... rules are files-ng specific. */ .tree-row > .file-row > .expand-icon { -webkit-mask-image: url(../images/files/ui/sort_desc.svg);
diff --git a/ui/file_manager/file_manager/foreground/elements/BUILD.gn b/ui/file_manager/file_manager/foreground/elements/BUILD.gn index 339e115f..a6387f37 100644 --- a/ui/file_manager/file_manager/foreground/elements/BUILD.gn +++ b/ui/file_manager/file_manager/foreground/elements/BUILD.gn
@@ -58,6 +58,7 @@ ":files_metadata_box.m", ":files_metadata_entry.m", ":files_ripple.m", + ":files_safe_media.m", ":files_toggle_ripple.m", ] } @@ -213,6 +214,25 @@ js_library("files_safe_media") { } +polymer_modulizer("files_safe_media") { + js_file = "files_safe_media.js" + html_file = "files_safe_media.html" + html_type = "dom-module" + preserve_url_scheme = true + + auto_imports = + [ "ui/webui/resources/html/assert.html|assert,assertInstanceof" ] +} + +js_library("files_safe_media.m") { + sources = [ "$root_gen_dir/ui/file_manager/file_manager/foreground/elements/files_safe_media.m.js" ] + deps = [ + "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", + "//ui/webui/resources/js:assert.m", + ] + extra_deps = [ ":files_safe_media_module" ] +} + js_library("files_safe_media_webview_content") { }
diff --git a/ui/file_manager/file_manager/foreground/elements/files_quick_view.css b/ui/file_manager/file_manager/foreground/elements/files_quick_view.css index 75b112c6..fac024d 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_quick_view.css +++ b/ui/file_manager/file_manager/foreground/elements/files_quick_view.css
@@ -86,14 +86,6 @@ margin-right: auto; } -#metadata-button { - background-image: -webkit-image-set( - url(../images/files/ui/quick_view/info_outline.png) 1x, - url(../images/files/ui/quick_view/2x/info_outline.png) 2x); - background-position: center; - background-repeat: no-repeat; -} - #innerContentPanel { background-color: transparent; color: white;
diff --git a/ui/file_manager/file_manager/foreground/elements/files_safe_media.html b/ui/file_manager/file_manager/foreground/elements/files_safe_media.html index 0cd6e30f4..b86c0f8a 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_safe_media.html +++ b/ui/file_manager/file_manager/foreground/elements/files_safe_media.html
@@ -3,6 +3,8 @@ -- found in the LICENSE file. --> +<link rel="import" href="chrome://resources/html/polymer.html"> + <dom-module id="files-safe-media"> <template> <style> @@ -21,6 +23,5 @@ </style> <div id="content" class$="[[type]]"></div> </template> - <script src="files_safe_media.js"></script> </dom-module>
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/back.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/back.png deleted file mode 100644 index 66d2b85..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/back.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/cancel.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/cancel.png deleted file mode 100644 index accd9bf..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/cancel.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/close_button.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/close_button.png deleted file mode 100644 index 64e9752..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/close_button.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/close_button_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/close_button_white.png deleted file mode 100644 index 28b05fe1..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/close_button_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/delete_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/delete_white.png deleted file mode 100644 index 6d1aafb..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/delete_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_banner_clouds.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_banner_clouds.png deleted file mode 100644 index 226abc0..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_banner_clouds.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_banner_people.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_banner_people.png deleted file mode 100644 index f2af0c1..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_banner_people.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_logo.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_logo.png deleted file mode 100644 index 0417dc9..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/drive_logo.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_less.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_less.png deleted file mode 100644 index 2650576..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_less.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_less_active.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_less_active.png deleted file mode 100644 index 430391c..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_less_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_more.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_more.png deleted file mode 100644 index f63383a..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_more.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_more_active.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_more_active.png deleted file mode 100644 index a4a737a..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/expand_more_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_folder_check.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_folder_check.png deleted file mode 100644 index 7ab5a98a..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_folder_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_image_check.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_image_check.png deleted file mode 100644 index 93d14364a..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_image_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_image_check_active.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_image_check_active.png deleted file mode 100644 index 3c8600a..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/grid_image_check_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/list_check.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/list_check.png deleted file mode 100644 index 925e66d..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/list_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/menu_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/menu_white.png deleted file mode 100644 index 4781d01..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/menu_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/refresh_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/refresh_white.png deleted file mode 100644 index 04a5580d..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/refresh_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/search_clear.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/search_clear.png deleted file mode 100644 index e9f9e4e..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/search_clear.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/search_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/search_white.png deleted file mode 100644 index 9ea2864..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/search_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/share.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/share.png deleted file mode 100644 index ebfff91c4..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/share.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/share_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/share_white.png deleted file mode 100644 index 91c1fb93..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/share_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/sort_asc.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/sort_asc.png deleted file mode 100644 index 419b29e..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/sort_asc.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/sort_desc.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/sort_desc.png deleted file mode 100644 index e7e74c5..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/sort_desc.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/sorting_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/sorting_white.png deleted file mode 100644 index d6a36ef0..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/sorting_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/vertical_separator.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/vertical_separator.png deleted file mode 100644 index c251cb5b..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/vertical_separator.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/view_list_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/view_list_white.png deleted file mode 100644 index cb17b41..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/view_list_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/view_thumbnail_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/view_thumbnail_white.png deleted file mode 100644 index 04f11fb..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/view_thumbnail_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/2x/warning_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/2x/warning_white.png deleted file mode 100644 index 9fc24d1..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/2x/warning_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/back.png b/ui/file_manager/file_manager/foreground/images/files/ui/back.png deleted file mode 100644 index 677902d0..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/back.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/cancel.png b/ui/file_manager/file_manager/foreground/images/files/ui/cancel.png deleted file mode 100644 index f898dbca..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/cancel.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/close_button.png b/ui/file_manager/file_manager/foreground/images/files/ui/close_button.png deleted file mode 100644 index 08f2516..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/close_button.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/close_button_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/close_button_white.png deleted file mode 100644 index 676e3423..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/close_button_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/clouds.png b/ui/file_manager/file_manager/foreground/images/files/ui/clouds.png deleted file mode 100644 index 1ee2b0cb..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/clouds.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/delete_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/delete_white.png deleted file mode 100644 index 32889c7..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/delete_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/drive_banner_clouds.png b/ui/file_manager/file_manager/foreground/images/files/ui/drive_banner_clouds.png deleted file mode 100644 index 95d7bf0..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/drive_banner_clouds.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/drive_banner_people.png b/ui/file_manager/file_manager/foreground/images/files/ui/drive_banner_people.png deleted file mode 100644 index bbeb0df1..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/drive_banner_people.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/drive_logo.png b/ui/file_manager/file_manager/foreground/images/files/ui/drive_logo.png deleted file mode 100644 index 3e17d94..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/drive_logo.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/expand_less.png b/ui/file_manager/file_manager/foreground/images/files/ui/expand_less.png deleted file mode 100644 index 48677d8..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/expand_less.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/expand_less_active.png b/ui/file_manager/file_manager/foreground/images/files/ui/expand_less_active.png deleted file mode 100644 index e871d02..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/expand_less_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/expand_more.png b/ui/file_manager/file_manager/foreground/images/files/ui/expand_more.png deleted file mode 100644 index 44de1691..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/expand_more.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/expand_more_active.png b/ui/file_manager/file_manager/foreground/images/files/ui/expand_more_active.png deleted file mode 100644 index 95d724c9..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/expand_more_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/grid_folder_check.png b/ui/file_manager/file_manager/foreground/images/files/ui/grid_folder_check.png deleted file mode 100644 index 4311b1e..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/grid_folder_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/grid_image_check.png b/ui/file_manager/file_manager/foreground/images/files/ui/grid_image_check.png deleted file mode 100644 index 45026a2..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/grid_image_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/grid_image_check_active.png b/ui/file_manager/file_manager/foreground/images/files/ui/grid_image_check_active.png deleted file mode 100644 index 8652ebfd..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/grid_image_check_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/list_check.png b/ui/file_manager/file_manager/foreground/images/files/ui/list_check.png deleted file mode 100644 index 4b313c4..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/list_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/menu.svg b/ui/file_manager/file_manager/foreground/images/files/ui/menu.svg deleted file mode 100644 index c34b180f..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/menu.svg +++ /dev/null
@@ -1,4 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 24 24" fill="#616161"> - <path d="M0 0h24v24H0z" fill="none"/> - <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/menu_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/menu_white.png deleted file mode 100644 index 13346f0..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/menu_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/quick_view/2x/info_outline.png b/ui/file_manager/file_manager/foreground/images/files/ui/quick_view/2x/info_outline.png deleted file mode 100644 index c00e8ba2..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/quick_view/2x/info_outline.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/quick_view/info_outline.png b/ui/file_manager/file_manager/foreground/images/files/ui/quick_view/info_outline.png deleted file mode 100644 index 6b8b9a005..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/quick_view/info_outline.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/refresh_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/refresh_white.png deleted file mode 100644 index 2c55e43b..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/refresh_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/search_clear.png b/ui/file_manager/file_manager/foreground/images/files/ui/search_clear.png deleted file mode 100644 index 3c9a00e..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/search_clear.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/search_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/search_white.png deleted file mode 100644 index fa0688a..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/search_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/share.png b/ui/file_manager/file_manager/foreground/images/files/ui/share.png deleted file mode 100644 index fe80bebf..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/share.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/share.svg b/ui/file_manager/file_manager/foreground/images/files/ui/share.svg deleted file mode 100644 index 748a8b6..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/share.svg +++ /dev/null
@@ -1,4 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 24 24" fill="#616161"> - <path d="M0 0h24v24H0z" fill="none"/> - <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/share_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/share_white.png deleted file mode 100644 index ce6bf55..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/share_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/sort_asc.png b/ui/file_manager/file_manager/foreground/images/files/ui/sort_asc.png deleted file mode 100644 index b120ed8..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/sort_asc.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/sort_asc.svg b/ui/file_manager/file_manager/foreground/images/files/ui/sort_asc.svg deleted file mode 100644 index 8ff3c00..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/sort_asc.svg +++ /dev/null
@@ -1,3 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"> - <path d="M14 12l-4-4-4 4h8"/> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/sort_desc.png b/ui/file_manager/file_manager/foreground/images/files/ui/sort_desc.png deleted file mode 100644 index 1da6d017f..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/sort_desc.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/vertical_separator.png b/ui/file_manager/file_manager/foreground/images/files/ui/vertical_separator.png deleted file mode 100644 index 512f37f..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/vertical_separator.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/view_list_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/view_list_white.png deleted file mode 100644 index 722593f3..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/view_list_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/view_thumbnail_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/view_thumbnail_white.png deleted file mode 100644 index 7d11864..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/view_thumbnail_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/visibility_white.svg b/ui/file_manager/file_manager/foreground/images/files/ui/visibility_white.svg deleted file mode 100644 index 3e883af..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/visibility_white.svg +++ /dev/null
@@ -1,4 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 48 48" fill="#FFFFFF"> - <path d="M0 0h48v48H0z" fill="none"/> - <path d="M24 9C14 9 5.46 15.22 2 24c3.46 8.78 12 15 22 15 10.01 0 18.54-6.22 22-15-3.46-8.78-11.99-15-22-15zm0 25c-5.52 0-10-4.48-10-10s4.48-10 10-10 10 4.48 10 10-4.48 10-10 10zm0-16c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6z"/> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/files/ui/warning_white.png b/ui/file_manager/file_manager/foreground/images/files/ui/warning_white.png deleted file mode 100644 index 244e77a7..0000000 --- a/ui/file_manager/file_manager/foreground/images/files/ui/warning_white.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_archive.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_archive.png deleted file mode 100644 index 2da5bd0c..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_archive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_audio.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_audio.png deleted file mode 100644 index 9312c8e..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_audio.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_excel.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_excel.png deleted file mode 100644 index 2983c428..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_excel.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder.png deleted file mode 100644 index 6528b77b..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_active.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_active.png deleted file mode 100644 index 38a5b08..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_shared.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_shared.png deleted file mode 100644 index 54b4187d..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_shared.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_shared_active.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_shared_active.png deleted file mode 100644 index 603eed4..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_folder_shared_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gdoc.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gdoc.png deleted file mode 100644 index ada3bf3..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gdoc.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gdraw.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gdraw.png deleted file mode 100644 index 8ec1198..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gdraw.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_generic.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_generic.png deleted file mode 100644 index 47451b6..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_generic.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gform.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gform.png deleted file mode 100644 index bac390a..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gform.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gmap.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gmap.png deleted file mode 100644 index b3f3bc1..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gmap.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gsheet.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gsheet.png deleted file mode 100644 index 49d2acc..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gsheet.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gsite.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gsite.png deleted file mode 100644 index 43440f7..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gsite.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gslides.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gslides.png deleted file mode 100644 index 28001511f..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gslides.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gtable.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gtable.png deleted file mode 100644 index a1cd251..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_gtable.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_image.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_image.png deleted file mode 100644 index 3fb4845..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_image.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_pdf.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_pdf.png deleted file mode 100644 index 568a387b..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_pdf.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_ppt.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_ppt.png deleted file mode 100644 index ed3e901..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_ppt.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_script.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_script.png deleted file mode 100644 index cb4ff5a..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_script.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_sites.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_sites.png deleted file mode 100644 index 01ad2c7..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_sites.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_team_drive_active.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_team_drive_active.png deleted file mode 100644 index c744788f..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_team_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_tini.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_tini.png deleted file mode 100644 index 17fda9b..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_tini.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_video.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_video.png deleted file mode 100644 index f0638fd..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_video.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_word.png b/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_word.png deleted file mode 100644 index 581c664..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/2x/filetype_word.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_archive.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_archive.png deleted file mode 100644 index 69740e4..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_archive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_audio.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_audio.png deleted file mode 100644 index 7d72bc3..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_audio.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_excel.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_excel.png deleted file mode 100644 index 668b1bd2..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_excel.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder.png deleted file mode 100644 index ea141ee2..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_active.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_active.png deleted file mode 100644 index 7ddc7d9..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_shared.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_shared.png deleted file mode 100644 index 4c253a2..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_shared.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_shared_active.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_shared_active.png deleted file mode 100644 index a1a2b27..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_folder_shared_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gdoc.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gdoc.png deleted file mode 100644 index 9a1d1c99..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gdoc.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gdraw.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gdraw.png deleted file mode 100644 index e7d5b2a..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gdraw.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_generic.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_generic.png deleted file mode 100644 index 9453b87..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_generic.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gform.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gform.png deleted file mode 100644 index 25faebe..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gform.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gmap.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gmap.png deleted file mode 100644 index e3e10c5..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gmap.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gsheet.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gsheet.png deleted file mode 100644 index 7c35302..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gsheet.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gsite.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gsite.png deleted file mode 100644 index 8333cf2..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gsite.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gslides.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gslides.png deleted file mode 100644 index 7878a5f..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gslides.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gtable.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_gtable.png deleted file mode 100644 index cfbefa44f..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_gtable.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_image.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_image.png deleted file mode 100644 index 04ddbce2..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_image.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_pdf.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_pdf.png deleted file mode 100644 index 8de8f8f8..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_pdf.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_ppt.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_ppt.png deleted file mode 100644 index 596660e..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_ppt.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_script.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_script.png deleted file mode 100644 index 6b57b369e..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_script.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_sites.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_sites.png deleted file mode 100644 index 1f42004..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_sites.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_team_drive_active.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_team_drive_active.png deleted file mode 100644 index c7ad618..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_team_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_tini.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_tini.png deleted file mode 100644 index eb979a1b..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_tini.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_video.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_video.png deleted file mode 100644 index 0afea5e..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_video.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/filetype/filetype_word.png b/ui/file_manager/file_manager/foreground/images/filetype/filetype_word.png deleted file mode 100644 index 715fce4c..0000000 --- a/ui/file_manager/file_manager/foreground/images/filetype/filetype_word.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/android.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/android.png deleted file mode 100644 index ec72af6..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/android.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/android_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/android_active.png deleted file mode 100644 index 5547298..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/android_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/archive.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/archive.png deleted file mode 100644 index 2da5bd0c..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/archive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/archive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/archive_active.png deleted file mode 100644 index ecf1f5f8..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/archive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/audio.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/audio.png deleted file mode 100644 index 2b89c4e3..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/audio.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/audio_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/audio_active.png deleted file mode 100644 index 06dbbb0..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/audio_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/cd.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/cd.png deleted file mode 100644 index 2b9a368..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/cd.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/cd_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/cd_active.png deleted file mode 100644 index de89ab1..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/cd_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/computer.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/computer.png deleted file mode 100644 index d62cdda..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/computer.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/computer_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/computer_active.png deleted file mode 100644 index 789d9fc..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/computer_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/devices.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/devices.png deleted file mode 100644 index 33b93ea..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/devices.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/devices_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/devices_active.png deleted file mode 100644 index a810be7..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/devices_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/downloads.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/downloads.png deleted file mode 100644 index 5b8cfe57..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/downloads.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/downloads_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/downloads_active.png deleted file mode 100644 index b8a057e..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/downloads_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/drive.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/drive.png deleted file mode 100644 index bb086fc..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/drive_active.png deleted file mode 100644 index d9a6764..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/hard_drive.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/hard_drive.png deleted file mode 100644 index 482ec04..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/hard_drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/hard_drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/hard_drive_active.png deleted file mode 100644 index 8fc711af..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/hard_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/images.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/images.png deleted file mode 100644 index 78b23a0..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/images.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/images_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/images_active.png deleted file mode 100644 index 0910951b..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/images_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/linux_files.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/linux_files.png deleted file mode 100644 index d27d9516..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/linux_files.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/linux_files_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/linux_files_active.png deleted file mode 100644 index 05eaca65..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/linux_files_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/my_files.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/my_files.png deleted file mode 100644 index d37949d..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/my_files.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/my_files_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/my_files_active.png deleted file mode 100644 index 0c4db82..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/my_files_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/offline.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/offline.png deleted file mode 100644 index 3858ce2..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/offline.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/offline_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/offline_active.png deleted file mode 100644 index 3ab55acd..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/offline_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/phone.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/phone.png deleted file mode 100644 index 5626bb2a3..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/phone.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/phone_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/phone_active.png deleted file mode 100644 index 170f78b..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/phone_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/recent.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/recent.png deleted file mode 100644 index 46837bf..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/recent.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/recent_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/recent_active.png deleted file mode 100644 index 4f82b40c..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/recent_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/sd.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/sd.png deleted file mode 100644 index b8b17eb..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/sd.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/sd_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/sd_active.png deleted file mode 100644 index 7c758ac..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/sd_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/service_drive.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/service_drive.png deleted file mode 100644 index 4b55d2c..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/service_drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/service_drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/service_drive_active.png deleted file mode 100644 index 003dd93c..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/service_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/shared.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/shared.png deleted file mode 100644 index ad2986a9..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/shared.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/shared_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/shared_active.png deleted file mode 100644 index 4f89d83..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/shared_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/shortcut.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/shortcut.png deleted file mode 100644 index 7624712..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/shortcut.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/shortcut_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/shortcut_active.png deleted file mode 100644 index 5f3b010..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/shortcut_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/smb.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/smb.png deleted file mode 100644 index 5701e0a..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/smb.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/team_drive.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/team_drive.png deleted file mode 100644 index 1fa54ff1..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/team_drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/team_drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/team_drive_active.png deleted file mode 100644 index c744788f..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/team_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/usb.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/usb.png deleted file mode 100644 index 985ecac..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/usb.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/usb_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/usb_active.png deleted file mode 100644 index e1b9ccf..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/usb_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/videos.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/videos.png deleted file mode 100644 index c5fe4e5..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/videos.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/2x/videos_active.png b/ui/file_manager/file_manager/foreground/images/volumes/2x/videos_active.png deleted file mode 100644 index 272498c..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/2x/videos_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/android.png b/ui/file_manager/file_manager/foreground/images/volumes/android.png deleted file mode 100644 index 854d18bd..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/android.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/android_active.png b/ui/file_manager/file_manager/foreground/images/volumes/android_active.png deleted file mode 100644 index a9d40c5..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/android_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/archive.png b/ui/file_manager/file_manager/foreground/images/volumes/archive.png deleted file mode 100644 index eaa55296..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/archive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/archive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/archive_active.png deleted file mode 100644 index aecf342..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/archive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/audio.png b/ui/file_manager/file_manager/foreground/images/volumes/audio.png deleted file mode 100644 index 81a1423..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/audio.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/audio_active.png b/ui/file_manager/file_manager/foreground/images/volumes/audio_active.png deleted file mode 100644 index 35bd6fa..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/audio_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/cd.png b/ui/file_manager/file_manager/foreground/images/volumes/cd.png deleted file mode 100644 index 8677a90..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/cd.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/cd_active.png b/ui/file_manager/file_manager/foreground/images/volumes/cd_active.png deleted file mode 100644 index 27244eb..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/cd_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/computer.png b/ui/file_manager/file_manager/foreground/images/volumes/computer.png deleted file mode 100644 index c0c7039f..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/computer.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/computer_active.png b/ui/file_manager/file_manager/foreground/images/volumes/computer_active.png deleted file mode 100644 index 22c9a213..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/computer_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/devices.png b/ui/file_manager/file_manager/foreground/images/volumes/devices.png deleted file mode 100644 index cd34d57..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/devices.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/devices_active.png b/ui/file_manager/file_manager/foreground/images/volumes/devices_active.png deleted file mode 100644 index 1048210a..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/devices_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/downloads.png b/ui/file_manager/file_manager/foreground/images/volumes/downloads.png deleted file mode 100644 index 3043558..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/downloads.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/downloads_active.png b/ui/file_manager/file_manager/foreground/images/volumes/downloads_active.png deleted file mode 100644 index 48660af0..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/downloads_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/drive.png b/ui/file_manager/file_manager/foreground/images/volumes/drive.png deleted file mode 100644 index 39f375e..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/drive_active.png deleted file mode 100644 index 7ef629f..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/hard_drive.png b/ui/file_manager/file_manager/foreground/images/volumes/hard_drive.png deleted file mode 100644 index 24fab8f..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/hard_drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/hard_drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/hard_drive_active.png deleted file mode 100644 index ebb68221..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/hard_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/images.png b/ui/file_manager/file_manager/foreground/images/volumes/images.png deleted file mode 100644 index 2d2d9fa..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/images.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/images_active.png b/ui/file_manager/file_manager/foreground/images/volumes/images_active.png deleted file mode 100644 index c60b9107..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/images_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/linux_files.png b/ui/file_manager/file_manager/foreground/images/volumes/linux_files.png deleted file mode 100644 index b105f05a..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/linux_files.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/linux_files_active.png b/ui/file_manager/file_manager/foreground/images/volumes/linux_files_active.png deleted file mode 100644 index e29a786..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/linux_files_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/my_files.png b/ui/file_manager/file_manager/foreground/images/volumes/my_files.png deleted file mode 100644 index 6ce8b72..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/my_files.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/my_files_active.png b/ui/file_manager/file_manager/foreground/images/volumes/my_files_active.png deleted file mode 100644 index b8a0506..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/my_files_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/offline.png b/ui/file_manager/file_manager/foreground/images/volumes/offline.png deleted file mode 100644 index a3a59ee..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/offline.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/offline_active.png b/ui/file_manager/file_manager/foreground/images/volumes/offline_active.png deleted file mode 100644 index 5ac8595..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/offline_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/phone.png b/ui/file_manager/file_manager/foreground/images/volumes/phone.png deleted file mode 100644 index 2febbcf..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/phone.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/phone_active.png b/ui/file_manager/file_manager/foreground/images/volumes/phone_active.png deleted file mode 100644 index 59371214..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/phone_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/plugin_vm.svg b/ui/file_manager/file_manager/foreground/images/volumes/plugin_vm.svg deleted file mode 100644 index f69dd86..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/plugin_vm.svg +++ /dev/null
@@ -1,3 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 20 20"> - <path fill="rgb(90,90,90)" d="M11 11H8v2.2l3 .4V11zm0-3.6l-3 .4V10h3V7.4zm1 6.4l2 .3V17H.8c-.5 0-.8-.3-.8-.8V15h3V5.1C3 4.5 3.5 4 4.1 4H14v2.9l-2 .3V10h2v1h-2v2.8zm4 5.2c-.6 0-1-.4-1-1V2c0-.6.4-1 1-1s1 .4 1 1v16c0 .6-.4 1-1 1zm3 0c-.6 0-1-.4-1-1V2c0-.6.4-1 1-1s1 .4 1 1v16c0 .6-.4 1-1 1z"/> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/plugin_vm_active.svg b/ui/file_manager/file_manager/foreground/images/volumes/plugin_vm_active.svg deleted file mode 100644 index 8d4627b7..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/plugin_vm_active.svg +++ /dev/null
@@ -1,3 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 20 20"> - <path fill="rgb(51,103,214)" d="M11 11H8v2.2l3 .4V11zm0-3.6l-3 .4V10h3V7.4zm1 6.4l2 .3V17H.8c-.5 0-.8-.3-.8-.8V15h3V5.1C3 4.5 3.5 4 4.1 4H14v2.9l-2 .3V10h2v1h-2v2.8zm4 5.2c-.6 0-1-.4-1-1V2c0-.6.4-1 1-1s1 .4 1 1v16c0 .6-.4 1-1 1zm3 0c-.6 0-1-.4-1-1V2c0-.6.4-1 1-1s1 .4 1 1v16c0 .6-.4 1-1 1z"/> -</svg>
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/recent.png b/ui/file_manager/file_manager/foreground/images/volumes/recent.png deleted file mode 100644 index 206867d..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/recent.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/recent_active.png b/ui/file_manager/file_manager/foreground/images/volumes/recent_active.png deleted file mode 100644 index 480855d..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/recent_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/sd.png b/ui/file_manager/file_manager/foreground/images/volumes/sd.png deleted file mode 100644 index 2482c91..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/sd.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/sd_active.png b/ui/file_manager/file_manager/foreground/images/volumes/sd_active.png deleted file mode 100644 index 6110ab5..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/sd_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/service_drive.png b/ui/file_manager/file_manager/foreground/images/volumes/service_drive.png deleted file mode 100644 index 0d0eb58..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/service_drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/service_drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/service_drive_active.png deleted file mode 100644 index 498c77a6..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/service_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/shared.png b/ui/file_manager/file_manager/foreground/images/volumes/shared.png deleted file mode 100644 index c55eb90..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/shared.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/shared_active.png b/ui/file_manager/file_manager/foreground/images/volumes/shared_active.png deleted file mode 100644 index 20b0d52a..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/shared_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/shortcut.png b/ui/file_manager/file_manager/foreground/images/volumes/shortcut.png deleted file mode 100644 index 471c49f..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/shortcut.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/shortcut_active.png b/ui/file_manager/file_manager/foreground/images/volumes/shortcut_active.png deleted file mode 100644 index 18a83cc..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/shortcut_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/smb.png b/ui/file_manager/file_manager/foreground/images/volumes/smb.png deleted file mode 100644 index 46f7131..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/smb.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/team_drive.png b/ui/file_manager/file_manager/foreground/images/volumes/team_drive.png deleted file mode 100644 index a192032..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/team_drive.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/team_drive_active.png b/ui/file_manager/file_manager/foreground/images/volumes/team_drive_active.png deleted file mode 100644 index c7ad618..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/team_drive_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/usb.png b/ui/file_manager/file_manager/foreground/images/volumes/usb.png deleted file mode 100644 index 97e42c5..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/usb.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/usb_active.png b/ui/file_manager/file_manager/foreground/images/volumes/usb_active.png deleted file mode 100644 index c867ae8..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/usb_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/videos.png b/ui/file_manager/file_manager/foreground/images/volumes/videos.png deleted file mode 100644 index a796951..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/videos.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/images/volumes/videos_active.png b/ui/file_manager/file_manager/foreground/images/volumes/videos_active.png deleted file mode 100644 index cdf5e5df..0000000 --- a/ui/file_manager/file_manager/foreground/images/volumes/videos_active.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/file_manager/foreground/js/ui/banners.js b/ui/file_manager/file_manager/foreground/js/ui/banners.js index 7034d8e1..bcf8025 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/banners.js +++ b/ui/file_manager/file_manager/foreground/js/ui/banners.js
@@ -266,11 +266,6 @@ const wrapper = util.createChild(container, 'drive-welcome-wrapper'); util.createChild(wrapper, 'drive-welcome-icon'); - if (type === 'header' && !util.isFilesNg()) { - util.createChild(wrapper, 'banner-cloud-bg'); - util.createChild(wrapper, 'banner-people'); - } - let close, links; if (util.isFilesNg()) { const message = util.createChild(wrapper, 'drive-welcome-message');
diff --git a/ui/file_manager/file_manager_resources.grd b/ui/file_manager/file_manager_resources.grd index 19f6730..c09193d3 100644 --- a/ui/file_manager/file_manager_resources.grd +++ b/ui/file_manager/file_manager_resources.grd
@@ -103,13 +103,6 @@ <!-- Resources used for non-flattened HTML files. --> <include name="IDR_FILE_MANAGER_DRIVE_WELCOME_STYLE" file="file_manager/foreground/css/drive_welcome.css" type="BINDATA" /> - <include name="IDR_FILE_MANAGER_IMG_UI_CLOUDS" file="file_manager/foreground/images/files/ui/clouds.png" type="BINDATA" /> - <!-- TODO (oto@): remove next 2 resources in the files-ng cleanup process --> - <include name="IDR_FILE_MANAGER_IMG_UI_DRIVE_WELCOME_LOGO" file="file_manager/foreground/images/files/ui/drive_logo.png" type="BINDATA" /> - <include name="IDR_FILE_MANAGER_IMG_UI_2X_DRIVE_WELCOME_LOGO" file="file_manager/foreground/images/files/ui/2x/drive_logo.png" type="BINDATA" /> - <include name="IDR_FILE_MANAGER_IMG_UI_DRIVE_LOGO" file="file_manager/foreground/images/files/ui/drive_logo.svg" type="BINDATA" /> - <include name="IDR_FILE_MANAGER_IMG_UI_DRIVE_WELCOME_PEOPLE" file="file_manager/foreground/images/files/ui/drive_banner_people.png" type="BINDATA" /> - <include name="IDR_FILE_MANAGER_IMG_UI_2X_DRIVE_WELCOME_PEOPLE" file="file_manager/foreground/images/files/ui/2x/drive_banner_people.png" type="BINDATA" /> <!-- The VideoPlayer app pages and scripts. --> <include name="IDR_VIDEO_PLAYER_MANIFEST" file="video_player/manifest.json" type="BINDATA" />
diff --git a/ui/login/display_manager.js b/ui/login/display_manager.js index 92fb1e3a..e89db24 100644 --- a/ui/login/display_manager.js +++ b/ui/login/display_manager.js
@@ -45,14 +45,11 @@ * Must be kept in sync with webui_accelerator_mapping.cc. */ /** @const */ var ACCELERATOR_CANCEL = 'cancel'; -/** @const */ var ACCELERATOR_ENROLLMENT = 'enrollment'; -/** @const */ var ACCELERATOR_KIOSK_ENABLE = 'kiosk_enable'; /** @const */ var ACCELERATOR_VERSION = 'version'; /** @const */ var ACCELERATOR_RESET = 'reset'; /** @const */ var ACCELERATOR_APP_LAUNCH_BAILOUT = 'app_launch_bailout'; /** @const */ var ACCELERATOR_APP_LAUNCH_NETWORK_CONFIG = 'app_launch_network_config'; -/** @const */ var ACCELERATOR_SEND_FEEDBACK = "send_feedback"; /* Possible UI states of the error screen. */ /** @const */ var ERROR_SCREEN_UI_STATE = { @@ -380,21 +377,6 @@ if (this.currentScreen && this.currentScreen.cancel) { this.currentScreen.cancel(); } - } else if (name == ACCELERATOR_ENROLLMENT) { - if (attributes.startEnrollmentAllowed || - currentStepId == SCREEN_GAIA_SIGNIN || - currentStepId == SCREEN_PACKAGED_LICENSE || - currentStepId == SCREEN_ACCOUNT_PICKER) { - chrome.send('toggleEnrollmentScreen'); - } else { - console.warn('No action for current step ID: ' + currentStepId); - } - } else if (name == ACCELERATOR_KIOSK_ENABLE) { - if (attributes.toggleKioskAllowed || - currentStepId == SCREEN_GAIA_SIGNIN || - currentStepId == SCREEN_ACCOUNT_PICKER) { - chrome.send('toggleKioskEnableScreen'); - } } else if (name == ACCELERATOR_VERSION) { if (this.allowToggleVersion_) $('version-labels').hidden = !$('version-labels').hidden; @@ -411,8 +393,6 @@ } else if (name == ACCELERATOR_APP_LAUNCH_NETWORK_CONFIG) { if (currentStepId == SCREEN_APP_LAUNCH_SPLASH) chrome.send('networkConfigRequest'); - } else if (name == ACCELERATOR_SEND_FEEDBACK) { - chrome.send('sendFeedback'); } },
diff --git a/ui/login/display_manager_types.js b/ui/login/display_manager_types.js index 24dd83f..098e8b7 100644 --- a/ui/login/display_manager_types.js +++ b/ui/login/display_manager_types.js
@@ -10,8 +10,6 @@ /** * @typedef {{ * resetAllowed: (boolean|undefined), - * startEnrollmentAllowed: (boolean|undefined), - * toggleKioskAllowed: (boolean|undefined), * }} */ var DisplayManagerScreenAttributes = {}; @@ -23,18 +21,6 @@ DisplayManagerScreenAttributes.resetAllowed; /** - * True if enrollment accelerator should start enrollment. - * @type {boolean|undefined} - */ -DisplayManagerScreenAttributes.startEnrollmentAllowed; - -/** - * True if "enable kiosk" accelerator is allowed. - * @type {boolean|undefined} - */ -DisplayManagerScreenAttributes.toggleKioskAllowed; - -/** * Possible types of UI. * @enum {string} */
diff --git a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html index 3b6fa66..2e14f41d 100644 --- a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html +++ b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.html
@@ -148,14 +148,12 @@ margin-top: 4px; } </style> - <!-- TODO(crbug/1139958): Remove "not chromeos" block when chromeVox issue - is fixed--> + <!-- TODO(crbug/1139958): Remove "not chromeos" block when chromeVox issue is fixed--> + <!--Update both "not chromeos" and "chromeos" blocks if either changes--> +<if expr="not chromeos"> <dialog id="dialog" on-close="onNativeDialogClose_" on-cancel="onNativeDialogCancel_" part="dialog" -<if expr="not chromeos"> - aria-labelledby="title" -</if> - > + aria-labelledby="title"> <!-- This wrapper is necessary, such that the "pulse" animation is not erroneously played when the user clicks on the outer-most scrollbar. --> <div id="content-wrapper" part="wrapper"> @@ -177,6 +175,32 @@ <slot name="footer"></slot> </div> </dialog> +</if> +<if expr="chromeos"> + <dialog id="dialog" on-close="onNativeDialogClose_" + on-cancel="onNativeDialogCancel_" part="dialog"> + <!-- This wrapper is necessary, such that the "pulse" animation is not + erroneously played when the user clicks on the outer-most scrollbar. --> + <div id="content-wrapper" part="wrapper"> + <div class="top-container"> + <div id="title" class="title-container" tabindex="-1"> + <slot name="title"></slot> + </div> + <cr-icon-button id="close" class="icon-clear" + hidden$="[[!showCloseButton]]" aria-label$="[[closeText]]" + on-click="cancel" on-keypress="onCloseKeypress_"> + </cr-icon-button> + </div> + <slot name="header"></slot> + <div class="body-container" id="container" show-bottom-shadow + part="body-container"> + <slot name="body"></slot> + </div> + <slot name="button-container"></slot> + <slot name="footer"></slot> + </div> + </dialog> +</if> </template> <script src="cr_dialog.js"></script> </dom-module>
diff --git a/ui/webui/resources/cr_elements/icons.html b/ui/webui/resources/cr_elements/icons.html index a19c7bd..0d46919 100644 --- a/ui/webui/resources/cr_elements/icons.html +++ b/ui/webui/resources/cr_elements/icons.html
@@ -87,6 +87,10 @@ d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"> </path> </g> + <g id="work"> + <path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z"> + </path> + </g> </if> <g id="cancel"> <path
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/interfaces/LoadError.java b/weblayer/browser/java/org/chromium/weblayer_private/interfaces/LoadError.java index 6e99bd9..9a37dfa 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/interfaces/LoadError.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/interfaces/LoadError.java
@@ -20,6 +20,6 @@ int SSL_ERROR = 3; int CONNECTIVITY_ERROR = 4; int OTHER_ERROR = 5; - // Sent since 89. + // Sent since 88. int SAFE_BROWSING_ERROR = 6; }
diff --git a/weblayer/public/java/org/chromium/weblayer/LoadError.java b/weblayer/public/java/org/chromium/weblayer/LoadError.java index 835d6e30..e411f69 100644 --- a/weblayer/public/java/org/chromium/weblayer/LoadError.java +++ b/weblayer/public/java/org/chromium/weblayer/LoadError.java
@@ -48,7 +48,7 @@ /** * Safe browsing error. * - * @since 89 + * @since 88 */ int SAFE_BROWSING_ERROR = org.chromium.weblayer_private.interfaces.LoadError.SAFE_BROWSING_ERROR;