diff --git a/BUILD.gn b/BUILD.gn index 5381b33..08609dd 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -260,12 +260,11 @@ } if (is_fuchsia && !is_chromecast) { + # Add targets that only exist on Fuchsia. deps += [ ":d8_fuchsia", "//build/fuchsia/cipd", - "//fuchsia/engine:web_engine", - "//fuchsia/runners:cast_runner", - "//fuchsia/runners:web_runner", + "//fuchsia_web:gn_all", "//tools/fuchsia/size_tests:fuchsia_sizes", # Ensure this target, used by cipd, is built in all configurations.
diff --git a/DEPS b/DEPS index 40943c85..f368057 100644 --- a/DEPS +++ b/DEPS
@@ -279,15 +279,15 @@ # 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': '0803b5bb667ac1f24a9f36dbfbc8d4b7fd7b9154', + 'v8_revision': '9941bdcba032566bdf440513cba4a1d5066bdbeb', # 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': 'cd42f669abe00c43242299737859ba4a215b4bc7', + 'angle_revision': 'ee023e6af4ea32e22c9f19cfa0d1041dc9fbb5f1', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '5ca5b0ae5a7d0a2f05538d405426a5331ffd680b', + 'swiftshader_revision': 'e885694aca94c508e94ac7f67289f85298536966', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -354,7 +354,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': '251df4314f2c5fa05759fd4a9d79e8ff7c204f9f', + 'devtools_frontend_revision': '86bffd656c2f064aa110a85235804e2c521f3b35', # 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. @@ -390,7 +390,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': '70724a5180e9c6105dc4d6585e81b09516498c9a', + 'dawn_revision': '15691360729d9f97abfa4b4f1422540ce5567d55', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -434,11 +434,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'libcxxabi_revision': 'e44a32df6a74960c217ce9e6d17f6d544b6932a5', + 'libcxxabi_revision': '8b1770bc550a6e9d62a18a4612e94bf7cccf5151', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'libunwind_revision': '67bace775e66a513b5b1c9dfd0042e3766ca02d0', + 'libunwind_revision': '5e737be79cd244af1c36b4cccc0cba4c6a4306a3', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -747,7 +747,7 @@ Var('chromium_git') + '/external/github.com/toji/webvr.info.git' + '@' + 'c58ae99b9ff9e2aa4c524633519570bf33536248', 'src/docs/website': { - 'url': Var('chromium_git') + '/website.git' + '@' + '1da38cece144a8f2bcbb6f0f1d17486be448f887', + 'url': Var('chromium_git') + '/website.git' + '@' + 'b9ea7d6b756e7e7d3a8bb7accece4a7f150687c6', }, 'src/ios/third_party/earl_grey2/src': { @@ -1136,7 +1136,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'ca53c9067007992cc9be8833b655a07cbb609fab', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'b6083facb676c7580b27e2bb83a0e96c0b65dec9', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1533,7 +1533,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'a2ba21403c0a958883480c4191c8b5d48a350806', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '26f1ca3b42a13a5dc179334f972ad8847aded023', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1669,7 +1669,7 @@ 'condition': 'checkout_android', }, - 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@090d24c0ff24f139f95eb9ce0a331b6bee769903', + 'src/third_party/vulkan-deps': '{chromium_git}/vulkan-deps@74d505bc504e88cb5f009998ee47b5b5696342b7', 'src/third_party/vulkan_memory_allocator': Var('chromium_git') + '/external/github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git' + '@' + 'ebe84bec02c041d28f902da0214bf442743fc907', @@ -1708,7 +1708,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '70091fdb8d3d037b8f2919eb63e5a2bf6444deb7', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '94ad387f776d974a5ae0d1c926366e23673eaa9a', + Var('webrtc_git') + '/src.git' + '@' + '2d133637d17d3128a71fa2f1a2c0f0cf871c207d', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1781,7 +1781,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@df1ef77b64694078366c2df988627574b87b7a04', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@183012d61fa28504af86c09b89eb9117202f1c46', 'condition': 'checkout_src_internal', }, @@ -1811,7 +1811,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/help_app/app', - 'version': 'LmE2isk-twIjkeDlYtDz-8AI2GOs3DADLLqVWDWL5KIC', + 'version': '2cH_eZJ8Yeb55pBlbGm25zfTRUsKtrnjCvVH6vXhO50C', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/ash/assistant/ui/DEPS b/ash/assistant/ui/DEPS index 0af496a..cdc4331 100644 --- a/ash/assistant/ui/DEPS +++ b/ash/assistant/ui/DEPS
@@ -20,9 +20,20 @@ "+chromeos/services/libassistant/public/cpp", "+mojo/public/cpp", "+net/base", - "+third_party/abseil-cpp/absl", "+third_party/skia/include/core", "+ui", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ] specific_include_rules = {
diff --git a/ash/capture_mode/capture_mode_camera_controller.cc b/ash/capture_mode/capture_mode_camera_controller.cc index 73465f9..59da319b 100644 --- a/ash/capture_mode/capture_mode_camera_controller.cc +++ b/ash/capture_mode/capture_mode_camera_controller.cc
@@ -754,6 +754,14 @@ std::move(on_camera_list_received_for_test_)); } + const bool should_report_cameras_number = + !did_report_number_of_cameras_before_ || + (devices.size() != available_cameras_.size()); + if (should_report_cameras_number) { + did_report_number_of_cameras_before_ = true; + RecordNumberOfConnectedCameras(devices.size()); + } + if (!DidDevicesChange(devices, available_cameras_)) return;
diff --git a/ash/capture_mode/capture_mode_camera_controller.h b/ash/capture_mode/capture_mode_camera_controller.h index a6eab77..52d5d4a 100644 --- a/ash/capture_mode/capture_mode_camera_controller.h +++ b/ash/capture_mode/capture_mode_camera_controller.h
@@ -401,6 +401,10 @@ // while recording is in progress. absl::optional<int> in_recording_camera_disconnections_; + // Will be set to true the first time the number of connected cameras is + // reported. + bool did_report_number_of_cameras_before_ = false; + base::WeakPtrFactory<CaptureModeCameraController> weak_ptr_factory_{this}; };
diff --git a/ash/capture_mode/capture_mode_camera_unittests.cc b/ash/capture_mode/capture_mode_camera_unittests.cc index 2c526f50..d64ce19 100644 --- a/ash/capture_mode/capture_mode_camera_unittests.cc +++ b/ash/capture_mode/capture_mode_camera_unittests.cc
@@ -2436,6 +2436,50 @@ } } +// Tests that the number of connected cameras to the device is recorded whenever +// the number changes. +TEST_F(CaptureModeCameraTest, RecordNumberOfConnectedCamerasHistogramTest) { + constexpr char kHistogramNameBase[] = + "Ash.CaptureModeController.NumberOfConnectedCameras"; + + base::HistogramTester histogram_tester; + // Make sure the device change alert triggered by the SystemMonitor is handled + // before we connect a camera device. + { + base::RunLoop loop; + GetCameraController()->SetOnCameraListReceivedForTesting( + loop.QuitClosure()); + base::SystemMonitor::Get()->ProcessDevicesChanged( + base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE); + loop.Run(); + } + + // Verify that before we connect any camera device, there's 0 cameras and it + // has been recorded. + histogram_tester.ExpectBucketCount(kHistogramNameBase, 0, 1); + + // Connect one camera, verify that the number of one camera device has been + // recorded once. + AddFakeCamera("/dev/video", "fake cam ", "model 1"); + histogram_tester.ExpectBucketCount(kHistogramNameBase, 1, 1); + + // Connect the second camera, verify that the number of two camera devices has + // been recorded once. + AddFakeCamera("/dev/video1", "fake cam 2", "model 2"); + histogram_tester.ExpectBucketCount(kHistogramNameBase, 2, 1); + + // Disconnect the second camera, now the number of connected cameres drops + // back to one, verify that the number of one camera device has been recorded + // twice. + RemoveFakeCamera("/dev/video1"); + histogram_tester.ExpectBucketCount(kHistogramNameBase, 1, 2); + + // Connect the third camera, now the number of connected cameras is two again, + // verify that the number of two camera devices has been recorded twice. + AddFakeCamera("/dev/video2", "fake cam 3", "model 3"); + histogram_tester.ExpectBucketCount(kHistogramNameBase, 2, 2); +} + // Tests that the duration for disconnected camera to become available again is // recorded correctly both in clamshell and tablet mode. TEST_F(CaptureModeCameraTest, RecordCameraReconnectDurationHistogramTest) {
diff --git a/ash/capture_mode/capture_mode_metrics.cc b/ash/capture_mode/capture_mode_metrics.cc index 2263568..6b40efd 100644 --- a/ash/capture_mode/capture_mode_metrics.cc +++ b/ash/capture_mode/capture_mode_metrics.cc
@@ -56,6 +56,8 @@ "Ash.CaptureModeController.RecordingCameraSizeOnStart"; constexpr char kRecordingCameraPositionOnStart[] = "Ash.CaptureModeController.RecordingCameraPositionOnStart"; +constexpr char kNumberOfConnectedCameras[] = + "Ash.CaptureModeController.NumberOfConnectedCameras"; } // namespace @@ -184,6 +186,10 @@ num_camera_disconnections); } +void RecordNumberOfConnectedCameras(int num_camera_connected) { + base::UmaHistogramCounts100(kNumberOfConnectedCameras, num_camera_connected); +} + void RecordCameraReconnectDuration(int length_in_seconds, int grace_period_in_seconds) { base::UmaHistogramCustomCounts(
diff --git a/ash/capture_mode/capture_mode_metrics.h b/ash/capture_mode/capture_mode_metrics.h index 99e7079..803723c8 100644 --- a/ash/capture_mode/capture_mode_metrics.h +++ b/ash/capture_mode/capture_mode_metrics.h
@@ -183,6 +183,9 @@ // Records the number of camera disconnections during recording. void RecordCameraDisconnectionsDuringRecordings(int num_camera_disconnections); +// Records the given `num_camera_connected`. +void RecordNumberOfConnectedCameras(int num_camera_connected); + // Records the duration of camera becoming available again after camera // disconnection. void RecordCameraReconnectDuration(int length_in_seconds,
diff --git a/ash/components/arc/arc_features.cc b/ash/components/arc/arc_features.cc index 180f0ec3..9664552 100644 --- a/ash/components/arc/arc_features.cc +++ b/ash/components/arc/arc_features.cc
@@ -231,6 +231,11 @@ const base::Feature kVmGmsCoreLowMemoryKillerProtection{ "ArcVmGmsCoreLowMemoryKillerProtection", base::FEATURE_DISABLED_BY_DEFAULT}; +// Controls experimental key to enable pre-ANR handling for BroadcastQueue in +// ARCVM. +const base::Feature kVmBroadcastPreNotifyANR{"ArcVmBroadcastPreAnrHandling", + base::FEATURE_DISABLED_BY_DEFAULT}; + // If set, enable responsive balloon sizing. Concierge will listen on a VSOCK // for connections from LMKD in Android. When LMKD is about to kill an App, it // will signal the balloon sizing code, which may deflate the balloon instead
diff --git a/ash/components/arc/arc_features.h b/ash/components/arc/arc_features.h index d576a75..07fb4a7 100644 --- a/ash/components/arc/arc_features.h +++ b/ash/components/arc/arc_features.h
@@ -53,6 +53,7 @@ extern const base::FeatureParam<int> kVmBalloonPolicyModerateKiB; extern const base::FeatureParam<int> kVmBalloonPolicyCriticalKiB; extern const base::FeatureParam<int> kVmBalloonPolicyReclaimKiB; +extern const base::Feature kVmBroadcastPreNotifyANR; extern const base::Feature kVmGmsCoreLowMemoryKillerProtection; extern const base::FeatureParam<bool> kVmBalloonPolicyResponsive; extern const base::FeatureParam<int> kVmBalloonPolicyResponsiveTimeoutMs;
diff --git a/ash/components/arc/session/arc_vm_client_adapter.cc b/ash/components/arc/session/arc_vm_client_adapter.cc index 0e20501..00c3413 100644 --- a/ash/components/arc/session/arc_vm_client_adapter.cc +++ b/ash/components/arc/session/arc_vm_client_adapter.cc
@@ -332,6 +332,9 @@ if (start_params.enable_tts_caching) result.push_back("androidboot.arc.tts.caching=1"); + if (base::FeatureList::IsEnabled(arc::kVmBroadcastPreNotifyANR)) + result.push_back("androidboot.arc.broadcast_anr_prenotify=1"); + return result; }
diff --git a/ash/components/arc/session/arc_vm_client_adapter_unittest.cc b/ash/components/arc/session/arc_vm_client_adapter_unittest.cc index f29efac2..a8d6a6e2 100644 --- a/ash/components/arc/session/arc_vm_client_adapter_unittest.cc +++ b/ash/components/arc/session/arc_vm_client_adapter_unittest.cc
@@ -1878,6 +1878,24 @@ req.params(), "androidboot.arc_enable_gmscore_lmk_protection=1")); } +TEST_F(ArcVmClientAdapterTest, BroadcastPreANRDefault) { + StartMiniArc(); + auto request = GetTestConciergeClient()->start_arc_vm_request(); + for (const auto& param : request.params()) + EXPECT_EQ(std::string::npos, param.find("arc.broadcast_anr_prenotify")); +} + +TEST_F(ArcVmClientAdapterTest, BroadcastPreANREnabled) { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatureState(arc::kVmBroadcastPreNotifyANR, true); + + StartMiniArc(); + auto request = GetTestConciergeClient()->start_arc_vm_request(); + EXPECT_TRUE( + base::Contains(GetTestConciergeClient()->start_arc_vm_request().params(), + "androidboot.arc.broadcast_anr_prenotify=1")); +} + TEST_F(ArcVmClientAdapterTest, TrimVmMemory_Success) { SetValidUserInfo(); vm_tools::concierge::ReclaimVmMemoryResponse response;
diff --git a/ash/components/attestation/DEPS b/ash/components/attestation/DEPS index cd9bcfe..a3fb233 100644 --- a/ash/components/attestation/DEPS +++ b/ash/components/attestation/DEPS
@@ -7,8 +7,19 @@ "+components/account_id", "+crypto", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ] specific_include_rules = {
diff --git a/ash/components/audio/DEPS b/ash/components/audio/DEPS index 8636921..bf6385b 100644 --- a/ash/components/audio/DEPS +++ b/ash/components/audio/DEPS
@@ -11,6 +11,17 @@ "+services/media_session/public", "+ui/events/devices", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api/dbus", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/ash/components/cryptohome/DEPS b/ash/components/cryptohome/DEPS index 410db217..ca6fa87 100644 --- a/ash/components/cryptohome/DEPS +++ b/ash/components/cryptohome/DEPS
@@ -7,8 +7,19 @@ "+components/account_id", "+components/device_event_log", "+components/user_manager", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ] specific_include_rules = {
diff --git a/ash/components/hid_detection/fake_bluetooth_hid_detector.cc b/ash/components/hid_detection/fake_bluetooth_hid_detector.cc index 64bf3b6..63b663fa 100644 --- a/ash/components/hid_detection/fake_bluetooth_hid_detector.cc +++ b/ash/components/hid_detection/fake_bluetooth_hid_detector.cc
@@ -13,6 +13,7 @@ void FakeBluetoothHidDetector::SetInputDevicesStatus( InputDevicesStatus input_devices_status) { input_devices_status_ = input_devices_status; + num_set_input_devices_status_calls_++; } const BluetoothHidDetector::BluetoothHidDetectionStatus @@ -35,11 +36,14 @@ std::move(pairing_state)}; } -void FakeBluetoothHidDetector::SetBluetoothHidDetectionStatus( - absl::optional<BluetoothHidDetector::BluetoothHidMetadata> pairing_device, - absl::optional<BluetoothHidPairingState> pairing_state) { +void FakeBluetoothHidDetector::SimulatePairingStarted( + BluetoothHidDetector::BluetoothHidMetadata pairing_device) { current_pairing_device_ = std::move(pairing_device); - current_pairing_state_ = std::move(pairing_state); + NotifyBluetoothHidDetectionStatusChanged(); +} + +void FakeBluetoothHidDetector::SimulatePairingFinished() { + current_pairing_device_.reset(); NotifyBluetoothHidDetectionStatusChanged(); }
diff --git a/ash/components/hid_detection/fake_bluetooth_hid_detector.h b/ash/components/hid_detection/fake_bluetooth_hid_detector.h index 2b7b45c..04b5ef6 100644 --- a/ash/components/hid_detection/fake_bluetooth_hid_detector.h +++ b/ash/components/hid_detection/fake_bluetooth_hid_detector.h
@@ -20,16 +20,18 @@ void SetInputDevicesStatus(InputDevicesStatus input_devices_status) override; const BluetoothHidDetectionStatus GetBluetoothHidDetectionStatus() override; - // Updates the HID detection status returned by - // GetBluetoothHidDetectionStatus() and notifies the client. - void SetBluetoothHidDetectionStatus( - absl::optional<BluetoothHidDetector::BluetoothHidMetadata> pairing_device, - absl::optional<BluetoothHidPairingState> pairing_state); + void SimulatePairingStarted( + BluetoothHidDetector::BluetoothHidMetadata pairing_device); + void SimulatePairingFinished(); const InputDevicesStatus& input_devices_status() { return input_devices_status_; } + size_t num_set_input_devices_status_calls() { + return num_set_input_devices_status_calls_; + } + bool is_bluetooth_hid_detection_active() { return is_bluetooth_hid_detection_active_; } @@ -41,6 +43,8 @@ void PerformStopBluetoothHidDetection() override; InputDevicesStatus input_devices_status_; + size_t num_set_input_devices_status_calls_ = 0; + absl::optional<BluetoothHidMetadata> current_pairing_device_; absl::optional<BluetoothHidPairingState> current_pairing_state_; bool is_bluetooth_hid_detection_active_ = false;
diff --git a/ash/components/hid_detection/hid_detection_manager.h b/ash/components/hid_detection/hid_detection_manager.h index 6d413c7f..837a5c9 100644 --- a/ash/components/hid_detection/hid_detection_manager.h +++ b/ash/components/hid_detection/hid_detection_manager.h
@@ -22,6 +22,12 @@ // A device is connected via USB. kConnectedViaUsb, + // A device is being paired with via Bluetooth. + kPairingViaBluetooth, + + // A device is connected via Bluetooth. + kPairedViaBluetooth, + // A device is connected, but is not known to be USB (Bluetooth vs USB vs // serial). kConnected
diff --git a/ash/components/hid_detection/hid_detection_manager_impl.cc b/ash/components/hid_detection/hid_detection_manager_impl.cc index 8106214..df16d0c 100644 --- a/ash/components/hid_detection/hid_detection_manager_impl.cc +++ b/ash/components/hid_detection/hid_detection_manager_impl.cc
@@ -10,6 +10,7 @@ namespace ash::hid_detection { namespace { +using BluetoothHidType = BluetoothHidDetector::BluetoothHidType; using InputState = HidDetectionManager::InputState; // Global InputDeviceManagerBinder instance that can be overridden in tests. @@ -59,9 +60,13 @@ HidDetectionManager::HidDetectionStatus HidDetectionManagerImpl::ComputeHidDetectionStatus() const { + BluetoothHidDetector::BluetoothHidDetectionStatus bluetooth_status = + bluetooth_hid_detector_->GetBluetoothHidDetectionStatus(); return HidDetectionManager::HidDetectionStatus{ - GetInputMetadata(connected_pointer_id_), - GetInputMetadata(connected_keyboard_id_), + GetInputMetadata(connected_pointer_id_, BluetoothHidType::kPointer, + bluetooth_status.current_pairing_device), + GetInputMetadata(connected_keyboard_id_, BluetoothHidType::kKeyboard, + bluetooth_status.current_pairing_device), connected_touchscreen_id_.has_value()}; } @@ -111,7 +116,7 @@ } void HidDetectionManagerImpl::OnBluetoothHidStatusChanged() { - // TODO(gordonseto): Implement this. + NotifyHidDetectionStatusChanged(); } void HidDetectionManagerImpl::BindToInputDeviceManagerIfNeeded() { @@ -204,30 +209,41 @@ } HidDetectionManager::InputMetadata HidDetectionManagerImpl::GetInputMetadata( - const absl::optional<std::string>& device_id) const { - if (!device_id.has_value()) { - return InputMetadata(); + const absl::optional<std::string>& connected_device_id, + BluetoothHidType input_type, + const absl::optional<BluetoothHidDetector::BluetoothHidMetadata>& + current_pairing_device) const { + if (connected_device_id.has_value()) { + const device::mojom::InputDeviceInfoPtr& device = + device_id_to_device_map_.find(connected_device_id.value())->second; + DCHECK(device) + << " |connected_device_id| not found in |device_id_to_device_map_|"; + InputState state; + switch (device->type) { + case device::mojom::InputDeviceType::TYPE_BLUETOOTH: + state = InputState::kPairedViaBluetooth; + break; + case device::mojom::InputDeviceType::TYPE_USB: + state = InputState::kConnectedViaUsb; + break; + case device::mojom::InputDeviceType::TYPE_SERIO: + [[fallthrough]]; + case device::mojom::InputDeviceType::TYPE_UNKNOWN: + state = InputState::kConnected; + break; + } + return InputMetadata{state, device->name}; } - const device::mojom::InputDeviceInfoPtr& device = - device_id_to_device_map_.find(device_id.value())->second; - DCHECK(device) << " |device_id| not found in |device_id_to_device_map_|"; - InputState state; - switch (device->type) { - case device::mojom::InputDeviceType::TYPE_BLUETOOTH: - // TODO(gordonseto): Handle Bluetooth type. - state = InputState::kConnected; - break; - case device::mojom::InputDeviceType::TYPE_USB: - state = InputState::kConnectedViaUsb; - break; - case device::mojom::InputDeviceType::TYPE_SERIO: - [[fallthrough]]; - case device::mojom::InputDeviceType::TYPE_UNKNOWN: - state = InputState::kConnected; - break; + if (current_pairing_device.has_value() && + (current_pairing_device.value().type == input_type || + current_pairing_device.value().type == + BluetoothHidType::kKeyboardPointerCombo)) { + return InputMetadata{InputState::kPairingViaBluetooth, + current_pairing_device.value().name}; } - return InputMetadata{state, device->name}; + + return InputMetadata(); } void HidDetectionManagerImpl::SetInputDevicesStatus() {
diff --git a/ash/components/hid_detection/hid_detection_manager_impl.h b/ash/components/hid_detection/hid_detection_manager_impl.h index d97bf7b..131a584 100644 --- a/ash/components/hid_detection/hid_detection_manager_impl.h +++ b/ash/components/hid_detection/hid_detection_manager_impl.h
@@ -76,11 +76,17 @@ bool AttemptSetDeviceAsConnectedHid( const device::mojom::InputDeviceInfo& device); - // Returns InputMetadata based on |device_id|. A null |device_id| means no HID - // for that input is connected. If |device_id| is not null, it must be a - // key for an entry in |device_id_to_device_map_|. + // Computes an InputMetadata based on if an input device is connected or if a + // Bluetooth device of the same type as |input_type| is pairing. A null + // |connected_device_id| means no HID for that input is connected. If + // |connected_device_id| is not null, it must be a key for an entry in + // |device_id_to_device_map_|. A null |current_pairing_device| means no + // Bluetooth device is pairing. InputMetadata GetInputMetadata( - const absl::optional<std::string>& device_id) const; + const absl::optional<std::string>& connected_device_id, + BluetoothHidDetector::BluetoothHidType input_type, + const absl::optional<BluetoothHidDetector::BluetoothHidMetadata>& + current_pairing_device) const; // Informs |bluetooth_hid_detector_| what devices are missing. void SetInputDevicesStatus();
diff --git a/ash/components/hid_detection/hid_detection_manager_impl_unittest.cc b/ash/components/hid_detection/hid_detection_manager_impl_unittest.cc index 51816f1..cffc90d 100644 --- a/ash/components/hid_detection/hid_detection_manager_impl_unittest.cc +++ b/ash/components/hid_detection/hid_detection_manager_impl_unittest.cc
@@ -16,11 +16,15 @@ namespace ash::hid_detection { namespace { +using BluetoothHidMetadata = BluetoothHidDetector::BluetoothHidMetadata; +using BluetoothHidType = BluetoothHidDetector::BluetoothHidType; using InputMetadata = HidDetectionManager::InputMetadata; using InputState = HidDetectionManager::InputState; using InputDeviceType = device::mojom::InputDeviceType; using InputDevicesStatus = BluetoothHidDetector::InputDevicesStatus; +const char kTestHidName[] = "testName"; + enum HidType { kMouse, kTouchpad, @@ -124,19 +128,21 @@ void AddDevice(HidType hid_type, InputDeviceType device_type, - std::string* id_out = nullptr) { - AddDevice(std::vector{hid_type}, device_type, id_out); + std::string* id_out = nullptr, + const char* name = NULL) { + AddDevice(std::vector{hid_type}, device_type, id_out, name); } void AddDevice(std::vector<HidType> hid_types, InputDeviceType device_type, - std::string* id_out = nullptr) { + std::string* id_out = nullptr, + const char* name = NULL) { auto device = device::mojom::InputDeviceInfo::New(); device->id = num_devices_created_++; if (id_out) *id_out = device->id; - device->name = device->id; + device->name = name == NULL ? device->id : name; device->subsystem = device::mojom::InputDeviceSubsystem::SUBSYSTEM_INPUT; device->type = device_type; @@ -168,6 +174,18 @@ base::RunLoop().RunUntilIdle(); } + void SimulatePairingStarted( + BluetoothHidDetector::BluetoothHidMetadata pairing_device) { + fake_bluetooth_hid_detector_->SimulatePairingStarted( + std::move(pairing_device)); + base::RunLoop().RunUntilIdle(); + } + + void SimulatePairingFinished() { + fake_bluetooth_hid_detector_->SimulatePairingFinished(); + base::RunLoop().RunUntilIdle(); + } + void AssertHidDetectionStatus(InputMetadata pointer_metadata, InputMetadata keyboard_metadata, bool touchscreen_detected) { @@ -181,14 +199,21 @@ GetLastHidDetectionStatus()->keyboard_metadata.detected_hid_name); EXPECT_EQ(touchscreen_detected, GetLastHidDetectionStatus()->touchscreen_detected); - EXPECT_EQ(pointer_metadata.state == InputState::kSearching, + } + + void AssertInputDevicesStatus(InputDevicesStatus input_devices_status) { + EXPECT_EQ(input_devices_status.pointer_is_missing, fake_bluetooth_hid_detector_->input_devices_status() .pointer_is_missing); - EXPECT_EQ(keyboard_metadata.state == InputState::kSearching, + EXPECT_EQ(input_devices_status.keyboard_is_missing, fake_bluetooth_hid_detector_->input_devices_status() .keyboard_is_missing); } + size_t GetNumSetInputDevicesStatusCalls() { + return fake_bluetooth_hid_detector_->num_set_input_devices_status_calls(); + } + private: base::test::TaskEnvironment task_environment_; base::test::ScopedFeatureList scoped_feature_list_; @@ -239,11 +264,14 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/true); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); } TEST_F(HidDetectionManagerImplTest, StartDetection_PointerPreConnected) { @@ -255,10 +283,13 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kConnected, device_id}, + /*pointer_metadata=*/{InputState::kConnected, device_id}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); } TEST_F(HidDetectionManagerImplTest, StartDetection_KeyboardPreConnected) { @@ -270,10 +301,13 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, - /*keyboard_metadata=*/InputMetadata{InputState::kConnected, device_id}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kConnected, device_id}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = false}); } TEST_F(HidDetectionManagerImplTest, @@ -282,40 +316,52 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); std::string touchscreen_id1; AddDevice(HidType::kTouchscreen, InputDeviceType::TYPE_SERIO, &touchscreen_id1); EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/true); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); RemoveDevice(touchscreen_id1); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); StopHidDetection(); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); // Add another touchscreen device. This should not inform the delegate. std::string touchscreen_id2; @@ -323,21 +369,27 @@ &touchscreen_id2); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); // Remove the touchscreen device. This should not inform the delegate. RemoveDevice(touchscreen_id2); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); } TEST_F(HidDetectionManagerImplTest, @@ -346,60 +398,77 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); std::string pointer_id1; AddDevice(HidType::kMouse, InputDeviceType::TYPE_USB, &pointer_id1); EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kConnectedViaUsb, - pointer_id1}, + /*pointer_metadata=*/{InputState::kConnectedViaUsb, pointer_id1}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); RemoveDevice(pointer_id1); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); StopHidDetection(); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); // Add another pointer device. This should not inform the delegate. std::string pointer_id2; AddDevice(HidType::kMouse, InputDeviceType::TYPE_USB, &pointer_id2); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); // Remove the pointer device. This should not inform the delegate. RemoveDevice(pointer_id2); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); } TEST_F(HidDetectionManagerImplTest, @@ -408,60 +477,78 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); std::string keyboard_id1; AddDevice(HidType::kKeyboard, InputDeviceType::TYPE_USB, &keyboard_id1); EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kConnectedViaUsb, keyboard_id1}, + {InputState::kConnectedViaUsb, keyboard_id1}, /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = false}); RemoveDevice(keyboard_id1); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); StopHidDetection(); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); // Add another keyboard device. This should not inform the delegate. std::string keyboard_id2; AddDevice(HidType::kMouse, InputDeviceType::TYPE_USB, &keyboard_id2); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); // Remove the keyboard device. This should not inform the delegate. RemoveDevice(keyboard_id2); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); } TEST_F(HidDetectionManagerImplTest, @@ -476,22 +563,28 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/true); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); // Remove the first touchscreen device. The second touchscreen should be // detected and delegate notified. RemoveDevice(device_id1); EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/true); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); } TEST_F(HidDetectionManagerImplTest, @@ -506,20 +599,26 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kConnected, device_id1}, + /*pointer_metadata=*/{InputState::kConnected, device_id1}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); // Remove the first pointer. The second pointer should be detected and // delegate notified. RemoveDevice(device_id1); EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kConnected, device_id2}, + /*pointer_metadata=*/{InputState::kConnected, device_id2}, /*keyboard_metadata=*/ - InputMetadata{InputState::kSearching, /*detected_hid_name=*/""}, + {InputState::kSearching, /*detected_hid_name=*/""}, /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); } TEST_F(HidDetectionManagerImplTest, @@ -534,20 +633,26 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, - /*keyboard_metadata=*/InputMetadata{InputState::kConnected, device_id1}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kConnected, device_id1}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = false}); // Remove the first keyboard. The second keyboard should be detected and // delegate notified. RemoveDevice(device_id1); EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, - /*keyboard_metadata=*/InputMetadata{InputState::kConnected, device_id2}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kConnected, device_id2}, /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = false}); } TEST_F(HidDetectionManagerImplTest, @@ -565,25 +670,369 @@ EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kConnectedViaUsb, - device_id1}, - /*keyboard_metadata=*/InputMetadata{InputState::kConnected, device_id2}, + /*pointer_metadata=*/{InputState::kConnectedViaUsb, device_id1}, + /*keyboard_metadata=*/{InputState::kConnected, device_id2}, /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = false}); RemoveDevice(device_id1); EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kConnected, device_id2}, - /*keyboard_metadata=*/InputMetadata{InputState::kConnected, device_id2}, + /*pointer_metadata=*/{InputState::kConnected, device_id2}, + /*keyboard_metadata=*/{InputState::kConnected, device_id2}, /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = false}); RemoveDevice(device_id2); EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); AssertHidDetectionStatus( - /*pointer_metadata=*/InputMetadata{InputState::kSearching, - /*detected_hid_name=*/""}, - /*keyboard_metadata=*/InputMetadata{InputState::kConnected, device_id3}, + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kConnected, device_id3}, /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = false}); +} + +// TODO(gordonseto): Test add device for type already connected, remove device +// for type already connected. + +TEST_F(HidDetectionManagerImplTest, StartDetection_BluetoothPointerSuccess) { + StartHidDetection(); + EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); + ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + SimulatePairingStarted( + BluetoothHidMetadata{kTestHidName, BluetoothHidType::kPointer}); + EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + // Simulate the pairing succeeding. + AddDevice(HidType::kMouse, InputDeviceType::TYPE_BLUETOOTH, + /*id_out=*/nullptr, kTestHidName); + EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); + + SimulatePairingFinished(); + EXPECT_EQ(4u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); +} + +TEST_F(HidDetectionManagerImplTest, StartDetection_BluetoothPointerFailure) { + StartHidDetection(); + EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); + ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + SimulatePairingStarted( + BluetoothHidMetadata{kTestHidName, BluetoothHidType::kPointer}); + EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + // Simulate the pairing failing. + SimulatePairingFinished(); + EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); +} + +TEST_F(HidDetectionManagerImplTest, StartDetection_BluetoothKeyboardSuccess) { + StartHidDetection(); + EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); + ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + SimulatePairingStarted( + BluetoothHidMetadata{kTestHidName, BluetoothHidType::kKeyboard}); + EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + // Simulate the pairing succeeding. + AddDevice(HidType::kKeyboard, InputDeviceType::TYPE_BLUETOOTH, + /*id_out=*/nullptr, kTestHidName); + EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = false}); + + SimulatePairingFinished(); + EXPECT_EQ(4u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = false}); +} + +TEST_F(HidDetectionManagerImplTest, StartDetection_BluetoothKeyboardFailure) { + StartHidDetection(); + EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); + ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + SimulatePairingStarted( + BluetoothHidMetadata{kTestHidName, BluetoothHidType::kKeyboard}); + EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, /*detected_hid_name=*/""}, + /*keyboard_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + // Simulate the pairing failing. + SimulatePairingFinished(); + EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); +} + +TEST_F(HidDetectionManagerImplTest, + StartDetection_BluetoothKeyboardPointerComboSuccess) { + StartHidDetection(); + EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); + ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + SimulatePairingStarted(BluetoothHidMetadata{ + kTestHidName, BluetoothHidType::kKeyboardPointerCombo}); + EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + // Simulate the pairing succeeding. + AddDevice(std::vector{HidType::kKeyboard, HidType::kTouchpad}, + InputDeviceType::TYPE_BLUETOOTH, + /*id_out=*/nullptr, kTestHidName); + EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = false}); + + SimulatePairingFinished(); + EXPECT_EQ(4u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = false}); +} + +TEST_F(HidDetectionManagerImplTest, + StartDetection_BluetoothKeyboardComboFailure) { + StartHidDetection(); + EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); + ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + SimulatePairingStarted(BluetoothHidMetadata{ + kTestHidName, BluetoothHidType::kKeyboardPointerCombo}); + EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*keyboard_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); + + // Simulate the pairing failing. + SimulatePairingFinished(); + EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kSearching, + /*detected_hid_name=*/""}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = true, .keyboard_is_missing = true}); +} + +TEST_F(HidDetectionManagerImplTest, + StartDetection_BluetoothKeyboardPointerComboPointerPreConnected) { + std::string device_id1; + AddDevice(HidType::kTouchpad, InputDeviceType::TYPE_USB, &device_id1); + EXPECT_EQ(0u, GetNumHidDetectionStatusChangedCalls()); + + StartHidDetection(); + EXPECT_EQ(1u, GetNumHidDetectionStatusChangedCalls()); + ASSERT_TRUE(GetLastHidDetectionStatus().has_value()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kConnectedViaUsb, device_id1}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); + + SimulatePairingStarted(BluetoothHidMetadata{ + kTestHidName, BluetoothHidType::kKeyboardPointerCombo}); + EXPECT_EQ(2u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kConnectedViaUsb, device_id1}, + /*keyboard_metadata=*/{InputState::kPairingViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(0u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); + + // Simulate the pairing succeeding. + std::string device_id2; + AddDevice(std::vector{HidType::kKeyboard, HidType::kTouchpad}, + InputDeviceType::TYPE_BLUETOOTH, &device_id2, kTestHidName); + EXPECT_EQ(3u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kConnectedViaUsb, device_id1}, + /*keyboard_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = false}); + + SimulatePairingFinished(); + EXPECT_EQ(4u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kConnectedViaUsb, device_id1}, + /*keyboard_metadata=*/{InputState::kPairedViaBluetooth, kTestHidName}, + /*touchscreen_detected=*/false); + EXPECT_EQ(1u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = false}); + + // Disconnect the Bluetooth device. + RemoveDevice(device_id2); + EXPECT_EQ(5u, GetNumHidDetectionStatusChangedCalls()); + AssertHidDetectionStatus( + /*pointer_metadata=*/{InputState::kConnectedViaUsb, device_id1}, + /*keyboard_metadata=*/ + {InputState::kSearching, /*detected_hid_name=*/""}, + /*touchscreen_detected=*/false); + EXPECT_EQ(2u, GetNumSetInputDevicesStatusCalls()); + AssertInputDevicesStatus( + {.pointer_is_missing = false, .keyboard_is_missing = true}); } } // namespace ash::hid_detection
diff --git a/ash/components/login/auth/DEPS b/ash/components/login/auth/DEPS index a14e5f7..b2b690fc 100644 --- a/ash/components/login/auth/DEPS +++ b/ash/components/login/auth/DEPS
@@ -21,8 +21,19 @@ "+google_apis", "+net", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/boringssl/src/include", "+third_party/cros_system_api", "+url", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/ash/components/login/auth/auth_performer.cc b/ash/components/login/auth/auth_performer.cc index fb25b37..8983c7b 100644 --- a/ash/components/login/auth/auth_performer.cc +++ b/ash/components/login/auth/auth_performer.cc
@@ -68,25 +68,33 @@ DCHECK(context->GetChallengeResponseKeys().empty()); if (context->GetKey()->GetKeyType() == Key::KEY_TYPE_PASSWORD_PLAIN) { DCHECK(!context->IsUsingPin()); - if (context->GetKey()->GetLabel().empty()) { - const AuthFactorsData& auth_factors = context->GetAuthFactorsData(); - const cryptohome::KeyDefinition* key_def = - auth_factors.FindOnlinePasswordKey(); - if (!key_def) { - LOGIN_LOG(ERROR) << "Could not find Password key"; - std::move(callback).Run( - std::move(context), - CryptohomeError{user_data_auth::CRYPTOHOME_ERROR_KEY_NOT_FOUND}); - return; - } - context->GetKey()->SetLabel(key_def->label); - } // empty label SystemSaltGetter::Get()->GetSystemSalt(base::BindOnce( &AuthPerformer::HashKeyAndAuthenticate, weak_factory_.GetWeakPtr(), std::move(context), std::move(callback))); return; } // plain-text password + // The login code might speculatively set the "gaia" label in the user + // context, however at the cryptohome level the existing user key's label can + // be either "gaia" or "legacy-N" - which is what we need to use when talking + // to cryptohome. If in cryptohome, "gaia" is indeed the label, then at the + // end of this operation, gaia would be returned. This case applies to only + // "gaia" labels only because they are created at oobe. + if (context->GetKey()->GetLabel() == kCryptohomeGaiaKeyLabel || + context->GetKey()->GetLabel().empty()) { + const AuthFactorsData& auth_factors = context->GetAuthFactorsData(); + const cryptohome::KeyDefinition* key_def = + auth_factors.FindOnlinePasswordKey(); + if (!key_def) { + LOGIN_LOG(ERROR) << "Could not find Password key"; + std::move(callback).Run( + std::move(context), + CryptohomeError{user_data_auth::CRYPTOHOME_ERROR_KEY_NOT_FOUND}); + return; + } + context->GetKey()->SetLabel(key_def->label); + } + LOGIN_LOG(EVENT) << "Authenticating using key " << context->GetKey()->GetKeyType();
diff --git a/ash/components/tpm/DEPS b/ash/components/tpm/DEPS index ee09834..66bbcb8f 100644 --- a/ash/components/tpm/DEPS +++ b/ash/components/tpm/DEPS
@@ -11,6 +11,17 @@ "+components/policy/proto", "+google_apis/gaia", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index 64c6dac6..30d5e7cf 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -1456,7 +1456,7 @@ // Uses new AuthSession-based API in cryptohome to authenticate users during // sign-in. const base::Feature kUseAuthsessionAuthentication{ - "UseAuthsessionAuthentication", base::FEATURE_DISABLED_BY_DEFAULT}; + "UseAuthsessionAuthentication", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables using the BluetoothSystem Mojo interface for Bluetooth operations. const base::Feature kUseBluetoothSystemInAsh{"UseBluetoothSystemInAsh",
diff --git a/ash/public/cpp/resources/ash_public_unscaled_resources.grd b/ash/public/cpp/resources/ash_public_unscaled_resources.grd index 53422b4..ef41bb09 100644 --- a/ash/public/cpp/resources/ash_public_unscaled_resources.grd +++ b/ash/public/cpp/resources/ash_public_unscaled_resources.grd
@@ -23,6 +23,7 @@ <include name="IDR_OS_URL_HANDLER_APP_ICONS_48_PNG" file="unscaled_resources/os_url_handler_app_icon_48.png" type="BINDATA" /> <include name="IDR_OS_URL_HANDLER_APP_ICONS_128_PNG" file="unscaled_resources/os_url_handler_app_icon_128.png" type="BINDATA" /> <include name="IDR_OS_URL_HANDLER_APP_ICONS_192_PNG" file="unscaled_resources/os_url_handler_app_icon_192.png" type="BINDATA" /> + <include name="IDR_SETTINGS_RGB_KEYBOARD_RAINBOW_COLOR_48_PNG" file="unscaled_resources/rgb_keyboard_rainbow_color_48.png" type="BINDATA" /> <!-- Accessibility animations --> <include name="IDR_DICTATION_BUBBLE_ANIMATION" file="unscaled_resources/dictation_bubble_animation.json" type="BINDATA"/> </includes>
diff --git a/ash/public/cpp/resources/unscaled_resources/rgb_keyboard_rainbow_color_48.png b/ash/public/cpp/resources/unscaled_resources/rgb_keyboard_rainbow_color_48.png new file mode 100644 index 0000000..c34fe26 --- /dev/null +++ b/ash/public/cpp/resources/unscaled_resources/rgb_keyboard_rainbow_color_48.png Binary files differ
diff --git a/ash/services/recording/DEPS b/ash/services/recording/DEPS index 426d679c..158f02c 100644 --- a/ash/services/recording/DEPS +++ b/ash/services/recording/DEPS
@@ -10,7 +10,18 @@ "+mojo/public", "+services/audio/public", "+services/viz/privileged/mojom/compositing", - "+third_party/abseil-cpp/absl", "+ui/gfx", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/ash/style/icon_button.cc b/ash/style/icon_button.cc index ff1dae666..ae645f877 100644 --- a/ash/style/icon_button.cc +++ b/ash/style/icon_button.cc
@@ -17,6 +17,7 @@ #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia.h" +#include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icon_types.h" #include "ui/views/border.h" @@ -143,6 +144,12 @@ SchedulePaint(); } +void IconButton::SetBackgroundImage(const gfx::ImageSkia& background_image) { + background_image_ = gfx::ImageSkiaOperations::CreateResizedImage( + background_image, skia::ImageOperations::RESIZE_BEST, GetPreferredSize()); + SchedulePaint(); +} + void IconButton::SetIconColor(const SkColor icon_color) { if (icon_color_ == icon_color) return; @@ -187,6 +194,15 @@ flags.setStyle(cc::PaintFlags::kFill_Style); canvas->DrawCircle(gfx::PointF(rect.CenterPoint()), rect.width() / 2, flags); + + // Apply the background image. This is painted on top of the |color|. + if (!background_image_.isNull()) { + SkPath mask; + mask.addCircle(rect.CenterPoint().x(), rect.CenterPoint().y(), + rect.width() / 2); + canvas->ClipPath(mask, true); + canvas->DrawImageInt(background_image_, 0, 0, flags); + } } views::ImageButton::PaintButtonContents(canvas);
diff --git a/ash/style/icon_button.h b/ash/style/icon_button.h index 881dd64..58bd26b 100644 --- a/ash/style/icon_button.h +++ b/ash/style/icon_button.h
@@ -10,6 +10,7 @@ #include "ui/views/controls/button/image_button.h" namespace gfx { +class ImageSkia; struct VectorIcon; } // namespace gfx @@ -87,6 +88,11 @@ // wants to have different color from the default one. void SetBackgroundColor(const SkColor background_color); + // Sets the button's background image. The |background_image| is resized to + // fit the button. Note, if set, |background_image| is painted on top of + // the button's existing background color. + void SetBackgroundImage(const gfx::ImageSkia& background_image); + // Sets the icon's color. If the button is togglable, this will be the color // when it's not toggled. void SetIconColor(const SkColor icon_color);
diff --git a/ash/system/keyboard_brightness/unified_keyboard_brightness_slider_controller.cc b/ash/system/keyboard_brightness/unified_keyboard_brightness_slider_controller.cc index 74586f4..f560c621 100644 --- a/ash/system/keyboard_brightness/unified_keyboard_brightness_slider_controller.cc +++ b/ash/system/keyboard_brightness/unified_keyboard_brightness_slider_controller.cc
@@ -8,6 +8,7 @@ #include "ash/constants/ash_features.h" #include "ash/public/cpp/new_window_delegate.h" +#include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/rgb_keyboard/rgb_keyboard_manager.h" #include "ash/rgb_keyboard/rgb_keyboard_util.h" @@ -20,6 +21,7 @@ #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "chromeos/dbus/power/power_manager_client.h" +#include "ui/base/resource/resource_bundle.h" namespace ash { @@ -74,10 +76,21 @@ weak_factory_.GetWeakPtr()), IconButton::Type::kSmall, &kUnifiedMenuKeyboardBacklightIcon, IDS_ASH_STATUS_TRAY_KEYBOARD_BACKLIGHT_ACCESSIBLE_NAME); - button->SetBackgroundColor(ConvertBacklightColorToIconBackgroundColor( + + personalization_app::mojom::BacklightColor backlight_color = Shell::Get() ->keyboard_backlight_color_controller() - ->GetBacklightColor())); + ->GetBacklightColor(); + if (backlight_color == + personalization_app::mojom::BacklightColor::kRainbow) { + ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); + auto* image = + rb.GetImageSkiaNamed(IDR_SETTINGS_RGB_KEYBOARD_RAINBOW_COLOR_48_PNG); + button->SetBackgroundImage(*image); + } else { + button->SetBackgroundColor( + ConvertBacklightColorToIconBackgroundColor(backlight_color)); + } button->SetBorder(views::CreateRoundedRectBorder( /*thickness=*/4, /*corner_radius=*/16, AshColorProvider::Get()->GetContentLayerColor(
diff --git a/ash/wm/desks/desks_bar_view.cc b/ash/wm/desks/desks_bar_view.cc index c8bc94a..250c450d 100644 --- a/ash/wm/desks/desks_bar_view.cc +++ b/ash/wm/desks/desks_bar_view.cc
@@ -1273,7 +1273,7 @@ } void DesksBarView::OnDesksTemplatesButtonPressed() { - RecordLoadTemplateHistogram(); + RecordLoadSavedDeskLibraryHistogram(); overview_grid_->overview_session()->ShowDesksTemplatesGrids( IsZeroState(), base::GUID(), GetWidget()->GetNativeWindow()->GetRootWindow());
diff --git a/ash/wm/desks/templates/saved_desk_library_view.cc b/ash/wm/desks/templates/saved_desk_library_view.cc index 4fce0a7..e2f2e62 100644 --- a/ash/wm/desks/templates/saved_desk_library_view.cc +++ b/ash/wm/desks/templates/saved_desk_library_view.cc
@@ -168,6 +168,8 @@ owner_->OnLocatedEvent(event, /*is_touch=*/true); } + void OnKeyEvent(ui::KeyEvent* event) override { owner_->OnKeyEvent(event); } + private: SavedDeskLibraryView* const owner_; }; @@ -213,8 +215,7 @@ scroll_view_->SetDrawOverflowIndicator(false); // Don't paint a background. The overview grid already has one. scroll_view_->SetBackgroundColor(absl::nullopt); - // Arrow keys are used to select app icons. - scroll_view_->SetAllowKeyboardScrolling(false); + scroll_view_->SetAllowKeyboardScrolling(true); // Scroll view will have a gradient mask layer. scroll_view_->SetPaintToLayer(ui::LAYER_NOT_DRAWN); @@ -462,6 +463,34 @@ scroll_view_gradient_helper_->UpdateGradientZone(); } +void SavedDeskLibraryView::OnKeyEvent(ui::KeyEvent* event) { + bool is_scrolling_event; + switch (event->key_code()) { + case ui::VKEY_HOME: + case ui::VKEY_END: + is_scrolling_event = true; + // Do not process if home/end key are for text editing. + for (SavedDeskGridView* grid_view : grid_views_) { + if (grid_view->IsTemplateNameBeingModified()) { + is_scrolling_event = false; + break; + } + } + break; + case ui::VKEY_PRIOR: + case ui::VKEY_NEXT: + is_scrolling_event = true; + break; + default: + // Ignore all other key events as arrow keys are used for moving + // highlight. + is_scrolling_event = false; + break; + } + if (is_scrolling_event) + scroll_view_->vertical_scroll_bar()->OnKeyEvent(event); +} + void SavedDeskLibraryView::OnThemeChanged() { views::View::OnThemeChanged();
diff --git a/ash/wm/desks/templates/saved_desk_library_view.h b/ash/wm/desks/templates/saved_desk_library_view.h index 7668947..0ce8f35 100644 --- a/ash/wm/desks/templates/saved_desk_library_view.h +++ b/ash/wm/desks/templates/saved_desk_library_view.h
@@ -12,6 +12,7 @@ #include "base/guid.h" #include "ui/aura/window_observer.h" #include "ui/base/metadata/metadata_header_macros.h" +#include "ui/events/event.h" #include "ui/views/animation/bounds_animator.h" #include "ui/views/controls/label.h" #include "ui/views/controls/scroll_view.h" @@ -85,6 +86,7 @@ // views::View: void AddedToWidget() override; void Layout() override; + void OnKeyEvent(ui::KeyEvent* event) override; void OnThemeChanged() override; // aura::WindowObserver:
diff --git a/ash/wm/desks/templates/saved_desk_metrics_util.cc b/ash/wm/desks/templates/saved_desk_metrics_util.cc index 8c0b388..07ea25a5 100644 --- a/ash/wm/desks/templates/saved_desk_metrics_util.cc +++ b/ash/wm/desks/templates/saved_desk_metrics_util.cc
@@ -11,7 +11,7 @@ namespace ash { -void RecordLoadTemplateHistogram() { +void RecordLoadSavedDeskLibraryHistogram() { base::UmaHistogramBoolean(kLoadTemplateGridHistogramName, true); } @@ -22,8 +22,11 @@ true); } -void RecordLaunchTemplateHistogram() { - base::UmaHistogramBoolean(kLaunchTemplateHistogramName, true); +void RecordLaunchSavedDeskHistogram(DeskTemplateType type) { + base::UmaHistogramBoolean(type == DeskTemplateType::kTemplate + ? kLaunchTemplateHistogramName + : kLaunchSaveAndRecallHistogramName, + true); } void RecordNewSavedDeskHistogram(DeskTemplateType type) { @@ -39,15 +42,21 @@ status); } -void RecordUserTemplateCountHistogram(size_t entry_count, - size_t max_entry_count) { - UMA_HISTOGRAM_EXACT_LINEAR(kUserTemplateCountHistogramName, entry_count, - max_entry_count); +void RecordUserSavedDeskCountHistogram(DeskTemplateType type, + size_t entry_count, + size_t max_entry_count) { + if (type == DeskTemplateType::kTemplate) { + UMA_HISTOGRAM_EXACT_LINEAR(kUserTemplateCountHistogramName, entry_count, + max_entry_count); + } else { + UMA_HISTOGRAM_EXACT_LINEAR(kUserSaveAndRecallCountHistogramName, + entry_count, max_entry_count); + } } -void RecordWindowAndTabCountHistogram(DeskTemplate* desk_template) { +void RecordWindowAndTabCountHistogram(const DeskTemplate& desk_template) { const app_restore::RestoreData* restore_data = - desk_template->desk_restore_data(); + desk_template.desk_restore_data(); DCHECK(restore_data); int window_count = 0; @@ -65,7 +74,7 @@ } for (const auto& window_iter : iter.second) { - absl::optional<std::vector<GURL>> urls = window_iter.second->urls; + const absl::optional<std::vector<GURL>>& urls = window_iter.second->urls; if (!urls || urls->empty()) continue; @@ -75,9 +84,19 @@ } } - base::UmaHistogramCounts100(kWindowCountHistogramName, window_count); - base::UmaHistogramCounts100(kTabCountHistogramName, tab_count); - base::UmaHistogramCounts100(kWindowAndTabCountHistogramName, total_count); + if (desk_template.type() == DeskTemplateType::kTemplate) { + base::UmaHistogramCounts100(kTemplateWindowCountHistogramName, + window_count); + base::UmaHistogramCounts100(kTemplateTabCountHistogramName, tab_count); + base::UmaHistogramCounts100(kTemplateWindowAndTabCountHistogramName, + total_count); + } else { + base::UmaHistogramCounts100(kSaveAndRecallWindowCountHistogramName, + window_count); + base::UmaHistogramCounts100(kSaveAndRecallTabCountHistogramName, tab_count); + base::UmaHistogramCounts100(kSaveAndRecallWindowAndTabCountHistogramName, + total_count); + } } void RecordUnsupportedAppDialogShowHistogram() {
diff --git a/ash/wm/desks/templates/saved_desk_metrics_util.h b/ash/wm/desks/templates/saved_desk_metrics_util.h index 071702b..ac31984 100644 --- a/ash/wm/desks/templates/saved_desk_metrics_util.h +++ b/ash/wm/desks/templates/saved_desk_metrics_util.h
@@ -20,12 +20,11 @@ "Ash.DeskTemplate.LaunchFromTemplate"; constexpr char kAddOrUpdateTemplateStatusHistogramName[] = "Ash.DeskTemplate.AddOrUpdateTemplateStatus"; -constexpr char kWindowCountHistogramName[] = "Ash.DeskTemplate.WindowCount"; -constexpr char kTabCountHistogramName[] = "Ash.DeskTemplate.TabCount"; -constexpr char kWindowAndTabCountHistogramName[] = +constexpr char kTemplateWindowCountHistogramName[] = + "Ash.DeskTemplate.WindowCount"; +constexpr char kTemplateTabCountHistogramName[] = "Ash.DeskTemplate.TabCount"; +constexpr char kTemplateWindowAndTabCountHistogramName[] = "Ash.DeskTemplate.WindowAndTabCount"; -constexpr char kLaunchFromTemplateHistogramName[] = - "Ash.DeskTemplate.LaunchFromTemplate"; constexpr char kUserTemplateCountHistogramName[] = "Ash.DeskTemplate.UserTemplateCount"; constexpr char kUnsupportedAppDialogShowHistogramName[] = @@ -38,17 +37,28 @@ "Ash.DeskTemplate.NewSaveAndRecall"; constexpr char kDeleteSaveAndRecallHistogramName[] = "Ash.DeskTemplate.DeleteSaveAndRecall"; +constexpr char kLaunchSaveAndRecallHistogramName[] = + "Ash.DeskTemplate.LaunchSaveAndRecall"; +constexpr char kSaveAndRecallWindowCountHistogramName[] = + "Ash.DeskTemplate.SaveAndRecallWindowCount"; +constexpr char kSaveAndRecallTabCountHistogramName[] = + "Ash.DeskTemplate.SaveAndRecallTabCount"; +constexpr char kSaveAndRecallWindowAndTabCountHistogramName[] = + "Ash.DeskTemplate.SaveAndRecallWindowAndTabCount"; +constexpr char kUserSaveAndRecallCountHistogramName[] = + "Ash.DeskTemplate.UserSaveAndRecallCount"; // Wrappers calls base::uma with correct histogram name. -void RecordLoadTemplateHistogram(); +void RecordLoadSavedDeskLibraryHistogram(); void RecordDeleteSavedDeskHistogram(DeskTemplateType type); -void RecordLaunchTemplateHistogram(); +void RecordLaunchSavedDeskHistogram(DeskTemplateType type); void RecordNewSavedDeskHistogram(DeskTemplateType type); void RecordAddOrUpdateTemplateStatusHistogram( desks_storage::DeskModel::AddOrUpdateEntryStatus status); -void RecordUserTemplateCountHistogram(size_t entry_count, - size_t max_entry_count); -void RecordWindowAndTabCountHistogram(DeskTemplate* desk_template); +void RecordUserSavedDeskCountHistogram(DeskTemplateType type, + size_t entry_count, + size_t max_entry_count); +void RecordWindowAndTabCountHistogram(const DeskTemplate& desk_template); void RecordUnsupportedAppDialogShowHistogram(); void RecordReplaceTemplateHistogram();
diff --git a/ash/wm/desks/templates/saved_desk_presenter.cc b/ash/wm/desks/templates/saved_desk_presenter.cc index 60a490f..4466286 100644 --- a/ash/wm/desks/templates/saved_desk_presenter.cc +++ b/ash/wm/desks/templates/saved_desk_presenter.cc
@@ -57,33 +57,25 @@ desk_model_observation_.Observe(desk_model); GetAllEntries(base::GUID(), Shell::GetPrimaryRootWindow()); - should_show_templates_ui_ = GetEntryCount() > 0; + should_show_templates_ui_ = + (GetEntryCount(DeskTemplateType::kTemplate) + + GetEntryCount(DeskTemplateType::kSaveAndRecall)) > 0u; } SavedDeskPresenter::~SavedDeskPresenter() = default; -size_t SavedDeskPresenter::GetEntryCount() const { - return GetDeskModel()->GetEntryCount(); +size_t SavedDeskPresenter::GetEntryCount(DeskTemplateType type) const { + auto* model = GetDeskModel(); + return type == DeskTemplateType::kTemplate + ? model->GetDeskTemplateEntryCount() + : model->GetSaveAndRecallDeskEntryCount(); } -size_t SavedDeskPresenter::GetMaxEntryCount() const { - return GetDeskModel()->GetMaxEntryCount(); -} - -size_t SavedDeskPresenter::GetDeskTemplateEntryCount() const { - return GetDeskModel()->GetDeskTemplateEntryCount(); -} - -size_t SavedDeskPresenter::GetMaxDeskTemplateEntryCount() const { - return GetDeskModel()->GetMaxDeskTemplateEntryCount(); -} - -size_t SavedDeskPresenter::GetSaveAndRecallDeskEntryCount() const { - return GetDeskModel()->GetSaveAndRecallDeskEntryCount(); -} - -size_t SavedDeskPresenter::GetMaxSaveAndRecallDeskEntryCount() const { - return GetDeskModel()->GetMaxSaveAndRecallDeskEntryCount(); +size_t SavedDeskPresenter::GetMaxEntryCount(DeskTemplateType type) const { + auto* model = GetDeskModel(); + return type == DeskTemplateType::kTemplate + ? model->GetMaxDeskTemplateEntryCount() + : model->GetMaxSaveAndRecallDeskEntryCount(); } void SavedDeskPresenter::UpdateDesksTemplatesUI() { @@ -98,7 +90,9 @@ const bool in_tablet_mode = Shell::Get()->tablet_mode_controller()->InTabletMode(); - const bool has_saved_desks = GetEntryCount() > 0u; + const bool has_saved_desks = + (GetEntryCount(DeskTemplateType::kTemplate) + + GetEntryCount(DeskTemplateType::kSaveAndRecall)) > 0u; for (auto& overview_grid : overview_session_->grid_list()) { const bool is_showing_library = @@ -188,7 +182,7 @@ if (is_update) desk_template->set_updated_time(base::Time::Now()); else - RecordWindowAndTabCountHistogram(desk_template.get()); + RecordWindowAndTabCountHistogram(*desk_template); // Clone the desk template so one can be sent to the model, and the other as // part of the callback. @@ -260,9 +254,13 @@ if (status != desks_storage::DeskModel::DeleteEntryStatus::kOk) return; - if (record_for_type) + if (record_for_type) { RecordDeleteSavedDeskHistogram(*record_for_type); - RecordUserTemplateCountHistogram(GetEntryCount(), GetMaxEntryCount()); + RecordUserSavedDeskCountHistogram(*record_for_type, + GetEntryCount(*record_for_type), + GetMaxEntryCount(*record_for_type)); + } + RemoveUIEntries({uuid}); } @@ -280,10 +278,11 @@ base::OnceClosure on_update_ui_closure_for_testing = std::move(on_update_ui_closure_for_testing_); - const auto template_name = entry->template_name(); - const bool activate_desk = entry->type() == DeskTemplateType::kTemplate; + const auto saved_desk_name = entry->template_name(); + const auto saved_desk_type = entry->type(); + const bool activate_desk = saved_desk_type == DeskTemplateType::kTemplate; DesksController::Get()->CreateNewDeskForTemplate( - template_name, activate_desk, + saved_desk_name, activate_desk, base::BindOnce(&SavedDeskPresenter::OnNewDeskCreatedForTemplate, weak_ptr_factory_.GetWeakPtr(), std::move(entry), time_launch_started, delay, root_window)); @@ -291,7 +290,7 @@ if (on_update_ui_closure_for_testing) std::move(on_update_ui_closure_for_testing).Run(); - RecordLaunchTemplateHistogram(); + RecordLaunchSavedDeskHistogram(saved_desk_type); } void SavedDeskPresenter::OnNewDeskCreatedForTemplate( @@ -360,6 +359,9 @@ const bool is_zero_state = overview_grid->desks_bar_view()->IsZeroState(); if (auto* library_view = overview_grid->GetSavedDeskLibraryView()) { + // TODO(dandersson): Rework literally all of this. This path is only taken + // if the library has been visible in a session and we then save a desk. We + // should not need this special case. AddOrUpdateUIEntries({desk_template.get()}); if (!was_update) { @@ -375,16 +377,16 @@ if (on_update_ui_closure_for_testing_) std::move(on_update_ui_closure_for_testing_).Run(); - return; + } else { + // This will update the templates button and save as desks button too. This + // will call `GetAllEntries`. + overview_session_->ShowDesksTemplatesGrids( + is_zero_state, desk_template->uuid(), root_window); } - // This will update the templates button and save as desks button too. This - // will call `GetAllEntries`. - overview_session_->ShowDesksTemplatesGrids( - is_zero_state, desk_template->uuid(), root_window); - if (!was_update) { - if (desk_template->type() == DeskTemplateType::kSaveAndRecall) { + const auto saved_desk_type = desk_template->type(); + if (saved_desk_type == DeskTemplateType::kSaveAndRecall) { // We have successfully created a *new* desk template for Save & Recall, // so we are now going to close all the windows on the active desk and // also remove the desk. @@ -401,8 +403,10 @@ DeskCloseType::kCloseAllWindows); } - RecordNewSavedDeskHistogram(desk_template->type()); - RecordUserTemplateCountHistogram(GetEntryCount(), GetMaxEntryCount()); + RecordNewSavedDeskHistogram(saved_desk_type); + RecordUserSavedDeskCountHistogram(saved_desk_type, + GetEntryCount(saved_desk_type), + GetMaxEntryCount(saved_desk_type)); } // Note we do not run `on_update_ui_closure_for_testing` here as we want to
diff --git a/ash/wm/desks/templates/saved_desk_presenter.h b/ash/wm/desks/templates/saved_desk_presenter.h index dda53f0..4a41a20 100644 --- a/ash/wm/desks/templates/saved_desk_presenter.h +++ b/ash/wm/desks/templates/saved_desk_presenter.h
@@ -36,17 +36,11 @@ bool should_show_templates_ui() { return should_show_templates_ui_; } - size_t GetEntryCount() const; - - size_t GetMaxEntryCount() const; - - size_t GetDeskTemplateEntryCount() const; - - size_t GetMaxDeskTemplateEntryCount() const; - - size_t GetSaveAndRecallDeskEntryCount() const; - - size_t GetMaxSaveAndRecallDeskEntryCount() const; + // Retrieve the current and max count for a given saved desk type. Note that + // these are snapshots of the model state, which may not match the current UI + // state. + size_t GetEntryCount(DeskTemplateType type) const; + size_t GetMaxEntryCount(DeskTemplateType type) const; // Update the buttons of the desks templates UI and the visibility of the // templates grid. The grid contents are not updated. Updates
diff --git a/ash/wm/desks/templates/saved_desk_unittest.cc b/ash/wm/desks/templates/saved_desk_unittest.cc index 27cfc2ee..59dfbed 100644 --- a/ash/wm/desks/templates/saved_desk_unittest.cc +++ b/ash/wm/desks/templates/saved_desk_unittest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <array> #include <string> #include "ash/accessibility/test_accessibility_controller_client.h" @@ -73,6 +74,7 @@ #include "ui/compositor/layer.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" +#include "ui/events/keycodes/keyboard_codes_posix.h" #include "ui/events/test/event_generator.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" @@ -947,8 +949,9 @@ OpenOverviewAndShowTemplatesGrid(); const SavedDeskPresenter* saved_desk_presenter = saved_desk_util::GetSavedDeskPresenter(); - ASSERT_EQ(saved_desk_presenter->GetMaxDeskTemplateEntryCount(), - saved_desk_presenter->GetDeskTemplateEntryCount()); + ASSERT_EQ( + saved_desk_presenter->GetMaxEntryCount(DeskTemplateType::kTemplate), + saved_desk_presenter->GetEntryCount(DeskTemplateType::kTemplate)); // Verify that the button is re-enabled after we delete all entries. std::vector<const DeskTemplate*> entries = GetAllEntries(); @@ -991,8 +994,10 @@ OpenOverviewAndShowTemplatesGrid(); const SavedDeskPresenter* saved_desk_presenter = saved_desk_util::GetSavedDeskPresenter(); - ASSERT_EQ(saved_desk_presenter->GetMaxSaveAndRecallDeskEntryCount(), - saved_desk_presenter->GetSaveAndRecallDeskEntryCount()); + ASSERT_EQ( + saved_desk_presenter->GetMaxEntryCount( + DeskTemplateType::kSaveAndRecall), + saved_desk_presenter->GetEntryCount(DeskTemplateType::kSaveAndRecall)); // Verify that the button is re-enabled after we delete all entries. std::vector<const DeskTemplate*> entries = GetAllEntries(); @@ -2931,9 +2936,10 @@ /*is_update=*/false, Shell::GetPrimaryRootWindow(), std::move(desk_template)); - histogram_tester.ExpectBucketCount(kWindowCountHistogramName, 2, 1); - histogram_tester.ExpectBucketCount(kTabCountHistogramName, 6, 1); - histogram_tester.ExpectBucketCount(kWindowAndTabCountHistogramName, 6, 1); + histogram_tester.ExpectBucketCount(kTemplateWindowCountHistogramName, 2, 1); + histogram_tester.ExpectBucketCount(kTemplateTabCountHistogramName, 6, 1); + histogram_tester.ExpectBucketCount(kTemplateWindowAndTabCountHistogramName, 6, + 1); } // Tests that the user template count metric is recorded correctly. @@ -3796,6 +3802,38 @@ } } +// Tests that the scroll bar works with the keyboard. +TEST_F(SavedDeskTest, ScrollWithKeyboard) { + // Add 6 `kTemplate` entries and 6 `kSaveAndRecall` entries. + for (size_t i = 1; i <= 6; i++) { + AddEntry(base::GUID::GenerateRandomV4(), + "desk_template " + base::NumberToString(i), base::Time::Now(), + DeskTemplateType::kTemplate); + AddEntry(base::GUID::GenerateRandomV4(), + "saved_desk " + base::NumberToString(i), base::Time::Now(), + DeskTemplateType::kSaveAndRecall); + } + + OpenOverviewAndShowTemplatesGrid(); + + // Press keys to scroll through the whole library page, and verify the scroll + // position. + std::array<ui::KeyboardCode, 4> keys = {ui::VKEY_END, ui::VKEY_HOME, + ui::VKEY_NEXT, ui::VKEY_PRIOR}; + SavedDeskLibraryView* library_view = + GetOverviewGridList()[0]->GetSavedDeskLibraryView(); + SavedDeskLibraryViewTestApi test_api(library_view); + int scroll_position = + test_api.scroll_view()->vertical_scroll_bar()->GetPosition(); + for (ui::KeyboardCode key : keys) { + SendKey(key); + int new_scroll_position = + test_api.scroll_view()->vertical_scroll_bar()->GetPosition(); + EXPECT_NE(scroll_position, new_scroll_position); + scroll_position = new_scroll_position; + } +} + using DeskSaveAndRecallTest = SavedDeskTest; TEST_F(DeskSaveAndRecallTest, SaveDeskForLater) { @@ -3870,6 +3908,8 @@ } TEST_F(DeskSaveAndRecallTest, RecallSavedDesk) { + base::HistogramTester histogram_tester; + UpdateDisplay("800x600"); constexpr char16_t kDeskName[] = u"Save for later"; @@ -3899,6 +3939,9 @@ // Verify that the saved desk has been deleted. EXPECT_TRUE(GetAllEntries().empty()); + + // Assert that histogram metrics were recorded. + histogram_tester.ExpectTotalCount(kLaunchSaveAndRecallHistogramName, 1); } TEST_F(DeskSaveAndRecallTest, DeleteSaveAndRecallRecordsMetric) { @@ -3922,4 +3965,43 @@ histogram_tester.ExpectTotalCount(kDeleteSaveAndRecallHistogramName, 1); } +// Tests that if we've been in the library, then switched to a different desk, +// and then save the desk, that the desk is closed. Regression test for +// https://crbug.com/1329350. +TEST_F(DeskSaveAndRecallTest, ReEnterLibraryAndSaveDesk) { + UpdateDisplay("800x600"); + + auto* root = Shell::Get()->GetPrimaryRootWindow(); + + // Create a template that has a window. We can't use `AddEntry` here since we + // want a template that actually contains a window. The "Save desk for later" + // button is not enabled on empty desks. + auto test_window1 = CreateAppWindow(); + + OpenOverviewAndSaveTemplate(root); + + DesksController* desks_controller = DesksController::Get(); + EXPECT_EQ(1ul, desks_controller->desks().size()); + + // Click on the "Use template" button to launch the template. + SavedDeskItemView* item_view = GetItemViewFromTemplatesGrid(0); + ClickOnView(SavedDeskItemViewTestApi(item_view).launch_button()); + WaitForDesksTemplatesUI(); + + // Verify that we're still in overview mode and that a new desk has been + // created and activated. + EXPECT_TRUE(InOverviewSession()); + EXPECT_EQ(2ul, desks_controller->desks().size()); + EXPECT_EQ(1, desks_controller->GetActiveDeskIndex()); + + // Now save the desk. This should close the desk. + auto* save_desk_button = GetSaveDeskForLaterButtonForRoot(root); + EXPECT_TRUE(save_desk_button); + ClickOnView(save_desk_button); + WaitForDesksTemplatesUI(); + + // Verify that we're back to one desk. + EXPECT_EQ(1ul, desks_controller->desks().size()); +} + } // namespace ash
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index 66ff3b6d..1370dfad 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -1931,13 +1931,13 @@ save_desk_button_container_widget_->GetContentsView()); container->UpdateButtonEnableStateAndTooltip( SaveDeskTemplateButton::Type::kSaveAsTemplate, - saved_desk_presenter->GetDeskTemplateEntryCount(), - saved_desk_presenter->GetMaxDeskTemplateEntryCount(), + saved_desk_presenter->GetEntryCount(DeskTemplateType::kTemplate), + saved_desk_presenter->GetMaxEntryCount(DeskTemplateType::kTemplate), num_incognito_windows_, num_unsupported_windows_, size()); container->UpdateButtonEnableStateAndTooltip( SaveDeskTemplateButton::Type::kSaveForLater, - saved_desk_presenter->GetSaveAndRecallDeskEntryCount(), - saved_desk_presenter->GetMaxSaveAndRecallDeskEntryCount(), + saved_desk_presenter->GetEntryCount(DeskTemplateType::kSaveAndRecall), + saved_desk_presenter->GetMaxEntryCount(DeskTemplateType::kSaveAndRecall), num_incognito_windows_, num_unsupported_windows_, size()); // Set the widget position above the overview item window and default width
diff --git a/base/allocator/partition_allocator/partition_alloc_base/numerics/checked_math_impl.h b/base/allocator/partition_allocator/partition_alloc_base/numerics/checked_math_impl.h index 4cac447a..ea6396e 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/numerics/checked_math_impl.h +++ b/base/allocator/partition_allocator/partition_alloc_base/numerics/checked_math_impl.h
@@ -158,14 +158,15 @@ const UnsignedDst uy = SafeUnsignedAbs(y); const UnsignedDst uresult = static_cast<UnsignedDst>(ux * uy); const bool is_negative = - std::is_signed<T>::value && static_cast<SignedDst>(x ^ y) < 0; + std::is_signed<T>::value && x && y && static_cast<SignedDst>(x ^ y) < 0; // We have a fast out for unsigned identity or zero on the second operand. // After that it's an unsigned overflow check on the absolute value, with // a +1 bound for a negative result. if (uy > UnsignedDst(!std::is_signed<T>::value || is_negative) && ux > (std::numeric_limits<T>::max() + UnsignedDst(is_negative)) / uy) return false; - *result = is_negative ? 0 - uresult : uresult; + *result = is_negative ? static_cast<T>(-1) - static_cast<T>(uresult - 1) + : static_cast<T>(uresult); return true; } @@ -196,7 +197,8 @@ bool is_valid = true; if (CheckedMulFastOp<Promotion, Promotion>::is_supported) { // The fast op may be available with the promoted type. - is_valid = CheckedMulFastOp<Promotion, Promotion>::Do(x, y, &presult); + is_valid = CheckedMulFastOp<Promotion, Promotion>::Do( + static_cast<Promotion>(x), static_cast<Promotion>(y), &presult); } else if (IsIntegerArithmeticSafe<Promotion, T, U>::value) { presult = static_cast<Promotion>(x) * static_cast<Promotion>(y); } else {
diff --git a/base/allocator/partition_allocator/partition_alloc_base/numerics/clamped_math_impl.h b/base/allocator/partition_allocator/partition_alloc_base/numerics/clamped_math_impl.h index e4693af..507b6b5 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/numerics/clamped_math_impl.h +++ b/base/allocator/partition_allocator/partition_alloc_base/numerics/clamped_math_impl.h
@@ -56,8 +56,9 @@ // special case of numeric_limits<T>::min(), by evaluating the bit pattern as // a signed integer value. If it is the overflow case, we end up subtracting // one from the unsigned result, thus saturating to numeric_limits<T>::max(). - return static_cast<T>(SafeUnsignedAbs(value) - - IsValueNegative<T>(SafeUnsignedAbs(value))); + return static_cast<T>( + SafeUnsignedAbs(value) - + IsValueNegative<T>(static_cast<T>(SafeUnsignedAbs(value)))); } template <
diff --git a/base/allocator/partition_allocator/partition_alloc_base/numerics/safe_conversions_impl.h b/base/allocator/partition_allocator/partition_alloc_base/numerics/safe_conversions_impl.h index 2ef712cd..cb188b3 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/numerics/safe_conversions_impl.h +++ b/base/allocator/partition_allocator/partition_alloc_base/numerics/safe_conversions_impl.h
@@ -70,8 +70,9 @@ static_assert(std::is_integral<T>::value, "Type must be integral"); using SignedT = typename std::make_signed<T>::type; using UnsignedT = typename std::make_unsigned<T>::type; - return static_cast<SignedT>( - (static_cast<UnsignedT>(x) ^ -SignedT(is_negative)) + is_negative); + return static_cast<SignedT>((static_cast<UnsignedT>(x) ^ + static_cast<UnsignedT>(-SignedT(is_negative))) + + is_negative); } // This performs a safe, absolute value via unsigned overflow. @@ -243,9 +244,10 @@ static constexpr T Adjust(T value) { static_assert(std::is_same<T, Dst>::value, ""); static_assert(kShift < DstLimits::digits, ""); - return static_cast<T>( - ConditionalNegate(SafeUnsignedAbs(value) & ~((T(1) << kShift) - T(1)), - IsValueNegative(value))); + using UnsignedDst = typename std::make_unsigned_t<T>; + return static_cast<T>(ConditionalNegate( + SafeUnsignedAbs(value) & ~((UnsignedDst{1} << kShift) - UnsignedDst{1}), + IsValueNegative(value))); } template <typename T,
diff --git a/base/containers/checked_range_unittest.cc b/base/containers/checked_range_unittest.cc index 4880059d..1e0ffe79 100644 --- a/base/containers/checked_range_unittest.cc +++ b/base/containers/checked_range_unittest.cc
@@ -10,6 +10,7 @@ #include "base/ranges/algorithm.h" #include "base/strings/string_piece.h" +#include "base/test/gtest_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { @@ -233,16 +234,21 @@ ""); } -TEST(CheckedContiguousRange, OutOfBoundsDeath) { +TEST(CheckedContiguousRangeDeathTest, OutOfBounds) { std::vector<int> empty_vector; CheckedContiguousRange<std::vector<int>> empty_range(empty_vector); - ASSERT_DEATH_IF_SUPPORTED(empty_range[0], ""); - ASSERT_DEATH_IF_SUPPORTED(empty_range.front(), ""); - ASSERT_DEATH_IF_SUPPORTED(empty_range.back(), ""); + EXPECT_CHECK_DEATH(empty_range[0]); + EXPECT_CHECK_DEATH(empty_range.front()); + EXPECT_CHECK_DEATH(empty_range.back()); static constexpr int array[] = {0, 1, 2}; constexpr CheckedContiguousRange<const int[3]> range(array); - ASSERT_DEATH_IF_SUPPORTED(range[3], ""); + EXPECT_CHECK_DEATH(range[3]); + + CheckedContiguousRange<std::vector<int>> default_range; + EXPECT_CHECK_DEATH(default_range[0]); + EXPECT_CHECK_DEATH(default_range.front()); + EXPECT_CHECK_DEATH(default_range.back()); } } // namespace base
diff --git a/base/metrics/persistent_memory_allocator.cc b/base/metrics/persistent_memory_allocator.cc index 4f8d17a..9f53ff9d 100644 --- a/base/metrics/persistent_memory_allocator.cc +++ b/base/metrics/persistent_memory_allocator.cc
@@ -15,6 +15,7 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/sparse_histogram.h" #include "base/notreached.h" +#include "base/numerics/checked_math.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_piece.h" #include "base/system/sys_info.h" @@ -326,8 +327,8 @@ bool readonly) : mem_base_(static_cast<char*>(memory.base)), mem_type_(memory.type), - mem_size_(static_cast<uint32_t>(size)), - mem_page_(static_cast<uint32_t>((page_size ? page_size : size))), + mem_size_(checked_cast<uint32_t>(size)), + mem_page_(checked_cast<uint32_t>((page_size ? page_size : size))), #if BUILDFLAG(IS_NACL) vm_page_size_(4096U), // SysInfo is not built for NACL. #else @@ -646,8 +647,8 @@ } // Round up the requested size, plus header, to the next allocation alignment. - uint32_t size = static_cast<uint32_t>(req_size + sizeof(BlockHeader)); - size = base::bits::AlignUp(size, kAllocAlignment); + uint32_t size = checked_cast<uint32_t>(req_size + sizeof(BlockHeader)); + size = bits::AlignUp(size, kAllocAlignment); if (size <= sizeof(BlockHeader) || size > mem_page_) { NOTREACHED(); return kReferenceNull;
diff --git a/base/numerics/checked_math_impl.h b/base/numerics/checked_math_impl.h index 00d48d4..bf607cc 100644 --- a/base/numerics/checked_math_impl.h +++ b/base/numerics/checked_math_impl.h
@@ -157,14 +157,15 @@ const UnsignedDst uy = SafeUnsignedAbs(y); const UnsignedDst uresult = static_cast<UnsignedDst>(ux * uy); const bool is_negative = - std::is_signed<T>::value && static_cast<SignedDst>(x ^ y) < 0; + std::is_signed<T>::value && x && y && static_cast<SignedDst>(x ^ y) < 0; // We have a fast out for unsigned identity or zero on the second operand. // After that it's an unsigned overflow check on the absolute value, with // a +1 bound for a negative result. if (uy > UnsignedDst(!std::is_signed<T>::value || is_negative) && ux > (std::numeric_limits<T>::max() + UnsignedDst(is_negative)) / uy) return false; - *result = is_negative ? 0 - uresult : uresult; + *result = is_negative ? static_cast<T>(-1) - static_cast<T>(uresult - 1) + : static_cast<T>(uresult); return true; } @@ -194,7 +195,10 @@ bool is_valid = true; if (CheckedMulFastOp<Promotion, Promotion>::is_supported) { // The fast op may be available with the promoted type. - is_valid = CheckedMulFastOp<Promotion, Promotion>::Do(x, y, &presult); + // The casts here are safe because of the "value in range" conditional + // above. + is_valid = CheckedMulFastOp<Promotion, Promotion>::Do( + static_cast<Promotion>(x), static_cast<Promotion>(y), &presult); } else if (IsIntegerArithmeticSafe<Promotion, T, U>::value) { presult = static_cast<Promotion>(x) * static_cast<Promotion>(y); } else {
diff --git a/base/numerics/clamped_math_impl.h b/base/numerics/clamped_math_impl.h index 061f8c4..7425764b 100644 --- a/base/numerics/clamped_math_impl.h +++ b/base/numerics/clamped_math_impl.h
@@ -57,8 +57,9 @@ // special case of numeric_limits<T>::min(), by evaluating the bit pattern as // a signed integer value. If it is the overflow case, we end up subtracting // one from the unsigned result, thus saturating to numeric_limits<T>::max(). - return static_cast<T>(SafeUnsignedAbs(value) - - IsValueNegative<T>(SafeUnsignedAbs(value))); + return static_cast<T>( + SafeUnsignedAbs(value) - + IsValueNegative<T>(static_cast<T>(SafeUnsignedAbs(value)))); } template <
diff --git a/base/numerics/safe_conversions.h b/base/numerics/safe_conversions.h index b11308db..5192f048 100644 --- a/base/numerics/safe_conversions.h +++ b/base/numerics/safe_conversions.h
@@ -120,21 +120,27 @@ template <typename T> struct SaturationDefaultLimits : public std::numeric_limits<T> { static constexpr T NaN() { - return std::numeric_limits<T>::has_quiet_NaN - ? std::numeric_limits<T>::quiet_NaN() - : T(); + if constexpr (std::numeric_limits<T>::has_quiet_NaN) { + return std::numeric_limits<T>::quiet_NaN(); + } else { + return T(); + } } using std::numeric_limits<T>::max; static constexpr T Overflow() { - return std::numeric_limits<T>::has_infinity - ? std::numeric_limits<T>::infinity() - : std::numeric_limits<T>::max(); + if constexpr (std::numeric_limits<T>::has_infinity) { + return std::numeric_limits<T>::infinity(); + } else { + return std::numeric_limits<T>::max(); + } } using std::numeric_limits<T>::lowest; static constexpr T Underflow() { - return std::numeric_limits<T>::has_infinity - ? std::numeric_limits<T>::infinity() * -1 - : std::numeric_limits<T>::lowest(); + if constexpr (std::numeric_limits<T>::has_infinity) { + return std::numeric_limits<T>::infinity() * -1; + } else { + return std::numeric_limits<T>::lowest(); + } } };
diff --git a/base/numerics/safe_conversions_impl.h b/base/numerics/safe_conversions_impl.h index 4910cc9..2a0970d 100644 --- a/base/numerics/safe_conversions_impl.h +++ b/base/numerics/safe_conversions_impl.h
@@ -71,8 +71,9 @@ static_assert(std::is_integral<T>::value, "Type must be integral"); using SignedT = typename std::make_signed<T>::type; using UnsignedT = typename std::make_unsigned<T>::type; - return static_cast<SignedT>( - (static_cast<UnsignedT>(x) ^ -SignedT(is_negative)) + is_negative); + return static_cast<SignedT>((static_cast<UnsignedT>(x) ^ + static_cast<UnsignedT>(-SignedT(is_negative))) + + is_negative); } // This performs a safe, absolute value via unsigned overflow. @@ -244,9 +245,10 @@ static constexpr T Adjust(T value) { static_assert(std::is_same<T, Dst>::value, ""); static_assert(kShift < DstLimits::digits, ""); - return static_cast<T>( - ConditionalNegate(SafeUnsignedAbs(value) & ~((T(1) << kShift) - T(1)), - IsValueNegative(value))); + using UnsignedDst = typename std::make_unsigned_t<T>; + return static_cast<T>(ConditionalNegate( + SafeUnsignedAbs(value) & ~((UnsignedDst{1} << kShift) - UnsignedDst{1}), + IsValueNegative(value))); } template <typename T,
diff --git a/build/fuchsia/linux_internal.sdk.sha1 b/build/fuchsia/linux_internal.sdk.sha1 index 8fd6b4e..7fa9f89 100644 --- a/build/fuchsia/linux_internal.sdk.sha1 +++ b/build/fuchsia/linux_internal.sdk.sha1
@@ -1 +1 @@ -8.20220527.1.1 +8.20220527.2.1
diff --git a/cc/layers/layer.cc b/cc/layers/layer.cc index 5000df2..aee80650 100644 --- a/cc/layers/layer.cc +++ b/cc/layers/layer.cc
@@ -52,7 +52,7 @@ LayerList children; gfx::Size bounds; unsigned bitfields; - SkColor background_color; + SkColor4f background_color; TouchActionRegion touch_action_region; ElementId element_id; void* rare_inputs; @@ -83,7 +83,7 @@ contents_opaque_for_text(false), is_drawable(false), double_sided(true), - background_color(0) {} + background_color(SkColors::kTransparent) {} Layer::Inputs::~Inputs() = default; @@ -526,7 +526,7 @@ layer_tree_host()->SetHasCopyRequest(true); } -void Layer::SetBackgroundColor(SkColor background_color) { +void Layer::SetBackgroundColor(SkColor4f background_color) { DCHECK(IsPropertyChangeAllowed()); auto& inputs = inputs_.Write(*this); if (inputs.background_color == background_color) @@ -536,9 +536,9 @@ SetNeedsCommit(); } -void Layer::SetSafeOpaqueBackgroundColor(SkColor background_color) { +void Layer::SetSafeOpaqueBackgroundColor(SkColor4f background_color) { DCHECK(IsPropertyChangeAllowed()); - SkColor opaque_color = SkColorSetA(background_color, SK_AlphaOPAQUE); + SkColor4f opaque_color = background_color.makeOpaque(); auto& inputs = EnsureLayerTreeInputs(); if (inputs.safe_opaque_background_color == opaque_color) return; @@ -546,39 +546,42 @@ SetNeedsPushProperties(); } -SkColor Layer::SafeOpaqueBackgroundColor(SkColor host_background_color) const { +SkColor4f Layer::SafeOpaqueBackgroundColor( + SkColor4f host_background_color) const { if (contents_opaque()) { if (!IsAttached() || !IsUsingLayerLists()) { // In layer tree mode, PropertyTreeBuilder should have calculated the safe // opaque background color and called SetSafeOpaqueBackgroundColor(). DCHECK(layer_tree_inputs()); - DCHECK_EQ(SkColorGetA(layer_tree_inputs()->safe_opaque_background_color), - SK_AlphaOPAQUE); + DCHECK(layer_tree_inputs()->safe_opaque_background_color.isOpaque()); return layer_tree_inputs()->safe_opaque_background_color; } // In layer list mode, the PropertyTreeBuilder algorithm doesn't apply // because it depends on the layer tree hierarchy. Instead we use // background_color() if it's not transparent, or layer_tree_host_'s // background_color(), with the alpha channel forced to be opaque. - SkColor color = background_color() == SK_ColorTRANSPARENT - ? host_background_color - : background_color(); - return SkColorSetA(color, SK_AlphaOPAQUE); + SkColor4f color = background_color() == SkColors::kTransparent + ? host_background_color + : background_color(); + return color.makeOpaque(); } - if (SkColorGetA(background_color()) == SK_AlphaOPAQUE) { + if (background_color().isOpaque()) { // The layer is not opaque while the background color is, meaning that the - // background color doesn't cover the whole layer. Use SK_ColorTRANSPARENT - // to avoid intrusive checkerboard where the layer is not covered by the - // background color. - return SK_ColorTRANSPARENT; + // background color doesn't cover the whole layer. Use + // SkColors::kTransparent to avoid intrusive checkerboard where the layer is + // not covered by the background color. + return SkColors::kTransparent; } return background_color(); } -SkColor Layer::SafeOpaqueBackgroundColor() const { - SkColor host_background_color = - IsAttached() ? layer_tree_host()->pending_commit_state()->background_color - : layer_tree_inputs()->safe_opaque_background_color; +SkColor4f Layer::SafeOpaqueBackgroundColor() const { + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + SkColor4f host_background_color = + IsAttached() + ? SkColor4f::FromColor( + layer_tree_host()->pending_commit_state()->background_color) + : layer_tree_inputs()->safe_opaque_background_color; return SafeOpaqueBackgroundColor(host_background_color); } @@ -1464,9 +1467,12 @@ const auto& inputs = inputs_.Read(*this); layer->SetElementId(inputs.element_id); layer->SetHasTransformNode(has_transform_node()); - layer->SetBackgroundColor(inputs.background_color); + // TODO(crbug/1308932): Remove toSkColor and FromColor and make all SkColor4f. + layer->SetBackgroundColor(inputs.background_color.toSkColor()); layer->SetSafeOpaqueBackgroundColor( - SafeOpaqueBackgroundColor(commit_state.background_color)); + SafeOpaqueBackgroundColor( + SkColor4f::FromColor(commit_state.background_color)) + .toSkColor()); layer->SetBounds(inputs.bounds); layer->SetTransformTreeIndex(transform_tree_index(property_trees)); layer->SetEffectTreeIndex(effect_tree_index(property_trees));
diff --git a/cc/layers/layer.h b/cc/layers/layer.h index c99407a..4cf7628 100644 --- a/cc/layers/layer.h +++ b/cc/layers/layer.h
@@ -171,15 +171,15 @@ // Set and get the background color for the layer. This color is not used by // basic Layers, but subclasses may make use of it. - virtual void SetBackgroundColor(SkColor background_color); - SkColor background_color() const { + virtual void SetBackgroundColor(SkColor4f background_color); + SkColor4f background_color() const { return inputs_.Read(*this).background_color; } // For layer tree mode only. In layer list mode, client doesn't need to set // it. Sets an opaque background color for the layer, to be used in place of // the background_color() if the layer says contents_opaque() is true. - void SetSafeOpaqueBackgroundColor(SkColor background_color); + void SetSafeOpaqueBackgroundColor(SkColor4f background_color); // Returns a background color with opaqueness equal to the value of // contents_opaque(). @@ -189,13 +189,14 @@ // from background_color() and the argument host_background_color. // Otherwise, it returns something non-opaque. It prefers to return the // background_color(), but if the background_color() is opaque (and this layer - // claims to not be), then SK_ColorTRANSPARENT is returned to avoid intrusive - // checkerboard where the layer is not covered by the background_color(). - SkColor SafeOpaqueBackgroundColor(SkColor host_background_color) const; + // claims to not be), then SkColors::kTransparent is returned to avoid + // intrusive checkerboard where the layer is not covered by the + // background_color(). + SkColor4f SafeOpaqueBackgroundColor(SkColor4f host_background_color) const; // Same as the one-argument version, except that host_background_color is // layer_tree_host()->pending_commit_state()->background_color. - SkColor SafeOpaqueBackgroundColor() const; + SkColor4f SafeOpaqueBackgroundColor() const; // For layer tree mode only. // Set and get the position of this layer, relative to its parent. This is @@ -999,7 +1000,7 @@ bool is_drawable : 1; bool double_sided : 1; - SkColor background_color; + SkColor4f background_color; TouchActionRegion touch_action_region; ElementId element_id; @@ -1053,7 +1054,7 @@ // surface that darws in a render pass. viz::SubtreeCaptureId subtree_capture_id; - SkColor safe_opaque_background_color = SK_ColorTRANSPARENT; + SkColor4f safe_opaque_background_color = SkColors::kTransparent; FilterOperations filters; FilterOperations backdrop_filters;
diff --git a/cc/layers/layer_unittest.cc b/cc/layers/layer_unittest.cc index cf9021d..112d869b 100644 --- a/cc/layers/layer_unittest.cc +++ b/cc/layers/layer_unittest.cc
@@ -1001,7 +1001,7 @@ // SetNeedsCommit to be called. EXPECT_SET_NEEDS_COMMIT( 1, test_layer->SetTransformOrigin(gfx::Point3F(1.23f, 4.56f, 0.f))); - EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetBackgroundColor(SK_ColorLTGRAY)); + EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetBackgroundColor(SkColors::kLtGray)); EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetMasksToBounds(true)); EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetClipRect(gfx::Rect(1, 2, 3, 4))); EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetRoundedCorner({1, 2, 3, 4})); @@ -1360,23 +1360,17 @@ for (int layer_opaque = 0; layer_opaque < 2; ++layer_opaque) { for (int host_opaque = 0; host_opaque < 2; ++host_opaque) { layer->SetContentsOpaque(!!contents_opaque); - layer->SetBackgroundColor(layer_opaque ? SK_ColorRED - : SK_ColorTRANSPARENT); + layer->SetBackgroundColor(layer_opaque ? SkColors::kRed + : SkColors::kTransparent); layer_tree_host->set_background_color( host_opaque ? SK_ColorRED : SK_ColorTRANSPARENT); layer_tree_host->property_trees()->set_needs_rebuild(true); layer_tree_host->BuildPropertyTreesForTesting(); - SkColor safe_color = layer->SafeOpaqueBackgroundColor(); - if (contents_opaque) { - EXPECT_EQ(SkColorGetA(safe_color), 255u) - << "Flags: " << contents_opaque << ", " << layer_opaque << ", " - << host_opaque << "\n"; - } else { - EXPECT_NE(SkColorGetA(safe_color), 255u) - << "Flags: " << contents_opaque << ", " << layer_opaque << ", " - << host_opaque << "\n"; - } + EXPECT_EQ(contents_opaque, + layer->SafeOpaqueBackgroundColor().isOpaque()) + << "Flags: " << contents_opaque << ", " << layer_opaque << ", " + << host_opaque << "\n"; } } }
diff --git a/cc/layers/picture_layer.cc b/cc/layers/picture_layer.cc index b922bb7dd..09d5f09 100644 --- a/cc/layers/picture_layer.cc +++ b/cc/layers/picture_layer.cc
@@ -125,7 +125,8 @@ gfx::Size layer_size = bounds(); auto& recording_source = recording_source_.Write(*this); - recording_source->SetBackgroundColor(SafeOpaqueBackgroundColor()); + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. + recording_source->SetBackgroundColor(SafeOpaqueBackgroundColor().toSkColor()); recording_source->SetRequiresClear( !contents_opaque() && !picture_layer_inputs_.client->FillsBoundsCompletely());
diff --git a/cc/layers/solid_color_layer.cc b/cc/layers/solid_color_layer.cc index adf0319e..8cc831e 100644 --- a/cc/layers/solid_color_layer.cc +++ b/cc/layers/solid_color_layer.cc
@@ -23,8 +23,8 @@ SolidColorLayer::~SolidColorLayer() = default; -void SolidColorLayer::SetBackgroundColor(SkColor color) { - SetContentsOpaque(SkColorGetA(color) == 255); +void SolidColorLayer::SetBackgroundColor(SkColor4f color) { + SetContentsOpaque(color.isOpaque()); Layer::SetBackgroundColor(color); }
diff --git a/cc/layers/solid_color_layer.h b/cc/layers/solid_color_layer.h index 77dabef..ea24db7 100644 --- a/cc/layers/solid_color_layer.h +++ b/cc/layers/solid_color_layer.h
@@ -25,7 +25,7 @@ std::unique_ptr<LayerImpl> CreateLayerImpl( LayerTreeImpl* tree_impl) const override; - void SetBackgroundColor(SkColor color) override; + void SetBackgroundColor(SkColor4f color) override; protected: SolidColorLayer();
diff --git a/cc/layers/solid_color_layer_impl_unittest.cc b/cc/layers/solid_color_layer_impl_unittest.cc index c921c64..bae4ed23 100644 --- a/cc/layers/solid_color_layer_impl_unittest.cc +++ b/cc/layers/solid_color_layer_impl_unittest.cc
@@ -184,7 +184,7 @@ UpdateDrawProperties(host.get()); EXPECT_FALSE(layer->contents_opaque()); - layer->SetBackgroundColor(SkColorSetARGB(255, 10, 20, 30)); + layer->SetBackgroundColor({0.2f, 0.3f, 0.4f, 1.0f}); EXPECT_TRUE(layer->contents_opaque()); auto& unsafe_state = host->GetUnsafeStateForCommit(); @@ -220,7 +220,7 @@ host->CommitComplete({base::TimeTicks(), base::TimeTicks::Now()}); EXPECT_TRUE(layer->contents_opaque()); - layer->SetBackgroundColor(SkColorSetARGB(254, 10, 20, 30)); + layer->SetBackgroundColor({0.2f, 0.3f, 0.4f, 0.9f}); EXPECT_FALSE(layer->contents_opaque()); completion_event_ptr = std::make_unique<CompletionEvent>(
diff --git a/cc/layers/surface_layer_unittest.cc b/cc/layers/surface_layer_unittest.cc index 2ba37517..e43ee7f 100644 --- a/cc/layers/surface_layer_unittest.cc +++ b/cc/layers/surface_layer_unittest.cc
@@ -138,7 +138,7 @@ layer->SetSurfaceId(primary_id, DeadlinePolicy::UseSpecifiedDeadline(2u)); layer->SetSurfaceId(primary_id, DeadlinePolicy::UseExistingDeadline()); layer->SetOldestAcceptableFallback(primary_id); - layer->SetBackgroundColor(SK_ColorBLUE); + layer->SetBackgroundColor(SkColors::kBlue); layer->SetStretchContentToFillBounds(true); EXPECT_TRUE( @@ -175,7 +175,7 @@ viz::LocalSurfaceId(2, base::UnguessableToken::Create())); layer->SetOldestAcceptableFallback(fallback_id); layer->SetSurfaceId(fallback_id, DeadlinePolicy::UseExistingDeadline()); - layer->SetBackgroundColor(SK_ColorGREEN); + layer->SetBackgroundColor(SkColors::kGreen); layer->SetStretchContentToFillBounds(false); // Verify that fallback surface id is not recorded on the layer tree host as
diff --git a/cc/layers/texture_layer_unittest.cc b/cc/layers/texture_layer_unittest.cc index 945dec206..3a8feeb 100644 --- a/cc/layers/texture_layer_unittest.cc +++ b/cc/layers/texture_layer_unittest.cc
@@ -1031,7 +1031,7 @@ solid_layer_ = SolidColorLayer::Create(); solid_layer_->SetBounds(gfx::Size(10, 10)); solid_layer_->SetIsDrawable(true); - solid_layer_->SetBackgroundColor(SK_ColorWHITE); + solid_layer_->SetBackgroundColor(SkColors::kWhite); root->AddChild(solid_layer_); parent_layer_ = Layer::Create(); @@ -1067,7 +1067,7 @@ resource_changed_ = true; texture_layer_->SetNeedsDisplay(); // Force a change to make sure we draw a frame. - solid_layer_->SetBackgroundColor(SK_ColorGRAY); + solid_layer_->SetBackgroundColor(SkColors::kGray); break; case 3: // Layer shouldn't have been updated. @@ -1383,7 +1383,7 @@ // A drawable layer so that frames always get drawn. solid_color_layer_ = SolidColorLayer::Create(); solid_color_layer_->SetIsDrawable(true); - solid_color_layer_->SetBackgroundColor(SK_ColorRED); + solid_color_layer_->SetBackgroundColor(SkColors::kRed); solid_color_layer_->SetBounds(gfx::Size(10, 10)); root_->AddChild(solid_color_layer_);
diff --git a/cc/test/layer_tree_pixel_test.cc b/cc/test/layer_tree_pixel_test.cc index 4e5dac3..ab975ed 100644 --- a/cc/test/layer_tree_pixel_test.cc +++ b/cc/test/layer_tree_pixel_test.cc
@@ -231,8 +231,9 @@ layer->SetHitTestable(true); layer->SetBounds(rect.size()); layer->SetPosition(gfx::PointF(rect.origin())); + // TODO(crbug/1308932): Remove FromColor and use just SkColor4f. layer->SetOffsetToTransformParent(gfx::Vector2dF(rect.OffsetFromOrigin())); - layer->SetBackgroundColor(color); + layer->SetBackgroundColor(SkColor4f::FromColor(color)); return layer; }
diff --git a/cc/trees/layer_tree_host_pixeltest_masks.cc b/cc/trees/layer_tree_host_pixeltest_masks.cc index 876586f..811f7f8f 100644 --- a/cc/trees/layer_tree_host_pixeltest_masks.cc +++ b/cc/trees/layer_tree_host_pixeltest_masks.cc
@@ -254,7 +254,7 @@ LayerList layers = layer_tree_host()->root_layer()->children(); DCHECK_EQ(3u, layers.size()); // Set background to red. - layers[0]->SetBackgroundColor(SK_ColorRED); + layers[0]->SetBackgroundColor(SkColors::kRed); // Remove the green layer. layers.erase(layers.begin() + 1); layer_tree_host()->root_layer()->SetChildLayerList(layers);
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index 57c7074b..97dc7ad5 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -8503,7 +8503,7 @@ // LayerTreeFrameSink was not released. We must receive the ack. EXPECT_TRUE(received_ack_); // Cause damage so that we draw and swap. - layer_tree_host()->root_layer()->SetBackgroundColor(SK_ColorGREEN); + layer_tree_host()->root_layer()->SetBackgroundColor(SkColors::kGreen); break; case 2: // LayerTreeFrameSink was released. The ack must be discarded. @@ -10023,7 +10023,7 @@ void AddLayerThatObscuresPictureLayer() { auto covering_layer = SolidColorLayer::Create(); covering_layer->SetBounds(gfx::Size(100, 100)); - covering_layer->SetBackgroundColor(SK_ColorRED); + covering_layer->SetBackgroundColor(SkColors::kRed); covering_layer->SetIsDrawable(true); layer_tree_host()->root_layer()->AddChild(covering_layer); added_obscuring_layer_ = true;
diff --git a/cc/trees/property_tree_builder.cc b/cc/trees/property_tree_builder.cc index 4cf9508..00eb3a8 100644 --- a/cc/trees/property_tree_builder.cc +++ b/cc/trees/property_tree_builder.cc
@@ -716,13 +716,15 @@ void SetSafeOpaqueBackgroundColor(const DataForRecursion& data_from_ancestor, Layer* layer, DataForRecursion* data_for_children) { - SkColor background_color = layer->background_color(); + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. + SkColor background_color = layer->background_color().toSkColor(); data_for_children->safe_opaque_background_color = SkColorGetA(background_color) == 255 ? background_color : data_from_ancestor.safe_opaque_background_color; + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. layer->SetSafeOpaqueBackgroundColor( - data_for_children->safe_opaque_background_color); + SkColor4f::FromColor(data_for_children->safe_opaque_background_color)); } void PropertyTreeBuilderContext::BuildPropertyTreesInternal(
diff --git a/chrome/VERSION b/chrome/VERSION index 0da2f65..40c76534 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=104 MINOR=0 -BUILD=5087 +BUILD=5088 PATCH=0
diff --git a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/TabSwitcherAndStartSurfaceLayoutTest.java b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/TabSwitcherAndStartSurfaceLayoutTest.java index aa6f45d..cb5ccaca 100644 --- a/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/TabSwitcherAndStartSurfaceLayoutTest.java +++ b/chrome/android/features/start_surface/javatests/src/org/chromium/chrome/features/start_surface/TabSwitcherAndStartSurfaceLayoutTest.java
@@ -1054,8 +1054,7 @@ @Override public void check(View view, NoMatchingViewException noMatchException) { if (noMatchException != null) throw noMatchException; - float tabListPadding = - TabUiThemeProvider.getTabGridCardMarginForDialogAnimation(view.getContext()); + float tabListPadding = TabUiThemeProvider.getTabGridCardMargin(view.getContext()); float messageCardMargin = TabUiThemeProvider.getMessageCardMarginDimension(view.getContext());
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogView.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogView.java index ee16a00..183b795 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogView.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogView.java
@@ -108,7 +108,7 @@ public TabGridDialogView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; - mTabGridCardPadding = TabUiThemeProvider.getTabGridCardMarginForDialogAnimation(mContext); + mTabGridCardPadding = TabUiThemeProvider.getTabGridCardMargin(mContext); mToolbarHeight = (int) mContext.getResources().getDimension(R.dimen.tab_group_toolbar_height); mBackgroundDrawableColor = @@ -727,7 +727,9 @@ mCurrentDialogAnimator.end(); } mCurrentDialogAnimator = mHideDialogAnimation; - mScrimCoordinator.hideScrim(true); + if (mScrimCoordinator.isShowingScrim()) { + mScrimCoordinator.hideScrim(true); + } mHideDialogAnimation.start(); }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java index f015eee..7d320ba 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinder.java
@@ -10,6 +10,7 @@ import android.graphics.Bitmap; import android.graphics.Matrix; import android.text.TextUtils; +import android.util.Size; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; @@ -26,6 +27,7 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Callback; +import org.chromium.chrome.browser.tab.TabUtils; import org.chromium.chrome.tab_ui.R; import org.chromium.components.browser_ui.widget.chips.ChipView; import org.chromium.ui.modelutil.PropertyKey; @@ -334,11 +336,15 @@ // Use placeholder drawable before the real thumbnail is available. thumbnail.setColorThumbnailPlaceHolder( model.get(TabProperties.IS_INCOGNITO), model.get(TabProperties.IS_SELECTED)); + Callback<Bitmap> callback = result -> { if (result != null) { if (TabUiFeatureUtilities.isTabletGridTabSwitcherPolishEnabled(view.getContext())) { // Adjust bitmap to thumbnail. - updateThumbnailMatrix(thumbnail, result, model); + final Size thumbnailSize = + TabUtils.deriveThumbnailSize(model.get(TabProperties.GRID_CARD_WIDTH), + model.get(TabProperties.GRID_CARD_HEIGHT), view.getContext()); + updateThumbnailMatrix(thumbnail, result, thumbnailSize); } else { thumbnail.setScaleType(ScaleType.FIT_CENTER); thumbnail.setAdjustViewBounds(true); @@ -354,15 +360,16 @@ } /** - * Update @{@link Matrix} of ImageView. Bitmap is scaled to larger of the two dimens, then top-center - * aligned. + * Update @{@link Matrix} of ImageView. Bitmap is scaled to larger of the two dimens, then + * top-center aligned. * @param thumbnail Destination image view @{@link TabGridThumbnailView}. * @param source Image bitmap to resize. - * @param model PropertyModel containing the destination properties. + * @param destinationSize Desired width and height for source. */ - private static void updateThumbnailMatrix(TabGridThumbnailView thumbnail, Bitmap source, PropertyModel model) { - int newWidth = model.get(TabProperties.GRID_CARD_WIDTH); - int newHeight = model.get(TabProperties.GRID_CARD_HEIGHT); + private static void updateThumbnailMatrix( + TabGridThumbnailView thumbnail, Bitmap source, Size destinationSize) { + int newWidth = destinationSize.getWidth(); + int newHeight = destinationSize.getHeight(); if (newWidth <= 0 || newHeight <= 0 || (newWidth == source.getWidth() && newHeight == source.getHeight())) { thumbnail.setScaleType(ScaleType.FIT_CENTER);
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java index dfda9ffa..57b15569 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java
@@ -32,8 +32,6 @@ import org.chromium.chrome.browser.tasks.pseudotab.PseudoTab; import org.chromium.chrome.browser.tasks.tab_management.TabProperties.UiType; import org.chromium.chrome.tab_ui.R; -import org.chromium.ui.base.DeviceFormFactor; -import org.chromium.ui.base.ViewUtils; import org.chromium.ui.modelutil.MVCListAdapter; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -317,31 +315,20 @@ private void updateThumbnailAndSpanCount() { updateThumbnailLocation(); - if (mMode == TabListMode.GRID && DeviceFormFactor.isNonMultiDisplayContextOnTablet(mContext) - && TabUiFeatureUtilities.isGridTabSwitcherEnabled(mContext)) { + if (mMode == TabListMode.GRID + && TabUiFeatureUtilities.isTabletGridTabSwitcherEnabled(mContext)) { // Determine and set span count final GridLayoutManager layoutManager = (GridLayoutManager) mRecyclerView.getLayoutManager(); mMediator.updateSpanCount(layoutManager, mContext.getResources().getConfiguration().orientation, mContext.getResources().getConfiguration().screenWidthDp); - - float expectedThumbnailAspectRatio = 1.f; - if (TabUiFeatureUtilities.isTabThumbnailAspectRatioNotOne()) { - expectedThumbnailAspectRatio = TabUtils.getTabThumbnailAspectRatio(mContext); - } - final int screenWidthPx = ViewUtils.dpToPx( - mContext, mContext.getResources().getConfiguration().screenWidthDp); - // Determine column width and account for margins on left and right. - int itemWidthPx = (screenWidthPx / layoutManager.getSpanCount()); - // Determine thumbnail height based on width and image aspect ratio. Add top title - // height and account for margins on top and bottom. - int itemHeightPx = ((int) ((itemWidthPx * 1f) / expectedThumbnailAspectRatio)) - + (int) mContext.getResources().getDimension( - R.dimen.tab_list_card_title_height); + // Determine grid card width and account for margins on left and right. + final int cardWidthPx = (layoutManager.getWidth() / layoutManager.getSpanCount()); + final int cardHeightPx = TabUtils.deriveGridCardHeight(cardWidthPx, mContext); for (int i = 0; i < mModel.size(); i++) { - mModel.get(i).model.set(TabProperties.GRID_CARD_WIDTH, itemWidthPx); - mModel.get(i).model.set(TabProperties.GRID_CARD_HEIGHT, itemHeightPx); + mModel.get(i).model.set(TabProperties.GRID_CARD_WIDTH, cardWidthPx); + mModel.get(i).model.set(TabProperties.GRID_CARD_HEIGHT, cardHeightPx); } } }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java index 638bd855..4e17de4 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherCoordinator.java
@@ -46,6 +46,7 @@ import org.chromium.chrome.tab_ui.R; import org.chromium.components.browser_ui.widget.MenuOrKeyboardActionController; import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator; +import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator.SystemUiScrimDelegate; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modelutil.LayoutViewBuilder; import org.chromium.ui.modelutil.PropertyModel; @@ -299,10 +300,12 @@ }); if (TabUiFeatureUtilities.isTabGroupsAndroidEnabled(activity)) { + ScrimCoordinator gridDialogScrimCoordinator = + shouldUseNewScrim() ? createScrimCoordinator() : scrimCoordinator; mTabGridDialogCoordinator = new TabGridDialogCoordinator(activity, tabModelSelector, tabContentManager, tabCreatorManager, mCoordinatorView, this, mMediator, this::getTabGridDialogAnimationSourceView, shareDelegateSupplier, - scrimCoordinator, rootView); + gridDialogScrimCoordinator, rootView); mMediator.setTabGridDialogController(mTabGridDialogCoordinator.getDialogController()); } else { mTabGridDialogCoordinator = null; @@ -356,6 +359,29 @@ mLifecycleDispatcher.register(this); } + /** + * Tablet Tab Switcher polish uses a scrim to show/hide tab switcher. + * Create a new scrim via a new scrim coordinator for tab group dialog. + * @return if tab switcher polish is enabled on tablets. + */ + private boolean shouldUseNewScrim() { + return TabUiFeatureUtilities.isTabletGridTabSwitcherPolishEnabled(mRootView.getContext()); + } + + private ScrimCoordinator createScrimCoordinator() { + ViewGroup coordinator = mActivity.findViewById(org.chromium.chrome.R.id.coordinator); + SystemUiScrimDelegate delegate = new SystemUiScrimDelegate() { + @Override + public void setStatusBarScrimFraction(float scrimFraction) {} + + @Override + public void setNavigationBarScrimFraction(float scrimFraction) {} + }; + return new ScrimCoordinator(mActivity, delegate, coordinator, + coordinator.getContext().getColor( + org.chromium.chrome.R.color.omnibox_focused_fading_background_color)); + } + @VisibleForTesting public static boolean hasAppendedMessagesForTesting() { return sAppendedMessagesForTesting;
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiThemeProvider.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiThemeProvider.java index 80a625a2..d145093 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiThemeProvider.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiThemeProvider.java
@@ -526,7 +526,7 @@ * @param context {@link Context} to retrieve dimension. * @return The margin between tab cards in float number. */ - public static float getTabGridCardMarginForDialogAnimation(Context context) { + public static float getTabGridCardMargin(Context context) { int[] attrs = {R.attr.tabGridMargin}; TypedArray ta = context.obtainStyledAttributes(getThemeOverlayStyleResourceId(), attrs);
diff --git a/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinderUnitTest.java b/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinderUnitTest.java index 198ad2c..3effed6 100644 --- a/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinderUnitTest.java +++ b/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabGridViewBinderUnitTest.java
@@ -4,14 +4,18 @@ package org.chromium.chrome.browser.tasks.tab_management; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.junit.Assert.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; import android.content.Context; import android.content.res.Resources; +import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Matrix; @@ -55,10 +59,14 @@ private TabGridThumbnailView mThumbnailView; @Captor private ArgumentCaptor<Callback<Bitmap>> mCallbackCaptor; + @Mock + private TypedArray mTypedArray; private PropertyModel mModel; private LayoutParams mLayoutParams; private Bitmap mBitmap; + private static final int RESOURCE_ID = 123; + private static final float RESOURCE_DIMEN = 10; @Before public void setUp() { @@ -73,6 +81,10 @@ when(mViewGroup.fastFindViewById(R.id.tab_thumbnail)).thenReturn(mThumbnailView); when(mViewGroup.getContext()).thenReturn(mContext); when(mContext.getResources()).thenReturn(mResources); + when(mContext.obtainStyledAttributes(eq(R.style.ThemeRefactorOverlay_Enabled_TabUi), any())) + .thenReturn(mTypedArray); + when(mTypedArray.getResourceId(anyInt(), anyInt())).thenReturn(RESOURCE_ID); + when(mResources.getDimension(anyInt())).thenReturn(RESOURCE_DIMEN); // Mock tablet. when(mResources.getInteger(org.chromium.ui.R.integer.min_screen_width_bucket)).thenReturn(3); @@ -89,14 +101,16 @@ @Test public void bindClosableTabWithCardWidth_updateCardAndThumbnail() { - // Update width - 200. - final int updatedWidth = 200; - mModel.set(TabProperties.GRID_CARD_WIDTH, updatedWidth); + // Update width. + // updatedBitmapWidth = updatedCardWidth - margins = 200 - 40 = 160. + // updatedBitmapHeight = INIT_HEIGHT - margins = 200 - 40 - 160. + final int updatedCardWidth = 200; + mModel.set(TabProperties.GRID_CARD_WIDTH, updatedCardWidth); TabGridViewBinder.bindClosableTab(mModel, mViewGroup, TabProperties.GRID_CARD_WIDTH); - verify(mViewGroup).setMinimumWidth(updatedWidth); + verify(mViewGroup).setMinimumWidth(updatedCardWidth); verify(mThumbnailView).setColorThumbnailPlaceHolder(false, true); - assertThat(mLayoutParams.width, equalTo(updatedWidth)); + assertThat(mLayoutParams.width, equalTo(updatedCardWidth)); verify(mFetcher).fetch(mCallbackCaptor.capture()); mCallbackCaptor.getValue().onResult(mBitmap); @@ -112,17 +126,19 @@ @Test public void bindClosableTabWithCardWidthWithPolishEnabled_updateCardAndThumbnail() { TabUiFeatureUtilities.setTabletGridTabSwitcherPolishEnabledForTesting(true); - // Update width. - final int updatedWidth = 200; - mModel.set(TabProperties.GRID_CARD_WIDTH, updatedWidth); + // Update card width. + // updatedBitmapWidth = updatedCardWidth - margins = 200 - 40 = 160. + // updatedBitmapHeight = INIT_HEIGHT - margins = 200 - 40 - 160. + final int updatedCardWidth = 200; + mModel.set(TabProperties.GRID_CARD_WIDTH, updatedCardWidth); // Call. TabGridViewBinder.bindClosableTab(mModel, mViewGroup, TabProperties.GRID_CARD_WIDTH); // Verify. - verify(mViewGroup).setMinimumWidth(updatedWidth); + verify(mViewGroup).setMinimumWidth(updatedCardWidth); verify(mThumbnailView).setColorThumbnailPlaceHolder(false, true); - assertThat(mLayoutParams.width, equalTo(updatedWidth)); + assertThat(mLayoutParams.width, equalTo(updatedCardWidth)); verify(mFetcher).fetch(mCallbackCaptor.capture()); // Pass bitmap to callback and verify thumbnail updated with image resize. @@ -136,9 +152,9 @@ verifyNoMoreInteractions(mThumbnailView); // Verify metrics scale + translate. - // Scale = updatedWidth / INIT_WIDTH = 200 / 100 = 2. - float expectedScale = 2.f; - // xTranslate = (destinationWidth - scaledWidth) /2 = (200 - (100*2))/2 = 0. + // Scale = updatedBitmapWidth / INIT_WIDTH = 160 / 100 = 1.6f. + float expectedScale = 1.6f; + // xTranslate = (updatedBitmapWidth - scaledWidth) /2 = (160 - (100*1.6))/2 = 0. float expectedXTrans = 0.f; assertImageMatrix(matrixCaptor, expectedScale, expectedXTrans); } @@ -149,17 +165,19 @@ LayoutParams thumbnailParams = new LayoutParams(INIT_WIDTH, INIT_HEIGHT); when(mThumbnailView.getLayoutParams()).thenReturn(thumbnailParams); - // Update height. - final int updatedHeight = 400; - mModel.set(TabProperties.GRID_CARD_HEIGHT, updatedHeight); + // Update card height = 400. + // updatedBitmapWidth = INIT_WIDTH - margins = 100 - 40 = 60. + // updatedBitmapHeight = updatedCardHeight - margins = 400 - 40 - 360. + final int updatedCardHeight = 400; + mModel.set(TabProperties.GRID_CARD_HEIGHT, updatedCardHeight); // Call. TabGridViewBinder.bindClosableTab(mModel, mViewGroup, TabProperties.GRID_CARD_HEIGHT); // Verify. - verify(mViewGroup).setMinimumHeight(updatedHeight); + verify(mViewGroup).setMinimumHeight(updatedCardHeight); verify(mThumbnailView).setColorThumbnailPlaceHolder(false, true); - assertThat(mLayoutParams.height, equalTo(updatedHeight)); + assertThat(mLayoutParams.height, equalTo(updatedCardHeight)); assertThat(thumbnailParams.height, equalTo(LayoutParams.MATCH_PARENT)); verify(mFetcher).fetch(mCallbackCaptor.capture()); @@ -175,10 +193,10 @@ verifyNoMoreInteractions(mThumbnailView); // Verify metrics scale + translate. - // Scale = updatedHeight / INIT_HEIGHT = 400 / 200 = 2. - float expectedScale = 2.f; - // xTranslate = (destinationWidth - scaledWidth) /2 = (100 - (100*2))/2 = -50. - float expectedXTrans = -50.f; + // Scale = updatedBitmapHeight / INIT_HEIGHT = 360 / 200 = 1.8f. + float expectedScale = 1.8f; + // xTranslate = (updatedBitmapWidth - scaledWidth) /2 = (60 - (100*1.8))/2 = -60. + float expectedXTrans = -60f; assertImageMatrix(matrixCaptor, expectedScale, expectedXTrans); }
diff --git a/chrome/android/java/res/layout/send_tab_to_self_feature_unavailable_prompt.xml b/chrome/android/java/res/layout/send_tab_to_self_feature_unavailable_prompt.xml index bfdfbb5..430122dc 100644 --- a/chrome/android/java/res/layout/send_tab_to_self_feature_unavailable_prompt.xml +++ b/chrome/android/java/res/layout/send_tab_to_self_feature_unavailable_prompt.xml
@@ -11,8 +11,7 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="@dimen/min_touch_target_size" - android:orientation="vertical" - android:paddingBottom="32dp"> + android:orientation="vertical"> <ImageView android:id="@+id/empty_state_image" @@ -40,7 +39,16 @@ android:paddingStart="30dp" android:paddingEnd="30dp" android:paddingTop="16dp" + android:paddingBottom="32dp" android:ellipsize="end" android:textAppearance="@style/TextAppearance.TextLarge.Secondary" android:text="@string/send_tab_to_self_when_signed_in_unavailable"/> + + <!-- TODO(crbug.com/1295204): Make this visible by default after launch. --> + <org.chromium.chrome.browser.share.send_tab_to_self.ManageAccountDevicesLinkView + android:id="@+id/manage_account_devices_link" + android:visibility="gone" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:paddingTop="16dp" /> </LinearLayout>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java index 5409bba9..d62686c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java
@@ -33,6 +33,7 @@ import org.chromium.chrome.browser.browsing_data.ClearBrowsingDataTabsFragment; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.history_clusters.HistoryClustersCoordinator; +import org.chromium.chrome.browser.history_clusters.QueryState; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; import org.chromium.chrome.browser.profiles.Profile; @@ -168,9 +169,10 @@ if (showHistoryClustersImmediately) { mContentView = mHistoryClustersCoordinator.getActivityContentView(); - if (!TextUtils.isEmpty(historyClustersQuery)) { - mHistoryClustersCoordinator.setQuery(historyClustersQuery); - } + QueryState queryState = TextUtils.isEmpty(historyClustersQuery) + ? QueryState.forQueryless() + : QueryState.forQuery(historyClustersQuery); + mHistoryClustersCoordinator.setQueryState(queryState); } else { mContentView = mSelectableListLayout; } @@ -330,7 +332,7 @@ return; } else if (mContentView == mSelectableListLayout && mHistoryClustersCoordinator != null) { mContentView = mHistoryClustersCoordinator.getActivityContentView(); - mHistoryClustersCoordinator.setQuery(""); + mHistoryClustersCoordinator.setQueryState(QueryState.forQueryless()); } else { mContentView = mSelectableListLayout; mContentManager.startLoadingItems();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/history/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/history/OWNERS index 0fa757c..491c149 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/history/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/history/OWNERS
@@ -1 +1,2 @@ twellington@chromium.org +pnoland@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS index c3497f2..aa5139c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "-chrome", "+chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiFeatureUtilities.java", + "+chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabUiThemeProvider.java", "+chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilities.java", "+chrome/android/java/src/org/chromium/chrome/browser/ActivityTabProvider.java", "+chrome/android/java/src/org/chromium/chrome/browser/ActivityUtils.java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUtils.java index 83e4070..1da254f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUtils.java
@@ -10,6 +10,7 @@ import android.content.res.Resources; import android.graphics.Point; import android.graphics.Rect; +import android.util.Size; import android.view.Display; import androidx.annotation.Nullable; @@ -21,6 +22,7 @@ import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.tab.state.CriticalPersistedTabData; import org.chromium.chrome.browser.tasks.tab_management.TabUiFeatureUtilities; +import org.chromium.chrome.browser.tasks.tab_management.TabUiThemeProvider; import org.chromium.components.browser_ui.site_settings.WebsitePreferenceBridge; import org.chromium.components.content_settings.ContentSettingValues; import org.chromium.components.content_settings.ContentSettingsType; @@ -176,4 +178,47 @@ float value = (float) TabUiFeatureUtilities.THUMBNAIL_ASPECT_RATIO.getValue(); return MathUtils.clamp(value, 0.5f, 2.0f); } + + /** + * Derive grid card height based on width, expected thumbnail aspect ratio and margins. + * @param cardWidthPx width of the card + * @param context to derive view margins + * @return computed card height. + */ + public static int deriveGridCardHeight(int cardWidthPx, Context context) { + int tabThumbnailHeight = (int) ((cardWidthPx - getThumbnailWidthDiff(context)) + / getTabThumbnailAspectRatio(context)); + int cardHeightPx = tabThumbnailHeight + getThumbnailHeightDiff(context); + return cardHeightPx; + } + + /** + * Derive thumbnail size based on parent card size. + * @param gridCardWidth width of parent card. + * @param gridCardHeight height of parent card. + * @param context to derive view margins. + * @return computed width and height of thumbnail. + */ + public static Size deriveThumbnailSize(int gridCardWidth, int gridCardHeight, Context context) { + int thumbnailWidth = gridCardWidth - getThumbnailWidthDiff(context); + int thumbnailHeight = gridCardHeight - getThumbnailHeightDiff(context); + return new Size(thumbnailWidth, thumbnailHeight); + } + + private static int getThumbnailHeightDiff(Context context) { + final int tabGridCardMargin = (int) TabUiThemeProvider.getTabGridCardMargin(context); + final int thumbnailMargin = (int) context.getResources().getDimension( + org.chromium.chrome.tab_ui.R.dimen.tab_grid_card_thumbnail_margin); + int heightMargins = (2 * tabGridCardMargin) + thumbnailMargin; + final int titleHeight = (int) context.getResources().getDimension( + org.chromium.chrome.tab_ui.R.dimen.tab_list_card_title_height); + return titleHeight + heightMargins; + } + + private static int getThumbnailWidthDiff(Context context) { + final int tabGridCardMargin = (int) TabUiThemeProvider.getTabGridCardMargin(context); + final int thumbnailMargin = (int) context.getResources().getDimension( + org.chromium.chrome.tab_ui.R.dimen.tab_grid_card_thumbnail_margin); + return 2 * (tabGridCardMargin + thumbnailMargin); + } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediatorTest.java index 5f422c7..2a398c1a 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediatorTest.java
@@ -239,8 +239,8 @@ } @Test - public void testStartSearch() { - mMediator.startSearch("pandas"); + public void testSetQueryState() { + mMediator.setQueryState(QueryState.forQuery("pandas")); assertEquals(mToolbarModel.get(HistoryClustersToolbarProperties.QUERY_STATE).getQuery(), "pandas"); }
diff --git a/chrome/browser/android/compositor/compositor_view.cc b/chrome/browser/android/compositor/compositor_view.cc index cb5e813..d820af8e 100644 --- a/chrome/browser/android/compositor/compositor_view.cc +++ b/chrome/browser/android/compositor/compositor_view.cc
@@ -86,7 +86,7 @@ compositor_.reset(content::Compositor::Create(this, window_android)); root_layer_->SetIsDrawable(true); - root_layer_->SetBackgroundColor(SK_ColorWHITE); + root_layer_->SetBackgroundColor(SkColors::kWhite); // It is safe to not keep a ref on the feature checker because it adds one // internally in CheckGpuFeatureAvailability and unrefs after the callback is @@ -234,7 +234,8 @@ void CompositorView::SetBackground(bool visible, SkColor color) { // TODO(crbug.com/770911): Set the background color on the compositor. - root_layer_->SetBackgroundColor(color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + root_layer_->SetBackgroundColor(SkColor4f::FromColor(color)); root_layer_->SetIsDrawable(visible); }
diff --git a/chrome/browser/android/compositor/layer/contextual_search_layer.cc b/chrome/browser/android/compositor/layer/contextual_search_layer.cc index 67f1d96d..b1c2d84 100644 --- a/chrome/browser/android/compositor/layer/contextual_search_layer.cc +++ b/chrome/browser/android/compositor/layer/contextual_search_layer.cc
@@ -169,9 +169,12 @@ // Apply a blend based on the ripple opacity. The resulting color will // be an interpolation between the background color of the Search Bar and // a lighter shade of the background color of the Ripple. - bar_banner_container_->SetBackgroundColor(color_utils::AlphaBlend( - kBarBannerRippleBackgroundColor, search_bar_background_color, - 0.25f * search_bar_banner_ripple_opacity)); + // TODO(crbug/1308932): Remove toSkColor and FromColor and make all + // SkColor4f. + bar_banner_container_->SetBackgroundColor( + SkColor4f::FromColor(color_utils::AlphaBlend( + kBarBannerRippleBackgroundColor, search_bar_background_color, + 0.25f * search_bar_banner_ripple_opacity))); // ----------------------------------------------------------------- // Bar Banner Ripple @@ -318,8 +321,9 @@ search_promo_container_->SetBounds(search_promo_size); search_promo_container_->SetPosition(gfx::PointF(0.f, next_section_top)); search_promo_container_->SetMasksToBounds(true); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. search_promo_container_->SetBackgroundColor( - search_promo_background_color); + SkColor4f::FromColor(search_promo_background_color)); // Search Promo if (search_promo_->parent() != search_promo_container_) @@ -706,7 +710,8 @@ touch_highlight_layer_(cc::SolidColorLayer::Create()) { // Search Bar Banner bar_banner_container_->SetIsDrawable(true); - bar_banner_container_->SetBackgroundColor(kSearchBarBackgroundColor); + bar_banner_container_->SetBackgroundColor( + SkColor4f::FromColor(kSearchBarBackgroundColor)); bar_banner_ripple_->SetIsDrawable(true); bar_banner_ripple_->SetFillCenter(true); bar_banner_text_->SetIsDrawable(true); @@ -721,7 +726,8 @@ // Search Opt Out Promo search_promo_container_->SetIsDrawable(true); - search_promo_container_->SetBackgroundColor(kSearchBackgroundColor); + search_promo_container_->SetBackgroundColor( + SkColor4f::FromColor(kSearchBackgroundColor)); search_promo_->SetIsDrawable(true); // Related Searches sections @@ -749,7 +755,8 @@ // Touch Highlight Layer touch_highlight_layer_->SetIsDrawable(true); - touch_highlight_layer_->SetBackgroundColor(kTouchHighlightColor); + touch_highlight_layer_->SetBackgroundColor( + SkColor4f::FromColor(kTouchHighlightColor)); } ContextualSearchLayer::~ContextualSearchLayer() {
diff --git a/chrome/browser/android/compositor/layer/overlay_panel_layer.cc b/chrome/browser/android/compositor/layer/overlay_panel_layer.cc index 0caf18e..16a1735 100644 --- a/chrome/browser/android/compositor/layer/overlay_panel_layer.cc +++ b/chrome/browser/android/compositor/layer/overlay_panel_layer.cc
@@ -175,7 +175,9 @@ bar_background_->SetBounds(background_size); bar_background_->SetPosition( gfx::PointF(0.f, bar_top_y + rounded_top_height)); - bar_background_->SetBackgroundColor(bar_background_color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + bar_background_->SetBackgroundColor( + SkColor4f::FromColor(bar_background_color)); // --------------------------------------------------------------------------- // Bar Text @@ -307,7 +309,8 @@ content_container_->SetPosition( gfx::PointF(0.f, content_offset_y)); content_container_->SetBounds(gfx::Size(panel_width, panel_height)); - content_container_->SetBackgroundColor(bar_background_color); + content_container_->SetBackgroundColor( + SkColor4f::FromColor(bar_background_color)); if (content_layer) { if (content_layer->parent() != content_container_) content_container_->AddChild(content_layer); @@ -349,7 +352,7 @@ bar_border_->SetBounds(bar_border_size); bar_border_->SetPosition( gfx::PointF(0.f, border_y)); - bar_border_->SetBackgroundColor(separator_line_color); + bar_border_->SetBackgroundColor(SkColor4f::FromColor(separator_line_color)); if (bar_border_->parent() != layer_) layer_->AddChild(bar_border_); } else if (bar_border_.get() && bar_border_->parent()) {
diff --git a/chrome/browser/android/compositor/layer/tab_layer.cc b/chrome/browser/android/compositor/layer/tab_layer.cc index e29ff62..e79b6d4 100644 --- a/chrome/browser/android/compositor/layer/tab_layer.cc +++ b/chrome/browser/android/compositor/layer/tab_layer.cc
@@ -346,8 +346,11 @@ front_border_inner_shadow_->SetBorder(border_inner_shadow_resource->Border( border_inner_shadow_size)); - side_padding_->SetBackgroundColor(default_background_color); - bottom_padding_->SetBackgroundColor(default_background_color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + side_padding_->SetBackgroundColor( + SkColor4f::FromColor(default_background_color)); + bottom_padding_->SetBackgroundColor( + SkColor4f::FromColor(default_background_color)); gfx::Rect rounded_descaled_content_area( base::ClampRound(descaled_local_content_area.x()),
diff --git a/chrome/browser/android/compositor/layer/toolbar_layer.cc b/chrome/browser/android/compositor/layer/toolbar_layer.cc index dfcda573..c444d8c 100644 --- a/chrome/browser/android/compositor/layer/toolbar_layer.cc +++ b/chrome/browser/android/compositor/layer/toolbar_layer.cc
@@ -58,7 +58,9 @@ toolbar_background_layer_->SetBounds(resource->toolbar_rect().size()); toolbar_background_layer_->SetPosition( gfx::PointF(resource->toolbar_rect().origin())); - toolbar_background_layer_->SetBackgroundColor(toolbar_background_color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + toolbar_background_layer_->SetBackgroundColor( + SkColor4f::FromColor(toolbar_background_color)); bool url_bar_visible = resource->location_bar_content_rect().width() != 0; url_bar_background_layer_->SetHideLayerAndSubtree(!url_bar_visible); @@ -145,8 +147,9 @@ progress_bar_background_layer_->SetBounds( gfx::Size(progress_bar_background_width, progress_bar_background_height)); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. progress_bar_background_layer_->SetBackgroundColor( - progress_bar_background_color); + SkColor4f::FromColor(progress_bar_background_color)); } bool is_progress_bar_visible = SkColorGetA(progress_bar_background_color); @@ -156,7 +159,9 @@ gfx::PointF(progress_bar_x, progress_bar_y)); progress_bar_layer_->SetBounds( gfx::Size(progress_bar_width, progress_bar_height)); - progress_bar_layer_->SetBackgroundColor(progress_bar_color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + progress_bar_layer_->SetBackgroundColor( + SkColor4f::FromColor(progress_bar_color)); } } @@ -202,7 +207,7 @@ } debug_layer_->SetIsDrawable(true); - debug_layer_->SetBackgroundColor(SK_ColorGREEN); + debug_layer_->SetBackgroundColor(SkColors::kGreen); debug_layer_->SetOpacity(0.5f); }
diff --git a/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.cc b/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.cc index 9b8f988b..5c026a6 100644 --- a/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.cc +++ b/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.cc
@@ -43,7 +43,7 @@ color_overlay_->SetIsDrawable(true); color_overlay_->SetOpacity(0.0f); - color_overlay_->SetBackgroundColor(SK_ColorBLACK); + color_overlay_->SetBackgroundColor(SkColors::kBlack); color_overlay_->SetPosition(gfx::PointF(0.f, 0.f)); layer()->AddChild(color_overlay_); }
diff --git a/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc b/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc index 9600bdf..267274e 100644 --- a/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc +++ b/chrome/browser/android/compositor/scene_layer/tab_strip_scene_layer.cc
@@ -51,7 +51,7 @@ scrollable_strip_layer_->AddChild(new_tab_button_); } - tab_strip_layer_->SetBackgroundColor(SK_ColorBLACK); + tab_strip_layer_->SetBackgroundColor(SkColors::kBlack); tab_strip_layer_->SetIsDrawable(true); tab_strip_layer_->AddChild(scrollable_strip_layer_); @@ -165,7 +165,8 @@ } scrim_layer_->SetIsDrawable(true); - scrim_layer_->SetBackgroundColor(color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + scrim_layer_->SetBackgroundColor(SkColor4f::FromColor(color)); scrim_layer_->SetBounds(gfx::Size(width, height)); scrim_layer_->SetPosition(gfx::PointF(x, y)); scrim_layer_->SetOpacity(alpha);
diff --git a/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer.cc b/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer.cc index 9c5f2a9..ec9ee07d 100644 --- a/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer.cc +++ b/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer.cc
@@ -17,6 +17,9 @@ constexpr base::TimeDelta kHandleDefaultAnrTime = base::Seconds(10); // Time to recover ANR in services. constexpr base::TimeDelta kHandleServiceAnrTime = base::Seconds(20); +// Time to recover ANR in broadcast queue. +// TODO(khmel): This might require to separate foreground/background queue. +constexpr base::TimeDelta kHandleBroadcastAnrTime = base::Seconds(10); } // namespace @@ -62,6 +65,9 @@ case mojom::AnrType::BACKGROUND_SERVICE: delta = kHandleServiceAnrTime; break; + case mojom::AnrType::BROADCAST: + delta = kHandleBroadcastAnrTime; + break; default: delta = kHandleDefaultAnrTime; }
diff --git a/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc b/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc index 66011948..c940cb2 100644 --- a/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc +++ b/chrome/browser/ash/arc/instance_throttle/arc_power_throttle_observer_unittest.cc
@@ -213,4 +213,29 @@ EXPECT_FALSE(observer.active()); } +TEST_F(ArcPowerThrottleObserverTest, Broadcast) { + ArcPowerThrottleObserver observer; + int call_count = 0; + int active_count = 0; + observer.StartObserving( + profile(), + base::BindRepeating(&TestCallback, &call_count, &active_count)); + + observer.OnPreAnr(mojom::AnrType::BROADCAST); + EXPECT_EQ(1, call_count); + EXPECT_EQ(1, active_count); + EXPECT_TRUE(observer.active()); + + task_environment().FastForwardBy(base::Milliseconds(9999)); + EXPECT_EQ(1, call_count); + EXPECT_EQ(1, active_count); + EXPECT_TRUE(observer.active()); + + // Only now the lock becomes inactive. + task_environment().FastForwardBy(base::Milliseconds(1)); + EXPECT_EQ(2, call_count); + EXPECT_EQ(1, active_count); + EXPECT_FALSE(observer.active()); +} + } // namespace arc
diff --git a/chrome/browser/ash/kerberos/kerberos_credentials_manager.cc b/chrome/browser/ash/kerberos/kerberos_credentials_manager.cc index 40bbee0..c88417ae 100644 --- a/chrome/browser/ash/kerberos/kerberos_credentials_manager.cc +++ b/chrome/browser/ash/kerberos/kerberos_credentials_manager.cc
@@ -316,15 +316,19 @@ principal_expander_ = std::make_unique<VariableExpander>(substitutions); // Connect to a signal that indicates when Kerberos files change. - KerberosClient::Get()->ConnectToKerberosFileChangedSignal( - base::BindRepeating(&KerberosCredentialsManager::OnKerberosFilesChanged, - weak_factory_.GetWeakPtr())); + kerberos_file_changed_signal_subscription_ = + KerberosClient::Get()->SubscribeToKerberosFileChangedSignal( + base::BindRepeating( + &KerberosCredentialsManager::OnKerberosFilesChanged, + weak_factory_.GetWeakPtr())); // Connect to a signal that indicates when a Kerberos ticket is about to // expire. - KerberosClient::Get()->ConnectToKerberosTicketExpiringSignal( - base::BindRepeating(&KerberosCredentialsManager::OnKerberosTicketExpiring, - weak_factory_.GetWeakPtr())); + kerberos_ticket_expiring_signal_subscription_ = + KerberosClient::Get()->SubscribeToKerberosTicketExpiringSignal( + base::BindRepeating( + &KerberosCredentialsManager::OnKerberosTicketExpiring, + weak_factory_.GetWeakPtr())); // Listen to pref changes. pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
diff --git a/chrome/browser/ash/kerberos/kerberos_credentials_manager.h b/chrome/browser/ash/kerberos/kerberos_credentials_manager.h index c33c7ca..a26bdb2f 100644 --- a/chrome/browser/ash/kerberos/kerberos_credentials_manager.h +++ b/chrome/browser/ash/kerberos/kerberos_credentials_manager.h
@@ -9,6 +9,7 @@ #include <vector> #include "base/callback.h" +#include "base/callback_list.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" @@ -275,6 +276,11 @@ // Observer for Kerberos-related prefs. std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; + // Subscriptions whose destruction will cancel the corresponding callbacks. + // The callbacks are used to listen to signals from KerberosClient. + base::CallbackListSubscription kerberos_file_changed_signal_subscription_; + base::CallbackListSubscription kerberos_ticket_expiring_signal_subscription_; + // Keeps track of accounts currently being added. std::vector<std::unique_ptr<KerberosAddAccountRunner>> add_account_runners_;
diff --git a/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.cc b/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.cc index 0a516524..065670d 100644 --- a/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.cc +++ b/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.cc
@@ -5,7 +5,6 @@ #include "chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h" #include <memory> -#include <utility> #include "base/memory/singleton.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager.h" @@ -16,46 +15,18 @@ namespace ash { -namespace { - -Profile* GetPrimaryProfileFromContext(content::BrowserContext* context) { - if (!user_manager::UserManager::IsInitialized()) - return nullptr; - // Get original profile, so it gets primary profile faster if context is - // incognito profile. - Profile* profile = Profile::FromBrowserContext(context)->GetOriginalProfile(); - if (!ProfileHelper::IsPrimaryProfile(profile)) { - const auto* primary_user = - user_manager::UserManager::Get()->GetPrimaryUser(); - if (!primary_user) - return nullptr; - // Get primary profile from primary user. Note that it only gets primary - // profile if it is fully created. - profile = ProfileHelper::Get()->GetProfileByUser(primary_user); - } - return profile; -} - -} // namespace - // static KerberosCredentialsManager* KerberosCredentialsManagerFactory::GetExisting( content::BrowserContext* context) { - Profile* const primary_profile = GetPrimaryProfileFromContext(context); - if (!primary_profile) - return nullptr; return static_cast<KerberosCredentialsManager*>( - GetInstance()->GetServiceForBrowserContext(primary_profile, false)); + GetInstance()->GetServiceForBrowserContext(context, /*create=*/false)); } // static KerberosCredentialsManager* KerberosCredentialsManagerFactory::Get( content::BrowserContext* context) { - Profile* const primary_profile = GetPrimaryProfileFromContext(context); - if (!primary_profile) - return nullptr; return static_cast<KerberosCredentialsManager*>( - GetInstance()->GetServiceForBrowserContext(primary_profile, true)); + GetInstance()->GetServiceForBrowserContext(context, /*create=*/true)); } // static @@ -66,9 +37,8 @@ KerberosCredentialsManagerFactory::KerberosCredentialsManagerFactory() : BrowserContextKeyedServiceFactory( - "KerberosCredentialsManager", - BrowserContextDependencyManager::GetInstance()), - service_instance_created_(false) {} + /*name=*/"KerberosCredentialsManager", + BrowserContextDependencyManager::GetInstance()) {} KerberosCredentialsManagerFactory::~KerberosCredentialsManagerFactory() = default; @@ -80,13 +50,13 @@ KeyedService* KerberosCredentialsManagerFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { - Profile* const profile = Profile::FromBrowserContext(context); - // Verify that UserManager is initialized before calling IsPrimaryProfile. if (!user_manager::UserManager::IsInitialized()) return nullptr; - // Verify that we create instance for a primary profile. + Profile* const profile = Profile::FromBrowserContext(context); + + // We only create a service instance for primary profiles. if (!ProfileHelper::IsPrimaryProfile(profile)) return nullptr; @@ -94,11 +64,6 @@ if (profile->AsTestingProfile()) return nullptr; - // Make sure one and only one instance is ever created. - if (service_instance_created_) - return nullptr; - service_instance_created_ = true; - PrefService* local_state = g_browser_process->local_state(); return new KerberosCredentialsManager(local_state, profile); }
diff --git a/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h b/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h index 565c42a..72b63f9 100644 --- a/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h +++ b/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h
@@ -18,56 +18,44 @@ class KerberosCredentialsManager; // Singleton that creates and owns one KerberosCredentialsManager instance -// associated with primary profile. Note that KerberosCredentialsManager holds -// non-owning pointer to primary profile, so its life-time depends on the -// life-time of the primary profile. +// associated with each primary profile. Note that each +// KerberosCredentialsManager holds a non-owned pointer to its respective +// primary profile, so its life-time depends on the life-time of that profile. +// Multiple primary profiles only happen in tests. class KerberosCredentialsManagerFactory : public BrowserContextKeyedServiceFactory { public: - // Get existing service instance associated with the primary profile. - // Note that the interface still expects the context in case primary profile - // creation is not finalized. It returns nullptr if primary profile doesn't - // exist or primary profile has changed. + // Gets the existing service instance associated with the given profile. + // Returns nullptr for non-primary profiles. static KerberosCredentialsManager* GetExisting( content::BrowserContext* context); - // Get existing service instance or create a service instance associated with - // the primary profile. - // Note that the interface still expects the context in case primary profile - // creation is not finalized. It returns nullptr if primary profile doesn't - // exist or primary profile has changed. + // Gets the existing service instance or creates a service instance associated + // with the given profile. Returns nullptr for non-primary profiles. static KerberosCredentialsManager* Get(content::BrowserContext* context); + // Gets a singleton instance of the factory. static KerberosCredentialsManagerFactory* GetInstance(); + // Disallow copy and assignment. + KerberosCredentialsManagerFactory(const KerberosCredentialsManagerFactory&) = + delete; + KerberosCredentialsManagerFactory& operator=( + const KerberosCredentialsManagerFactory&) = delete; + private: friend struct base::DefaultSingletonTraits<KerberosCredentialsManagerFactory>; KerberosCredentialsManagerFactory(); ~KerberosCredentialsManagerFactory() override; - // Not copyable. - KerberosCredentialsManagerFactory(const KerberosCredentialsManagerFactory&) = - delete; - KerberosCredentialsManagerFactory& operator=( - const KerberosCredentialsManagerFactory&) = delete; - + // BrowserContextKeyedServiceFactory overrides: ----------------------------- bool ServiceIsCreatedWithBrowserContext() const override; // Returns nullptr in case context is not a primary profile. Otherwise returns - // valid KerberosCredentialsManager. + // a valid KerberosCredentialsManager. KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; - - // This is workaround to make sure we create only one service (singleton) and - // prevent errors when two primary profiles are present (which normally - // shouldn't happen, except in tests). - // Additional reason to keep this workaround for now is that - // KerberosCredentialsManager cannot be restarted at the moment, because it's - // tightly coupled with KerberosClient singleton. - // Note that it is potential risk for multi-threaded initialization (which is - // not supported at the moment). - mutable bool service_instance_created_; }; } // namespace ash
diff --git a/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory_browsertest.cc b/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory_browsertest.cc index bb2aad6..c40fd15 100644 --- a/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory_browsertest.cc +++ b/chrome/browser/ash/kerberos/kerberos_credentials_manager_factory_browsertest.cc
@@ -44,11 +44,10 @@ ASSERT_NE(incognito_profile, profile); ASSERT_EQ(incognito_profile->GetOriginalProfile(), profile); - // Verify, that Get is not creating a new instance for incognito profile. + // Verify that Get returns nullptr for the incognito profile. KerberosCredentialsManager* manager = - KerberosCredentialsManagerFactory::GetExisting(profile); - ASSERT_TRUE(manager); - ASSERT_EQ(KerberosCredentialsManagerFactory::Get(incognito_profile), manager); + KerberosCredentialsManagerFactory::GetExisting(incognito_profile); + ASSERT_FALSE(manager); CloseBrowserSynchronously(incognito_browser); } @@ -61,14 +60,12 @@ Profile* const other_profile = ProfileHelper::GetSigninProfile(); ASSERT_NE(other_profile, profile); ASSERT_NE(other_profile->GetOriginalProfile(), profile); - ASSERT_TRUE(!ProfileHelper::IsPrimaryProfile(other_profile)); + ASSERT_FALSE(ProfileHelper::IsPrimaryProfile(other_profile)); - // Verify, that Get is not creating a new instance for other (non-primary) - // profile. + // Verify that Get returns nullptr for other (non-primary) profile. KerberosCredentialsManager* manager = - KerberosCredentialsManagerFactory::GetExisting(profile); - ASSERT_TRUE(manager); - ASSERT_EQ(KerberosCredentialsManagerFactory::Get(other_profile), manager); + KerberosCredentialsManagerFactory::GetExisting(other_profile); + ASSERT_FALSE(manager); } } // namespace ash
diff --git a/chrome/browser/ash/kerberos/kerberos_credentials_manager_test.cc b/chrome/browser/ash/kerberos/kerberos_credentials_manager_test.cc index 4c945604..cb30358 100644 --- a/chrome/browser/ash/kerberos/kerberos_credentials_manager_test.cc +++ b/chrome/browser/ash/kerberos/kerberos_credentials_manager_test.cc
@@ -138,7 +138,7 @@ explicit MockKerberosFilesHandler(base::RepeatingClosure get_kerberos_files) : KerberosFilesHandler(get_kerberos_files) {} - ~MockKerberosFilesHandler() = default; + ~MockKerberosFilesHandler() override = default; MOCK_METHOD(void, DeleteFiles, ()); };
diff --git a/chrome/browser/ash/lock_screen_apps/app_window_metrics_tracker.cc b/chrome/browser/ash/lock_screen_apps/app_window_metrics_tracker.cc index 41049a5..65f740d3 100644 --- a/chrome/browser/ash/lock_screen_apps/app_window_metrics_tracker.cc +++ b/chrome/browser/ash/lock_screen_apps/app_window_metrics_tracker.cc
@@ -137,7 +137,7 @@ void AppWindowMetricsTracker::RenderFrameCreated( content::RenderFrameHost* frame_host) { - if (frame_host->GetParent()) + if (frame_host->GetParentOrOuterDocument()) return; SetState(State::kWindowShown);
diff --git a/chrome/browser/ash/login/session/user_session_manager.cc b/chrome/browser/ash/login/session/user_session_manager.cc index 89152160..cb32bea 100644 --- a/chrome/browser/ash/login/session/user_session_manager.cc +++ b/chrome/browser/ash/login/session/user_session_manager.cc
@@ -1133,25 +1133,21 @@ } // Need to iterate over all users and their OAuth2 session state. - const user_manager::UserList& users = user_manager->GetLoggedInUsers(); - for (user_manager::UserList::const_iterator it = users.begin(); - it != users.end(); ++it) { - if (!(*it)->is_profile_created()) + for (const user_manager::User* user : user_manager->GetLoggedInUsers()) { + if (!user->is_profile_created()) continue; - Profile* user_profile = ProfileHelper::Get()->GetProfileByUserUnsafe(*it); - bool should_restore_session = pending_signin_restore_sessions_.find( - (*it)->GetAccountId().GetUserEmail()) != - pending_signin_restore_sessions_.end(); + Profile* user_profile = ProfileHelper::Get()->GetProfileByUser(user); + DCHECK(user_profile); OAuth2LoginManager* login_manager = OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile); if (login_manager->SessionRestoreIsRunning()) { // If we come online for the first time after successful offline login, // we need to kick off OAuth token verification process again. login_manager->ContinueSessionRestore(); - } else if (should_restore_session) { - pending_signin_restore_sessions_.erase( - (*it)->GetAccountId().GetUserEmail()); + } else if (pending_signin_restore_sessions_.erase( + user->GetAccountId().GetUserEmail()) > 0) { + // Restore it, if the account is contained in the pending set. RestoreAuthSessionImpl(user_profile, false /* has_auth_cookies */); } }
diff --git a/chrome/browser/ash/login/users/avatar/user_image_manager_browsertest.cc b/chrome/browser/ash/login/users/avatar/user_image_manager_browsertest.cc index fe8399f..3a7e8b37 100644 --- a/chrome/browser/ash/login/users/avatar/user_image_manager_browsertest.cc +++ b/chrome/browser/ash/login/users/avatar/user_image_manager_browsertest.cc
@@ -87,7 +87,7 @@ constexpr char kRandomTokenStrForTesting[] = "random-token-str-for-testing"; policy::CloudPolicyStore* GetStoreForUser(const user_manager::User* user) { - Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user); + Profile* profile = ProfileHelper::Get()->GetProfileByUser(user); if (!profile) { ADD_FAILURE(); return NULL; @@ -507,7 +507,7 @@ UserImageManagerImpl::IgnoreProfileDataDownloadDelayForTesting(); LoginUser(test_account_id1_); - UpdatePrimaryAccountInfo(ProfileHelper::Get()->GetProfileByUserUnsafe(user)); + UpdatePrimaryAccountInfo(ProfileHelper::Get()->GetProfileByUser(user)); run_loop_ = std::make_unique<base::RunLoop>(); UserImageManager* user_image_manager =
diff --git a/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc b/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc index 5936bf8b..3a990df9 100644 --- a/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc +++ b/chrome/browser/ash/login/users/avatar/user_image_manager_impl.cc
@@ -757,13 +757,17 @@ } signin::IdentityManager* UserImageManagerImpl::GetIdentityManager() { + const user_manager::User* user = GetUser(); + DCHECK(user && user->is_profile_created()); return IdentityManagerFactory::GetForProfile( - ProfileHelper::Get()->GetProfileByUserUnsafe(GetUser())); + ProfileHelper::Get()->GetProfileByUser(user)); } network::mojom::URLLoaderFactory* UserImageManagerImpl::GetURLLoaderFactory() { + const user_manager::User* user = GetUser(); + DCHECK(user && user->is_profile_created()); return ProfileHelper::Get() - ->GetProfileByUserUnsafe(GetUser()) + ->GetProfileByUser(user) ->GetDefaultStoragePartition() ->GetURLLoaderFactoryForBrowserProcess() .get();
diff --git a/chrome/browser/ash/smb_client/smb_service_factory.cc b/chrome/browser/ash/smb_client/smb_service_factory.cc index d8e95425..a21ebc27a 100644 --- a/chrome/browser/ash/smb_client/smb_service_factory.cc +++ b/chrome/browser/ash/smb_client/smb_service_factory.cc
@@ -35,12 +35,12 @@ SmbService* SmbServiceFactory::Get(content::BrowserContext* context) { return static_cast<SmbService*>( - GetInstance()->GetServiceForBrowserContext(context, true)); + GetInstance()->GetServiceForBrowserContext(context, /*create=*/true)); } SmbService* SmbServiceFactory::FindExisting(content::BrowserContext* context) { return static_cast<SmbService*>( - GetInstance()->GetServiceForBrowserContext(context, false)); + GetInstance()->GetServiceForBrowserContext(context, /*create=*/false)); } SmbServiceFactory* SmbServiceFactory::GetInstance() { @@ -49,7 +49,7 @@ SmbServiceFactory::SmbServiceFactory() : BrowserContextKeyedServiceFactory( - "SmbService", + /*name=*/"SmbService", BrowserContextDependencyManager::GetInstance()) { DependsOn(file_system_provider::ServiceFactory::GetInstance()); DependsOn(AuthPolicyCredentialsManagerFactory::GetInstance()); @@ -57,7 +57,7 @@ DependsOn(file_manager::VolumeManagerFactory::GetInstance()); } -SmbServiceFactory::~SmbServiceFactory() {} +SmbServiceFactory::~SmbServiceFactory() = default; bool SmbServiceFactory::ServiceIsCreatedWithBrowserContext() const { return true;
diff --git a/chrome/browser/background_fetch/background_fetch_permission_context.cc b/chrome/browser/background_fetch/background_fetch_permission_context.cc index 7f7a134..85b7da7 100644 --- a/chrome/browser/background_fetch/background_fetch_permission_context.cc +++ b/chrome/browser/background_fetch/background_fetch_permission_context.cc
@@ -73,7 +73,6 @@ } void BackgroundFetchPermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/background_fetch/background_fetch_permission_context.h b/chrome/browser/background_fetch/background_fetch_permission_context.h index 6fd37e8..f08029c 100644 --- a/chrome/browser/background_fetch/background_fetch_permission_context.h +++ b/chrome/browser/background_fetch/background_fetch_permission_context.h
@@ -35,7 +35,6 @@ const GURL& requesting_origin, const GURL& embedding_origin) const override; void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/background_sync/periodic_background_sync_permission_context.cc b/chrome/browser/background_sync/periodic_background_sync_permission_context.cc index 0e081501..4741cec1 100644 --- a/chrome/browser/background_sync/periodic_background_sync_permission_context.cc +++ b/chrome/browser/background_sync/periodic_background_sync_permission_context.cc
@@ -119,7 +119,6 @@ } void PeriodicBackgroundSyncPermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/background_sync/periodic_background_sync_permission_context.h b/chrome/browser/background_sync/periodic_background_sync_permission_context.h index f0e81d9..f6aaabe3 100644 --- a/chrome/browser/background_sync/periodic_background_sync_permission_context.h +++ b/chrome/browser/background_sync/periodic_background_sync_permission_context.h
@@ -58,7 +58,6 @@ const GURL& requesting_origin, const GURL& embedding_origin) const override; void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc index a79958c..86350fde 100644 --- a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc +++ b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc
@@ -133,12 +133,6 @@ // latter. requests_.clear(); active_fetchers_.clear(); - - // Need to delete |shared_data_decoder_| in the same IO thread in which it is - // used. This avoids the possibility of deleting it prior to decoding requests - // using it completing. - content::GetIOThreadTaskRunner({})->DeleteSoon( - FROM_HERE, std::move(shared_data_decoder_)); } void BitmapFetcherService::CancelRequest(int request_id) {
diff --git a/chrome/browser/browser_about_handler.cc b/chrome/browser/browser_about_handler.cc index 9e534ff..3285e42 100644 --- a/chrome/browser/browser_about_handler.cc +++ b/chrome/browser/browser_about_handler.cc
@@ -58,14 +58,14 @@ bool HandleNonNavigationAboutURL(const GURL& url) { const std::string spec(url.spec()); - if (base::LowerCaseEqualsASCII(spec, chrome::kChromeUIRestartURL)) { + if (base::EqualsCaseInsensitiveASCII(spec, chrome::kChromeUIRestartURL)) { // Call AttemptRestart after chrome::Navigate() completes to avoid access of // gtk objects after they are destroyed by BrowserWindowGtk::Close(). base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&chrome::AttemptRestart)); return true; } - if (base::LowerCaseEqualsASCII(spec, chrome::kChromeUIQuitURL)) { + if (base::EqualsCaseInsensitiveASCII(spec, chrome::kChromeUIQuitURL)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&chrome::AttemptExit)); return true;
diff --git a/chrome/browser/devtools/chrome_devtools_session.cc b/chrome/browser/devtools/chrome_devtools_session.cc index 3419683..8b1d5f8 100644 --- a/chrome/browser/devtools/chrome_devtools_session.cc +++ b/chrome/browser/devtools/chrome_devtools_session.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/devtools/chrome_devtools_session.h" #include <memory> +#include <type_traits> #include "base/metrics/histogram_functions.h" #include "base/metrics/metrics_hashes.h" #include "base/strings/string_number_conversions.h" @@ -25,25 +26,50 @@ #include "chrome/browser/devtools/protocol/window_manager_handler.h" #endif +namespace { + +template <typename Handler> +bool IsDomainAvailableToUntrustedClient() { + return std::disjunction_v<std::is_same<Handler, PageHandler>, + std::is_same<Handler, EmulationHandler>, + std::is_same<Handler, TargetHandler>>; +} + +} // namespace + ChromeDevToolsSession::ChromeDevToolsSession( content::DevToolsAgentHostClientChannel* channel) : dispatcher_(this), client_channel_(channel) { content::DevToolsAgentHost* agent_host = channel->GetAgentHost(); if (agent_host->GetWebContents() && agent_host->GetType() == content::DevToolsAgentHost::kTypePage) { - page_handler_ = std::make_unique<PageHandler>( - agent_host, agent_host->GetWebContents(), &dispatcher_); - security_handler_ = std::make_unique<SecurityHandler>( - agent_host->GetWebContents(), &dispatcher_); - if (channel->GetClient()->IsTrusted()) { + if (IsDomainAvailableToUntrustedClient<PageHandler>() || + channel->GetClient()->IsTrusted()) { + page_handler_ = std::make_unique<PageHandler>( + agent_host, agent_host->GetWebContents(), &dispatcher_); + } + if (IsDomainAvailableToUntrustedClient<SecurityHandler>() || + channel->GetClient()->IsTrusted()) { + security_handler_ = std::make_unique<SecurityHandler>( + agent_host->GetWebContents(), &dispatcher_); + } + if (IsDomainAvailableToUntrustedClient<CastHandler>() || + channel->GetClient()->IsTrusted()) { cast_handler_ = std::make_unique<CastHandler>( agent_host->GetWebContents(), &dispatcher_); } } - emulation_handler_ = - std::make_unique<EmulationHandler>(agent_host, &dispatcher_); - target_handler_ = std::make_unique<TargetHandler>(&dispatcher_); - if (channel->GetClient()->IsTrusted()) { + if (IsDomainAvailableToUntrustedClient<EmulationHandler>() || + channel->GetClient()->IsTrusted()) { + emulation_handler_ = + std::make_unique<EmulationHandler>(agent_host, &dispatcher_); + } + if (IsDomainAvailableToUntrustedClient<TargetHandler>() || + channel->GetClient()->IsTrusted()) { + target_handler_ = std::make_unique<TargetHandler>(&dispatcher_); + } + if (IsDomainAvailableToUntrustedClient<BrowserHandler>() || + channel->GetClient()->IsTrusted()) { browser_handler_ = std::make_unique<BrowserHandler>(&dispatcher_, agent_host->GetId()); }
diff --git a/chrome/browser/devtools/protocol/devtools_protocol_browsertest.cc b/chrome/browser/devtools/protocol/devtools_protocol_browsertest.cc index 18b4f89..efea2f6f 100644 --- a/chrome/browser/devtools/protocol/devtools_protocol_browsertest.cc +++ b/chrome/browser/devtools/protocol/devtools_protocol_browsertest.cc
@@ -572,6 +572,20 @@ EXPECT_EQ(static_cast<int>(manager->infobar_count()), 1); } +IN_PROC_BROWSER_TEST_F(DevToolsProtocolTest, UntrustedClient) { + std::unique_ptr<base::DictionaryValue> params(new base::DictionaryValue()); + SetIsTrusted(false); + Attach(); + EXPECT_FALSE( + SendCommand("HeapProfiler.enable", nullptr, true)); // Implemented in V8 + EXPECT_FALSE( + SendCommand("LayerTree.enable", nullptr, true)); // Implemented in blink + EXPECT_FALSE(SendCommand("Memory.prepareForLeakDetection", nullptr, + true)); // Implemented in content + EXPECT_FALSE( + SendCommand("Cast.enable", nullptr, true)); // Implemented in content +} + class NetworkResponseProtocolTest : public DevToolsProtocolTest { protected: base::Value::Dict FetchAndWaitForResponse(const GURL& url) {
diff --git a/chrome/browser/display_capture/display_capture_permission_context.cc b/chrome/browser/display_capture/display_capture_permission_context.cc index fe986fd4..874be95 100644 --- a/chrome/browser/display_capture/display_capture_permission_context.cc +++ b/chrome/browser/display_capture/display_capture_permission_context.cc
@@ -22,7 +22,6 @@ } void DisplayCapturePermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/display_capture/display_capture_permission_context.h b/chrome/browser/display_capture/display_capture_permission_context.h index 4a0a202..e8c0cbf2 100644 --- a/chrome/browser/display_capture/display_capture_permission_context.h +++ b/chrome/browser/display_capture/display_capture_permission_context.h
@@ -26,7 +26,6 @@ const GURL& embedding_origin) const override; void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc index 3f1f631..d0e08fd 100644 --- a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc +++ b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc
@@ -874,11 +874,14 @@ // ui::kColorAlertHighSeverity)); } -const gfx::ImageSkia* ContentAnalysisDialog::GetTopImage() const { - const bool use_dark = color_utils::IsDark( +bool ContentAnalysisDialog::ShouldUseDarkTopImage() const { + return color_utils::IsDark( contents_view_->GetColorProvider()->GetColor(ui::kColorDialogBackground)); +} + +const gfx::ImageSkia* ContentAnalysisDialog::GetTopImage() const { return ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( - GetTopImageId(use_dark)); + GetTopImageId(ShouldUseDarkTopImage())); } bool ContentAnalysisDialog::is_print_scan() const {
diff --git a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h index 530d2e28..28fe5e7 100644 --- a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h +++ b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h
@@ -146,6 +146,9 @@ // `dialog_state_`. ui::ColorId GetSideImageBackgroundColor() const; + // Returns true if should use dark version of top image. + bool ShouldUseDarkTopImage() const; + // Returns the appropriate top image depending on `dialog_state_`. const gfx::ImageSkia* GetTopImage() const;
diff --git a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog_browsertest.cc b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog_browsertest.cc index 3e83a6e..490a57c3 100644 --- a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog_browsertest.cc +++ b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog_browsertest.cc
@@ -390,7 +390,9 @@ // The top image is the pending one corresponding to the access point. const gfx::ImageSkia& actual_image = dialog->GetTopImageForTesting()->GetImage(); - int expected_image_id = IDR_UPLOAD_SCANNING; + const bool use_dark = dialog->ShouldUseDarkTopImage(); + int expected_image_id = + use_dark ? IDR_UPLOAD_SCANNING_DARK : IDR_UPLOAD_SCANNING; gfx::ImageSkia* expected_image = ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( expected_image_id); @@ -413,8 +415,11 @@ // point and scan type. const gfx::ImageSkia& actual_image = dialog->GetTopImageForTesting()->GetImage(); + const bool use_dark = dialog->ShouldUseDarkTopImage(); int expected_image_id = - success() ? IDR_UPLOAD_SUCCESS : IDR_UPLOAD_VIOLATION; + success() + ? (use_dark ? IDR_UPLOAD_SUCCESS_DARK : IDR_UPLOAD_SUCCESS) + : (use_dark ? IDR_UPLOAD_VIOLATION_DARK : IDR_UPLOAD_VIOLATION); gfx::ImageSkia* expected_image = ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( expected_image_id);
diff --git a/chrome/browser/geolocation/geolocation_permission_context_delegate.cc b/chrome/browser/geolocation/geolocation_permission_context_delegate.cc index c37e7db..91f3a27 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_delegate.cc +++ b/chrome/browser/geolocation/geolocation_permission_context_delegate.cc
@@ -21,7 +21,6 @@ default; bool GeolocationPermissionContextDelegate::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture, @@ -31,9 +30,9 @@ bool permission_set; bool new_permission; - if (extensions_context_.DecidePermission(web_contents, id, requesting_origin, - user_gesture, callback, - &permission_set, &new_permission)) { + if (extensions_context_.DecidePermission(id, requesting_origin, user_gesture, + callback, &permission_set, + &new_permission)) { DCHECK_EQ(!!*callback, permission_set); if (permission_set) { content::RenderFrameHost* const render_frame_host =
diff --git a/chrome/browser/geolocation/geolocation_permission_context_delegate.h b/chrome/browser/geolocation/geolocation_permission_context_delegate.h index 141bb54..58c8dc0e 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_delegate.h +++ b/chrome/browser/geolocation/geolocation_permission_context_delegate.h
@@ -34,7 +34,6 @@ // checks that it is only code from valid iframes. // It also adds special logic when called through an extension. bool DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture,
diff --git a/chrome/browser/geolocation/geolocation_permission_context_delegate_android.cc b/chrome/browser/geolocation/geolocation_permission_context_delegate_android.cc index 2aa82c4..c981c38 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_delegate_android.cc +++ b/chrome/browser/geolocation/geolocation_permission_context_delegate_android.cc
@@ -29,30 +29,34 @@ ~GeolocationPermissionContextDelegateAndroid() = default; bool GeolocationPermissionContextDelegateAndroid::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture, permissions::BrowserPermissionCallback* callback, permissions::GeolocationPermissionContext* context) { + content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( + id.render_process_id(), id.render_frame_id()); + DCHECK(rfh); + + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); + DCHECK(web_contents); + if (web_contents->GetDelegate() && web_contents->GetDelegate()->GetInstalledWebappGeolocationContext()) { - content::RenderFrameHost* const render_frame_host = - content::RenderFrameHost::FromID(id.render_process_id(), - id.render_frame_id()); InstalledWebappBridge::PermissionCallback permission_callback = base::BindOnce( &permissions::GeolocationPermissionContext::NotifyPermissionSet, context->GetWeakPtr(), id, requesting_origin, permissions::PermissionUtil::GetLastCommittedOriginAsURL( - render_frame_host->GetMainFrame()), + rfh->GetMainFrame()), std::move(*callback), false /* persist */); InstalledWebappBridge::DecidePermission(requesting_origin, std::move(permission_callback)); return true; } return GeolocationPermissionContextDelegate::DecidePermission( - web_contents, id, requesting_origin, user_gesture, callback, context); + id, requesting_origin, user_gesture, callback, context); } bool GeolocationPermissionContextDelegateAndroid::IsInteractable(
diff --git a/chrome/browser/geolocation/geolocation_permission_context_delegate_android.h b/chrome/browser/geolocation/geolocation_permission_context_delegate_android.h index 388f7c2..aa58ed0 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_delegate_android.h +++ b/chrome/browser/geolocation/geolocation_permission_context_delegate_android.h
@@ -22,7 +22,6 @@ // GeolocationPermissionContext::Delegate: bool DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture,
diff --git a/chrome/browser/geolocation/geolocation_permission_context_extensions.cc b/chrome/browser/geolocation/geolocation_permission_context_extensions.cc index 9960f28f..bcde340 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_extensions.cc +++ b/chrome/browser/geolocation/geolocation_permission_context_extensions.cc
@@ -49,7 +49,6 @@ } bool GeolocationPermissionContextExtensions::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& request_id, const GURL& requesting_frame, bool user_gesture, @@ -57,6 +56,13 @@ bool* permission_set, bool* new_permission) { #if BUILDFLAG(ENABLE_EXTENSIONS) + + content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( + request_id.render_process_id(), request_id.render_frame_id()); + + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); + GURL requesting_frame_origin = requesting_frame.DeprecatedGetOriginAsURL(); extensions::WebViewPermissionHelper* web_view_permission_helper =
diff --git a/chrome/browser/geolocation/geolocation_permission_context_extensions.h b/chrome/browser/geolocation/geolocation_permission_context_extensions.h index ce27ec8..b6677fa 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_extensions.h +++ b/chrome/browser/geolocation/geolocation_permission_context_extensions.h
@@ -38,8 +38,7 @@ // permission has been set to |new_permission|. Consumes |callback| if it // returns true while setting |permission_set| to false, otherwise |callback| // is not used. - bool DecidePermission(content::WebContents* web_contents, - const permissions::PermissionRequestID& request_id, + bool DecidePermission(const permissions::PermissionRequestID& request_id, const GURL& requesting_frame, bool user_gesture, base::OnceCallback<void(ContentSetting)>* callback,
diff --git a/chrome/browser/history_clusters/BUILD.gn b/chrome/browser/history_clusters/BUILD.gn index c5ecde1..3190539 100644 --- a/chrome/browser/history_clusters/BUILD.gn +++ b/chrome/browser/history_clusters/BUILD.gn
@@ -36,6 +36,7 @@ "java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersToolbar.java", "java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersToolbarProperties.java", "java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersViewBinder.java", + "java/src/org/chromium/chrome/browser/history_clusters/QueryState.java", ] deps = [
diff --git a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersCoordinator.java b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersCoordinator.java index 38a678f..3eba269 100644 --- a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersCoordinator.java +++ b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersCoordinator.java
@@ -20,7 +20,6 @@ import org.chromium.base.Function; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.browser.history_clusters.HistoryClustersItemProperties.ItemType; -import org.chromium.chrome.browser.history_clusters.HistoryClustersToolbarProperties.QueryState; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.tab.Tab; import org.chromium.components.browser_ui.widget.selectable_list.SelectableItemView; @@ -90,8 +89,8 @@ } } - public void setQuery(String query) { - mMediator.startSearch(query); + public void setQueryState(QueryState queryState) { + mMediator.setQueryState(queryState); } /** @@ -176,7 +175,7 @@ @Override public boolean onMenuItemClick(MenuItem menuItem) { if (menuItem.getItemId() == R.id.search_menu_id) { - mMediator.startSearch(""); + mMediator.setQueryState(QueryState.forQuery("")); return true; } return false;
diff --git a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediator.java b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediator.java index fb9fe5a..81873db 100644 --- a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediator.java +++ b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersMediator.java
@@ -25,7 +25,6 @@ import org.chromium.base.Promise; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.browser.history_clusters.HistoryClustersItemProperties.ItemType; -import org.chromium.chrome.browser.history_clusters.HistoryClustersToolbarProperties.QueryState; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.ui.favicon.FaviconUtils; import org.chromium.components.browser_ui.widget.RoundedIconGenerator; @@ -146,10 +145,15 @@ mCallbackController.destroy(); } - void startSearch(String query) { - mToolbarModel.set(HistoryClustersToolbarProperties.QUERY_STATE, QueryState.forQuery(query)); + void setQueryState(QueryState queryState) { + mToolbarModel.set(HistoryClustersToolbarProperties.QUERY_STATE, queryState); + if (!queryState.isSearching()) { + mModelList.clear(); + startQuery(""); + } } + @VisibleForTesting void startQuery(String query) { mPromise = mHistoryClustersBridge.queryClusters(query); mPromise.then(mCallbackController.makeCancelable(this::queryComplete)); @@ -195,10 +199,10 @@ private void queryComplete(HistoryClustersResult result) { boolean isQueryless = result.getQuery().isEmpty(); - if (isQueryless) { + if (isQueryless && !hasToggleItem()) { PropertyModel toggleModel = new PropertyModel(HistoryClustersItemProperties.ALL_KEYS); ListItem toggleItem = new ListItem(ItemType.TOGGLE, toggleModel); - mModelList.add(toggleItem); + mModelList.add(0, toggleItem); } for (HistoryCluster cluster : result.getClusters()) { @@ -211,7 +215,7 @@ mModelList.add(clusterItem); if (isQueryless) { clusterModel.set(HistoryClustersItemProperties.CLICK_HANDLER, - (v) -> startSearch(cluster.getLabel())); + (v) -> setQueryState(QueryState.forQuery(cluster.getLabel()))); clusterModel.set(HistoryClustersItemProperties.END_BUTTON_DRAWABLE, null); clusterModel.set(HistoryClustersItemProperties.LABEL, null); continue; @@ -267,6 +271,10 @@ } } + private boolean hasToggleItem() { + return mModelList.size() > 0 && mModelList.get(0).type == ItemType.TOGGLE; + } + @VisibleForTesting void hideCluster( HistoryCluster cluster, PropertyModel clusterModel, List<ListItem> itemsToHide) {
diff --git a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersToolbarProperties.java b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersToolbarProperties.java index 4354abe..fa5ebef 100644 --- a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersToolbarProperties.java +++ b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersToolbarProperties.java
@@ -4,38 +4,10 @@ package org.chromium.chrome.browser.history_clusters; -import androidx.annotation.NonNull; - import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel.WritableObjectPropertyKey; class HistoryClustersToolbarProperties { - static class QueryState { - private final String mQuery; - private final boolean mIsSearching; - - static QueryState forQuery(@NonNull String query) { - return new QueryState(query, true); - } - - static QueryState forQueryless() { - return new QueryState(null, false); - } - - private QueryState(String query, boolean isSearching) { - mQuery = query; - mIsSearching = isSearching; - } - - String getQuery() { - return mQuery; - } - - boolean isSearching() { - return mIsSearching; - } - } - static final WritableObjectPropertyKey<QueryState> QUERY_STATE = new WritableObjectPropertyKey<>("query state");
diff --git a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersViewBinder.java b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersViewBinder.java index bab2243..d0f44a8 100644 --- a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersViewBinder.java +++ b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/HistoryClustersViewBinder.java
@@ -7,7 +7,6 @@ import android.view.View; import android.view.View.OnClickListener; -import org.chromium.chrome.browser.history_clusters.HistoryClustersToolbarProperties.QueryState; import org.chromium.components.browser_ui.widget.selectable_list.SelectableListLayout; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel;
diff --git a/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/QueryState.java b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/QueryState.java new file mode 100644 index 0000000..12635f4f --- /dev/null +++ b/chrome/browser/history_clusters/java/src/org/chromium/chrome/browser/history_clusters/QueryState.java
@@ -0,0 +1,39 @@ +// Copyright 2022 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.history_clusters; + +import androidx.annotation.NonNull; + +/** + * Class representing the state of the search UI. There are two meaningful properties: whether a + * search is currently active and what that search is. Making these properties distinct lets us + * distinguish between a state where a search is active but no text is entered and one where no + * search is active. + */ +public class QueryState { + private final String mQuery; + private final boolean mIsSearching; + + public static QueryState forQuery(@NonNull String query) { + return new QueryState(query, true); + } + + public static QueryState forQueryless() { + return new QueryState(null, false); + } + + private QueryState(String query, boolean isSearching) { + mQuery = query; + mIsSearching = isSearching; + } + + String getQuery() { + return mQuery; + } + + boolean isSearching() { + return mIsSearching; + } +} \ No newline at end of file
diff --git a/chrome/browser/idle/idle_detection_permission_context.cc b/chrome/browser/idle/idle_detection_permission_context.cc index 193eba7..7764daa 100644 --- a/chrome/browser/idle/idle_detection_permission_context.cc +++ b/chrome/browser/idle/idle_detection_permission_context.cc
@@ -44,7 +44,6 @@ } void IdleDetectionPermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, @@ -58,6 +57,12 @@ // PermissionMenuModel::PermissionMenuModel which prevents users from manually // allowing the permission. if (browser_context()->IsOffTheRecord()) { + content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( + id.render_process_id(), id.render_frame_id()); + + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); + // Random number of seconds in the range [1.0, 2.0). double delay_seconds = 1.0 + 1.0 * base::RandDouble(); VisibilityTimerTabHelper::CreateForWebContents(web_contents); @@ -73,7 +78,7 @@ return; } - PermissionContextBase::DecidePermission(web_contents, id, requesting_origin, + PermissionContextBase::DecidePermission(id, requesting_origin, embedding_origin, user_gesture, std::move(callback)); }
diff --git a/chrome/browser/idle/idle_detection_permission_context.h b/chrome/browser/idle/idle_detection_permission_context.h index 4413422..ab9e08a 100644 --- a/chrome/browser/idle/idle_detection_permission_context.h +++ b/chrome/browser/idle/idle_detection_permission_context.h
@@ -28,7 +28,6 @@ bool allowed) override; bool IsRestrictedToSecureOrigins() const override; void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/idle/idle_detection_permission_context_unittest.cc b/chrome/browser/idle/idle_detection_permission_context_unittest.cc index 38eaa12..60cba843 100644 --- a/chrome/browser/idle/idle_detection_permission_context_unittest.cc +++ b/chrome/browser/idle/idle_detection_permission_context_unittest.cc
@@ -88,8 +88,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, base::DoNothing()); + permission_context.RequestPermission(id, url, true /* user_gesture */, + base::DoNothing()); // Should be blocked after 1-2 seconds, but the timer is reset whenever the // tab is not visible, so these 500ms never add up to >= 1 second. @@ -158,10 +158,10 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.RequestPermission( - web_contents(), id1, url, /*user_gesture=*/true, base::DoNothing()); - permission_context.RequestPermission( - web_contents(), id2, url, /*user_gesture=*/true, base::DoNothing()); + permission_context.RequestPermission(id1, url, /*user_gesture=*/true, + base::DoNothing()); + permission_context.RequestPermission(id2, url, /*user_gesture=*/true, + base::DoNothing()); EXPECT_EQ(0, permission_context.permission_set_count()); EXPECT_EQ(CONTENT_SETTING_ASK,
diff --git a/chrome/browser/lacros/policy_ui_lacros_browsertest.cc b/chrome/browser/lacros/policy_ui_lacros_browsertest.cc index ba64da5..4f29f8f 100644 --- a/chrome/browser/lacros/policy_ui_lacros_browsertest.cc +++ b/chrome/browser/lacros/policy_ui_lacros_browsertest.cc
@@ -77,7 +77,7 @@ return; } - const policies = statusSection.querySelectorAll('fieldset'); + const policies = getPolicyFieldsets(); const statuses = {}; for (let i = 0; i < policies.length; ++i) { const legend = policies[i].querySelector('legend').textContent;
diff --git a/chrome/browser/media/webrtc/media_stream_device_permission_context.cc b/chrome/browser/media/webrtc/media_stream_device_permission_context.cc index 9c986266..2798adc 100644 --- a/chrome/browser/media/webrtc/media_stream_device_permission_context.cc +++ b/chrome/browser/media/webrtc/media_stream_device_permission_context.cc
@@ -39,18 +39,6 @@ MediaStreamDevicePermissionContext::~MediaStreamDevicePermissionContext() {} -void MediaStreamDevicePermissionContext::DecidePermission( - content::WebContents* web_contents, - const permissions::PermissionRequestID& id, - const GURL& requesting_origin, - const GURL& embedding_origin, - bool user_gesture, - permissions::BrowserPermissionCallback callback) { - permissions::PermissionContextBase::DecidePermission( - web_contents, id, requesting_origin, embedding_origin, user_gesture, - std::move(callback)); -} - ContentSetting MediaStreamDevicePermissionContext::GetPermissionStatusInternal( content::RenderFrameHost* render_frame_host, const GURL& requesting_origin,
diff --git a/chrome/browser/media/webrtc/media_stream_device_permission_context.h b/chrome/browser/media/webrtc/media_stream_device_permission_context.h index 293a4c8..ac8d83f 100644 --- a/chrome/browser/media/webrtc/media_stream_device_permission_context.h +++ b/chrome/browser/media/webrtc/media_stream_device_permission_context.h
@@ -22,15 +22,6 @@ ~MediaStreamDevicePermissionContext() override; - // PermissionContextBase: - void DecidePermission( - content::WebContents* web_contents, - const permissions::PermissionRequestID& id, - const GURL& requesting_origin, - const GURL& embedding_origin, - bool user_gesture, - permissions::BrowserPermissionCallback callback) override; - // TODO(xhwang): GURL.DeprecatedGetOriginAsURL() shouldn't be used as the // origin. Need to refactor to use url::Origin. crbug.com/527149 is filed for // this.
diff --git a/chrome/browser/media_galleries/media_galleries_test_util.cc b/chrome/browser/media_galleries/media_galleries_test_util.cc index d3ceadc..e4ed0907 100644 --- a/chrome/browser/media_galleries/media_galleries_test_util.cc +++ b/chrome/browser/media_galleries/media_galleries_test_util.cc
@@ -31,7 +31,6 @@ #if BUILDFLAG(IS_MAC) #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" -#include "components/policy/core/common/preferences_mock_mac.h" #endif // BUILDFLAG(IS_MAC) #if BUILDFLAG(IS_WIN) @@ -152,10 +151,6 @@ ASSERT_TRUE(fake_dir_.CreateUniqueTempDir()); -#if BUILDFLAG(IS_MAC) - mac_preferences_ = std::make_unique<MockPreferences>(); -#endif // BUILDFLAG(IS_MAC) - ChangeMediaPathOverrides(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_ANDROID) }
diff --git a/chrome/browser/media_galleries/media_galleries_test_util.h b/chrome/browser/media_galleries/media_galleries_test_util.h index a9cf9814..cf6969d9 100644 --- a/chrome/browser/media_galleries/media_galleries_test_util.h +++ b/chrome/browser/media_galleries/media_galleries_test_util.h
@@ -28,10 +28,6 @@ class Profile; -#if BUILDFLAG(IS_MAC) -class MockPreferences; -#endif - scoped_refptr<extensions::Extension> AddMediaGalleriesApp( const std::string& name, const std::vector<std::string>& media_galleries_permissions, @@ -76,9 +72,6 @@ registry_util::RegistryOverrideManager registry_override_; #endif -#if BUILDFLAG(IS_MAC) - std::unique_ptr<MockPreferences> mac_preferences_; -#endif }; extern base::FilePath MakeMediaGalleriesTestingPath(const std::string& dir);
diff --git a/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc b/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc index 049da44..a08c502 100644 --- a/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc +++ b/chrome/browser/metrics/power/power_metrics_reporter_unittest.cc
@@ -237,7 +237,7 @@ const char* kScenarioSuffix = ".VideoCapture"; const std::vector<const char*> suffixes({"", kScenarioSuffix}); ExpectHistogramSamples(&histogram_tester_, suffixes, - {{"PerformanceMonitor.AverageCPU2.Total", 500}}); + {{"PerformanceMonitor.AverageCPU3.Total", 500}}); } #if BUILDFLAG(IS_MAC)
diff --git a/chrome/browser/metrics/power/power_metrics_unittest.cc b/chrome/browser/metrics/power/power_metrics_unittest.cc index dbf1537..b91678d 100644 --- a/chrome/browser/metrics/power/power_metrics_unittest.cc +++ b/chrome/browser/metrics/power/power_metrics_unittest.cc
@@ -64,9 +64,6 @@ ProcessMonitor::Metrics process_metrics; process_metrics.cpu_usage = 0.20; -#if BUILDFLAG(IS_WIN) - process_metrics.precise_cpu_usage = 0.30; -#endif #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_AIX) // Returns the number of average idle cpu wakeups per second since the last @@ -87,10 +84,7 @@ ReportAggregatedProcessMetricsHistograms(process_metrics, suffixes); ExpectHistogramSamples(&histogram_tester, suffixes, { - {"PerformanceMonitor.AverageCPU2.Total", 20}, -#if BUILDFLAG(IS_WIN) - {"PerformanceMonitor.AverageCPU3.Total", 30}, -#endif + {"PerformanceMonitor.AverageCPU3.Total", 20}, #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_AIX)
diff --git a/chrome/browser/metrics/power/process_metrics_recorder_util.cc b/chrome/browser/metrics/power/process_metrics_recorder_util.cc index 4d96df88..9a1348f 100644 --- a/chrome/browser/metrics/power/process_metrics_recorder_util.cc +++ b/chrome/browser/metrics/power/process_metrics_recorder_util.cc
@@ -31,15 +31,9 @@ void RecordProcessHistograms(const char* histogram_suffix, const ProcessMonitor::Metrics& metrics) { base::UmaHistogramCustomCounts( - base::StrCat({"PerformanceMonitor.AverageCPU2.", histogram_suffix}), + base::StrCat({"PerformanceMonitor.AverageCPU3.", histogram_suffix}), metrics.cpu_usage * kCPUUsageFactor, kCPUUsageHistogramMin, kCPUUsageHistogramMax, kCPUUsageHistogramBucketCount); -#if BUILDFLAG(IS_WIN) - base::UmaHistogramCustomCounts( - base::StrCat({"PerformanceMonitor.AverageCPU3.", histogram_suffix}), - metrics.precise_cpu_usage * kCPUUsageFactor, kCPUUsageHistogramMin, - kCPUUsageHistogramMax, kCPUUsageHistogramBucketCount); -#endif #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_AIX) base::UmaHistogramCounts10000(
diff --git a/chrome/browser/metrics/power/process_monitor.cc b/chrome/browser/metrics/power/process_monitor.cc index 6da28d11..465563e 100644 --- a/chrome/browser/metrics/power/process_monitor.cc +++ b/chrome/browser/metrics/power/process_monitor.cc
@@ -54,10 +54,12 @@ ProcessMonitor::Metrics SampleMetrics(base::ProcessMetrics& process_metrics) { ProcessMonitor::Metrics metrics; - metrics.cpu_usage = process_metrics.GetPlatformIndependentCPUUsage(); #if BUILDFLAG(IS_WIN) - metrics.precise_cpu_usage = process_metrics.GetPreciseCPUUsage(); + metrics.cpu_usage = process_metrics.GetPreciseCPUUsage(); +#else + metrics.cpu_usage = process_metrics.GetPlatformIndependentCPUUsage(); #endif + #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_AIX) metrics.idle_wakeups = process_metrics.GetIdleWakeupsPerSecond(); @@ -109,10 +111,6 @@ const ProcessMonitor::Metrics& rhs) { lhs.cpu_usage += rhs.cpu_usage; -#if BUILDFLAG(IS_WIN) - lhs.precise_cpu_usage += rhs.precise_cpu_usage; -#endif - #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_AIX) lhs.idle_wakeups += rhs.idle_wakeups;
diff --git a/chrome/browser/metrics/power/process_monitor.h b/chrome/browser/metrics/power/process_monitor.h index 76dc797..0c84f43b 100644 --- a/chrome/browser/metrics/power/process_monitor.h +++ b/chrome/browser/metrics/power/process_monitor.h
@@ -58,19 +58,6 @@ // can exceed 100% in multi-thread processes running on multi-core systems. double cpu_usage = 0.0; -#if BUILDFLAG(IS_WIN) - // The percentage of time spent executing, across all threads of the - // process, in the interval since the last time the metric was sampled. This - // can exceed 100% in multi-thread processes running on multi-core systems. - // - // Calculated using the more precise QueryProcessCycleTime. - // - // TODO(pmonette): Replace the regular version of |cpu_usage| with the - // precise one and remove the extra field once we've validated that the - // precise version is indeed better. - double precise_cpu_usage = 0.0; -#endif - #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_AIX) // Returns the number of average idle cpu wakeups per second since the last
diff --git a/chrome/browser/notifications/notification_permission_context.cc b/chrome/browser/notifications/notification_permission_context.cc index 500d78ae..a19f7698 100644 --- a/chrome/browser/notifications/notification_permission_context.cc +++ b/chrome/browser/notifications/notification_permission_context.cc
@@ -126,7 +126,6 @@ #endif void NotificationPermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, @@ -152,6 +151,12 @@ // PermissionMenuModel::PermissionMenuModel which prevents users from manually // allowing the permission. if (browser_context()->IsOffTheRecord()) { + content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( + id.render_process_id(), id.render_frame_id()); + + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); + // Random number of seconds in the range [1.0, 2.0). double delay_seconds = 1.0 + 1.0 * base::RandDouble(); VisibilityTimerTabHelper::CreateForWebContents(web_contents); @@ -185,7 +190,7 @@ #endif // BUILDFLAG(IS_ANDROID) permissions::PermissionContextBase::DecidePermission( - web_contents, id, requesting_origin, embedding_origin, user_gesture, + id, requesting_origin, embedding_origin, user_gesture, std::move(callback)); }
diff --git a/chrome/browser/notifications/notification_permission_context.h b/chrome/browser/notifications/notification_permission_context.h index afce47c..6df287f 100644 --- a/chrome/browser/notifications/notification_permission_context.h +++ b/chrome/browser/notifications/notification_permission_context.h
@@ -114,7 +114,6 @@ // PermissionContextBase implementation. void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/notifications/notification_permission_context_unittest.cc b/chrome/browser/notifications/notification_permission_context_unittest.cc index 6c5e7c9..21deb6a 100644 --- a/chrome/browser/notifications/notification_permission_context_unittest.cc +++ b/chrome/browser/notifications/notification_permission_context_unittest.cc
@@ -273,13 +273,14 @@ .content_setting); // Requesting permission for different origins should fail. - permissions::PermissionRequestID fake_id( - 0 /* render_process_id */, 0 /* render_frame_id */, + permissions::PermissionRequestID request_id( + web_contents()->GetMainFrame()->GetProcess()->GetID(), + web_contents()->GetMainFrame()->GetRoutingID(), permissions::PermissionRequestID::RequestLocalId()); ContentSetting result = CONTENT_SETTING_DEFAULT; - context.DecidePermission(web_contents(), fake_id, requesting_origin, - embedding_origin, true /* user_gesture */, + context.DecidePermission(request_id, requesting_origin, embedding_origin, + true /* user_gesture */, base::BindOnce(&StoreContentSetting, &result)); ASSERT_EQ(result, CONTENT_SETTING_BLOCK); @@ -355,8 +356,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, base::DoNothing()); + permission_context.RequestPermission(id, url, true /* user_gesture */, + base::DoNothing()); // Should be blocked after 1-2 seconds, but the timer is reset whenever the // tab is not visible, so these 500ms never add up to >= 1 second. @@ -427,10 +428,10 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.RequestPermission( - web_contents(), id1, url, true /* user_gesture */, base::DoNothing()); - permission_context.RequestPermission( - web_contents(), id2, url, true /* user_gesture */, base::DoNothing()); + permission_context.RequestPermission(id1, url, true /* user_gesture */, + base::DoNothing()); + permission_context.RequestPermission(id2, url, true /* user_gesture */, + base::DoNothing()); EXPECT_EQ(0, permission_context.permission_set_count()); EXPECT_EQ(CONTENT_SETTING_ASK,
diff --git a/chrome/browser/page_load_metrics/observers/prerender_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/prerender_page_load_metrics_observer_browsertest.cc index d84dd93..f16df1d 100644 --- a/chrome/browser/page_load_metrics/observers/prerender_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/prerender_page_load_metrics_observer_browsertest.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "build/build_config.h" + #include "base/containers/contains.h" #include "chrome/browser/page_load_metrics/integration_tests/metric_integration_test.h" #include "chrome/browser/prerender/prerender_utils.h" @@ -56,8 +58,14 @@ content::test::PrerenderTestHelper prerender_helper_; }; +// TODO(crbug.com/1329881): Re-enable this test +#if BUILDFLAG(IS_MAC) +#define MAYBE_Activate_SpeculationRule DISABLED_Activate_SpeculationRule +#else +#define MAYBE_Activate_SpeculationRule Activate_SpeculationRule +#endif IN_PROC_BROWSER_TEST_F(PrerenderPageLoadMetricsObserverBrowserTest, - Activate_SpeculationRule) { + MAYBE_Activate_SpeculationRule) { ASSERT_TRUE(embedded_test_server()->Start()); // Navigate to an initial page. @@ -185,8 +193,15 @@ PrerenderPageLoad::kTiming_ActivationToLargestContentfulPaintName)); } +// TODO(crbug.com/1329881): Re-enable this test +#if BUILDFLAG(IS_MAC) +#define MAYBE_Activate_Embedder_DirectURLInput \ + DISABLED_Activate_Embedder_DirectURLInput +#else +#define MAYBE_Activate_Embedder_DirectURLInput Activate_Embedder_DirectURLInput +#endif IN_PROC_BROWSER_TEST_F(PrerenderPageLoadMetricsObserverBrowserTest, - Activate_Embedder_DirectURLInput) { + MAYBE_Activate_Embedder_DirectURLInput) { ASSERT_TRUE(embedded_test_server()->Start()); GURL prerender_url = embedded_test_server()->GetURL("/title2.html"); @@ -329,8 +344,14 @@ EXPECT_FALSE(base::Contains(entries, prerender_url)); } +// TODO(crbug.com/1329881): Re-enable this test +#if BUILDFLAG(IS_MAC) +#define MAYBE_Redirection DISABLED_Redirection +#else +#define MAYBE_Redirection Redirection +#endif IN_PROC_BROWSER_TEST_F(PrerenderPageLoadMetricsObserverBrowserTest, - Redirection) { + MAYBE_Redirection) { ASSERT_TRUE(embedded_test_server()->Start()); // Navigate to an initial page.
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc index f7c46bc..8bbd9c0 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc +++ b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc
@@ -3480,7 +3480,7 @@ ASSERT_EQ(all_frames_value, main_frame_value); } -#if BUILDFLAG(IS_MAC) // crbug.com/1277391 +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS) // crbug.com/1277391 #define MAYBE_PageLCPAnimatedImage DISABLED_PageLCPAnimatedImage #else #define MAYBE_PageLCPAnimatedImage PageLCPAnimatedImage
diff --git a/chrome/browser/payments/payment_handler_permission_context_unittest.cc b/chrome/browser/payments/payment_handler_permission_context_unittest.cc index a159c99..c4f58ea 100644 --- a/chrome/browser/payments/payment_handler_permission_context_unittest.cc +++ b/chrome/browser/payments/payment_handler_permission_context_unittest.cc
@@ -87,7 +87,7 @@ web_contents()->GetMainFrame()->GetRoutingID(), permissions::PermissionRequestID::RequestLocalId()); permission_context.RequestPermission( - web_contents(), id, url, true, + id, url, true, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context)));
diff --git a/chrome/browser/performance_manager/policies/policy_features.cc b/chrome/browser/performance_manager/policies/policy_features.cc index f47e084..bbcafdf 100644 --- a/chrome/browser/performance_manager/policies/policy_features.cc +++ b/chrome/browser/performance_manager/policies/policy_features.cc
@@ -72,12 +72,12 @@ const base::FeatureParam<bool> kTrimArcVmOnFirstMemoryPressureAfterArcVmBoot = { &kTrimArcVmOnMemoryPressure, "TrimArcVmOnFirstMemoryPressureAfterArcVmBoot", - false}; + true}; const base::FeatureParam<bool> kOnlyDropCachesOnFirstMemoryPressureAfterArcVmBoot = { &kTrimArcVmOnMemoryPressure, - "OnlyDropCachesOnFirstMemoryPressureAfterArcVmBoot", false}; + "OnlyDropCachesOnFirstMemoryPressureAfterArcVmBoot", true}; const base::FeatureParam<int> kTrimArcVmMaxPagesPerIteration = { &kTrimArcVmOnMemoryPressure, "MaxPageLimit", arc::ArcSession::kNoPageLimit};
diff --git a/chrome/browser/permissions/permission_context_base_permissions_policy_unittest.cc b/chrome/browser/permissions/permission_context_base_permissions_policy_unittest.cc index 225b75a..5ffe078 100644 --- a/chrome/browser/permissions/permission_context_base_permissions_policy_unittest.cc +++ b/chrome/browser/permissions/permission_context_base_permissions_policy_unittest.cc
@@ -107,8 +107,7 @@ permissions::PermissionRequestID id( rfh, permission_request_id_generator_.GenerateNextId()); pcb->RequestPermission( - content::WebContents::FromRenderFrameHost(rfh), id, - rfh->GetLastCommittedURL(), /*user_gesture=*/true, + id, rfh->GetLastCommittedURL(), /*user_gesture=*/true, base::BindOnce(&PermissionContextBasePermissionsPolicyTest:: RequestPermissionForFrameFinished, base::Unretained(this)));
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js index 45697c7..5e30218 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/user_action_monitor.js
@@ -357,9 +357,11 @@ UserActionMonitor.instance; BridgeHelper.registerHandler( - BridgeTargets.USER_ACTION_MONITOR, BridgeActions.CREATE, + BridgeConstants.UserActionMonitor.TARGET, + BridgeConstants.UserActionMonitor.Action.CREATE, (actions) => new Promise(resolve => UserActionMonitor.create(actions, resolve))); BridgeHelper.registerHandler( - BridgeTargets.USER_ACTION_MONITOR, BridgeActions.DESTROY, + BridgeConstants.UserActionMonitor.TARGET, + BridgeConstants.UserActionMonitor.Action.DESTROY, () => UserActionMonitor.destroy());
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js index 0d04aa75..2663f9d 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/background_bridge.js
@@ -323,7 +323,8 @@ */ async create(actions) { return BridgeHelper.sendMessage( - BridgeTargets.USER_ACTION_MONITOR, BridgeActions.CREATE, actions); + BridgeConstants.UserActionMonitor.TARGET, + BridgeConstants.UserActionMonitor.Action.CREATE, actions); }, /** @@ -332,6 +333,7 @@ */ async destroy() { return BridgeHelper.sendMessage( - BridgeTargets.USER_ACTION_MONITOR, BridgeActions.DESTROY); + BridgeConstants.UserActionMonitor.TARGET, + BridgeConstants.UserActionMonitor.Action.DESTORY); }, };
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js b/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js index a020bb7..9f76ada 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/common/bridge_constants.js
@@ -17,7 +17,6 @@ LOG_STORE: 'LogStore', PANEL: 'Panel', PANEL_BACKGROUND: 'PanelBackground', - USER_ACTION_MONITOR: 'UserActionMonitor', }; /** * The class that a message is being sent to. @@ -101,6 +100,16 @@ SET_ENABLED: 'setEnabled', }, }, + + UserActionMonitor: { + /** @public {BridgeTarget} */ + TARGET: 'UserActionMonitor', + /** @enum {string} */ + Action: { + CREATE: 'create', + DESTROY: 'destroy', + }, + }, }; /** @@ -109,10 +118,8 @@ BridgeActions = { ADD_MENU_ITEM: 'addMenuItem', CLEAR_LOG: 'clearLog', - CREATE: 'create', CREATE_ALL_NODE_MENU_BACKGROUNDS: 'createAllNodeMenuBackgrounds', CREATE_NEW_I_SEARCH: 'createNewISearch', - DESTROY: 'destroy', DESTROY_I_SEARCH: 'destroyISearch', FOCUS_TAB: 'focusTab', GET_ACTIONS_FOR_CURRENT_NODE: 'getActionsForCurrentNode', @@ -138,6 +145,7 @@ * BridgeConstants.ChromeVoxState.Action | * BridgeConstants.CommandHandler.Action | * BridgeConstants.EventSourceState.Action | - * BridgeConstants.GestureCommandHandler.Action} + * BridgeConstants.GestureCommandHandler.Action | + * BridgeConstants.UserActionMonitor.Action} */ BridgeAction;
diff --git a/chrome/browser/resources/new_tab_page/background_manager.ts b/chrome/browser/resources/new_tab_page/background_manager.ts index f308550..109628e 100644 --- a/chrome/browser/resources/new_tab_page/background_manager.ts +++ b/chrome/browser/resources/new_tab_page/background_manager.ts
@@ -110,6 +110,9 @@ if (image.positionY) { url.searchParams.append('positionY', image.positionY); } + if (image.scrimDisplay) { + url.searchParams.append('scrimDisplay', image.scrimDisplay); + } if (url.href === this.url_) { return; }
diff --git a/chrome/browser/resources/new_tab_page/untrusted/background_image.html b/chrome/browser/resources/new_tab_page/untrusted/background_image.html index 34e2f43..7986c2d 100644 --- a/chrome/browser/resources/new_tab_page/untrusted/background_image.html +++ b/chrome/browser/resources/new_tab_page/untrusted/background_image.html
@@ -36,6 +36,7 @@ #gradient { background: radial-gradient(transparent 50%, black), linear-gradient(transparent, black); + display: $i18n{scrimDisplay}; opacity: .2; } </style>
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn b/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn index 8c8a04d..74aad8b 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn +++ b/chrome/browser/resources/settings/chromeos/personalization_page/BUILD.gn
@@ -51,6 +51,7 @@ ":wallpaper_browser_proxy", "..:deep_linking_behavior", "..:os_route", + "..:prefs_behavior", "..:route_observer_behavior", "../..:router", "../ambient_mode_page:ambient_mode_browser_proxy",
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/change_picture.js b/chrome/browser/resources/settings/chromeos/personalization_page/change_picture.js index 88c96db..a905526c 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/change_picture.js +++ b/chrome/browser/resources/settings/chromeos/personalization_page/change_picture.js
@@ -7,132 +7,161 @@ * 'settings-change-picture' is the settings subpage containing controls to * edit a ChromeOS user's picture. */ -import '//resources/cr_elements/chromeos/cr_picture/cr_picture_list.js'; -import '//resources/cr_elements/chromeos/cr_picture/cr_picture_pane.js'; +import 'chrome://resources/cr_elements/chromeos/cr_picture/cr_picture_list.js'; +import 'chrome://resources/cr_elements/chromeos/cr_picture/cr_picture_pane.js'; import '../../settings_shared_css.js'; -import {CrPicture} from '//resources/cr_elements/chromeos/cr_picture/cr_picture_types.js'; -import {convertImageSequenceToPng, isEncodedPngDataUrlAnimated} from '//resources/cr_elements/chromeos/cr_picture/png.js'; -import {assert, assertNotReached} from '//resources/js/assert.m.js'; -import {I18nBehavior} from '//resources/js/i18n_behavior.m.js'; -import {WebUIListenerBehavior} from '//resources/js/web_ui_listener_behavior.m.js'; -import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {CrPicture} from 'chrome://resources/cr_elements/chromeos/cr_picture/cr_picture_types.js'; +import {isEncodedPngDataUrlAnimated} from 'chrome://resources/cr_elements/chromeos/cr_picture/png.js'; import {getInstance as getAnnouncerInstance} from 'chrome://resources/cr_elements/cr_a11y_announcer/cr_a11y_announcer.js'; +import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; +import {I18nBehavior, I18nBehaviorInterface} from 'chrome://resources/js/i18n_behavior.m.js'; +import {WebUIListenerBehavior, WebUIListenerBehaviorInterface} from 'chrome://resources/js/web_ui_listener_behavior.m.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {loadTimeData} from '../../i18n_setup.js'; -import {Route, Router} from '../../router.js'; -import {DeepLinkingBehavior} from '../deep_linking_behavior.js'; +import {DeepLinkingBehavior, DeepLinkingBehaviorInterface} from '../deep_linking_behavior.js'; import {recordSettingChange} from '../metrics_recorder.js'; import {routes} from '../os_route.js'; -import {RouteObserverBehavior} from '../route_observer_behavior.js'; +import {RouteObserverBehavior, RouteObserverBehaviorInterface} from '../route_observer_behavior.js'; import {ChangePictureBrowserProxy, ChangePictureBrowserProxyImpl, DefaultImage} from './change_picture_browser_proxy.js'; -Polymer({ - _template: html`{__html_template__}`, - is: 'settings-change-picture', +/** + * @constructor + * @extends {PolymerElement} + * @implements {DeepLinkingBehaviorInterface} + * @implements {RouteObserverBehaviorInterface} + * @implements {I18nBehaviorInterface} + * @implements {WebUIListenerBehaviorInterface} + */ +const SettingsChangePictureElementBase = mixinBehaviors( + [ + DeepLinkingBehavior, RouteObserverBehavior, I18nBehavior, + WebUIListenerBehavior + ], + PolymerElement); - behaviors: [ - DeepLinkingBehavior, - RouteObserverBehavior, - I18nBehavior, - WebUIListenerBehavior, - ], +/** @polymer */ +class SettingsChangePictureElement extends SettingsChangePictureElementBase { + static get is() { + return 'settings-change-picture'; + } - properties: { - /** - * True if the user has a plugged-in webcam. - * @private {boolean} - */ - cameraPresent_: { - type: Boolean, - value: false, - }, + static get template() { + return html`{__html_template__}`; + } - /** - * The currently selected item. This property is bound to the iron-selector - * and never directly assigned. This may be undefined momentarily as - * the selection changes due to iron-selector implementation details. - * @private {?CrPicture.ImageElement} - */ - selectedItem_: { - type: Object, - value: null, - }, - - /** - * The current set of the default user images. - * @private {?Array<!DefaultImage>} - */ - currentDefaultImages_: { - type: Object, - value: null, - }, - - /** - * True when camera video mode is enabled. - * @private {boolean} - */ - cameraVideoModeEnabled_: { - type: Boolean, - value() { - return loadTimeData.getBoolean('changePictureVideoModeEnabled'); + static get properties() { + return { + /** + * True if the user has a plugged-in webcam. + * @private {boolean} + */ + cameraPresent_: { + type: Boolean, + value: false, }, - readOnly: true, - }, - /** - * Author info of the default image. - * @private {string} - */ - authorInfo_: String, + /** + * The currently selected item. This property is bound to the + * iron-selector and never directly assigned. This may be undefined + * momentarily as the selection changes due to iron-selector + * implementation details. + * @private {?CrPicture.ImageElement} + */ + selectedItem_: { + type: Object, + value: null, + }, - /** - * Website info of the default image. - * @private {string} - */ - websiteInfo_: String, + /** + * The current set of the default user images. + * @private {?Array<!DefaultImage>} + */ + currentDefaultImages_: { + type: Object, + value: null, + }, - /** @private */ - oldImageLabel_: String, + /** + * True when camera video mode is enabled. + * @private {boolean} + */ + cameraVideoModeEnabled_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('changePictureVideoModeEnabled'); + }, + readOnly: true, + }, - /** - * Used by DeepLinkingBehavior to focus this page's deep links. - * @type {!Set<!chromeos.settings.mojom.Setting>} - */ - supportedSettingIds: { - type: Object, - value: () => - new Set([chromeos.settings.mojom.Setting.kChangeDeviceAccountImage]), - }, - }, + /** + * Author info of the default image. + * @private {string} + */ + authorInfo_: String, - listeners: { - 'discard-image': 'onDiscardImage_', - 'image-activate': 'onImageActivate_', - 'focus-action': 'onFocusAction_', - 'photo-taken': 'onPhotoTaken_', - 'switch-mode': 'onSwitchMode_', - }, + /** + * Website info of the default image. + * @private {string} + */ + websiteInfo_: String, - /** @private {?ChangePictureBrowserProxy} */ - browserProxy_: null, + /** @private */ + oldImageLabel_: String, - /** @private {?CrPictureListElement} */ - pictureList_: null, + /** + * Used by DeepLinkingBehavior to focus this page's deep links. + * @type {!Set<!chromeos.settings.mojom.Setting>} + */ + supportedSettingIds: { + type: Object, + value: () => new Set( + [chromeos.settings.mojom.Setting.kChangeDeviceAccountImage]), + }, + }; + } - /** @private {boolean} */ - oldImagePending_: false, + constructor() { + super(); + + /** @private {!ChangePictureBrowserProxy} */ + this.browserProxy_ = ChangePictureBrowserProxyImpl.getInstance(); + + /** @private {?CrPictureListElement} */ + this.pictureList_ = null; + + /** @private {boolean} */ + this.oldImagePending_ = false; + } /** @override */ ready() { - this.browserProxy_ = ChangePictureBrowserProxyImpl.getInstance(); + super.ready(); + this.pictureList_ = /** @type {CrPictureListElement} */ (this.$.pictureList); - }, + + this.addEventListener('discard-image', this.onDiscardImage_); + this.addEventListener('image-activate', (e) => { + this.onImageActivate_( + /** @type {!CustomEvent<!CrPicture.ImageElement>} */ (e)); + }); + this.addEventListener('focus-action', this.onFocusAction_); + this.addEventListener('photo-taken', (e) => { + this.onPhotoTaken_( + /** @type {!CustomEvent<{photoDataUrl: string}>} */ (e)); + }); + this.addEventListener('switch-mode', (e) => { + this.onSwitchMode_(/** @type {!CustomEvent<boolean>} */ (e)); + }); + } /** @override */ - attached() { + connectedCallback() { + super.connectedCallback(); + this.addWebUIListener( 'default-images-changed', this.receiveDefaultImages_.bind(this)); this.addWebUIListener( @@ -146,7 +175,7 @@ 'profile-image-changed', this.receiveProfileImage_.bind(this)); this.addWebUIListener( 'camera-presence-changed', this.receiveCameraPresence_.bind(this)); - }, + } /** * Overridden from DeepLinkingBehavior. @@ -160,7 +189,7 @@ this.pictureList_.setFocus(); return false; - }, + } /** @protected */ @@ -174,7 +203,7 @@ // Ensure we deactivate the camera when we navigate away. this.selectedItem_ = null; } - }, + } /** * Handler for the 'default-images-changed' event. @@ -183,7 +212,7 @@ */ receiveDefaultImages_(info) { this.currentDefaultImages_ = info.current_default_images; - }, + } /** * Handler for the 'selected-image-changed' event. Is only called with @@ -193,7 +222,7 @@ */ receiveSelectedImage_(imageUrl) { this.pictureList_.setSelectedImageUrl(imageUrl); - }, + } /** * Handler for the 'old-image-changed' event. The Old image is any selected @@ -207,7 +236,7 @@ isEncodedPngDataUrlAnimated(imageUrl) ? 'oldVideo' : 'oldPhoto'); this.oldImagePending_ = false; this.pictureList_.setOldImageUrl(imageUrl); - }, + } /** * Handler for the 'preview-deprecated-image' event. @@ -223,7 +252,7 @@ imageInfo.author ? this.i18n('authorCreditText', imageInfo.author) : ''; this.websiteInfo_ = imageInfo.website; this.selectedItem_ = null; - }, + } /** * Whether the source info should be shown. @@ -234,7 +263,7 @@ */ shouldShowSourceInfo_(selectedItem, authorInfo, websiteInfo) { return !selectedItem && (authorInfo || websiteInfo); - }, + } /** * Handler for the 'profile-image-changed' event. @@ -244,7 +273,7 @@ */ receiveProfileImage_(imageUrl, selected) { this.pictureList_.setProfileImageUrl(imageUrl, selected); - }, + } /** * Handler for the 'camera-presence-changed' event. @@ -253,7 +282,7 @@ */ receiveCameraPresence_(cameraPresent) { this.cameraPresent_ = cameraPresent; - }, + } /** * Selects an image element. @@ -284,7 +313,7 @@ default: assertNotReached('Selected unknown image type'); } - }, + } /** * Handler for when an image is activated. @@ -293,12 +322,12 @@ */ onImageActivate_(event) { this.selectImage_(event.detail); - }, + } /** Focus the action button in the picture pane. */ onFocusAction_() { /** CrPicturePaneElement */ (this.$.picturePane).focusActionButton(); - }, + } /** * @param {!CustomEvent<{photoDataUrl: string}>} event @@ -311,7 +340,7 @@ this.pictureList_.setFocus(); getAnnouncerInstance().announce( loadTimeData.getString('photoCaptureAccessibleText')); - }, + } /** * @param {!CustomEvent<boolean>} event @@ -321,7 +350,7 @@ const videomode = event.detail; getAnnouncerInstance().announce(this.i18n( videomode ? 'videoModeAccessibleText' : 'photoModeAccessibleText')); - }, + } /** * Callback the iron-a11y-keys "keys-pressed" event bubbles up from the @@ -332,7 +361,7 @@ onCameraPaneKeysPressed_(event) { this.$.pictureList.focus(); this.$.pictureList.onKeysPressed(event); - }, + } /** @private */ onDiscardImage_() { @@ -343,8 +372,14 @@ this.pictureList_.setOldImageUrl(CrPicture.kDefaultImageUrl); // Revert to profile image as we don't know what last used default image is. this.browserProxy_.selectProfileImage(); - this.fire('iron-announce', {text: this.i18n('photoDiscardAccessibleText')}); - }, + + const event = new CustomEvent('iron-announce', { + bubbles: true, + composed: true, + detail: {text: this.i18n('photoDiscardAccessibleText')} + }); + this.dispatchEvent(event); + } /** * @param {CrPicture.ImageElement} selectedItem @@ -353,7 +388,7 @@ */ getImageSrc_(selectedItem) { return (selectedItem && selectedItem.dataset.url) || ''; - }, + } /** * @param {CrPicture.ImageElement} selectedItem @@ -363,5 +398,8 @@ getImageType_(selectedItem) { return (selectedItem && selectedItem.dataset.type) || CrPicture.SelectionTypes.NONE; - }, -}); + } +} + +customElements.define( + SettingsChangePictureElement.is, SettingsChangePictureElement);
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/change_picture_browser_proxy.js b/chrome/browser/resources/settings/chromeos/personalization_page/change_picture_browser_proxy.js index ca6a04da..fec2af1 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/change_picture_browser_proxy.js +++ b/chrome/browser/resources/settings/chromeos/personalization_page/change_picture_browser_proxy.js
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {addSingletonGetter} from 'chrome://resources/js/cr.m.js'; - /** * An object describing a default image. * @typedef {{ @@ -101,8 +99,17 @@ requestSelectedImage() { chrome.send('requestSelectedImage'); } + + /** @return {!ChangePictureBrowserProxy} */ + static getInstance() { + return instance || (instance = new ChangePictureBrowserProxyImpl()); + } + + /** @param {!ChangePictureBrowserProxy} obj */ + static setInstance(obj) { + instance = obj; + } } -// The singleton instance_ is replaced with a test version of this wrapper -// during testing. -addSingletonGetter(ChangePictureBrowserProxyImpl); +/** @type {?ChangePictureBrowserProxy} */ +let instance = null;
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/dark_mode_subpage.html b/chrome/browser/resources/settings/chromeos/personalization_page/dark_mode_subpage.html deleted file mode 100644 index 948becf..0000000 --- a/chrome/browser/resources/settings/chromeos/personalization_page/dark_mode_subpage.html +++ /dev/null
@@ -1,39 +0,0 @@ -<style include="settings-shared"></style> -<div id="darkModeEnablerDiv"> - <settings-toggle-button - id="darkModeToggleButton" - class="hr" - pref="{{prefs.ash.dark_mode.enabled}}" - label="[[getDarkModeOnOffLabel_(prefs.ash.dark_mode.enabled.value)]]" - deep-link-focus-id$="[[Setting.kDarkModeOnOff]]"> - </settings-toggle-button> -</div> -<div id="darkModeThemedDiv"> - <div class="settings-box"> - <div class="settings-box-text start" aria-hidden="true"> - <div id="darkModeThemedLabel" class="label"> - $i18n{darkModeThemedRadioGroupTitle} - </div> - <div id="darkModeThemedSubLabel" class="secondary label"> - $i18n{darkModeThemedRadioGroupDescription} - </div> - </div> - </div> - <div class="list-frame"> - <settings-radio-group id="darkModeThemedRadioGroup" - pref="{{prefs.ash.dark_mode.color_mode_themed}}" - group-aria-label="$i18n{darkModeThemedRadioGroupTitle}" - deep-link-focus-id$="[[Setting.kDarkModeThemed]]"> - <cr-radio-button id="darkModeThemedOn" - name="true" class="list-item underbar" - pref="[[prefs.ash.dark_mode.color_mode_themed]]" - label="$i18n{darkModeThemedOn}"> - </cr-radio-button> - <cr-radio-button id="darkModeThemedOff" - name="false" class="list-item" - pref="[[prefs.ash.dark_mode.color_mode_themed]]" - label="$i18n{darkModeThemedOff}"> - </cr-radio-button> - </settings-radio-group> - </div> -</div>
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/dark_mode_subpage.js b/chrome/browser/resources/settings/chromeos/personalization_page/dark_mode_subpage.js deleted file mode 100644 index c616bae..0000000 --- a/chrome/browser/resources/settings/chromeos/personalization_page/dark_mode_subpage.js +++ /dev/null
@@ -1,78 +0,0 @@ -// Copyright 2021 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. - -/** - * 'settings-dark-mode-subpage' is the setting subpage containing - * dark mode settings to switch between dark and light mode, theming, - * and a scheduler. - */ -import '../../controls/settings_radio_group.js'; -import '../../controls/settings_toggle_button.js'; -import '../../prefs/prefs.js'; -import '//resources/cr_elements/cr_radio_button/cr_radio_button.m.js'; - -import {I18nBehavior} from '//resources/js/i18n_behavior.m.js'; -import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; - -import {Route, Router} from '../../router.js'; -import {DeepLinkingBehavior} from '../deep_linking_behavior.js'; -import {routes} from '../os_route.js'; -import {PrefsBehavior} from '../prefs_behavior.js'; -import {RouteObserverBehavior} from '../route_observer_behavior.js'; - -Polymer({ - _template: html`{__html_template__}`, - is: 'settings-dark-mode-subpage', - - behaviors: [ - RouteObserverBehavior, - DeepLinkingBehavior, - I18nBehavior, - PrefsBehavior, - ], - - properties: { - /** Preferences state. */ - prefs: { - type: Object, - notify: true, - }, - - /** - * Used by DeepLinkingBehavior to focus this page's deep links. - * @type {!Set<!chromeos.settings.mojom.Setting>} - */ - supportedSettingIds: { - type: Object, - value: () => new Set([ - chromeos.settings.mojom.Setting.kDarkModeOnOff, - chromeos.settings.mojom.Setting.kDarkModeThemed - ]), - }, - - }, - - /** - * RouteObserverBehavior - * @param {!Route} route - * @param {!Route} oldRoute - * @protected - */ - currentRouteChanged(route, oldRoute) { - if (route !== routes.DARK_MODE) { - return; - } - this.attemptDeepLink(); - }, - - /** - * @return {string} - * @private - */ - getDarkModeOnOffLabel_() { - return this.i18n( - this.getPref('ash.dark_mode.enabled').value ? 'darkModeOn' : - 'darkModeOff'); - }, -});
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_hub_browser_proxy.js b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_hub_browser_proxy.js index b6ba0b98..6d575c9 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_hub_browser_proxy.js +++ b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_hub_browser_proxy.js
@@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -import {addSingletonGetter} from 'chrome://resources/js/cr.m.js'; -// clang-format on - /** @interface */ export class PersonalizationHubBrowserProxy { openPersonalizationHub() {} @@ -19,6 +15,17 @@ openPersonalizationHub() { chrome.send('openPersonalizationHub'); } + + /** @return {!PersonalizationHubBrowserProxy} */ + static getInstance() { + return instance || (instance = new PersonalizationHubBrowserProxyImpl()); + } + + /** @param {!PersonalizationHubBrowserProxy} obj */ + static setInstance(obj) { + instance = obj; + } } -addSingletonGetter(PersonalizationHubBrowserProxyImpl); +/** @type {?PersonalizationHubBrowserProxy} */ +let instance = null;
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js index 58937622..656f3129 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js +++ b/chrome/browser/resources/settings/chromeos/personalization_page/personalization_page.js
@@ -8,104 +8,118 @@ */ import '../ambient_mode_page/ambient_mode_page.js'; import '../ambient_mode_page/ambient_mode_photos_page.js'; -import '//resources/cr_elements/cr_link_row/cr_link_row.js'; +import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js'; import './change_picture.js'; import '../../settings_page/settings_animated_pages.js'; import '../../settings_page/settings_subpage.js'; import '../../settings_shared_css.js'; -import {I18nBehavior} from '//resources/js/i18n_behavior.m.js'; -import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {I18nBehavior, I18nBehaviorInterface} from 'chrome://resources/js/i18n_behavior.m.js'; +import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {loadTimeData} from '../../i18n_setup.js'; import {Route, Router} from '../../router.js'; -import {DeepLinkingBehavior} from '../deep_linking_behavior.js'; +import {DeepLinkingBehavior, DeepLinkingBehaviorInterface} from '../deep_linking_behavior.js'; import {routes} from '../os_route.js'; -import {RouteObserverBehavior} from '../route_observer_behavior.js'; +import {RouteObserverBehavior, RouteObserverBehaviorInterface} from '../route_observer_behavior.js'; import {PersonalizationHubBrowserProxy, PersonalizationHubBrowserProxyImpl} from './personalization_hub_browser_proxy.js'; import {WallpaperBrowserProxy, WallpaperBrowserProxyImpl} from './wallpaper_browser_proxy.js'; -Polymer({ - _template: html`{__html_template__}`, - is: 'settings-personalization-page', +/** + * @constructor + * @extends {PolymerElement} + * @implements {DeepLinkingBehaviorInterface} + * @implements {I18nBehaviorInterface} + * @implements {RouteObserverBehaviorInterface} + */ +const SettingsPersonalizationPageElementBase = mixinBehaviors( + [DeepLinkingBehavior, I18nBehavior, RouteObserverBehavior], PolymerElement); - behaviors: [ - DeepLinkingBehavior, - I18nBehavior, - RouteObserverBehavior, - ], +/** @polymer */ +class SettingsPersonalizationPageElement extends + SettingsPersonalizationPageElementBase { + static get is() { + return 'settings-personalization-page'; + } - properties: { - /** - * Preferences state. - */ - prefs: Object, + static get template() { + return html`{__html_template__}`; + } - /** @private */ - showWallpaperRow_: {type: Boolean, value: true}, + static get properties() { + return { + /** + * Preferences state. + */ + prefs: Object, - /** @private */ - isWallpaperPolicyControlled_: {type: Boolean, value: true}, + /** @private */ + showWallpaperRow_: {type: Boolean, value: true}, - /** @private */ - isAmbientModeEnabled_: { - type: Boolean, - value() { - return loadTimeData.getBoolean('isAmbientModeEnabled'); + /** @private */ + isWallpaperPolicyControlled_: {type: Boolean, value: true}, + + /** @private */ + isAmbientModeEnabled_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('isAmbientModeEnabled'); + }, + readOnly: true, }, - readOnly: true, - }, - /** @private */ - isPersonalizationHubEnabled_: { - type: Boolean, - value() { - return loadTimeData.getBoolean('isPersonalizationHubEnabled'); + /** @private */ + isPersonalizationHubEnabled_: { + type: Boolean, + value() { + return loadTimeData.getBoolean('isPersonalizationHubEnabled'); + }, + readOnly: true, }, - readOnly: true, - }, - /** @private {!Map<string, string>} */ - focusConfig_: { - type: Object, - value() { - const map = new Map(); - if (routes.CHANGE_PICTURE) { - map.set(routes.CHANGE_PICTURE.path, '#changePictureRow'); - } else if (routes.AMBIENT_MODE) { - map.set(routes.AMBIENT_MODE.path, '#ambientModeRow'); + /** @private {!Map<string, string>} */ + focusConfig_: { + type: Object, + value() { + const map = new Map(); + if (routes.CHANGE_PICTURE) { + map.set(routes.CHANGE_PICTURE.path, '#changePictureRow'); + } else if (routes.AMBIENT_MODE) { + map.set(routes.AMBIENT_MODE.path, '#ambientModeRow'); + } + + return map; } + }, - return map; - } - }, - - /** - * Used by DeepLinkingBehavior to focus this page's deep links. - * @type {!Set<!chromeos.settings.mojom.Setting>} - */ - supportedSettingIds: { - type: Object, - value: () => new Set([chromeos.settings.mojom.Setting.kOpenWallpaper]), - }, - }, - - /** @private {?PersonalizationHubBrowserProxy} */ - personalizationHubBrowserProxy_: null, - - /** @private {?WallpaperBrowserProxy} */ - wallpaperBrowserProxy_: null, + /** + * Used by DeepLinkingBehavior to focus this page's deep links. + * @type {!Set<!chromeos.settings.mojom.Setting>} + */ + supportedSettingIds: { + type: Object, + value: () => new Set([chromeos.settings.mojom.Setting.kOpenWallpaper]), + }, + }; + } /** @override */ - created() { + constructor() { + super(); + + /** @private {!WallpaperBrowserProxy} */ this.wallpaperBrowserProxy_ = WallpaperBrowserProxyImpl.getInstance(); + + /** @private {!PersonalizationHubBrowserProxy} */ this.personalizationHubBrowserProxy_ = PersonalizationHubBrowserProxyImpl.getInstance(); - }, + } /** @override */ ready() { + super.ready(); + this.wallpaperBrowserProxy_.isWallpaperSettingVisible().then( isWallpaperSettingVisible => { this.showWallpaperRow_ = isWallpaperSettingVisible; @@ -114,11 +128,11 @@ isPolicyControlled => { this.isWallpaperPolicyControlled_ = isPolicyControlled; }); - }, + } /** * @param {!Route} route - * @param {!Route} oldRoute + * @param {!Route=} oldRoute */ currentRouteChanged(route, oldRoute) { // Does not apply to this page. @@ -127,29 +141,29 @@ } this.attemptDeepLink(); - }, + } /** * @private */ openWallpaperManager_() { this.wallpaperBrowserProxy_.openWallpaperManager(); - }, + } /** @private */ openPersonalizationHub_() { this.personalizationHubBrowserProxy_.openPersonalizationHub(); - }, + } /** @private */ navigateToChangePicture_() { Router.getInstance().navigateTo(routes.CHANGE_PICTURE); - }, + } /** @private */ navigateToAmbientMode_() { Router.getInstance().navigateTo(routes.AMBIENT_MODE); - }, + } /** * @param {boolean} toggleValue @@ -159,5 +173,8 @@ getAmbientModeRowSubLabel_(toggleValue) { return this.i18n( toggleValue ? 'ambientModeEnabled' : 'ambientModeDisabled'); - }, -}); + } +} + +customElements.define( + SettingsPersonalizationPageElement.is, SettingsPersonalizationPageElement);
diff --git a/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_browser_proxy.js b/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_browser_proxy.js index 13ae634..1ec8321 100644 --- a/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_browser_proxy.js +++ b/chrome/browser/resources/settings/chromeos/personalization_page/wallpaper_browser_proxy.js
@@ -2,9 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -import {addSingletonGetter, sendWithPromise} from 'chrome://resources/js/cr.m.js'; -// clang-format on +import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; /** @interface */ export class WallpaperBrowserProxy { @@ -40,6 +38,17 @@ openWallpaperManager() { chrome.send('openWallpaperManager'); } + + /** @return {!WallpaperBrowserProxy} */ + static getInstance() { + return instance || (instance = new WallpaperBrowserProxyImpl()); + } + + /** @param {!WallpaperBrowserProxy} obj */ + static setInstance(obj) { + instance = obj; + } } -addSingletonGetter(WallpaperBrowserProxyImpl); +/** @type {?WallpaperBrowserProxy} */ +let instance = null;
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.html b/chrome/browser/resources/settings/languages_page/languages_page.html index 919f38f..6451fb0 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.html +++ b/chrome/browser/resources/settings/languages_page/languages_page.html
@@ -60,20 +60,11 @@ <settings-animated-pages id="pages" section="languages" focus-config="[[focusConfig_]]"> <div route-path="default"> - <template is="dom-if" if="[[enableDesktopRestructuredLanguageSettings_]]"> - <cr-link-row on-click="onLanguagesSubpageClick_" - id="languagesSubpageTrigger" - label="$i18n{languagesListTitle}" - role-description="$i18n{subpageArrowRoleDescription}"> - </cr-link-row> - </template> - <template is="dom-if" if="[[!enableDesktopRestructuredLanguageSettings_]]"> - <settings-languages-subpage - languages="{{languages}}" - prefs="{{prefs}}" - language-helper="{{languageHelper}}"> - </settings-languages-subpage> - </template> + <settings-languages-subpage + languages="{{languages}}" + prefs="{{prefs}}" + language-helper="{{languageHelper}}"> + </settings-languages-subpage> <settings-toggle-button id="enableSpellcheckingToggle" class="hr" @@ -185,17 +176,4 @@ </settings-subpage> </template> </if> <!-- not is_macosx --> - <template is="dom-if" route-path="/languageSettings" - no-search="[[!enableDesktopRestructuredLanguageSettings_]]"> - <settings-subpage - associated-control="[[$$('#languagesSubpageTrigger')]]" - page-title="$i18n{languagesListTitle}" - no-search="[[!enableDesktopRestructuredLanguageSettings_]]"> - <settings-languages-subpage - languages="{{languages}}" - prefs="{{prefs}}" - language-helper="{{languageHelper}}"> - </settings-languages-subpage> - </settings-subpage> - </template> </settings-animated-pages>
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.ts b/chrome/browser/resources/settings/languages_page/languages_page.ts index 07d852e..e171549 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.ts +++ b/chrome/browser/resources/settings/languages_page/languages_page.ts
@@ -42,7 +42,6 @@ import {DomRepeatEvent, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BaseMixin} from '../base_mixin.js'; -import {loadTimeData} from '../i18n_setup.js'; import {PrefsMixin, PrefsMixinInterface} from '../prefs/prefs_mixin.js'; import {routes} from '../route.js'; import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js'; @@ -104,18 +103,6 @@ */ detailLanguage_: Object, - enableDesktopRestructuredLanguageSettings_: { - type: Boolean, - value() { - let enabled = false; - // <if expr="not chromeos_lacros"> - enabled = loadTimeData.getBoolean( - 'enableDesktopRestructuredLanguageSettings'); - // </if> - return enabled; - }, - }, - hideSpellCheckLanguages_: { type: Boolean, value: false, @@ -132,15 +119,6 @@ map.set(routes.EDIT_DICTIONARY.path, '#spellCheckSubpageTrigger'); } // </if> - // <if expr="not chromeos_lacros"> - if (loadTimeData.getBoolean( - 'enableDesktopRestructuredLanguageSettings')) { - if (routes.LANGUAGE_SETTINGS) { - map.set( - routes.LANGUAGE_SETTINGS.path, '#languagesSubpageTrigger'); - } - } - // </if> return map; }, }, @@ -162,7 +140,6 @@ languageHelper: LanguageHelper; private spellCheckLanguages_: Array<LanguageState|SpellCheckLanguageState>; private detailLanguage_?: LanguageState; - private enableDesktopRestructuredLanguageSettings_: boolean; private hideSpellCheckLanguages_: boolean; private showAddLanguagesDialog_: boolean; private focusConfig_: FocusConfig; @@ -344,17 +321,6 @@ } } - // <if expr="not chromeos_lacros"> - /** - * Opens the Language Settings page. - */ - private onLanguagesSubpageClick_() { - if (this.enableDesktopRestructuredLanguageSettings_) { - Router.getInstance().navigateTo(routes.LANGUAGE_SETTINGS); - } - } - // </if> - /** * Toggles the expand button within the element being listened to. */
diff --git a/chrome/browser/resources/settings/route.ts b/chrome/browser/resources/settings/route.ts index fdba8d4..c5157e93 100644 --- a/chrome/browser/resources/settings/route.ts +++ b/chrome/browser/resources/settings/route.ts
@@ -178,11 +178,6 @@ // <if expr="not chromeos_ash and not is_macosx"> r.EDIT_DICTIONARY = r.LANGUAGES.createChild('/editDictionary'); // </if> - // <if expr="not chromeos_ash and not chromeos_lacros"> - if (loadTimeData.getBoolean('enableDesktopRestructuredLanguageSettings')) { - r.LANGUAGE_SETTINGS = r.LANGUAGES.createChild('/languageSettings'); - } - // </if> if (visibility.downloads !== false) { r.DOWNLOADS = r.ADVANCED.createSection('/downloads', 'downloads');
diff --git a/chrome/browser/resources/settings/settings_routes.ts b/chrome/browser/resources/settings/settings_routes.ts index a990b44..75b48c69c 100644 --- a/chrome/browser/resources/settings/settings_routes.ts +++ b/chrome/browser/resources/settings/settings_routes.ts
@@ -28,7 +28,6 @@ IMPORT_DATA: Route, INCOMPATIBLE_APPLICATIONS: Route, LANGUAGES: Route, - LANGUAGE_SETTINGS: Route, MANAGE_PROFILE: Route, ON_STARTUP: Route, PASSWORDS: Route,
diff --git a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/DevicePickerBottomSheetContent.java b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/DevicePickerBottomSheetContent.java index cfc2e6c4..ccbfa68 100644 --- a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/DevicePickerBottomSheetContent.java +++ b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/DevicePickerBottomSheetContent.java
@@ -5,13 +5,7 @@ package org.chromium.chrome.browser.share.send_tab_to_self; import android.content.Context; -import android.content.Intent; import android.content.res.Resources; -import android.graphics.Bitmap; -import android.net.Uri; -import android.provider.Browser; -import android.text.SpannableString; -import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -20,22 +14,11 @@ import android.widget.ListView; import android.widget.TextView; -import org.chromium.base.IntentUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.browserservices.intents.WebappConstants; -import org.chromium.chrome.browser.document.ChromeLauncherActivity; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.profiles.Profile; -import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; import org.chromium.components.browser_ui.bottomsheet.BottomSheetContent; import org.chromium.components.browser_ui.bottomsheet.BottomSheetController; -import org.chromium.components.browser_ui.widget.RoundedCornerImageView; -import org.chromium.components.embedder_support.util.UrlConstants; -import org.chromium.components.signin.base.AccountInfo; -import org.chromium.components.signin.identitymanager.ConsentLevel; -import org.chromium.components.signin.identitymanager.IdentityManager; -import org.chromium.ui.text.NoUnderlineClickableSpan; -import org.chromium.ui.text.SpanApplier; import org.chromium.ui.widget.Toast; import java.util.List; @@ -84,53 +67,7 @@ listView.setAdapter(mAdapter); listView.setOnItemClickListener(this); - createManageDevicesLink(listView); - } - - private void createManageDevicesLink(ListView deviceListView) { - ViewGroup containerView = (ViewGroup) LayoutInflater.from(mContext).inflate( - R.layout.send_tab_to_self_manage_devices_link, null); - deviceListView.addFooterView(containerView); - - AccountInfo account = getSharingAccountInfo(); - assert account != null : "The user must be signed in to share a tab"; - - // The avatar can be null in tests. - if (account.getAccountImage() != null) { - RoundedCornerImageView avatarView = containerView.findViewById(R.id.account_avatar); - int accountAvatarSizePx = Math.round( - ACCOUNT_AVATAR_SIZE_DP * mContext.getResources().getDisplayMetrics().density); - avatarView.setImageBitmap(Bitmap.createScaledBitmap( - account.getAccountImage(), accountAvatarSizePx, accountAvatarSizePx, false)); - avatarView.setRoundedCorners(accountAvatarSizePx / 2, accountAvatarSizePx / 2, - accountAvatarSizePx / 2, accountAvatarSizePx / 2); - } - - Resources resources = mContext.getResources(); - // The link is opened in a new tab to avoid exiting the current page, which the user - // possibly wants to share (maybe they just clicked "Manage devices" by mistake). - SpannableString linkText = SpanApplier.applySpans( - resources.getString( - R.string.send_tab_to_self_manage_devices_link, account.getEmail()), - new SpanApplier.SpanInfo("<link>", "</link>", - new NoUnderlineClickableSpan( - mContext, this::openManageDevicesPageInNewTab))); - TextView linkView = containerView.findViewById(R.id.manage_devices_link); - linkView.setText(linkText); - linkView.setMovementMethod(LinkMovementMethod.getInstance()); - } - - private void openManageDevicesPageInNewTab(View unused) { - Intent intent = - new Intent() - .setAction(Intent.ACTION_VIEW) - .setData(Uri.parse(UrlConstants.GOOGLE_ACCOUNT_DEVICE_ACTIVITY_URL)) - .setClass(mContext, ChromeLauncherActivity.class) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - .putExtra(Browser.EXTRA_APPLICATION_ID, mContext.getPackageName()) - .putExtra(WebappConstants.REUSE_URL_MATCHING_TAB_ELSE_NEW_TAB, true); - IntentUtils.addTrustedIntentExtras(intent); - mContext.startActivity(intent); + listView.addFooterView(new ManageAccountDevicesLinkView(mContext)); } @Override @@ -227,11 +164,4 @@ mController.hideContent(this, true); } - - private static AccountInfo getSharingAccountInfo() { - IdentityManager identityManager = IdentityServicesProvider.get().getIdentityManager( - Profile.getLastUsedRegularProfile()); - return identityManager.findExtendedAccountInfoByEmailAddress( - identityManager.getPrimaryAccountInfo(ConsentLevel.SIGNIN).getEmail()); - } }
diff --git a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/ManageAccountDevicesLinkView.java b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/ManageAccountDevicesLinkView.java new file mode 100644 index 0000000..61ad6d2 --- /dev/null +++ b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/ManageAccountDevicesLinkView.java
@@ -0,0 +1,115 @@ +// Copyright 2022 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.share.send_tab_to_self; + +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.net.Uri; +import android.provider.Browser; +import android.text.SpannableString; +import android.text.method.LinkMovementMethod; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.TextView; + +import org.chromium.base.IntentUtils; +import org.chromium.chrome.R; +import org.chromium.chrome.browser.browserservices.intents.WebappConstants; +import org.chromium.chrome.browser.document.ChromeLauncherActivity; +import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; +import org.chromium.components.browser_ui.widget.RoundedCornerImageView; +import org.chromium.components.embedder_support.util.UrlConstants; +import org.chromium.components.signin.base.AccountInfo; +import org.chromium.components.signin.identitymanager.ConsentLevel; +import org.chromium.components.signin.identitymanager.IdentityManager; +import org.chromium.ui.text.NoUnderlineClickableSpan; +import org.chromium.ui.text.SpanApplier; + +/** View containing the sharing account's avatar, email and a link to manage its target devices. */ +public class ManageAccountDevicesLinkView extends FrameLayout { + private static final int ACCOUNT_AVATAR_SIZE_DP = 24; + + public ManageAccountDevicesLinkView(Context context) { + this(context, null); + } + + public ManageAccountDevicesLinkView(Context context, AttributeSet attrs) { + super(context, attrs); + inflateIfVisible(); + } + + @Override + public void setVisibility(int visibility) { + super.setVisibility(visibility); + inflateIfVisible(); + } + + // TODO(crbug.com/1219434): For now the account information is only filled once the view becomes + // visible, so it can still be declared in the XML if there is no account. After launch, fill + // the data immediately. + private void inflateIfVisible() { + if (getVisibility() != View.VISIBLE) { + return; + } + + // The view was already inflated, nothing else to do. + if (getChildCount() > 0) { + return; + } + + LayoutInflater.from(getContext()) + .inflate(R.layout.send_tab_to_self_manage_devices_link, this); + + AccountInfo account = getSharingAccountInfo(); + assert account != null; + + // The avatar can be null in tests. + if (account.getAccountImage() != null) { + RoundedCornerImageView avatarView = findViewById(R.id.account_avatar); + int accountAvatarSizePx = + Math.round(ACCOUNT_AVATAR_SIZE_DP * getResources().getDisplayMetrics().density); + avatarView.setImageBitmap(Bitmap.createScaledBitmap( + account.getAccountImage(), accountAvatarSizePx, accountAvatarSizePx, false)); + avatarView.setRoundedCorners(accountAvatarSizePx / 2, accountAvatarSizePx / 2, + accountAvatarSizePx / 2, accountAvatarSizePx / 2); + } + + // The link is opened in a new tab to avoid exiting the current page, which the user + // possibly wants to share (maybe they just clicked "Manage devices" by mistake). + SpannableString linkText = SpanApplier.applySpans( + getResources().getString( + R.string.send_tab_to_self_manage_devices_link, account.getEmail()), + new SpanApplier.SpanInfo("<link>", "</link>", + new NoUnderlineClickableSpan( + getContext(), this::openManageDevicesPageInNewTab))); + TextView linkView = findViewById(R.id.manage_devices_link); + linkView.setText(linkText); + linkView.setMovementMethod(LinkMovementMethod.getInstance()); + } + + private void openManageDevicesPageInNewTab(View unused) { + Intent intent = + new Intent() + .setAction(Intent.ACTION_VIEW) + .setData(Uri.parse(UrlConstants.GOOGLE_ACCOUNT_DEVICE_ACTIVITY_URL)) + .setClass(getContext(), ChromeLauncherActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .putExtra(Browser.EXTRA_APPLICATION_ID, getContext().getPackageName()) + .putExtra(WebappConstants.REUSE_URL_MATCHING_TAB_ELSE_NEW_TAB, true); + IntentUtils.addTrustedIntentExtras(intent); + getContext().startActivity(intent); + } + + private static AccountInfo getSharingAccountInfo() { + IdentityManager identityManager = IdentityServicesProvider.get().getIdentityManager( + Profile.getLastUsedRegularProfile()); + return identityManager.findExtendedAccountInfoByEmailAddress( + identityManager.getPrimaryAccountInfo(ConsentLevel.SIGNIN).getEmail()); + } +}
diff --git a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/NoTargetDeviceBottomSheetContent.java b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/NoTargetDeviceBottomSheetContent.java index dcc845c..d3aadc85 100644 --- a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/NoTargetDeviceBottomSheetContent.java +++ b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/NoTargetDeviceBottomSheetContent.java
@@ -9,8 +9,11 @@ import android.view.View; import android.view.ViewGroup; +import androidx.annotation.VisibleForTesting; + import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.components.browser_ui.bottomsheet.BottomSheetContent; /** Content shown if the send-tab-to-self feature is ready but there are no target devices. */ @@ -18,8 +21,17 @@ private final View mContentView; public NoTargetDeviceBottomSheetContent(Context context) { + this(context, ChromeFeatureList.isEnabled(ChromeFeatureList.SEND_TAB_TO_SELF_SIGNIN_PROMO)); + } + + /** Exposed so tests don't call ChromeFeatureList.isEnabled(), which requires native. */ + @VisibleForTesting + public NoTargetDeviceBottomSheetContent(Context context, boolean isPromoFeatureEnabled) { mContentView = (ViewGroup) LayoutInflater.from(context).inflate( R.layout.send_tab_to_self_feature_unavailable_prompt, null); + if (isPromoFeatureEnabled) { + mContentView.findViewById(R.id.manage_account_devices_link).setVisibility(View.VISIBLE); + } // TODO(crbug.com/1298185): This is cumulating both signed-out and single device users. // Those should be recorded separately instead. RecordUserAction.record("SharingHubAndroid.SendTabToSelf.NoTargetDevices");
diff --git a/chrome/browser/share/android/java_sources.gni b/chrome/browser/share/android/java_sources.gni index b96c2a6..3827d812 100644 --- a/chrome/browser/share/android/java_sources.gni +++ b/chrome/browser/share/android/java_sources.gni
@@ -64,6 +64,7 @@ "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/scroll_capture/ScrollCaptureManagerDelegateImpl.java", "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/DevicePickerBottomSheetAdapter.java", "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/DevicePickerBottomSheetContent.java", + "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/ManageAccountDevicesLinkView.java", "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/MetricsRecorder.java", "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/NoTargetDeviceBottomSheetContent.java", "//chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/send_tab_to_self/NotificationManager.java",
diff --git a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfBottomSheetRenderTest.java b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfBottomSheetRenderTest.java index f6f3c534..70b444e 100644 --- a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfBottomSheetRenderTest.java +++ b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfBottomSheetRenderTest.java
@@ -14,6 +14,7 @@ import androidx.appcompat.content.res.AppCompatResources; import androidx.test.filters.MediumTest; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -64,10 +65,9 @@ @Mock private BottomSheetController mBottomSheetController; - @Test - @MediumTest - @Feature("RenderTest") - public void testDevicePickerBottomSheet() throws Throwable { + @Before + public void setUp() { + // Set up account data to be shown by the UI. AccountInfo account = createFakeAccount(); when(mIdentityManager.getPrimaryAccountInfo(ConsentLevel.SIGNIN)).thenReturn(account); when(mIdentityManager.findExtendedAccountInfoByEmailAddress(account.getEmail())) @@ -75,7 +75,12 @@ when(mIdentityServicesProvider.getIdentityManager(mProfile)).thenReturn(mIdentityManager); IdentityServicesProvider.setInstanceForTests(mIdentityServicesProvider); Profile.setLastUsedProfileForTesting(mProfile); + } + @Test + @MediumTest + @Feature("RenderTest") + public void testDevicePickerBottomSheet() throws Throwable { long todayTimestamp = Calendar.getInstance().getTimeInMillis(); List<TargetDeviceInfo> devices = Arrays.asList( new TargetDeviceInfo("My Phone", "guid1", DeviceType.PHONE, todayTimestamp), @@ -94,16 +99,29 @@ @Test @MediumTest @Feature("RenderTest") - public void testNoTargetDeviceBottomSheet() throws Throwable { + public void testNoTargetDeviceBottomSheetWithPromoFeatureDisabled() throws Throwable { View view = TestThreadUtils.runOnUiThreadBlockingNoException(() -> { - NoTargetDeviceBottomSheetContent sheetContent = - new NoTargetDeviceBottomSheetContent(getActivity()); + NoTargetDeviceBottomSheetContent sheetContent = new NoTargetDeviceBottomSheetContent( + getActivity(), /*isPromoFeatureEnabled=*/false); getActivity().setContentView(sheetContent.getContentView()); return sheetContent.getContentView(); }); mRenderTestRule.render(view, "no_target_device"); } + @Test + @MediumTest + @Feature("RenderTest") + public void testNoTargetDeviceBottomSheetWithPromoFeatureEnabled() throws Throwable { + View view = TestThreadUtils.runOnUiThreadBlockingNoException(() -> { + NoTargetDeviceBottomSheetContent sheetContent = new NoTargetDeviceBottomSheetContent( + getActivity(), /*isPromoFeatureEnabled=*/true); + getActivity().setContentView(sheetContent.getContentView()); + return sheetContent.getContentView(); + }); + mRenderTestRule.render(view, "no_target_device_with_account"); + } + // TODO(crbug.com/1219434): This duplicates the account in AccountManagerTestRule, so tests can // later adopt the rule without failing the golden diffs. That's not done now because it // requires changing the device picker to depend on ProfileDataCache instead of IdentityManager.
diff --git a/chrome/browser/storage/durable_storage_permission_context.cc b/chrome/browser/storage/durable_storage_permission_context.cc index 994f52e..80c8f76 100644 --- a/chrome/browser/storage/durable_storage_permission_context.cc +++ b/chrome/browser/storage/durable_storage_permission_context.cc
@@ -35,7 +35,6 @@ } void DurableStoragePermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/storage/durable_storage_permission_context.h b/chrome/browser/storage/durable_storage_permission_context.h index 279b0be..e913ae1 100644 --- a/chrome/browser/storage/durable_storage_permission_context.h +++ b/chrome/browser/storage/durable_storage_permission_context.h
@@ -24,7 +24,6 @@ // PermissionContextBase implementation. // Grant if requesting_origin is bookmarked. void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/storage/durable_storage_permission_context_unittest.cc b/chrome/browser/storage/durable_storage_permission_context_unittest.cc index 388f1a40..e68e9797 100644 --- a/chrome/browser/storage/durable_storage_permission_context_unittest.cc +++ b/chrome/browser/storage/durable_storage_permission_context_unittest.cc
@@ -103,8 +103,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.DecidePermission( - web_contents(), id, url, url, true /* user_gesture */, base::DoNothing()); + permission_context.DecidePermission(id, url, url, true /* user_gesture */, + base::DoNothing()); // Success. EXPECT_EQ(1, permission_context.permission_set_count()); EXPECT_TRUE(permission_context.last_permission_set_persisted()); @@ -129,8 +129,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.DecidePermission( - web_contents(), id, url, url, true /* user_gesture */, base::DoNothing()); + permission_context.DecidePermission(id, url, url, true /* user_gesture */, + base::DoNothing()); // Success. EXPECT_EQ(1, permission_context.permission_set_count()); EXPECT_TRUE(permission_context.last_permission_set_persisted()); @@ -157,8 +157,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.DecidePermission( - web_contents(), id, url, url, true /* user_gesture */, base::DoNothing()); + permission_context.DecidePermission(id, url, url, true /* user_gesture */, + base::DoNothing()); // Success. EXPECT_EQ(1, permission_context.permission_set_count()); EXPECT_TRUE(permission_context.last_permission_set_persisted()); @@ -181,8 +181,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.DecidePermission( - web_contents(), id, url, url, true /* user_gesture */, base::DoNothing()); + permission_context.DecidePermission(id, url, url, true /* user_gesture */, + base::DoNothing()); // We shouldn't be granted. EXPECT_EQ(1, permission_context.permission_set_count()); @@ -212,8 +212,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.DecidePermission( - web_contents(), id, url, url, true /* user_gesture */, base::DoNothing()); + permission_context.DecidePermission(id, url, url, true /* user_gesture */, + base::DoNothing()); // We shouldn't be granted. EXPECT_EQ(1, permission_context.permission_set_count()); EXPECT_FALSE(permission_context.last_permission_set_persisted()); @@ -238,9 +238,8 @@ ASSERT_EQ(CONTENT_SETTING_DEFAULT, permission_context.last_permission_set_setting()); - permission_context.DecidePermission(web_contents(), id, requesting_url, url, - true /* user_gesture */, - base::DoNothing()); + permission_context.DecidePermission( + id, requesting_url, url, true /* user_gesture */, base::DoNothing()); // We shouldn't be granted. EXPECT_EQ(1, permission_context.permission_set_count()); EXPECT_FALSE(permission_context.last_permission_set_persisted());
diff --git a/chrome/browser/storage_access_api/storage_access_grant_permission_context.cc b/chrome/browser/storage_access_api/storage_access_grant_permission_context.cc index d7ab6253..ac2edf4 100644 --- a/chrome/browser/storage_access_api/storage_access_grant_permission_context.cc +++ b/chrome/browser/storage_access_api/storage_access_grant_permission_context.cc
@@ -59,7 +59,6 @@ } void StorageAccessGrantPermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, @@ -100,7 +99,7 @@ } // Show prompt. - PermissionContextBase::DecidePermission(web_contents, id, requesting_origin, + PermissionContextBase::DecidePermission(id, requesting_origin, embedding_origin, user_gesture, std::move(callback)); }
diff --git a/chrome/browser/storage_access_api/storage_access_grant_permission_context.h b/chrome/browser/storage_access_api/storage_access_grant_permission_context.h index 16485cd..1c1c548a 100644 --- a/chrome/browser/storage_access_api/storage_access_grant_permission_context.h +++ b/chrome/browser/storage_access_api/storage_access_grant_permission_context.h
@@ -43,7 +43,6 @@ // PermissionContextBase: bool IsRestrictedToSecureOrigins() const override; void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/chrome/browser/storage_access_api/storage_access_grant_permission_context_unittest.cc b/chrome/browser/storage_access_api/storage_access_grant_permission_context_unittest.cc index a7a766e..34918a79 100644 --- a/chrome/browser/storage_access_api/storage_access_grant_permission_context_unittest.cc +++ b/chrome/browser/storage_access_api/storage_access_grant_permission_context_unittest.cc
@@ -78,7 +78,7 @@ ContentSetting result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, requesting_origin, embedding_origin, + fake_id, requesting_origin, embedding_origin, /*user_gesture=*/true, base::BindOnce(&SaveResult, &result)); base::RunLoop().RunUntilIdle(); @@ -116,7 +116,7 @@ ContentSetting result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, GetRequesterURL(), GetTopLevelURL(), + fake_id, GetRequesterURL(), GetTopLevelURL(), /*user_gesture=*/true, base::BindOnce(&SaveResult, &result)); EXPECT_EQ(CONTENT_SETTING_BLOCK, result); } @@ -139,7 +139,7 @@ ContentSetting result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, GetRequesterURL(), GetTopLevelURL(), + fake_id, GetRequesterURL(), GetTopLevelURL(), /*user_gesture=*/true, base::BindOnce(&SaveResult, &result)); base::RunLoop().RunUntilIdle(); @@ -168,7 +168,7 @@ ContentSetting result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, GetRequesterURL(), GetTopLevelURL(), + fake_id, GetRequesterURL(), GetTopLevelURL(), /*user_gesture=*/false, base::BindOnce(&SaveResult, &result)); EXPECT_EQ(CONTENT_SETTING_BLOCK, result); } @@ -212,7 +212,7 @@ ContentSetting result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, GetRequesterURL(), GetTopLevelURL(), + fake_id, GetRequesterURL(), GetTopLevelURL(), /*user_gesture=*/true, base::BindOnce(&SaveResult, &result)); base::RunLoop().RunUntilIdle(); @@ -240,7 +240,7 @@ // it gets auto-granted as the limit has not been reached for it yet. result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, alternate_requester_url, GetTopLevelURL(), + fake_id, alternate_requester_url, GetTopLevelURL(), /*user_gesture=*/true, base::BindOnce(&SaveResult, &result)); base::RunLoop().RunUntilIdle(); @@ -270,7 +270,7 @@ ContentSetting result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, GetRequesterURL(), GetTopLevelURL(), + fake_id, GetRequesterURL(), GetTopLevelURL(), /*user_gesture=*/true, base::BindOnce(&SaveResult, &result)); base::RunLoop().RunUntilIdle(); @@ -308,7 +308,7 @@ ContentSetting result = CONTENT_SETTING_DEFAULT; permission_context.DecidePermission( - web_contents(), fake_id, GetRequesterURL(), GetTopLevelURL(), + fake_id, GetRequesterURL(), GetTopLevelURL(), /*user_gesture=*/true, base::BindOnce(&SaveResult, &result)); base::RunLoop().RunUntilIdle();
diff --git a/chrome/browser/sync/test/integration/preferences_helper.cc b/chrome/browser/sync/test/integration/preferences_helper.cc index c43a091..b86d3928 100644 --- a/chrome/browser/sync/test/integration/preferences_helper.cc +++ b/chrome/browser/sync/test/integration/preferences_helper.cc
@@ -8,13 +8,10 @@ #include "base/bind.h" #include "base/notreached.h" -#include "base/threading/thread_restrictions.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" -#include "chrome/common/chrome_constants.h" #include "components/pref_registry/pref_registry_syncable.h" -#include "components/prefs/persistent_pref_store.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" @@ -67,24 +64,6 @@ } } -scoped_refptr<PrefStore> BuildPrefStoreFromPrefsFile(Profile* profile) { - base::RunLoop run_loop; - profile->GetPrefs()->CommitPendingWrite(run_loop.QuitClosure()); - run_loop.Run(); - - auto pref_store = base::MakeRefCounted<JsonPrefStore>( - profile->GetPath().Append(chrome::kPreferencesFilename)); - base::ScopedAllowBlockingForTesting allow_blocking; - PersistentPrefStore::PrefReadError result = pref_store->ReadPrefs(); - if (result != PersistentPrefStore::PREF_READ_ERROR_NONE) { - ADD_FAILURE() - << " Failed reading the prefs file into the store, error code " - << result; - } - - return pref_store; -} - bool BooleanPrefMatches(const char* pref_name) { bool reference_value = GetPrefs(0)->GetBoolean(pref_name); for (int i = 1; i < test()->num_clients(); ++i) {
diff --git a/chrome/browser/sync/test/integration/preferences_helper.h b/chrome/browser/sync/test/integration/preferences_helper.h index bfeb9deb..8cd88c3 100644 --- a/chrome/browser/sync/test/integration/preferences_helper.h +++ b/chrome/browser/sync/test/integration/preferences_helper.h
@@ -64,10 +64,6 @@ const char* pref_name, const base::ListValue& new_value); -// Reads preferences from a given profile's pref file (after flushing) and loads -// them into a new created pref store. -scoped_refptr<PrefStore> BuildPrefStoreFromPrefsFile(Profile* profile); - // Used to verify that the boolean preference with name |pref_name| has the // same value across all profiles. [[nodiscard]] bool BooleanPrefMatches(const char* pref_name);
diff --git a/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc b/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc index bf04a788..d86341c 100644 --- a/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_preferences_sync_test.cc
@@ -5,8 +5,10 @@ #include <map> #include "base/files/file_util.h" +#include "base/path_service.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" +#include "base/threading/thread_restrictions.h" #include "base/values.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/sync/test/integration/preferences_helper.h" @@ -14,6 +16,7 @@ #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/sync/test/integration/updated_progress_marker_checker.h" #include "chrome/common/chrome_constants.h" +#include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/json_pref_store.h" @@ -27,7 +30,6 @@ namespace { -using preferences_helper::BuildPrefStoreFromPrefsFile; using preferences_helper::ChangeBooleanPref; using preferences_helper::GetPrefs; using preferences_helper::GetRegistry; @@ -87,7 +89,7 @@ } IN_PROC_BROWSER_TEST_F(SingleClientPreferencesSyncTest, - ShouldRemoveBadDataWhenRegistering) { + PRE_ShouldRemoveBadDataWhenRegistering) { // Populate the data store with data of type boolean but register as string. SetPreexistingPreferencesFileContents( 0, "{\"testing\":{\"my-test-preference\":true}}"); @@ -95,6 +97,11 @@ PrefRegistrySyncable* registry = GetRegistry(GetProfile(0)); registry->RegisterStringPref("testing.my-test-preference", "default-value", user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); + + registry->RegisterStringPref("testing.unrelated-preference", "", + user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); + + // Make sure that the preference is exposed with its default value. const PrefService::Preference* preference = GetProfile(0)->GetPrefs()->FindPreference("testing.my-test-preference"); ASSERT_THAT(preference, NotNull()); @@ -106,9 +113,42 @@ // recognized as a default value. --> file a bug! EXPECT_TRUE(preference->IsDefaultValue()); - // To verify the bad data has been removed, we read the JSON file from disk. - scoped_refptr<PrefStore> pref_store = - BuildPrefStoreFromPrefsFile(GetProfile(0)); + // The next test (without "PRE_") will verify that the bad data was actually + // removed from the disk. + // Set some unrelated pref, so the next test can sanity check that the prefs + // file was opened correctly. + GetProfile(0)->GetPrefs()->SetString("testing.unrelated-preference", "cool"); +} + +IN_PROC_BROWSER_TEST_F(SingleClientPreferencesSyncTest, + ShouldRemoveBadDataWhenRegistering) { + // Note: Do *not* call SetupClients() here, so that the Profile's PrefService + // doesn't get created. (Otherwise it might interfere with manually reading + // the prefs file below.) + base::FilePath user_data_dir; + base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); + base::FilePath prefs_path = user_data_dir.Append(GetProfileBaseName(0)) + .Append(chrome::kPreferencesFilename); + + // To verify the bad data has been removed, read the JSON file from disk + // directly (without going through PrefService). + auto pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); + base::ScopedAllowBlockingForTesting allow_blocking; + PersistentPrefStore::PrefReadError read_result = pref_store->ReadPrefs(); + ASSERT_EQ(read_result, PersistentPrefStore::PREF_READ_ERROR_NONE) + << " Failed reading the prefs file into the store, error code " + << read_result; + + // Sanity check: An unrelated pref that was set in the previous test is still + // here. + const base::Value* unrelated_pref; + ASSERT_TRUE( + pref_store->GetValue("testing.unrelated-preference", &unrelated_pref)); + ASSERT_TRUE(unrelated_pref->is_string()); + ASSERT_EQ(unrelated_pref->GetString(), "cool"); + + // Finally, the actual test expectation: The pref which had a value of the + // wrong type previously has been cleared. const base::Value* result; EXPECT_FALSE(pref_store->GetValue("testing.my-test-preference", &result)); }
diff --git a/chrome/browser/thumbnail/DEPS b/chrome/browser/thumbnail/DEPS index 00f797e..02be6da0 100644 --- a/chrome/browser/thumbnail/DEPS +++ b/chrome/browser/thumbnail/DEPS
@@ -26,7 +26,6 @@ "+skia", "+testing/gmock", "+testing/gtest", - "+third_party/abseil-cpp/absl", "+third_party/android_opengl/etc1", "+third_party/skia/include", "+ui",
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 603b86e..e7d9b4f 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -4702,6 +4702,8 @@ "views/safe_browsing/prompt_for_scanning_modal_dialog.h", "views/safe_browsing/tailored_security_unconsented_modal.cc", "views/safe_browsing/tailored_security_unconsented_modal.h", + "views/send_tab_to_self/manage_account_devices_link_view.cc", + "views/send_tab_to_self/manage_account_devices_link_view.h", "views/send_tab_to_self/send_tab_to_self_bubble_device_button.cc", "views/send_tab_to_self/send_tab_to_self_bubble_device_button.h", "views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.cc",
diff --git a/chrome/browser/ui/android/overlay/overlay_window_android.cc b/chrome/browser/ui/android/overlay/overlay_window_android.cc index a61bdf6..5583b0e 100644 --- a/chrome/browser/ui/android/overlay/overlay_window_android.cc +++ b/chrome/browser/ui/android/overlay/overlay_window_android.cc
@@ -38,7 +38,7 @@ surface_layer_->SetIsDrawable(true); surface_layer_->SetStretchContentToFillBounds(true); surface_layer_->SetMayContainVideo(true); - surface_layer_->SetBackgroundColor(SK_ColorBLACK); + surface_layer_->SetBackgroundColor(SkColors::kBlack); gfx::Rect source_bounds = controller_->GetSourceBounds();
diff --git a/chrome/browser/ui/ash/desks/desks_client_browsertest.cc b/chrome/browser/ui/ash/desks/desks_client_browsertest.cc index 575a917..1ba5efb1 100644 --- a/chrome/browser/ui/ash/desks/desks_client_browsertest.cc +++ b/chrome/browser/ui/ash/desks/desks_client_browsertest.cc
@@ -20,6 +20,7 @@ #include "ash/wm/desks/desk.h" #include "ash/wm/desks/desks_controller.h" #include "ash/wm/desks/desks_test_util.h" +#include "ash/wm/desks/templates/saved_desk_metrics_util.h" #include "ash/wm/desks/templates/saved_desk_test_util.h" #include "ash/wm/desks/templates/saved_desk_util.h" #include "ash/wm/overview/overview_test_util.h" @@ -2013,9 +2014,8 @@ ClickExpandedStateTemplatesButton(); } - constexpr char kLaunchFromTemplateHistogramName[] = - "Ash.DeskTemplate.LaunchFromTemplate"; - histogram_tester.ExpectTotalCount(kLaunchFromTemplateHistogramName, launches); + histogram_tester.ExpectTotalCount(ash::kLaunchTemplateHistogramName, + launches); } // Tests that launching a desk template records the appropriate performance
diff --git a/chrome/browser/ui/ash/network/enrollment_dialog_view.cc b/chrome/browser/ui/ash/network/enrollment_dialog_view.cc index a97293a..a3c2ac7 100644 --- a/chrome/browser/ui/ash/network/enrollment_dialog_view.cc +++ b/chrome/browser/ui/ash/network/enrollment_dialog_view.cc
@@ -261,7 +261,7 @@ return false; client_cert::ClientCertConfig cert_config; - OncToClientCertConfig(onc_source, *policy, &cert_config); + OncToClientCertConfig(onc_source, policy->GetDict(), &cert_config); if (cert_config.client_cert_type != onc::client_cert::kPattern) return false;
diff --git a/chrome/browser/ui/color/chrome_color_id.h b/chrome/browser/ui/color/chrome_color_id.h index 0deff5e..c79f69a9 100644 --- a/chrome/browser/ui/color/chrome_color_id.h +++ b/chrome/browser/ui/color/chrome_color_id.h
@@ -137,7 +137,8 @@ E(kColorNewTabPageHeader, ThemeProperties::COLOR_NTP_HEADER) \ E(kColorNewTabPageLink, ThemeProperties::COLOR_NTP_LINK) \ E(kColorNewTabPageLogo, ThemeProperties::COLOR_NTP_LOGO) \ - E_CPONLY(kColorNewTabPageLogoUnthemed) \ + E_CPONLY(kColorNewTabPageLogoUnthemedDark) \ + E_CPONLY(kColorNewTabPageLogoUnthemedLight) \ E(kColorNewTabPageMostVisitedTileBackground, \ ThemeProperties::COLOR_NTP_SHORTCUT) \ E_CPONLY(kColorNewTabPageMostVisitedTileBackgroundUnthemed) \
diff --git a/chrome/browser/ui/color/chrome_color_mixer.cc b/chrome/browser/ui/color/chrome_color_mixer.cc index 5708a8c..5100c9e 100644 --- a/chrome/browser/ui/color/chrome_color_mixer.cc +++ b/chrome/browser/ui/color/chrome_color_mixer.cc
@@ -323,8 +323,9 @@ mixer[kColorNewTabPageHeader] = {SkColorSetRGB(0x96, 0x96, 0x96)}; mixer[kColorNewTabPageLink] = {dark_mode ? gfx::kGoogleBlue300 : SkColorSetRGB(0x06, 0x37, 0x74)}; - mixer[kColorNewTabPageLogo] = {kColorNewTabPageLogoUnthemed}; - mixer[kColorNewTabPageLogoUnthemed] = {SkColorSetRGB(0xEE, 0xEE, 0xEE)}; + mixer[kColorNewTabPageLogo] = {kColorNewTabPageLogoUnthemedLight}; + mixer[kColorNewTabPageLogoUnthemedDark] = {gfx::kGoogleGrey700}; + mixer[kColorNewTabPageLogoUnthemedLight] = {SkColorSetRGB(0xEE, 0xEE, 0xEE)}; if (dark_mode) { mixer[kColorNewTabPageMostVisitedTileBackground] = {gfx::kGoogleGrey900}; } else {
diff --git a/chrome/browser/ui/views/OWNERS b/chrome/browser/ui/views/OWNERS index b4bf3d09..50d59d3 100644 --- a/chrome/browser/ui/views/OWNERS +++ b/chrome/browser/ui/views/OWNERS
@@ -9,6 +9,7 @@ connily@chromium.org corising@chromium.org dfried@chromium.org +dpenning@chromium.org ellyjones@chromium.org kylixrd@chromium.org msw@chromium.org
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc index 7c77d6a..7286fbd0 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.cc
@@ -204,22 +204,20 @@ ui::DialogModelButton::Params().AddAccelerator( ui::Accelerator(ui::VKEY_E, ui::EF_ALT_DOWN))) .AddTextfield( + kBookmarkName, l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_NAME_LABEL), bookmark_node->GetTitle(), - ui::DialogModelTextfield::Params() - .SetId(kBookmarkName) - .SetAccessibleName(l10n_util::GetStringUTF16( - IDS_BOOKMARK_AX_BUBBLE_NAME_LABEL))) + ui::DialogModelTextfield::Params().SetAccessibleName( + l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_BUBBLE_NAME_LABEL))) .AddCombobox( + kBookmarkFolder, l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_FOLDER_LABEL), std::make_unique<RecentlyUsedFoldersComboModel>( bookmark_model, bookmark_model->GetMostRecentlyAddedUserNodeForURL(url)), - ui::DialogModelCombobox::Params() - .SetId(kBookmarkFolder) - .SetCallback(base::BindRepeating( - &BookmarkBubbleDelegate::OnComboboxAction, - base::Unretained(bubble_delegate)))) + ui::DialogModelCombobox::Params().SetCallback( + base::BindRepeating(&BookmarkBubbleDelegate::OnComboboxAction, + base::Unretained(bubble_delegate)))) .SetInitiallyFocusedField(kBookmarkName) .Build();
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view_browsertest.cc b/chrome/browser/ui/views/location_bar/location_bar_view_browsertest.cc index 434854a..1fd5345 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view_browsertest.cc +++ b/chrome/browser/ui/views/location_bar/location_bar_view_browsertest.cc
@@ -238,7 +238,7 @@ ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), kMockNonsecureURL)); EXPECT_EQ(security_state::WARNING, helper->GetSecurityLevel()); EXPECT_TRUE(location_bar_view->location_icon_view()->ShouldShowLabel()); - EXPECT_TRUE(base::LowerCaseEqualsASCII( + EXPECT_TRUE(base::EqualsCaseInsensitiveASCII( location_bar_view->location_icon_view()->GetText(), "not secure")); }
diff --git a/chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.cc b/chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.cc new file mode 100644 index 0000000..56e0eff --- /dev/null +++ b/chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.cc
@@ -0,0 +1,110 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.h" + +#include <string> +#include <utility> +#include <vector> + +#include "base/bind.h" +#include "base/callback.h" +#include "chrome/browser/ui/send_tab_to_self/send_tab_to_self_bubble_controller.h" +#include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/grit/generated_resources.h" +#include "components/signin/public/identity_manager/account_info.h" +#include "third_party/skia/include/core/SkColor.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/color/color_id.h" +#include "ui/gfx/geometry/insets.h" +#include "ui/gfx/geometry/size.h" +#include "ui/gfx/image/image_skia.h" +#include "ui/gfx/image/image_skia_operations.h" +#include "ui/gfx/range/range.h" +#include "ui/views/background.h" +#include "ui/views/controls/image_view.h" +#include "ui/views/controls/separator.h" +#include "ui/views/controls/styled_label.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/layout/layout_provider.h" +#include "ui/views/style/typography.h" +#include "ui/views/view.h" + +namespace send_tab_to_self { + +namespace { + +// This sneakily matches the value of SendTabToSelfBubbleDeviceButton, which is +// inherited from views::HoverButton and isn't ever exposed. +constexpr int kManageDevicesLinkTopMargin = 6; +constexpr int kManageDevicesLinkBottomMargin = kManageDevicesLinkTopMargin + 1; + +constexpr int kAccountAvatarSize = 24; + +} // namespace + +std::unique_ptr<views::View> BuildManageAccountDevicesLinkView( + base::WeakPtr<SendTabToSelfBubbleController> controller) { + if (!controller) { + return std::make_unique<views::View>(); + } + + auto view = std::make_unique<views::View>(); + view->SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical)); + view->AddChildView(std::make_unique<views::Separator>()); + + auto* container = view->AddChildView(std::make_unique<views::View>()); + container->SetBackground(views::CreateThemedSolidBackground( + ui::kColorMenuItemBackgroundHighlighted)); + + auto* provider = ChromeLayoutProvider::Get(); + gfx::Insets margins = provider->GetInsetsMetric(views::INSETS_DIALOG); + margins.set_top(kManageDevicesLinkTopMargin); + margins.set_bottom(kManageDevicesLinkBottomMargin); + int between_child_spacing = + provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL); + container->SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kHorizontal, margins, + between_child_spacing)); + + AccountInfo account = controller->GetSharingAccountInfo(); + DCHECK(!account.IsEmpty()); + gfx::ImageSkia square_avatar = account.account_image.AsImageSkia(); + // The color used in `circle_mask` is irrelevant as long as it's opaque; only + // the alpha channel matters. + gfx::ImageSkia circle_mask = + gfx::ImageSkiaOperations::CreateImageWithCircleBackground( + square_avatar.size().width() / 2, SK_ColorWHITE, gfx::ImageSkia()); + gfx::ImageSkia round_avatar = + gfx::ImageSkiaOperations::CreateMaskedImage(square_avatar, circle_mask); + auto* avatar_view = + container->AddChildView(std::make_unique<views::ImageView>()); + avatar_view->SetImage(gfx::ImageSkiaOperations::CreateResizedImage( + round_avatar, skia::ImageOperations::RESIZE_BEST, + gfx::Size(kAccountAvatarSize, kAccountAvatarSize))); + + auto* link_view = + container->AddChildView(std::make_unique<views::StyledLabel>()); + link_view->SetDefaultTextStyle(views::style::STYLE_SECONDARY); + + // Only part of the string in |link_view| must be styled as a link and + // clickable. This range is marked in the *.grd entry by the first 2 + // placeholders. This GetStringFUTF16() call replaces them with empty strings + // (no-op) and saves the range in |offsets[0]| and |offsets[1]|. + std::vector<size_t> offsets; + link_view->SetText(l10n_util::GetStringFUTF16( + IDS_SEND_TAB_TO_SELF_MANAGE_DEVICES_LINK, + {std::u16string(), std::u16string(), base::UTF8ToUTF16(account.email)}, + &offsets)); + DCHECK_EQ(3u, offsets.size()); + link_view->AddStyleRange( + gfx::Range(offsets[0], offsets[1]), + views::StyledLabel::RangeStyleInfo::CreateForLink(base::BindRepeating( + &SendTabToSelfBubbleController::OnManageDevicesClicked, controller))); + + return view; +} + +} // namespace send_tab_to_self
diff --git a/chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.h b/chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.h new file mode 100644 index 0000000..7c98f15 --- /dev/null +++ b/chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.h
@@ -0,0 +1,25 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_SEND_TAB_TO_SELF_MANAGE_ACCOUNT_DEVICES_LINK_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_SEND_TAB_TO_SELF_MANAGE_ACCOUNT_DEVICES_LINK_VIEW_H_ + +#include <memory> + +#include "base/memory/weak_ptr.h" + +namespace views { +class View; +} // namespace views + +namespace send_tab_to_self { + +class SendTabToSelfBubbleController; + +std::unique_ptr<views::View> BuildManageAccountDevicesLinkView( + base::WeakPtr<SendTabToSelfBubbleController> controller); + +} // namespace send_tab_to_self + +#endif // CHROME_BROWSER_UI_VIEWS_SEND_TAB_TO_SELF_MANAGE_ACCOUNT_DEVICES_LINK_VIEW_H_
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_browsertest.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_browsertest.cc index e7b2ae5c..31c196df 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_browsertest.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_browsertest.cc
@@ -89,11 +89,15 @@ } IN_PROC_BROWSER_TEST_F(SendTabToSelfBubbleTest, InvokeUi_ShowSigninPromo) { + // Last updated in crrev.com/c/3669248. + set_baseline("3669248"); ShowAndVerifyUi(); } IN_PROC_BROWSER_TEST_F(SendTabToSelfBubbleTest, InvokeUi_ShowNoTargetDevicePromo) { + // Last updated in crrev.com/c/3669248. + set_baseline("3669248"); ShowAndVerifyUi(); }
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.cc index 0e36cfd..3909b5e2 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.cc
@@ -12,23 +12,18 @@ #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/toolbar_button_provider.h" +#include "chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.h" #include "chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_device_button.h" #include "chrome/browser/ui/views/sharing_hub/sharing_hub_bubble_util.h" #include "chrome/grit/generated_resources.h" #include "components/send_tab_to_self/features.h" #include "components/send_tab_to_self/target_device_info.h" -#include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_types.h" -#include "ui/color/color_id.h" -#include "ui/gfx/image/image_skia_operations.h" #include "ui/views/accessibility/view_accessibility.h" -#include "ui/views/border.h" #include "ui/views/controls/scroll_view.h" -#include "ui/views/controls/separator.h" -#include "ui/views/controls/styled_label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/style/typography.h" #include "ui/views/view_class_properties.h" @@ -48,13 +43,6 @@ // with arrow keys possible. constexpr int kDeviceButtonGroup = 0; -// This sneakily matches the value of SendTabToSelfBubbleDeviceButton, which is -// inherited from views::HoverButton and isn't ever exposed. -constexpr int kManageDevicesLinkTopMargin = 6; -constexpr int kManageDevicesLinkBottomMargin = kManageDevicesLinkTopMargin + 1; - -constexpr int kAccountAvatarSize = 24; - } // namespace SendTabToSelfDevicePickerBubbleView::SendTabToSelfDevicePickerBubbleView( @@ -117,12 +105,6 @@ Hide(); } -void SendTabToSelfDevicePickerBubbleView::OnManageDevicesClicked( - const ui::Event& event) { - controller_->OnManageDevicesClicked(event); - Hide(); -} - const views::View* SendTabToSelfDevicePickerBubbleView::GetButtonContainerForTesting() const { return scroll_view_->contents(); @@ -140,8 +122,7 @@ CreateHintTextLabel(); CreateDevicesScrollView(); - AddChildView(std::make_unique<views::Separator>()); - CreateManageDevicesLink(); + AddChildView(BuildManageAccountDevicesLinkView(controller_)); } void SendTabToSelfDevicePickerBubbleView::AddedToWidget() { @@ -194,57 +175,4 @@ SetInitiallyFocusedView(device_list_view->children()[0]); } -void SendTabToSelfDevicePickerBubbleView::CreateManageDevicesLink() { - auto* container = AddChildView(std::make_unique<views::View>()); - container->SetBackground(views::CreateThemedSolidBackground( - ui::kColorMenuItemBackgroundHighlighted)); - - auto* provider = ChromeLayoutProvider::Get(); - gfx::Insets margins = provider->GetInsetsMetric(views::INSETS_DIALOG); - margins.set_top(kManageDevicesLinkTopMargin); - margins.set_bottom(kManageDevicesLinkBottomMargin); - int between_child_spacing = - provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL); - container->SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::Orientation::kHorizontal, margins, - between_child_spacing)); - - AccountInfo account = controller_->GetSharingAccountInfo(); - DCHECK(!account.IsEmpty()); - gfx::ImageSkia square_avatar = account.account_image.AsImageSkia(); - // The color used in `circle_mask` is irrelevant as long as it's opaque; only - // the alpha channel matters. - gfx::ImageSkia circle_mask = - gfx::ImageSkiaOperations::CreateImageWithCircleBackground( - square_avatar.size().width() / 2, SK_ColorWHITE, gfx::ImageSkia()); - gfx::ImageSkia round_avatar = - gfx::ImageSkiaOperations::CreateMaskedImage(square_avatar, circle_mask); - auto* avatar_view = - container->AddChildView(std::make_unique<views::ImageView>()); - avatar_view->SetImage(gfx::ImageSkiaOperations::CreateResizedImage( - round_avatar, skia::ImageOperations::RESIZE_BEST, - gfx::Size(kAccountAvatarSize, kAccountAvatarSize))); - - auto* link_view = - container->AddChildView(std::make_unique<views::StyledLabel>()); - link_view->SetDefaultTextStyle(views::style::STYLE_SECONDARY); - - // Only part of the string in |link_view| must be styled as a link and - // clickable. This range is marked in the *.grd entry by the first 2 - // placeholders. This GetStringFUTF16() call replaces them with empty strings - // (no-op) and saves the range in |offsets[0]| and |offsets[1]|. - std::vector<size_t> offsets; - link_view->SetText(l10n_util::GetStringFUTF16( - IDS_SEND_TAB_TO_SELF_MANAGE_DEVICES_LINK, - {std::u16string(), std::u16string(), base::UTF8ToUTF16(account.email)}, - &offsets)); - DCHECK_EQ(3u, offsets.size()); - // This object outlives its |link_view| child so base::Unretained() is safe. - link_view->AddStyleRange( - gfx::Range(offsets[0], offsets[1]), - views::StyledLabel::RangeStyleInfo::CreateForLink(base::BindRepeating( - &SendTabToSelfDevicePickerBubbleView::OnManageDevicesClicked, - base::Unretained(this)))); -} - } // namespace send_tab_to_self
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.h b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.h index 2a753c05..43e5d38 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.h +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_device_picker_bubble_view.h
@@ -19,10 +19,6 @@ class WebContents; } // namespace content -namespace ui { -class Event; -} // namespace ui - namespace send_tab_to_self { class SendTabToSelfBubbleController; @@ -57,8 +53,6 @@ void DeviceButtonPressed(SendTabToSelfBubbleDeviceButton* device_button); - void OnManageDevicesClicked(const ui::Event& event); - const views::View* GetButtonContainerForTesting() const; private:
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_promo_bubble_view.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_promo_bubble_view.cc index 26d905b..effa8c34 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_promo_bubble_view.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_promo_bubble_view.cc
@@ -11,12 +11,14 @@ #include "chrome/browser/ui/send_tab_to_self/send_tab_to_self_bubble_controller.h" #include "chrome/browser/ui/signin_view_controller.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/browser/ui/views/send_tab_to_self/manage_account_devices_link_view.h" #include "chrome/browser/ui/views/sharing_hub/sharing_hub_bubble_util.h" #include "chrome/grit/generated_resources.h" #include "components/signin/public/base/signin_metrics.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_types.h" -#include "ui/views/layout/fill_layout.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/view_class_properties.h" namespace send_tab_to_self { @@ -36,18 +38,22 @@ auto* provider = ChromeLayoutProvider::Get(); set_fixed_width( provider->GetDistanceMetric(views::DISTANCE_BUBBLE_PREFERRED_WIDTH)); - gfx::Insets margins = provider->GetInsetsMetric(views::INSETS_DIALOG); - margins.set_top(provider->GetDistanceMetric( - views::DISTANCE_DIALOG_CONTENT_MARGIN_TOP_CONTROL)); - margins.set_bottom(provider->GetDistanceMetric( - views::DISTANCE_DIALOG_CONTENT_MARGIN_BOTTOM_CONTROL)); - SetLayoutManager(std::make_unique<views::FillLayout>()); + set_margins( + gfx::Insets::TLBR(provider->GetDistanceMetric( + views::DISTANCE_DIALOG_CONTENT_MARGIN_TOP_CONTROL), + 0, 0, 0)); + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical)); auto* label = AddChildView(std::make_unique<views::Label>( l10n_util::GetStringUTF16(IDS_SEND_TAB_TO_SELF_PROMO_LABEL), views::style::CONTEXT_LABEL, views::style::STYLE_SECONDARY)); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); + label->SetProperty( + views::kMarginsKey, + gfx::Insets::VH(0, provider->GetDistanceMetric( + views::DISTANCE_BUTTON_HORIZONTAL_PADDING))); if (show_signin_button) { SetButtons(ui::DIALOG_BUTTON_OK); @@ -58,9 +64,17 @@ SetAcceptCallback(base::BindRepeating( &SendTabToSelfPromoBubbleView::OnSignInButtonClicked, base::Unretained(this))); - } else { - SetButtons(ui::DIALOG_BUTTON_NONE); + return; } + + SetButtons(ui::DIALOG_BUTTON_NONE); + auto* link_view = + AddChildView(BuildManageAccountDevicesLinkView(controller_)); + link_view->SetProperty( + views::kMarginsKey, + gfx::Insets::TLBR(provider->GetDistanceMetric( + views::DISTANCE_DIALOG_CONTENT_MARGIN_BOTTOM_TEXT), + 0, 0, 0)); } SendTabToSelfPromoBubbleView::~SendTabToSelfPromoBubbleView() {
diff --git a/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc b/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc index 19ecfeb..50a224d 100644 --- a/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc +++ b/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc
@@ -123,11 +123,11 @@ std::move(callback).Run(entry, std::move(content_view)); } else { entry->CacheView(std::move(content_view)); + loading_entry_ = entry; + loaded_callback_ = std::move(callback); content_proxy->SetAvailableCallback( base::BindOnce(&SidePanelContentSwappingContainer::RunLoadedCallback, base::Unretained(this))); - loading_entry_ = entry; - loaded_callback_ = std::move(callback); } } @@ -201,6 +201,15 @@ browser_view_->browser()->window()->CloseFeaturePromo( feature_engagement::kIPHReadingListInSidePanelFeature); } + + // Ensure that the correct combobox entry is selected. This may not be the + // case if `Show()` was called after registering a contextual entry. + if (entry_id.has_value()) { + DCHECK(header_combobox_); + header_combobox_->SetSelectedIndex( + combobox_model_->GetIndexForId(entry_id.value())); + } + SidePanelContentSwappingContainer* content_wrapper = static_cast<SidePanelContentSwappingContainer*>( GetContentView()->GetViewByID(kSidePanelContentWrapperViewId)); @@ -238,6 +247,7 @@ l10n_util::GetStringUTF16(IDS_TOOLTIP_SIDE_PANEL_SHOW)); browser_view_->right_aligned_side_panel()->RemoveChildViewT(content_view); + header_combobox_ = nullptr; base::RecordAction(base::UserMetricsAction("SidePanel.Hide")); } @@ -360,6 +370,12 @@ return absl::nullopt; } +absl::optional<SidePanelEntry::Id> SidePanelCoordinator::GetSelectedId() const { + if (!header_combobox_) + return absl::nullopt; + return combobox_model_->GetIdAt(header_combobox_->GetSelectedIndex()); +} + SidePanelRegistry* SidePanelCoordinator::GetActiveContextualRegistry() const { if (auto* web_contents = browser_view_->browser()->tab_strip_model()->GetActiveWebContents()) {
diff --git a/chrome/browser/ui/views/side_panel/side_panel_coordinator.h b/chrome/browser/ui/views/side_panel/side_panel_coordinator.h index 7629c276..914c6c4 100644 --- a/chrome/browser/ui/views/side_panel/side_panel_coordinator.h +++ b/chrome/browser/ui/views/side_panel/side_panel_coordinator.h
@@ -77,6 +77,9 @@ // entry exists. absl::optional<SidePanelEntry::Id> GetLastActiveEntryId() const; + // Returns the currently selected id in the combobox, if one is shown. + absl::optional<SidePanelEntry::Id> GetSelectedId() const; + SidePanelRegistry* GetActiveContextualRegistry() const; std::unique_ptr<views::View> CreateHeader();
diff --git a/chrome/browser/ui/views/side_panel/side_panel_coordinator_unittest.cc b/chrome/browser/ui/views/side_panel/side_panel_coordinator_unittest.cc index 2f10741..31baebd 100644 --- a/chrome/browser/ui/views/side_panel/side_panel_coordinator_unittest.cc +++ b/chrome/browser/ui/views/side_panel/side_panel_coordinator_unittest.cc
@@ -87,6 +87,14 @@ return coordinator_->last_active_global_entry_id_; } + absl::optional<SidePanelEntry::Id> GetSelectedId() { + return coordinator_->GetSelectedId(); + } + + bool ComboboxViewExists() { + return coordinator_->header_combobox_ != nullptr; + } + protected: raw_ptr<SidePanelCoordinator> coordinator_; raw_ptr<SidePanelRegistry> global_registry_; @@ -127,6 +135,41 @@ EXPECT_TRUE(browser_view()->right_aligned_side_panel()->GetVisible()); EXPECT_TRUE(GetLastActiveEntryId().has_value()); EXPECT_EQ(GetLastActiveEntryId().value(), SidePanelEntry::Id::kBookmarks); + + // Verify that the combobox entry for bookmarks is selected. + EXPECT_EQ(GetSelectedId(), SidePanelEntry::Id::kBookmarks); +} + +TEST_F(SidePanelCoordinatorTest, CloseInvalidatesComboboxPointer) { + // Verify no combobox exists before opening the side panel. + EXPECT_FALSE(ComboboxViewExists()); + + coordinator_->Toggle(); + EXPECT_TRUE(ComboboxViewExists()); + + // Verify that the pointer to the combobox view is invalidated after closing + // the side panel. + coordinator_->Toggle(); + EXPECT_FALSE(ComboboxViewExists()); +} + +TEST_F(SidePanelCoordinatorTest, TabSwitchInvalidatesComboboxPointerOnClose) { + // Verify no combobox exists before opening the side panel. + EXPECT_FALSE(ComboboxViewExists()); + + // Show a contextual entry on the first tab. + browser_view()->browser()->tab_strip_model()->ActivateTabAt(0); + coordinator_->Show(SidePanelEntry::Id::kSideSearch); + + // Switch to the second tab. + browser_view()->browser()->tab_strip_model()->ActivateTabAt(1); + + // Expect that the side panel closes. + EXPECT_FALSE(browser_view()->right_aligned_side_panel()->GetVisible()); + + // Verify that the pointer to the combobox view is invalidated after closing + // the side panel. + EXPECT_FALSE(ComboboxViewExists()); } TEST_F(SidePanelCoordinatorTest, SwapBetweenTabsWithReadingListOpen) { @@ -209,7 +252,7 @@ } // Test that the side panel closes if a contextual entry is deregistered while -// visible when no globel entries have been shown since the panel was opened. +// visible when no global entries have been shown since the panel was opened. TEST_F( SidePanelCoordinatorTest, ContextualEntryDeregisteredWhileVisibleClosesPanelIfNoLastSeenGlobalEntryExists) { @@ -244,7 +287,7 @@ } TEST_F(SidePanelCoordinatorTest, - SwapBetweenTabsAfterNavaigatingToContextualEntry) { + SwapBetweenTabsAfterNavigatingToContextualEntry) { // Open side panel and verify it opens to kReadingList by default. browser_view()->browser()->tab_strip_model()->ActivateTabAt(0); coordinator_->Toggle();
diff --git a/chrome/browser/ui/web_applications/web_app_browsertest.cc b/chrome/browser/ui/web_applications/web_app_browsertest.cc index 65259f8..69ac6b3 100644 --- a/chrome/browser/ui/web_applications/web_app_browsertest.cc +++ b/chrome/browser/ui/web_applications/web_app_browsertest.cc
@@ -434,24 +434,26 @@ IN_PROC_BROWSER_TEST_P(BackgroundColorChangeWebAppBrowserTest, BackgroundColorChange) { + const bool is_non_swa = GetBackgroundColorChangeTestMode() == + BackgroundColorChangeTestMode::kNonSWA; // Skip test parameterizations for non-system web apps that don't make sense. - if (GetBackgroundColorChangeTestMode() == - BackgroundColorChangeTestMode::kNonSWA && - PreferManifestBackgroundColor()) { + if (is_non_swa && PreferManifestBackgroundColor()) GTEST_SKIP(); - } const AppId app_id = WaitForAppInstall(); Browser* const app_browser = LaunchWebAppBrowser(app_id); content::WebContents* const web_contents = app_browser->tab_strip_model()->GetActiveWebContents(); + const bool is_dark_mode_state = + ui::NativeTheme::GetInstanceForNativeUi()->ShouldUseDarkColors(); // Wait for original background color to load. { content::BackgroundColorChangeWaiter waiter(web_contents); waiter.Wait(); - EXPECT_EQ(app_browser->app_controller()->GetBackgroundColor().value(), - SK_ColorWHITE); + EXPECT_EQ( + app_browser->app_controller()->GetBackgroundColor().value(), + !is_non_swa && is_dark_mode_state ? SK_ColorBLACK : SK_ColorWHITE); } content::AwaitDocumentOnLoadCompleted(web_contents); @@ -464,12 +466,16 @@ web_contents, "document.body.style.backgroundColor = 'cyan';")); waiter.Wait(); EXPECT_EQ(app_browser->app_controller()->GetBackgroundColor().value(), - PreferManifestBackgroundColor() ? SK_ColorWHITE : SK_ColorCYAN); + PreferManifestBackgroundColor() + ? (is_dark_mode_state ? SK_ColorBLACK : SK_ColorWHITE) + : SK_ColorCYAN); SkColor download_shelf_color; app_browser->app_controller()->GetThemeSupplier()->GetColor( ThemeProperties::COLOR_DOWNLOAD_SHELF, &download_shelf_color); EXPECT_EQ(download_shelf_color, - PreferManifestBackgroundColor() ? SK_ColorWHITE : SK_ColorCYAN); + PreferManifestBackgroundColor() + ? (is_dark_mode_state ? SK_ColorBLACK : SK_ColorWHITE) + : SK_ColorCYAN); } }
diff --git a/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom b/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom index 9a1d7cec..6ea9c4a 100644 --- a/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom +++ b/chrome/browser/ui/webui/new_tab_page/new_tab_page.mojom
@@ -46,6 +46,8 @@ string? repeat_y; string? position_x; string? position_y; + // The CSS styling property set on the background image's scrim. + string? scrim_display; }; // A generic theme.
diff --git a/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc b/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc index b4eeca8..cb2b140d 100644 --- a/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc +++ b/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler.cc
@@ -13,6 +13,7 @@ #include "base/base64.h" #include "base/bind.h" #include "base/containers/contains.h" +#include "base/containers/fixed_flat_set.h" #include "base/containers/flat_map.h" #include "base/cxx17_backports.h" #include "base/files/file_path.h" @@ -34,6 +35,7 @@ #include "chrome/browser/search/background/ntp_background_service_factory.h" #include "chrome/browser/search/background/ntp_custom_background_service.h" #include "chrome/browser/search_engines/template_url_service_factory.h" +#include "chrome/browser/themes/custom_theme_supplier.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/ui/chrome_select_file_policy.h" #include "chrome/browser/ui/color/chrome_color_id.h" @@ -72,6 +74,67 @@ const int64_t kMaxDownloadBytes = 1024 * 1024; const int64_t kMaxModuleFreImpressions = 8; +// Returns true if the scrim (dark gradient overlay) should be hidden for the +// NTP's background image. This is done to fix specific GWS themes where the +// visual impact of the scrim does not align with the artistic intent of +// partnered artists (see crbug.com/1329556). +// TODO(crbug.com/1320107): Remove the scrim for all GWS and custom background +// image configurations on the NTP. +bool ShouldHideScrim(const ThemeService* theme_service) { + DCHECK(theme_service); + const auto* theme_supplier = theme_service->GetThemeSupplier(); + if (!theme_supplier || + theme_supplier->get_theme_type() != CustomThemeSupplier::EXTENSION) { + return false; + } + + static constexpr auto kPrideThemeExtensionIdsNoScrim = + base::MakeFixedFlatSet<base::StringPiece>({ + "kkdpcclippggiadgghfmkggpemadbfcj", + "jogkmkalhlbppkpmjdpncmpdcinbkekh", + "gfkcjfbbpmldkajnebkophpelmcimglf", + "mchijkgkaabamaokgcnbmjpfoagkpjfc", + "cdabkdaechplopdfoahhjgkbjgillcme", + "depfhkphmnoonikdokgpejilanmcdonk", + "efiamifmcbajfehbkjemggiafognbljk", + "iclkbhippclhfamkdoigedgnnfbhefpl", + "ckfehdejjppobbllbkjgcpaockgdigen", + "figmdifbokklifinmmjcjdkkopjflhnj", + "nkgiaofmleojhehacfognclpmoolihko", + "npkdokffjmnleabnfihminmikibdhmfa", + "klnkeldihpjnjoopojllmnpepbpljico", + "iffdmpenldeofnlfjmbjcdmafhoekmka", + "mckialangcdpcdcflekinnpamfkmkobo", + }); + + const std::string& extension_id = theme_supplier->extension_id(); + return base::Contains(kPrideThemeExtensionIdsNoScrim, extension_id); +} + +// Returns true if we should force dark foreground colors for the Google logo +// and the One Google Bar. This is done to fix specific GWS themes where the +// always-light logo and OGB colors do not sufficiently contrast with lighter +// image backgrounds (see crbug.com/1329552). +// TODO(crbug.com/1328918): Address this in a general way and extend support to +// custom background images, not just CWS themes. +bool ShouldForceDarkForegroundColorsForLogoAndOGB( + const ThemeService* theme_service) { + const auto* theme_supplier = theme_service->GetThemeSupplier(); + if (!theme_supplier || + theme_supplier->get_theme_type() != CustomThemeSupplier::EXTENSION) { + return false; + } + static constexpr auto kPrideThemeExtensionIdsDarkForeground = + base::MakeFixedFlatSet<base::StringPiece>({ + "klnkeldihpjnjoopojllmnpepbpljico", + "iffdmpenldeofnlfjmbjcdmafhoekmka", + "mckialangcdpcdcflekinnpamfkmkobo", + }); + + const std::string& extension_id = theme_supplier->extension_id(); + return base::Contains(kPrideThemeExtensionIdsDarkForeground, extension_id); +} + new_tab_page::mojom::ThemePtr MakeTheme( const ui::ColorProvider& color_provider, const ui::ThemeProvider* theme_provider, @@ -94,7 +157,8 @@ text_color = color_provider.GetColor(kColorNewTabPageTextUnthemed); most_visited->background_color = color_provider.GetColor( kColorNewTabPageMostVisitedTileBackgroundUnthemed); - theme->logo_color = color_provider.GetColor(kColorNewTabPageLogoUnthemed); + theme->logo_color = + color_provider.GetColor(kColorNewTabPageLogoUnthemedLight); } else { text_color = color_provider.GetColor(kColorNewTabPageText); most_visited->background_color = @@ -165,6 +229,24 @@ } else { background_image = nullptr; } + + // The special case handling that removes the scrim and forces dark foreground + // colors should only be applied when the user does not have a custom + // background selected and has installed a GWS theme with a bundled background + // image. The first condition is necessary as a custom background image can be + // set while a GWS theme with a bundled image is concurrently enabled (see + // crbug.com/1329556 and crbug.com/1329552). + if (!custom_background.has_value() && + theme_provider->HasCustomImage(IDR_THEME_NTP_BACKGROUND)) { + if (ShouldForceDarkForegroundColorsForLogoAndOGB(theme_service)) { + theme->is_dark = false; + theme->logo_color = + color_provider.GetColor(kColorNewTabPageLogoUnthemedDark); + } + if (ShouldHideScrim(theme_service)) + background_image->scrim_display = "none"; + } + theme->background_image = std::move(background_image); if (custom_background.has_value()) { theme->background_image_attribution_1 =
diff --git a/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc b/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc index 16fd642d..61f1fa5 100644 --- a/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc +++ b/chrome/browser/ui/webui/new_tab_page/new_tab_page_handler_unittest.cc
@@ -405,7 +405,7 @@ SkColorSetRGB(0, 0, 1)); mock_color_provider_source_.SetColor(kColorNewTabPageTextUnthemed, SkColorSetRGB(0, 0, 2)); - mock_color_provider_source_.SetColor(kColorNewTabPageLogoUnthemed, + mock_color_provider_source_.SetColor(kColorNewTabPageLogoUnthemedLight, SkColorSetRGB(0, 0, 3)); mock_color_provider_source_.SetColor( kColorNewTabPageMostVisitedTileBackgroundUnthemed,
diff --git a/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc b/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc index 523fdbe..58b604f 100644 --- a/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc +++ b/chrome/browser/ui/webui/new_tab_page/untrusted_source.cc
@@ -145,7 +145,7 @@ } if (path == "background_image") { ServeBackgroundImage(url_param, GURL(), "cover", "no-repeat", "no-repeat", - "center", "center", std::move(callback)); + "center", "center", "inherit", std::move(callback)); return; } if (path == "custom_background_image") { @@ -172,6 +172,7 @@ params.count("repeatY") == 1 ? params["repeatY"] : "no-repeat", params.count("positionX") == 1 ? params["positionX"] : "center", params.count("positionY") == 1 ? params["positionY"] : "center", + params.count("scrimDisplay") == 1 ? params["scrimDisplay"] : "inherit", std::move(callback)); return; } @@ -275,6 +276,7 @@ const std::string& repeat_y, const std::string& position_x, const std::string& position_y, + const std::string& scrim_display, content::URLDataSource::GotDataCallback callback) { if (!url.is_valid() || !(url.SchemeIs(url::kHttpsScheme) || url.SchemeIs(content::kChromeUIUntrustedScheme))) { @@ -296,6 +298,7 @@ replacements["repeatY"] = repeat_y; replacements["positionX"] = position_x; replacements["positionY"] = position_y; + replacements["scrimDisplay"] = scrim_display; std::string html = FormatTemplate( IDR_NEW_TAB_PAGE_UNTRUSTED_BACKGROUND_IMAGE_HTML, replacements); std::move(callback).Run(base::RefCountedString::TakeString(&html));
diff --git a/chrome/browser/ui/webui/new_tab_page/untrusted_source.h b/chrome/browser/ui/webui/new_tab_page/untrusted_source.h index 81721f4..e0d444f0 100644 --- a/chrome/browser/ui/webui/new_tab_page/untrusted_source.h +++ b/chrome/browser/ui/webui/new_tab_page/untrusted_source.h
@@ -76,6 +76,7 @@ const std::string& repeat_y, const std::string& position_x, const std::string& position_y, + const std::string& scrim_display, content::URLDataSource::GotDataCallback callback); std::vector<content::URLDataSource::GotDataCallback>
diff --git a/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc b/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc index 882cbab..6ee6dbd9 100644 --- a/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc +++ b/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc
@@ -316,13 +316,12 @@ // Retrieve the text contents of the policy table cells for all policies. const std::string javascript = - "var entries = document.getElementById('policy-ui')" - " .querySelectorAll('.policy-table');" + "var entries = getAllPolicyTables();" "var policies = [];" "for (var i = 0; i < entries.length; ++i) {" - " var items = entries[i].querySelectorAll('.policy.row');" + " var items = getAllPolicyRows(entries[i]);" " for (var j = 0; j < items.length; ++j) {" - " var children = items[j].querySelectorAll('div');" + " var children = getAllPolicyRowDivs(items[j]);" " var values = [];" " for(var k = 0; k < children.length - 1; ++k) {" " values.push(children[k].textContent.trim());" @@ -558,7 +557,7 @@ return; } - const policies = statusSection.querySelectorAll('fieldset'); + const policies = getPolicyFieldsets(); const statuses = {}; for (let i = 0; i < policies.length; ++i) { const legend = policies[i].querySelector('legend').textContent; @@ -881,8 +880,7 @@ // Used to retrieve the contents of the policy precedence rows. const std::string kJavaScript = - "var precedence_row = document.getElementById('policy-ui')" - " .querySelector('.policy-table .precedence.row > .value');" + "var precedence_row = getPrecedenceRowValue();" "domAutomationController.send(precedence_row.textContent);"; };
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc index 1f81e2c..e705b2c 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_factory.cc
@@ -12,7 +12,6 @@ #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/printing/cups_printers_manager_factory.h" -#include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" @@ -63,15 +62,6 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - // Edge case: KerberosCredentialsManagerFactory::Get(profile) returns the - // instance associated with the primary profile, even if |profile| is not the - // primary profile, which can cause issues in multi-profile environments. - // Only call Get() if the profile is primary; see https://crbug.com/1103140. - KerberosCredentialsManager* kerberos_credentials_manager = - ProfileHelper::IsPrimaryProfile(profile) - ? KerberosCredentialsManagerFactory::Get(profile) - : nullptr; - return new OsSettingsManager( profile, local_search_service::LocalSearchServiceProxyFactory:: @@ -80,7 +70,7 @@ phonehub::PhoneHubManagerFactory::GetForProfile(profile), SyncServiceFactory::GetForProfile(profile), SupervisedUserServiceFactory::GetForProfile(profile), - kerberos_credentials_manager, + KerberosCredentialsManagerFactory::Get(profile), ArcAppListPrefsFactory::GetForBrowserContext(profile), IdentityManagerFactory::GetForProfile(profile), android_sms::AndroidSmsServiceFactory::GetForBrowserContext(profile),
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc index 3a659ba8..ef1a073 100644 --- a/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc +++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_manager_unittest.cc
@@ -14,7 +14,6 @@ #include "chrome/browser/ash/multidevice_setup/multidevice_setup_client_factory.h" #include "chrome/browser/ash/phonehub/phone_hub_manager_factory.h" #include "chrome/browser/ash/printing/cups_printers_manager_factory.h" -#include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/sync/sync_service_factory.h" @@ -54,10 +53,7 @@ pref_service_.registry()); local_search_service::LocalSearchServiceProxyFactory::GetInstance() ->SetLocalState(&pref_service_); - KerberosCredentialsManager* kerberos_credentials_manager = - ProfileHelper::IsPrimaryProfile(profile) - ? KerberosCredentialsManagerFactory::Get(profile) - : nullptr; + manager_ = std::make_unique<OsSettingsManager>( profile, local_search_service_proxy_.get(), multidevice_setup::MultiDeviceSetupClientFactory::GetForProfile( @@ -65,7 +61,7 @@ phonehub::PhoneHubManagerFactory::GetForProfile(profile), SyncServiceFactory::GetForProfile(profile), SupervisedUserServiceFactory::GetForProfile(profile), - kerberos_credentials_manager, + KerberosCredentialsManagerFactory::Get(profile), ArcAppListPrefsFactory::GetForBrowserContext(profile), IdentityManagerFactory::GetForProfile(profile), android_sms::AndroidSmsServiceFactory::GetForBrowserContext(profile),
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index 1919f5c..bda0b74e 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -280,9 +280,6 @@ base::FeatureList::IsEnabled(password_manager::features::kSendPasswords)); #if !BUILDFLAG(IS_CHROMEOS) - html_source->AddBoolean("enableDesktopRestructuredLanguageSettings", - base::FeatureList::IsEnabled( - language::kDesktopRestructuredLanguageSettings)); html_source->AddBoolean( "enableDesktopDetailedLanguageSettings", base::FeatureList::IsEnabled(language::kDesktopDetailedLanguageSettings));
diff --git a/chrome/browser/ui/window_name_prompt/window_name_prompt.cc b/chrome/browser/ui/window_name_prompt/window_name_prompt.cc index f709e14..5b4bc2c 100644 --- a/chrome/browser/ui/window_name_prompt/window_name_prompt.cc +++ b/chrome/browser/ui/window_name_prompt/window_name_prompt.cc
@@ -37,10 +37,10 @@ dialog_builder.model())) .AddCancelButton(base::DoNothing()) .AddTextfield( + kWindowNameFieldId, // Deliberately use no label - the dialog contains only this // textfield, and its title serves as a label for the textfield. - {}, base::UTF8ToUTF16(browser->user_title()), - ui::DialogModelTextfield::Params().SetId(kWindowNameFieldId)) + {}, base::UTF8ToUTF16(browser->user_title())) .SetInitiallyFocusedField(kWindowNameFieldId) .Build(); }
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index ade52c1..3d96104 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1653652279-7e49a0371314fee4848fa6c7fe25803951d94464.profdata +chrome-linux-main-1653674373-ae360f838a4fa534e501473833b13cfbbd93791b.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index e9c9af28..c86ae9b 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1653652279-f3ba122b98b3f07c3583a3e13e2924d041c801eb.profdata +chrome-mac-arm-main-1653674373-93e7a7459c3f91f24d82ce4da21ea54e657793e2.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 8528cc3..1eabfb8 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1653641971-56e7107e7ccc4d789391f6bc377a094117b5b0d9.profdata +chrome-win32-main-1653663221-586ad2636e97b2c092190f2c884a2a1942a84385.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index bb094e3..ead3d01 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1653641971-db00215fb1c60069dd72bc27b03cbd78aa9519d0.profdata +chrome-win64-main-1653663221-1d7f02af064b740916358abe3db80ef6b8a36865.profdata
diff --git a/chrome/chrome_cleaner/DEPS b/chrome/chrome_cleaner/DEPS index 034833c..bc98e1c 100644 --- a/chrome/chrome_cleaner/DEPS +++ b/chrome/chrome_cleaner/DEPS
@@ -9,7 +9,18 @@ "+mojo/public", "+sandbox/win/src", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/protobuf/src/google/protobuf", "+url", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/chrome/common/profiler/thread_profiler_browsertest.cc b/chrome/common/profiler/thread_profiler_browsertest.cc index 7468fd2..406a0af6 100644 --- a/chrome/common/profiler/thread_profiler_browsertest.cc +++ b/chrome/common/profiler/thread_profiler_browsertest.cc
@@ -161,6 +161,9 @@ #define MAYBE_GpuProcessMainThread DISABLED_GpuProcessMainThread #define MAYBE_GpuProcessIOThread DISABLED_GpuProcessIOThread #define MAYBE_GpuProcessCompositorThread DISABLED_GpuProcessCompositorThread +#define MAYBE_RendererProcessIOThread DISABLED_RendererProcessIOThread +#define MAYBE_RendererProcessCompositorThread \ + DISABLED_RendererProcessCompositorThread // Android doesn't have a network service process. #define MAYBE_NetworkServiceProcessIOThread \ DISABLED_NetworkServiceProcessIOThread @@ -170,6 +173,8 @@ #define MAYBE_GpuProcessMainThread GpuProcessMainThread #define MAYBE_GpuProcessIOThread GpuProcessIOThread #define MAYBE_GpuProcessCompositorThread GpuProcessCompositorThread +#define MAYBE_RendererProcessIOThread RendererProcessIOThread +#define MAYBE_RendererProcessCompositorThread RendererProcessCompositorThread #define MAYBE_NetworkServiceProcessIOThread NetworkServiceProcessIOThread #endif @@ -210,13 +215,14 @@ metrics::RENDERER_PROCESS, metrics::MAIN_THREAD)); } -IN_PROC_BROWSER_TEST_F(ThreadProfilerBrowserTest, RendererProcessIOThread) { +IN_PROC_BROWSER_TEST_F(ThreadProfilerBrowserTest, + MAYBE_RendererProcessIOThread) { EXPECT_TRUE(WaitForProfile(metrics::SampledProfile::PROCESS_STARTUP, metrics::RENDERER_PROCESS, metrics::IO_THREAD)); } IN_PROC_BROWSER_TEST_F(ThreadProfilerBrowserTest, - RendererProcessCompositorThread) { + MAYBE_RendererProcessCompositorThread) { EXPECT_TRUE(WaitForProfile(metrics::SampledProfile::PROCESS_STARTUP, metrics::RENDERER_PROCESS, metrics::COMPOSITOR_THREAD));
diff --git a/chrome/common/profiler/thread_profiler_platform_configuration.cc b/chrome/common/profiler/thread_profiler_platform_configuration.cc index f34a086..7682a3d 100644 --- a/chrome/common/profiler/thread_profiler_platform_configuration.cc +++ b/chrome/common/profiler/thread_profiler_platform_configuration.cc
@@ -228,7 +228,7 @@ // TODO(https://crbug.com/1326430): Enable for all the default processes. switch (process) { case metrics::CallStackProfileParams::Process::kRenderer: - return true; + return thread == metrics::CallStackProfileParams::Thread::kMain; default: return false;
diff --git a/chrome/common/profiler/thread_profiler_platform_configuration_unittest.cc b/chrome/common/profiler/thread_profiler_platform_configuration_unittest.cc index 0dca841b..b7d2d44 100644 --- a/chrome/common/profiler/thread_profiler_platform_configuration_unittest.cc +++ b/chrome/common/profiler/thread_profiler_platform_configuration_unittest.cc
@@ -198,13 +198,13 @@ EXPECT_TRUE(config()->IsEnabledForThread( metrics::CallStackProfileParams::Process::kRenderer, metrics::CallStackProfileParams::Thread::kMain)); - EXPECT_TRUE(config()->IsEnabledForThread( + EXPECT_FALSE(config()->IsEnabledForThread( metrics::CallStackProfileParams::Process::kRenderer, metrics::CallStackProfileParams::Thread::kIo)); - EXPECT_TRUE(config()->IsEnabledForThread( + EXPECT_FALSE(config()->IsEnabledForThread( metrics::CallStackProfileParams::Process::kRenderer, metrics::CallStackProfileParams::Thread::kCompositor)); - EXPECT_TRUE(config()->IsEnabledForThread( + EXPECT_FALSE(config()->IsEnabledForThread( metrics::CallStackProfileParams::Process::kRenderer, metrics::CallStackProfileParams::Thread::kServiceWorker));
diff --git a/chrome/test/data/extensions/api_test/debugger_file_access/background.js b/chrome/test/data/extensions/api_test/debugger_file_access/background.js index bebf2eb..b2d2c63 100644 --- a/chrome/test/data/extensions/api_test/debugger_file_access/background.js +++ b/chrome/test/data/extensions/api_test/debugger_file_access/background.js
@@ -14,6 +14,7 @@ async function runNotAllowedTest(method, params, expectAllowed) { const NOT_ALLOWED = "Not allowed"; + const NOT_FOUND = '\'Browser.setDownloadBehavior\' wasn\'t found'; const tab = await openTab(chrome.runtime.getURL('dummy.html')); const debuggee = {tabId: tab.id}; chrome.debugger.attach(debuggee, '1.2', function() { @@ -27,7 +28,7 @@ } catch (e) { } chrome.debugger.detach(debuggee, () => { - const allowed = message !== NOT_ALLOWED; + const allowed = message !== NOT_ALLOWED && message !== NOT_FOUND; if (allowed === expectAllowed) chrome.test.succeed(); else
diff --git a/chrome/test/data/extensions/api_test/debugger_inspect_worker/background.js b/chrome/test/data/extensions/api_test/debugger_inspect_worker/background.js index 6fc91d0..0cbda6d 100644 --- a/chrome/test/data/extensions/api_test/debugger_inspect_worker/background.js +++ b/chrome/test/data/extensions/api_test/debugger_inspect_worker/background.js
@@ -11,25 +11,14 @@ const debuggee = {tabId: tab.id}; await new Promise(resolve => chrome.debugger.attach(debuggee, protocolVersion, resolve)); - chrome.debugger.sendCommand(debuggee, 'ServiceWorker.enable', null); - let workerReadyCallback; - chrome.debugger.onEvent.addListener((source, method, params) => { - if (method !== 'ServiceWorker.workerVersionUpdated') - return; - const versions = params.versions; - if (!versions.length || versions[0].runningStatus !== 'running') - return; - workerReadyCallback(versions[0].versionId); - }); - const versionId = await new Promise(resolve => - workerReadyCallback = resolve); - await new Promise(resolve => - chrome.debugger.sendCommand(debuggee, 'ServiceWorker.inspectWorker', - {versionId}, resolve)) - chrome.test.assertTrue(!!chrome.runtime.lastError, - 'Expected ServiceWorker.inspectWorker to fail'); - chrome.test.assertEq('Permission denied', - JSON.parse(chrome.runtime.lastError.message).message); + await new Promise( + resolve => chrome.debugger.sendCommand( + debuggee, 'ServiceWorker.enable', resolve)); + chrome.test.assertTrue( + !!chrome.runtime.lastError, `'ServiceWorker.enable' wasn't found`); + chrome.test.assertEq( + `'ServiceWorker.enable' wasn't found`, + JSON.parse(chrome.runtime.lastError.message).message); chrome.test.succeed(); } ]));
diff --git a/chrome/test/data/webui/BUILD.gn b/chrome/test/data/webui/BUILD.gn index 70a78da..b31aa6c 100644 --- a/chrome/test/data/webui/BUILD.gn +++ b/chrome/test/data/webui/BUILD.gn
@@ -224,28 +224,6 @@ "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/multidevice_setup/integration_test.m.js", "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/multidevice_setup/setup_succeeded_page_test.m.js", "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/multidevice_setup/start_setup_page_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_behavior_mojo_tests.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_indicator_mojo_tests.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_apnlist_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_choose_mobile_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_config_element_behavior_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_config_input_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_config_select_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_config_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_config_toggle_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_icon_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_ip_config_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_list_item_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_list_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_nameservers_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_password_input_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_property_list_mojo_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_exclusions_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_input_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_select_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/network_siminfo_test.m.js", - "$root_gen_dir/chrome/test/data/webui/cr_components/chromeos/network/sim_lock_dialogs_test.m.js", ] } defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ]
diff --git a/chrome/test/data/webui/cr_components/certificate_manager_provisioning_test.ts b/chrome/test/data/webui/cr_components/certificate_manager_provisioning_test.ts index 3def7506..1b98257c 100644 --- a/chrome/test/data/webui/cr_components/certificate_manager_provisioning_test.ts +++ b/chrome/test/data/webui/cr_components/certificate_manager_provisioning_test.ts
@@ -128,6 +128,7 @@ return browserProxy.whenCalled('refreshCertificateProvisioningProcesses') .then(function() { + browserProxy.resetResolver('refreshCertificateProvisioningProcesses'); webUIListenerCallback( 'certificate-provisioning-processes-changed', [createSampleCertificateProvisioningProcess(false)]); @@ -172,6 +173,25 @@ assertFalse(!!dialog); }); }); + + test('OpensDialog_RefreshesData', async function() { + const dialogId = 'certificate-provisioning-details-dialog'; + const anchorForTest = document.createElement('a'); + document.body.appendChild(anchorForTest); + assertFalse(!!certProvisioningList.shadowRoot!.querySelector(dialogId)); + certProvisioningList.dispatchEvent( + new CustomEvent(CertificateProvisioningViewDetailsActionEvent, { + bubbles: true, + composed: true, + detail: { + model: createSampleCertificateProvisioningProcess(false), + anchor: anchorForTest + } + })); + const whenRefreshCalled = + browserProxy.whenCalled('refreshCertificateProvisioningProcesses'); + await whenRefreshCalled; + }); }); suite('DetailsDialogTests', function() {
diff --git a/chrome/test/data/webui/cr_components/chromeos/BUILD.gn b/chrome/test/data/webui/cr_components/chromeos/BUILD.gn index 819eb9e..c04d7b0 100644 --- a/chrome/test/data/webui/cr_components/chromeos/BUILD.gn +++ b/chrome/test/data/webui/cr_components/chromeos/BUILD.gn
@@ -6,10 +6,7 @@ assert(is_chromeos, "CrComponents Chromeos tests are Chrome OS only.") group("modulize") { - deps = [ - "multidevice_setup:modulize", - "network:modulize", - ] + deps = [ "multidevice_setup:modulize" ] } group("closure_compile") {
diff --git a/chrome/test/data/webui/cr_components/chromeos/bluetooth/bluetooth_pairing_ui_test.js b/chrome/test/data/webui/cr_components/chromeos/bluetooth/bluetooth_pairing_ui_test.js index dbc1f69..9d8147f 100644 --- a/chrome/test/data/webui/cr_components/chromeos/bluetooth/bluetooth_pairing_ui_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/bluetooth/bluetooth_pairing_ui_test.js
@@ -1055,4 +1055,25 @@ // Error text should no longer be showing. assertEquals(getDeviceSelectionPage().failedPairingDeviceId, ''); }); + + // Regression test for b/231738454. + test( + 'Mojo connections are closed after dialog is removed from DOM', + async function() { + await init(); + assertEquals(1, bluetoothConfig.getNumStartDiscoveryCalls()); + + // Remove the pairing dialog from the DOM. + bluetoothPairingUi.remove(); + + // Disable Bluetooth. + bluetoothConfig.setSystemState(BluetoothSystemState.kDisabled); + await flushTasks(); + + // Re-enable Bluetooth. If the Mojo connections are still alive, this + // will trigger discovery to start again. + bluetoothConfig.setSystemState(BluetoothSystemState.kEnabled); + await flushTasks(); + assertEquals(1, bluetoothConfig.getNumStartDiscoveryCalls()); + }); });
diff --git a/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js b/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js index 555e0b44..5d8f727 100644 --- a/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js +++ b/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js
@@ -103,6 +103,9 @@ * @private {?FakeDevicePairingHandler} */ this.lastPairingHandler_ = null; + + /** @private {number} */ + this.numStartDiscoveryCalls_ = 0; } /** @@ -144,6 +147,7 @@ this.lastDiscoveryDelegate_ = delegate; this.notifyDiscoveryStarted_(); this.notifyDelegatesPropertiesUpdated_(); + this.numStartDiscoveryCalls_++; } /** @@ -497,4 +501,11 @@ d => d.deviceProperties.id === deviceId); return device ? device : null; } + + /** + * @return {number} + */ + getNumStartDiscoveryCalls() { + return this.numStartDiscoveryCalls_; + } }
diff --git a/chrome/test/data/webui/cr_components/chromeos/cr_components_chromeos_v3_browsertest.js b/chrome/test/data/webui/cr_components/chromeos/cr_components_chromeos_v3_browsertest.js index 405aacc..1bb9f7b 100644 --- a/chrome/test/data/webui/cr_components/chromeos/cr_components_chromeos_v3_browsertest.js +++ b/chrome/test/data/webui/cr_components/chromeos/cr_components_chromeos_v3_browsertest.js
@@ -40,28 +40,28 @@ ['SpinnerPage', 'bluetooth/bluetooth_spinner_page_test.js'], ].forEach(test => registerTest('Bluetooth', 'bluetooth-pairing', ...test)); -[['CrPolicyNetworkBehaviorMojo', 'network/cr_policy_network_behavior_mojo_tests.m.js'], - ['CrPolicyNetworkIndicatorMojo', 'network/cr_policy_network_indicator_mojo_tests.m.js'], - ['NetworkApnlist', 'network/network_apnlist_test.m.js'], - ['NetworkChooseMobile', 'network/network_choose_mobile_test.m.js'], - ['NetworkConfig', 'network/network_config_test.m.js'], - ['NetworkConfigElementBehavior', 'network/network_config_element_behavior_test.m.js'], - ['NetworkConfigInput', 'network/network_config_input_test.m.js'], - ['NetworkConfigSelect', 'network/network_config_select_test.m.js'], - ['NetworkConfigToggle', 'network/network_config_toggle_test.m.js'], - ['NetworkIcon', 'network/network_icon_test.m.js'], - ['NetworkIpConfig', 'network/network_ip_config_test.m.js'], - ['NetworkList', 'network/network_list_test.m.js'], - ['NetworkListItem', 'network/network_list_item_test.m.js'], - ['NetworkNameservers', 'network/network_nameservers_test.m.js'], - ['NetworkPasswordInput', 'network/network_password_input_test.m.js'], - ['NetworkPropertyListMojo', 'network/network_property_list_mojo_test.m.js'], - ['NetworkProxyExclusions', 'network/network_proxy_exclusions_test.m.js'], - ['NetworkProxyInput', 'network/network_proxy_input_test.m.js'], - ['NetworkProxy', 'network/network_proxy_test.m.js'], - ['NetworkSelect', 'network/network_select_test.m.js'], - ['NetworkSiminfo', 'network/network_siminfo_test.m.js'], - ['SimLockDialogs', 'network/sim_lock_dialogs_test.m.js'], +[['CrPolicyNetworkBehaviorMojo', 'network/cr_policy_network_behavior_mojo_tests.js'], + ['CrPolicyNetworkIndicatorMojo', 'network/cr_policy_network_indicator_mojo_tests.js'], + ['NetworkApnlist', 'network/network_apnlist_test.js'], + ['NetworkChooseMobile', 'network/network_choose_mobile_test.js'], + ['NetworkConfig', 'network/network_config_test.js'], + ['NetworkConfigElementBehavior', 'network/network_config_element_behavior_test.js'], + ['NetworkConfigInput', 'network/network_config_input_test.js'], + ['NetworkConfigSelect', 'network/network_config_select_test.js'], + ['NetworkConfigToggle', 'network/network_config_toggle_test.js'], + ['NetworkIcon', 'network/network_icon_test.js'], + ['NetworkIpConfig', 'network/network_ip_config_test.js'], + ['NetworkList', 'network/network_list_test.js'], + ['NetworkListItem', 'network/network_list_item_test.js'], + ['NetworkNameservers', 'network/network_nameservers_test.js'], + ['NetworkPasswordInput', 'network/network_password_input_test.js'], + ['NetworkPropertyListMojo', 'network/network_property_list_mojo_test.js'], + ['NetworkProxyExclusions', 'network/network_proxy_exclusions_test.js'], + ['NetworkProxyInput', 'network/network_proxy_input_test.js'], + ['NetworkProxy', 'network/network_proxy_test.js'], + ['NetworkSelect', 'network/network_select_test.js'], + ['NetworkSiminfo', 'network/network_siminfo_test.js'], + ['SimLockDialogs', 'network/sim_lock_dialogs_test.js'], ].forEach(test => registerTest('NetworkComponents', 'os-settings', ...test)); [['NetworkDiagnostics', 'network_health/network_diagnostics_test.js'],
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/BUILD.gn b/chrome/test/data/webui/cr_components/chromeos/network/BUILD.gn index feaf09e7..ae1922e1 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/BUILD.gn +++ b/chrome/test/data/webui/cr_components/chromeos/network/BUILD.gn
@@ -1,38 +1,3 @@ # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - -import("//ui/webui/resources/cr_components/chromeos/os_cr_components.gni") -import("//ui/webui/resources/tools/js_modulizer.gni") - -js_modulizer("modulize") { - input_files = [ - "cr_policy_network_behavior_mojo_tests.js", - "cr_policy_network_indicator_mojo_tests.js", - "network_apnlist_test.js", - "network_choose_mobile_test.js", - "network_config_element_behavior_test.js", - "network_config_input_test.js", - "network_config_select_test.js", - "network_config_toggle_test.js", - "network_config_test.js", - "network_icon_test.js", - "network_ip_config_test.js", - "network_list_item_test.js", - "network_list_test.js", - "network_nameservers_test.js", - "network_password_input_test.js", - "network_property_list_mojo_test.js", - "network_proxy_exclusions_test.js", - "network_proxy_input_test.js", - "network_proxy_test.js", - "network_select_test.js", - "network_siminfo_test.js", - "sim_lock_dialogs_test.js", - ] - namespace_rewrites = - cr_components_chromeos_namespace_rewrites + [ - "network_config.MojoInterfaceProviderImpl|MojoInterfaceProviderImpl", - "test_util.eventToPromise|eventToPromise", - ] -}
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_behavior_mojo_tests.js b/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_behavior_mojo_tests.js index d4122c6..1d45ccf5 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_behavior_mojo_tests.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_behavior_mojo_tests.js
@@ -4,14 +4,12 @@ /** @fileoverview Suite of tests for CrPolicyIndicatorBehavior. */ -// clang-format off -// #import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -// #import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; -// -// #import {CrPolicyNetworkBehaviorMojo} from 'chrome://resources/cr_components/chromeos/network/cr_policy_network_behavior_mojo.m.js'; -// #import {CrPolicyIndicatorType} from 'chrome://resources/cr_elements/policy/cr_policy_indicator_behavior.m.js'; -// #import {Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; + +import {CrPolicyNetworkBehaviorMojo} from 'chrome://resources/cr_components/chromeos/network/cr_policy_network_behavior_mojo.m.js'; +import {CrPolicyIndicatorType} from 'chrome://resources/cr_elements/policy/cr_policy_indicator_behavior.m.js'; +import {Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('CrPolicyNetworkBehaviorMojo', function() { suiteSetup(async () => {
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_indicator_mojo_tests.js b/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_indicator_mojo_tests.js index d6fd42c..a9c6d68 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_indicator_mojo_tests.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/cr_policy_network_indicator_mojo_tests.js
@@ -4,19 +4,17 @@ /** @fileoverview Suite of tests for cr_policy-network-indicator-mojo. */ -// clang-format off -// #import 'chrome://resources/cr_components/chromeos/network/cr_policy_network_indicator_mojo.m.js'; -// #import 'chrome://test/cr_components/chromeos/network/cr_policy_strings.js'; +import 'chrome://resources/cr_components/chromeos/network/cr_policy_network_indicator_mojo.m.js'; +import 'chrome://test/cr_components/chromeos/network/cr_policy_strings.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('cr-policy-network-indicator-mojo', function() { /** @type {!CrPolicyNetworkIndicatorMojoElement|undefined} */ let indicator; function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); } @@ -26,7 +24,7 @@ indicator = document.createElement('cr-policy-network-indicator-mojo'); document.body.appendChild(indicator); - Polymer.dom.flush(); + flush(); return new Promise(resolve => setTimeout(resolve)); });
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_apnlist_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_apnlist_test.js index 393b0b0..6f7480a 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_apnlist_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_apnlist_test.js
@@ -2,20 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_apnlist.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_apnlist.m.js'; -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkNetworkApnlistTest', function() { /** @type {!NetworkApnlist|undefined} */ let apnlist; function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); } @@ -47,7 +45,7 @@ }, }, }); - Polymer.dom.flush(); + flush(); } /** @@ -84,7 +82,7 @@ }, }; document.body.appendChild(apnlist); - Polymer.dom.flush(); + flush(); }); test('Last good APN option', function() {
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_choose_mobile_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_choose_mobile_test.js index fea8024c..3bc05da 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_choose_mobile_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_choose_mobile_test.js
@@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_choose_mobile.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_choose_mobile.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkChooseMobileTest', function() { /** @type {!NetworkChooseMobile|undefined} */ @@ -25,7 +23,7 @@ } }; document.body.appendChild(chooseMobile); - Polymer.dom.flush(); + flush(); }); test('Scan button enabled state', function() { @@ -44,7 +42,7 @@ chooseMobile.deviceState = { scanning: false }; - Polymer.dom.flush(); + flush(); // Scan button is enabled. const isScanEnabled = !scanButton.disabled; @@ -54,7 +52,7 @@ chooseMobile.deviceState = { scanning: true }; - Polymer.dom.flush(); + flush(); // Scan button is disabled while the device is currently scanning. assertTrue(scanButton.disabled); @@ -74,7 +72,7 @@ cellular: {} } }; - Polymer.dom.flush(); + flush(); assertTrue(scanButton.disabled); } @@ -93,7 +91,7 @@ } }; chooseMobile.deviceState = {scanning: false}; - Polymer.dom.flush(); + flush(); const scanButton = chooseMobile.$$('cr-button'); const select = chooseMobile.$$('select');
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_config_element_behavior_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_config_element_behavior_test.js index 82a32ce2..678a0e6 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_config_element_behavior_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_config_element_behavior_test.js
@@ -2,17 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -// #import 'chrome://resources/mojo/services/network/public/mojom/ip_address.mojom-lite.js'; -// #import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; -// #import 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js'; -// #import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/cros_network_config.mojom-lite.js'; +import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +import 'chrome://resources/mojo/services/network/public/mojom/ip_address.mojom-lite.js'; +import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; +import 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js'; +import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/cros_network_config.mojom-lite.js'; -// #import {NetworkConfigElementBehavior} from 'chrome://resources/cr_components/chromeos/network/network_config_element_behavior.m.js'; -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {flush, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {NetworkConfigElementBehavior} from 'chrome://resources/cr_components/chromeos/network/network_config_element_behavior.m.js'; +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {flush, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('CrComponentsNetworkConfigElementBehaviorTest', function() { /** @type {!NetworkConfigElementBehavior} */ @@ -57,7 +55,7 @@ setup(function() { config = document.createElement('test-network-config-element'); document.body.appendChild(config); - Polymer.dom.flush(); + flush(); }); test('Policy indicator states', function() {
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_config_input_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_config_input_test.js index 84f1892..e6f01e7a 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_config_input_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_config_input_test.js
@@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://resources/cr_components/chromeos/network/network_config_input.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_config_input.m.js'; -// #import {keyEventOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {keyEventOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkConfigInputTest', function() { /** @type {!NetworkConfigInput|undefined} */ @@ -16,7 +14,7 @@ setup(function() { configInput = document.createElement('network-config-input'); document.body.appendChild(configInput); - Polymer.dom.flush(); + flush(); }); test('Enter key propagates up enter event', function(done) { @@ -27,7 +25,7 @@ // Simulate pressing enter on the input element. const inputEl = configInput.$$('cr-input'); - MockInteractions.keyEventOn( + keyEventOn( inputEl, 'keypress', /* keyCode */ 13, /* modifiers */ undefined, 'Enter'); });
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_config_select_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_config_select_test.js index 901ad5b..2487cd898 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_config_select_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_config_select_test.js
@@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_config_select.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_config_select.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkConfigSelectTest', function() { /** @type {!NetworkConfigSelect|undefined} */ @@ -17,7 +15,7 @@ configSelect = document.createElement('network-config-select'); configSelect.oncPrefix = 'Cellular.ActivationState'; document.body.appendChild(configSelect); - Polymer.dom.flush(); + flush(); }); test('Item enabled state', function() { @@ -32,7 +30,7 @@ // Add a non-cert item. configSelect.items = ['Activated']; - Polymer.dom.flush(); + flush(); const optionEl = configSelect.$$('option'); assertTrue(!!optionEl); @@ -48,7 +46,7 @@ configSelect.items = [ {deviceWide: true, hash: 'hash', issuedBy: 'me'} ]; - Polymer.dom.flush(); + flush(); optionEnabled = !optionEl.disabled; assertTrue(optionEnabled); @@ -57,7 +55,7 @@ configSelect.items = [ {deviceWide: true, hash: null, issuedBy: 'me'} ]; - Polymer.dom.flush(); + flush(); optionEnabled = !optionEl.disabled; assertFalse(optionEnabled); @@ -65,7 +63,7 @@ configSelect.items = [ {deviceWide: true, hash: null, issuedBy: 'me'} ]; - Polymer.dom.flush(); + flush(); optionEnabled = !optionEl.disabled; assertFalse(optionEnabled); @@ -75,7 +73,7 @@ configSelect.items = [ {deviceWide: true, hash: 'hash', issuedBy: 'me'} ]; - Polymer.dom.flush(); + flush(); optionEnabled = !optionEl.disabled; assertTrue(optionEnabled); @@ -83,7 +81,7 @@ configSelect.items = [ {deviceWide: false, hash: 'hash', issuedBy: 'me'} ]; - Polymer.dom.flush(); + flush(); optionEnabled = !optionEl.disabled; assertFalse(optionEnabled); });
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_config_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_config_test.js index b890c9d..6f3f75be 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_config_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_config_test.js
@@ -2,17 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_config.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_config.m.js'; -// #import {keyEventOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; -// #import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.js'; -// #import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.m.js'; -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// #import {eventToPromise} from '../../../test_util.js'; -// clang-format on +import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.m.js'; +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.js'; suite('network-config', function() { var networkConfig; @@ -33,7 +29,7 @@ suiteSetup(function() { mojoApi_ = new FakeNetworkConfig(); - network_config.MojoInterfaceProviderImpl.getInstance().remote_ = mojoApi_; + MojoInterfaceProviderImpl.getInstance().remote_ = mojoApi_; }); function setNetworkConfig(properties) { @@ -57,7 +53,7 @@ function initNetworkConfig() { document.body.appendChild(networkConfig); networkConfig.init(); - Polymer.dom.flush(); + flush(); } function initNetworkConfigWithCerts(hasServerCa, hasUserCert) { @@ -86,7 +82,7 @@ } function flushAsync() { - Polymer.dom.flush(); + flush(); return new Promise(resolve => { networkConfig.async(resolve); }); @@ -178,7 +174,7 @@ assertTrue(!!networkConfig.error); passwordInput.fire('keypress'); - Polymer.dom.flush(); + flush(); assertFalse(!!networkConfig.error); }); }); @@ -207,7 +203,7 @@ initNetworkConfig(); networkConfig.set('vpnType_', 'IKEv2'); - Polymer.dom.flush(); + flush(); assertEquals(3, networkConfig.get('ipsecAuthTypeItems_').length); assertTrue(!!networkConfig.$$('#ipsec-auth-type')); assertFalse(!!networkConfig.$$('#l2tp-username-input')); @@ -222,7 +218,7 @@ assertTrue(!!networkConfig.$$('#ipsec-remote-id-input')); networkConfig.set('ipsecAuthType_', 'PSK'); - Polymer.dom.flush(); + flush(); assertTrue(!!networkConfig.$$('#ipsec-psk-input')); assertFalse(!!networkConfig.$$('#vpnServerCa')); assertFalse(!!networkConfig.$$('#vpnUserCert')); @@ -232,7 +228,7 @@ assertTrue(!!networkConfig.$$('#ipsec-remote-id-input')); networkConfig.set('ipsecAuthType_', 'Cert'); - Polymer.dom.flush(); + flush(); assertFalse(!!networkConfig.$$('#ipsec-psk-input')); assertTrue(!!networkConfig.$$('#vpnServerCa')); assertTrue(!!networkConfig.$$('#vpnUserCert')); @@ -302,7 +298,7 @@ initNetworkConfig(); networkConfig.set('vpnType_', 'IKEv2'); networkConfig.set('ipsecAuthType_', 'PSK'); - Polymer.dom.flush(); + flush(); setMandatoryFields(); const configProperties = networkConfig.get('configProperties_'); @@ -568,7 +564,7 @@ // PSK input should appear and the dropdowns for server CA and user // certificate should be hidden. networkConfig.set('vpnType_', 'L2TP_IPsec'); - Polymer.dom.flush(); + flush(); assertEquals(2, networkConfig.get('ipsecAuthTypeItems_').length); assertEquals('PSK', networkConfig.ipsecAuthType_); assertFalse(!!networkConfig.$$('#ipsec-local-id-input')); @@ -582,7 +578,7 @@ // Switch the authentication type to Cert. The PSK input should be hidden // and the dropdowns for server CA and user certificate should appear. networkConfig.set('ipsecAuthType_', 'Cert'); - Polymer.dom.flush(); + flush(); assertFalse(!!networkConfig.$$('#ipsec-psk-input')); assertTrue(!!networkConfig.$$('#ipsec-auth-type')); assertTrue(!!networkConfig.$$('#l2tp-username-input')); @@ -659,7 +655,7 @@ test('PSK', function() { initNetworkConfig(); networkConfig.set('vpnType_', 'L2TP_IPsec'); - Polymer.dom.flush(); + flush(); setMandatoryFields(); const configProperties = networkConfig.get('configProperties_'); @@ -841,9 +837,9 @@ // Switch the VPN type to another and back again. Items should not change. networkConfig.set('vpnType_', 'L2TP_IPsec'); - Polymer.dom.flush(); + flush(); networkConfig.set('vpnType_', 'OpenVPN'); - Polymer.dom.flush(); + flush(); assertFalse(!!networkConfig.$$('#ipsec-auth-type')); assertFalse(!!networkConfig.$$('#l2tp-username-input')); assertTrue(!!networkConfig.$$('#openvpn-username-input')); @@ -891,11 +887,11 @@ test('Switch VPN Type', function() { const configProperties = networkConfig.get('configProperties_'); networkConfig.set('vpnType_', 'OpenVPN'); - Polymer.dom.flush(); + flush(); assertFalse(!!configProperties.typeConfig.vpn.wireguard); assertFalse(!!networkConfig.$$('#wireguard-ip-input')); networkConfig.set('vpnType_', 'WireGuard'); - Polymer.dom.flush(); + flush(); assertFalse(!!configProperties.typeConfig.vpn.openvpn); assertTrue(!!configProperties.typeConfig.vpn.wireguard); assertTrue(!!networkConfig.$$('#wireguard-ip-input')); @@ -903,7 +899,7 @@ test('Switch key config type', function() { networkConfig.set('vpnType_', 'WireGuard'); - Polymer.dom.flush(); + flush(); assertFalse(!!networkConfig.$$('#wireguardPrivateKeyInput')); networkConfig.set('wireguardKeyType_', 'UserInput'); return flushAsync().then(() => { @@ -913,7 +909,7 @@ test('Enable Connect', function() { networkConfig.set('vpnType_', 'WireGuard'); - Polymer.dom.flush(); + flush(); assertFalse(networkConfig.enableConnect); networkConfig.set('ipAddressInput_', '10.10.0.1'); const configProperties = networkConfig.get('configProperties_');
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_config_toggle_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_config_toggle_test.js index a37097e7..e08b7fd9 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_config_toggle_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_config_toggle_test.js
@@ -2,11 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://resources/cr_components/chromeos/network/network_config_toggle.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_config_toggle.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkConfigToggleTest', function() { /** @type {!NetworkConfigToggle|undefined} */ @@ -15,7 +13,7 @@ setup(function() { configToggle = document.createElement('network-config-toggle'); document.body.appendChild(configToggle); - Polymer.dom.flush(); + flush(); }); test('Policy on left', function() { @@ -29,7 +27,7 @@ assertTrue(!!toggle); configToggle.policyOnLeft = true; - Polymer.dom.flush(); + flush(); const leftIndicator = configToggle.$$('cr-policy-network-indicator-mojo'); assertTrue(leftIndicator.classList.contains('left'));
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_icon_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_icon_test.js index 8e1b304..fb2a10a 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_icon_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_icon_test.js
@@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_icon.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_icon.m.js'; -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkIconTest', function() { /** @type {!NetworkList|undefined} */ @@ -17,7 +15,7 @@ let mojom; function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); } @@ -27,7 +25,7 @@ networkIcon = document.createElement('network-icon'); document.body.appendChild(networkIcon); assertTrue(!!networkIcon); - Polymer.dom.flush(); + flush(); }); test('Display locked cellular icon', async function() {
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_ip_config_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_ip_config_test.js index 995e6c9..5110e6a 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_ip_config_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_ip_config_test.js
@@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_ip_config.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_ip_config.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// clang-format on +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkIpConfigTest', function() { /** @type {!NetworkIpConfig|undefined} */ @@ -17,7 +15,7 @@ setup(function() { ipConfig = document.createElement('network-ip-config'); document.body.appendChild(ipConfig); - Polymer.dom.flush(); + flush(); }); test('Enabled', function() { @@ -31,7 +29,7 @@ }, type: mojom.NetworkType.kWiFi, }; - Polymer.dom.flush(); + flush(); assertFalse(ipConfig.$$('#autoConfigIpToggle').disabled); }); @@ -44,7 +42,7 @@ ipConfig.managedProperties = { ipAddressConfigType: null, }; - Polymer.dom.flush(); + flush(); assertFalse(ipConfig.$$('#autoConfigIpToggle').disabled); // ipAddressConfigType policy is not enforced (kNone). @@ -54,7 +52,7 @@ policySource: mojom.PolicySource.kNone, }, }; - Polymer.dom.flush(); + flush(); assertFalse(ipConfig.$$('#autoConfigIpToggle').disabled); // ipAddressConfigType policy is enforced. @@ -64,7 +62,7 @@ policySource: mojom.PolicySource.kUserPolicyEnforced, }, }; - Polymer.dom.flush(); + flush(); assertTrue(ipConfig.$$('#autoConfigIpToggle').disabled); }); @@ -84,7 +82,7 @@ connectionState: mojom.ConnectionStateType.kNotConnected, type: mojom.NetworkType.kWiFi, }; - Polymer.dom.flush(); + flush(); const autoConfigIpToggle = ipConfig.$$('#autoConfigIpToggle'); const propertyList = ipConfig.$$('network-property-list-mojo'); @@ -105,14 +103,14 @@ const properties = OncMojo.getDefaultManagedProperties( mojom.NetworkType.kCellular, 'cellular'); ipConfig.managedProperties = properties; - Polymer.dom.flush(); + flush(); assertFalse(!!getAutoConfig()); const wifi = OncMojo.getDefaultManagedProperties( chromeos.networkConfig.mojom.NetworkType.kWiFi, 'someguid', ''); ipConfig.managedProperties = wifi; - Polymer.dom.flush(); + flush(); assertTrue(!!getAutoConfig()); });
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_list_item_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_list_item_test.js index 2e0cff9..4d47cd7 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_list_item_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_list_item_test.js
@@ -2,28 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_list_item.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_list_item.m.js'; +import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +import 'chrome://resources/mojo/services/network/public/mojom/ip_address.mojom-lite.js'; +import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; +import 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js'; +import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/cros_network_config.mojom-lite.js'; -// #import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -// #import 'chrome://resources/mojo/services/network/public/mojom/ip_address.mojom-lite.js'; -// #import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; -// #import 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js'; -// #import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/cros_network_config.mojom-lite.js'; - -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// #import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.js'; -// #import {setESimManagerRemoteForTesting} from 'chrome://resources/cr_components/chromeos/cellular_setup/mojo_interface_provider.m.js'; -// #import {FakeESimManagerRemote} from 'chrome://test/cr_components/chromeos/cellular_setup/fake_esim_manager_remote.js'; -// #import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.m.js'; -// #import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; -// #import {NetworkList} from 'chrome://resources/cr_components/chromeos/network/network_list_types.m.js'; -// #import {keyDownOn, move} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; -// #import {eventToPromise} from 'chrome://test/test_util.js'; -// #import {CellularSetupPageName} from 'chrome://resources/cr_components/chromeos/cellular_setup/cellular_types.m.js'; -// clang-format on +import {CellularSetupPageName} from 'chrome://resources/cr_components/chromeos/cellular_setup/cellular_types.m.js'; +import {setESimManagerRemoteForTesting} from 'chrome://resources/cr_components/chromeos/cellular_setup/mojo_interface_provider.m.js'; +import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.m.js'; +import {NetworkList} from 'chrome://resources/cr_components/chromeos/network/network_list_types.m.js'; +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {keyDownOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.js'; +import {FakeESimManagerRemote} from 'chrome://test/cr_components/chromeos/cellular_setup/fake_esim_manager_remote.js'; +import {eventToPromise} from 'chrome://test/test_util.js'; suite('NetworkListItemTest', function() { /** @type {!NetworkListItem|undefined} */ @@ -39,7 +35,7 @@ setup(function() { mojom = chromeos.networkConfig.mojom; mojoApi_ = new FakeNetworkConfig(); - network_config.MojoInterfaceProviderImpl.getInstance().remote_ = mojoApi_; + MojoInterfaceProviderImpl.getInstance().remote_ = mojoApi_; eSimManagerRemote = new FakeESimManagerRemote(); setESimManagerRemoteForTesting(eSimManagerRemote); }); @@ -50,7 +46,7 @@ setEventListeners(); eventTriggered = false; document.body.appendChild(listItem); - Polymer.dom.flush(); + flush(); } function initCellularNetwork(iccid, eid, simLocked) { @@ -79,7 +75,7 @@ } function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); } @@ -101,7 +97,7 @@ listItem.item = OncMojo.managedPropertiesToNetworkState(properties); // Update the network state. - Polymer.dom.flush(); + flush(); // The network icon exists now. networkIcon = listItem.$$('network-icon'); @@ -250,15 +246,15 @@ // Clicking the activate button should fire the show-cellular-setup event. const showCellularSetupPromise = - test_util.eventToPromise('show-cellular-setup', listItem); + eventToPromise('show-cellular-setup', listItem); activateButton.click(); const showCellularSetupEvent = await showCellularSetupPromise; assertEquals( showCellularSetupEvent.detail.pageName, - cellularSetup.CellularSetupPageName.PSIM_FLOW_UI); + CellularSetupPageName.PSIM_FLOW_UI); // Selecting the row should fire the show-detail event. - const showDetailPromise = test_util.eventToPromise('show-detail', listItem); + const showDetailPromise = eventToPromise('show-detail', listItem); listItem.$.divOuter.click(); const showDetailEvent = await showDetailPromise; assertEquals(showDetailEvent.detail, networkState); @@ -304,7 +300,7 @@ listItem.i18n('networkListItemUnavailableSimNetwork')); // Selecting the row should fire the show-detail event. - let showDetailPromise = test_util.eventToPromise('show-detail', listItem); + let showDetailPromise = eventToPromise('show-detail', listItem); listItem.$.divOuter.click(); let showDetailEvent = await showDetailPromise; assertEquals(showDetailEvent.detail, listItem.item); @@ -336,7 +332,7 @@ assertTrue(!!arrow); // Selecting the row should fire the show-detail event. - showDetailPromise = test_util.eventToPromise('show-detail', listItem); + showDetailPromise = eventToPromise('show-detail', listItem); listItem.$.divOuter.click(); showDetailEvent = await showDetailPromise; assertEquals(showDetailEvent.detail, networkState); @@ -395,7 +391,7 @@ assertTrue(!!arrow); // Selecting the row should fire the show-detail event. - const showDetailPromise = test_util.eventToPromise('show-detail', listItem); + const showDetailPromise = eventToPromise('show-detail', listItem); listItem.$.divOuter.click(); const showDetailEvent = await showDetailPromise; assertEquals(showDetailEvent.detail, networkState); @@ -719,8 +715,7 @@ await flushAsync(); // Selecting the row should fire the show-detail event. - const showDetailPromise = - test_util.eventToPromise('selected', listItem); + const showDetailPromise = eventToPromise('selected', listItem); listItem.$.divOuter.click(); const showDetailEvent = await showDetailPromise; assertEquals(showDetailEvent.detail, networkState);
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_list_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_list_test.js index 8e07fd7..0119449 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_list_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_list_test.js
@@ -2,20 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_list.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_list.m.js'; +import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; +import 'chrome://resources/mojo/services/network/public/mojom/ip_address.mojom-lite.js'; +import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; +import 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js'; +import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/cros_network_config.mojom-lite.js'; -// #import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js'; -// #import 'chrome://resources/mojo/services/network/public/mojom/ip_address.mojom-lite.js'; -// #import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/network_types.mojom-lite.js'; -// #import 'chrome://resources/mojo/mojo/public/mojom/base/time.mojom-lite.js'; -// #import 'chrome://resources/mojo/chromeos/services/network_config/public/mojom/cros_network_config.mojom-lite.js'; - -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// #import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; -// clang-format on +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkListTest', function() { /** @type {!NetworkList|undefined} */ @@ -32,7 +29,7 @@ networkList.style.height = '100%'; networkList.style.width = '100%'; document.body.appendChild(networkList); - Polymer.dom.flush(); + flush(); }); test('focus() focuses the first item', function() { @@ -41,7 +38,7 @@ OncMojo.getDefaultNetworkState(mojom.NetworkType.kWiFi, 'wifi'), ]; networkList.networks = testNetworks; - Polymer.dom.flush(); + flush(); // No items are focused initially. const items = networkList.shadowRoot.querySelectorAll('network-list-item');
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_nameservers_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_nameservers_test.js index 742af68..7e779e0 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_nameservers_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_nameservers_test.js
@@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_nameservers.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_nameservers.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkNameserversTest', function() { /** @type {!NetworkNameservers|undefined} */ @@ -16,7 +14,7 @@ setup(function() { nameservers = document.createElement('network-nameservers'); document.body.appendChild(nameservers); - Polymer.dom.flush(); + flush(); }); test('Select nameservers', async () => {
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_password_input_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_password_input_test.js index 009383b..a793fdf 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_password_input_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_password_input_test.js
@@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_password_input.m.js'; -// -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_password_input.m.js'; + +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('CrComponentsNetworkPasswordInputTest', function() { /** @type {!NetworkPasswordInput|undefined} */ @@ -16,7 +14,7 @@ setup(function() { networkPassword = document.createElement('network-password-input'); document.body.appendChild(networkPassword); - Polymer.dom.flush(); + flush(); }); test('Show password button', function() {
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_property_list_mojo_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_property_list_mojo_test.js index ddb14bd..97d4beb 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_property_list_mojo_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_property_list_mojo_test.js
@@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_property_list_mojo.m.js'; -// #import {FAKE_CREDENTIAL} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_property_list_mojo.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {FAKE_CREDENTIAL} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkPropertyListMojoTest', function() { /** @type {!NetworkPropertyListMojo|undefined} */ @@ -29,7 +27,7 @@ ]; document.body.appendChild(propertyList); - Polymer.dom.flush(); + flush(); }); function verifyEditableFieldTypes() { @@ -41,14 +39,14 @@ propertyList.editFieldTypes = { 'ipv4.ipAddress': 'String', }; - Polymer.dom.flush(); + flush(); // The input to edit the property now exists. assertNotEquals(null, propertyList.$$('cr-input')); } async function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); } @@ -105,7 +103,7 @@ // Simulate user switching off automatic. propertyList.allFieldsReadOnly = false; - Polymer.dom.flush(); + flush(); // Focus event has not fired, and the edited attribute still remains // false.
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_exclusions_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_exclusions_test.js index 037334c..7e8ad1e 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_exclusions_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_exclusions_test.js
@@ -2,12 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_proxy_exclusions.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_proxy_exclusions.m.js'; + // -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkProxyExclusionsTest', function() { /** @type {!NetworkProxyExclusions|undefined} */ @@ -16,14 +15,14 @@ setup(function() { proxyExclusions = document.createElement('network-proxy-exclusions'); document.body.appendChild(proxyExclusions); - Polymer.dom.flush(); + flush(); }); test('Clear fires proxy-exclusions-change event', function(done) { proxyExclusions.exclusions = [ 'one', 'two', 'three' ]; - Polymer.dom.flush(); + flush(); // Verify that clicking the clear button fires the proxy-exclusions-change // event and that the item was removed from the exclusions list.
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_input_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_input_test.js index 190362f0..ac6d4eb 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_input_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_input_test.js
@@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_proxy_input.m.js'; -// -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_proxy_input.m.js'; + +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkProxyInputTest', function() { /** @type {!NetworkProxyInput|undefined} */ @@ -16,7 +14,7 @@ setup(function() { proxyInput = document.createElement('network-proxy-input'); document.body.appendChild(proxyInput); - Polymer.dom.flush(); + flush(); }); test('Editable inputs', function() { @@ -25,7 +23,7 @@ assertTrue(proxyInput.$$('#port').readonly); proxyInput.editable = true; - Polymer.dom.flush(); + flush(); assertFalse(proxyInput.$$('#host').readonly); assertFalse(proxyInput.$$('#port').readonly);
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_test.js index 49c0b4ef..4a3204b 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_proxy_test.js
@@ -2,19 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_proxy.m.js'; -// -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_proxy.m.js'; + +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkProxyTest', function() { /** @type {!NetworkProxy|undefined} */ let netProxy; function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); } @@ -22,7 +20,7 @@ setup(function() { netProxy = document.createElement('network-proxy'); document.body.appendChild(netProxy); - Polymer.dom.flush(); + flush(); }); test('Proxy select option change fires proxy-change event', function(done) {
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_select_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_select_test.js index f9fd632..29c3b00 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_select_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_select_test.js
@@ -2,11 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://resources/cr_components/chromeos/network/network_select.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_select.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// clang-format on +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkSelectTest', function() { /** @type {!NetworkSelect|undefined} */ @@ -17,10 +15,10 @@ // imports have finished loading before initiating any tests. The Polymer 3 // version of the test does not use the OOBE host so this line should not // execute. - /* #ignore */ await cr.ui.Oobe.waitForOobeToLoad(); + // await cr.ui.Oobe.waitForOobeToLoad(); networkSelect = document.createElement('network-select'); document.body.appendChild(networkSelect); - Polymer.dom.flush(); + flush(); }); test('Scan progress visibility', function() { @@ -30,7 +28,7 @@ assertFalse(networkSelect.showScanProgress); networkSelect.showScanProgress = true; - Polymer.dom.flush(); + flush(); paperProgress = networkSelect.$$('paper-progress'); assertTrue(!!paperProgress); @@ -43,12 +41,12 @@ // Setting |enableWifiScans| to false should clear the scheduled scans. networkSelect.enableWifiScans = false; - Polymer.dom.flush(); + flush(); assertTrue(networkSelect.scanIntervalId_ === null); // Setting |enableWifiScans| back to true should re-schedule them. networkSelect.enableWifiScans = true; - Polymer.dom.flush(); + flush(); assertTrue(networkSelect.scanIntervalId_ !== null); }); });
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/network_siminfo_test.js b/chrome/test/data/webui/cr_components/chromeos/network/network_siminfo_test.js index eaf94fb..ee002506 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/network_siminfo_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/network_siminfo_test.js
@@ -2,14 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/network_siminfo.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/network_siminfo.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; -// clang-format on +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; suite('NetworkSiminfoTest', function() { /** @type {!NetworkSiminfo|undefined} */ @@ -31,7 +29,7 @@ }); async function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); } @@ -176,4 +174,4 @@ assertFalse(getSimLockButton().checked); assertTrue(!!getSimLockButtonTooltip()); }); -}); \ No newline at end of file +});
diff --git a/chrome/test/data/webui/cr_components/chromeos/network/sim_lock_dialogs_test.js b/chrome/test/data/webui/cr_components/chromeos/network/sim_lock_dialogs_test.js index 01f7e687..98ad402 100644 --- a/chrome/test/data/webui/cr_components/chromeos/network/sim_lock_dialogs_test.js +++ b/chrome/test/data/webui/cr_components/chromeos/network/sim_lock_dialogs_test.js
@@ -2,15 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// clang-format off -// #import 'chrome://os-settings/strings.m.js'; -// #import 'chrome://resources/cr_components/chromeos/network/sim_lock_dialogs.m.js'; +import 'chrome://os-settings/strings.m.js'; +import 'chrome://resources/cr_components/chromeos/network/sim_lock_dialogs.m.js'; -// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -// #import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.js'; -// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; -// #import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.m.js'; -// clang-format on +import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.m.js'; +import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js'; +import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; +import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.js'; suite('NetworkSimLockDialogsTest', function() { let simLockDialog; @@ -21,17 +19,16 @@ setup(function() { networkConfigRemote_ = new FakeNetworkConfig(); - network_config.MojoInterfaceProviderImpl.getInstance().remote_ = - networkConfigRemote_; + MojoInterfaceProviderImpl.getInstance().remote_ = networkConfigRemote_; simLockDialog = document.createElement('sim-lock-dialogs'); simLockDialog.deviceState = {}; document.body.appendChild(simLockDialog); - Polymer.dom.flush(); + flush(); }); async function flushAsync() { - Polymer.dom.flush(); + flush(); // Use setTimeout to wait for the next macrotask. return new Promise(resolve => setTimeout(resolve)); }
diff --git a/chrome/test/data/webui/new_tab_page/background_manager_test.ts b/chrome/test/data/webui/new_tab_page/background_manager_test.ts index e191f4a..c641020f 100644 --- a/chrome/test/data/webui/new_tab_page/background_manager_test.ts +++ b/chrome/test/data/webui/new_tab_page/background_manager_test.ts
@@ -90,6 +90,7 @@ repeatY: 'repeat', positionX: 'left', positionY: 'top', + scrimDisplay: 'none', attributionUrl: undefined, }); @@ -99,7 +100,7 @@ `url=${encodeURIComponent('https://example.com')}&` + `url2x=${encodeURIComponent('https://example2x.com')}&` + 'size=cover&repeatX=no-repeat&repeatY=repeat&positionX=left&' + - 'positionY=top'; + 'positionY=top&scrimDisplay=none'; assertEquals(expected, backgroundImage.url); });
diff --git a/chrome/test/data/webui/new_tab_page/test_support.ts b/chrome/test/data/webui/new_tab_page/test_support.ts index 76f2323..ba1784c 100644 --- a/chrome/test/data/webui/new_tab_page/test_support.ts +++ b/chrome/test/data/webui/new_tab_page/test_support.ts
@@ -81,6 +81,7 @@ positionY: undefined, repeatX: undefined, repeatY: undefined, + scrimDisplay: undefined, size: undefined, url2x: undefined, };
diff --git a/chrome/test/data/webui/settings/chromeos/people_page_change_picture_test.js b/chrome/test/data/webui/settings/chromeos/people_page_change_picture_test.js index 8d7cb69..f58ff38 100644 --- a/chrome/test/data/webui/settings/chromeos/people_page_change_picture_test.js +++ b/chrome/test/data/webui/settings/chromeos/people_page_change_picture_test.js
@@ -121,7 +121,7 @@ setup(async function() { browserProxy = new TestChangePictureBrowserProxy(); - ChangePictureBrowserProxyImpl.instance_ = browserProxy; + ChangePictureBrowserProxyImpl.setInstance(browserProxy); PolymerTest.clearBody(); changePicture = document.createElement('settings-change-picture'); document.body.appendChild(changePicture);
diff --git a/chrome/test/data/webui/settings/chromeos/personalization_page_test.js b/chrome/test/data/webui/settings/chromeos/personalization_page_test.js index 974d1b0..e86f0843 100644 --- a/chrome/test/data/webui/settings/chromeos/personalization_page_test.js +++ b/chrome/test/data/webui/settings/chromeos/personalization_page_test.js
@@ -52,7 +52,7 @@ setup(function() { WallpaperBrowserProxy = new TestWallpaperBrowserProxy(); - WallpaperBrowserProxyImpl.instance_ = WallpaperBrowserProxy; + WallpaperBrowserProxyImpl.setInstance(WallpaperBrowserProxy); createPersonalizationPage(); }); @@ -78,7 +78,8 @@ test('wallpaperSettingVisible', function() { personalizationPage.showWallpaperRow_ = false; flush(); - assertTrue(personalizationPage.$$('#wallpaperButton').hidden); + assertTrue(personalizationPage.shadowRoot.querySelector('#wallpaperButton') + .hidden); }); test('wallpaperPolicyControlled', async () => { @@ -88,8 +89,11 @@ createPersonalizationPage(); await WallpaperBrowserProxy.whenCalled('isWallpaperPolicyControlled'); flush(); - assertFalse(personalizationPage.$$('#wallpaperPolicyIndicator').hidden); - assertTrue(personalizationPage.$$('#wallpaperButton').disabled); + assertFalse(personalizationPage.shadowRoot + .querySelector('#wallpaperPolicyIndicator') + .hidden); + assertTrue(personalizationPage.shadowRoot.querySelector('#wallpaperButton') + .disabled); }); test('Deep link to open wallpaper button', async () => { @@ -119,7 +123,8 @@ const isAmbientModeEnabled = loadTimeData.getBoolean('isAmbientModeEnabled'); if(!isGuest && isAmbientModeEnabled){ - const row = personalizationPage.$$('#ambientModeRow'); + const row = + personalizationPage.shadowRoot.querySelector('#ambientModeRow'); assertTrue(!!row); row.click(); assertEquals(routes.AMBIENT_MODE, Router.getInstance().getCurrentRoute()); @@ -135,11 +140,13 @@ await waitAfterNextRender(personalizationPage); - const changePicturePage = personalizationPage.$$('settings-change-picture'); + const changePicturePage = + personalizationPage.shadowRoot.querySelector('settings-change-picture'); assertTrue(!!changePicturePage); - const deepLinkElement = changePicturePage.$$('#pictureList') - .$$('#selector') - .$$('[class="iron-selected"]'); + const deepLinkElement = + changePicturePage.shadowRoot.querySelector('#pictureList') + .shadowRoot.querySelector('#selector') + .$$('[class="iron-selected"]'); await waitAfterNextRender(deepLinkElement); assertEquals( deepLinkElement, getDeepActiveElement(),
diff --git a/chrome/test/data/webui/settings/chromeos/personalization_page_with_personalization_hub_test.js b/chrome/test/data/webui/settings/chromeos/personalization_page_with_personalization_hub_test.js index e5a0b52..fbb5dfc3 100644 --- a/chrome/test/data/webui/settings/chromeos/personalization_page_with_personalization_hub_test.js +++ b/chrome/test/data/webui/settings/chromeos/personalization_page_with_personalization_hub_test.js
@@ -33,8 +33,8 @@ setup(function() { PersonalizationHubBrowserProxy = new TestPersonalizationHubBrowserProxy(); - PersonalizationHubBrowserProxyImpl.instance_ = - PersonalizationHubBrowserProxy; + PersonalizationHubBrowserProxyImpl.setInstance( + PersonalizationHubBrowserProxy); createPersonalizationPage(); });
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index c29a3215..06442d2 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -117,22 +117,6 @@ }); GEN('#endif'); -GEN('#if !BUILDFLAG(IS_CHROMEOS_LACROS)'); -var CrSettingsLanguagesPageRestructuredTest = - class extends CrSettingsLanguagesPageTest { - /** @override */ - get featureListInternal() { - return {enabled: ['language::kDesktopRestructuredLanguageSettings']}; - } -}; -TEST_F( - 'CrSettingsLanguagesPageRestructuredTest', 'RestructuredLanguageSettings', - function() { - mocha.grep(languages_page_tests.TestNames.RestructuredLanguageSettings) - .run(); - }); -GEN('#endif'); - var CrSettingsLanguagesSubpageTest = class extends CrSettingsBrowserTest { /** @override */ get browsePreload() {
diff --git a/chrome/test/data/webui/settings/languages_page_tests.ts b/chrome/test/data/webui/settings/languages_page_tests.ts index cd8bfa4..cdaeea4 100644 --- a/chrome/test/data/webui/settings/languages_page_tests.ts +++ b/chrome/test/data/webui/settings/languages_page_tests.ts
@@ -5,13 +5,13 @@ // clang-format off import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {LanguageHelper, LanguagesBrowserProxyImpl, SettingsLanguagesPageElement} from 'chrome://settings/lazy_load.js'; -import {CrSettingsPrefs, Router, routes} from 'chrome://settings/settings.js'; +import {CrSettingsPrefs} from 'chrome://settings/settings.js'; // <if expr="not is_macosx"> import {loadTimeData, SettingsToggleButtonElement} from 'chrome://settings/settings.js'; -import {assertDeepEquals} from 'chrome://webui-test/chai_assert.js'; +import {assertEquals, assertDeepEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; // </if> -import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; +import {assertFalse} from 'chrome://webui-test/chai_assert.js'; // <if expr="_google_chrome"> import {assertNotEquals} from 'chrome://webui-test/chai_assert.js'; // </if> @@ -20,7 +20,7 @@ import {FakeChromeEvent} from 'chrome://webui-test/fake_chrome_event.js'; // </if> -import {fakeDataBind, isChildVisible} from 'chrome://webui-test/test_util.js'; +import {fakeDataBind} from 'chrome://webui-test/test_util.js'; import {FakeLanguageSettingsPrivate, getFakeLanguagePrefs} from './fake_language_settings_private.js'; import {FakeSettingsPrivate} from './fake_settings_private.js'; @@ -34,7 +34,6 @@ // <if expr="_google_chrome"> SpellcheckOfficialBuild: 'spellcheck_official', // </if> - RestructuredLanguageSettings: 'restructured language settings', }, }; @@ -323,60 +322,3 @@ }); // </if> }); - -suite(languages_page_tests.TestNames.RestructuredLanguageSettings, function() { - let languageHelper: LanguageHelper; - let languagesPage: SettingsLanguagesPageElement; - let browserProxy: TestLanguagesBrowserProxy; - - suiteSetup(function() { - document.body.innerHTML = ''; - CrSettingsPrefs.deferInitialization = true; - }); - - setup(function() { - const settingsPrefs = document.createElement('settings-prefs'); - const settingsPrivate = new FakeSettingsPrivate(getFakeLanguagePrefs()); - settingsPrefs.initialize( - settingsPrivate as unknown as typeof chrome.settingsPrivate); - document.body.appendChild(settingsPrefs); - return CrSettingsPrefs.initialized.then(function() { - // Set up test browser proxy. - browserProxy = new TestLanguagesBrowserProxy(); - LanguagesBrowserProxyImpl.setInstance(browserProxy); - - // Set up fake languageSettingsPrivate API. - const languageSettingsPrivate = - browserProxy.getLanguageSettingsPrivate() as unknown as - FakeLanguageSettingsPrivate; - languageSettingsPrivate.setSettingsPrefs(settingsPrefs); - - languagesPage = document.createElement('settings-languages-page'); - - // Prefs would normally be data-bound to settings-languages-page. - languagesPage.prefs = settingsPrefs.prefs; - fakeDataBind(settingsPrefs, languagesPage, 'prefs'); - - document.body.appendChild(languagesPage); - flush(); - - languageHelper = languagesPage.languageHelper; - return languageHelper.whenReady(); - }); - }); - - teardown(function() { - document.body.innerHTML = ''; - }); - - test('languageSubpageTriggerVisible', function() { - assertTrue(isChildVisible(languagesPage, '#languagesSubpageTrigger')); - }); - - test('languageSubpageTriggerClicked', function() { - languagesPage.shadowRoot! - .querySelector<HTMLElement>('#languagesSubpageTrigger')!.click(); - assertEquals( - Router.getInstance().getCurrentRoute(), routes.LANGUAGE_SETTINGS); - }); -});
diff --git a/chrome/test/enterprise/e2e/policy/translate_enabled/translate_enabled.py b/chrome/test/enterprise/e2e/policy/translate_enabled/translate_enabled.py index 4be98c5..d379a1e 100644 --- a/chrome/test/enterprise/e2e/policy/translate_enabled/translate_enabled.py +++ b/chrome/test/enterprise/e2e/policy/translate_enabled/translate_enabled.py
@@ -7,6 +7,7 @@ from infra import ChromeEnterpriseTestCase +@category("chrome_only") @environment(file="../policy_test.asset.textpb") class TranslateEnabledTest(ChromeEnterpriseTestCase): """Test the TranslateEnabled policy. @@ -48,4 +49,4 @@ @test def test_TranslatedEnabledIncognito(self): - self.test_TranslatedEnabled(incognito=True) \ No newline at end of file + self.test_TranslatedEnabled(incognito=True)
diff --git a/chromeos/ash/components/dbus/DEPS b/chromeos/ash/components/dbus/DEPS index ca7d39f..9a2bd53 100644 --- a/chromeos/ash/components/dbus/DEPS +++ b/chromeos/ash/components/dbus/DEPS
@@ -7,9 +7,20 @@ "+components/policy/proto", "+dbus", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api", # TODO(crbug.com/1164001): Remove after chromeos/dbus migration is done. - "+chromeos/dbus" + "+chromeos/dbus", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.cc b/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.cc index fbd080f5..2dbc934 100644 --- a/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.cc +++ b/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.cc
@@ -309,18 +309,20 @@ PostProtoResponse(std::move(callback), response, task_delay_); } -void FakeKerberosClient::ConnectToKerberosFileChangedSignal( +base::CallbackListSubscription +FakeKerberosClient::SubscribeToKerberosFileChangedSignal( KerberosFilesChangedCallback callback) { MaybeRecordFunctionCallForTesting(__FUNCTION__); - DCHECK(!kerberos_files_changed_callback_); - kerberos_files_changed_callback_ = callback; + DCHECK(callback); + return base::CallbackListSubscription(); } -void FakeKerberosClient::ConnectToKerberosTicketExpiringSignal( +base::CallbackListSubscription +FakeKerberosClient::SubscribeToKerberosTicketExpiringSignal( KerberosTicketExpiringCallback callback) { MaybeRecordFunctionCallForTesting(__FUNCTION__); - DCHECK(!kerberos_ticket_expiring_callback_); - kerberos_ticket_expiring_callback_ = callback; + DCHECK(callback); + return base::CallbackListSubscription(); } void FakeKerberosClient::SetTaskDelay(base::TimeDelta delay) {
diff --git a/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.h b/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.h index 1321670..5c437876 100644 --- a/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.h +++ b/chromeos/ash/components/dbus/kerberos/fake_kerberos_client.h
@@ -46,9 +46,9 @@ AcquireKerberosTgtCallback callback) override; void GetKerberosFiles(const kerberos::GetKerberosFilesRequest& request, GetKerberosFilesCallback callback) override; - void ConnectToKerberosFileChangedSignal( + base::CallbackListSubscription SubscribeToKerberosFileChangedSignal( KerberosFilesChangedCallback callback) override; - void ConnectToKerberosTicketExpiringSignal( + base::CallbackListSubscription SubscribeToKerberosTicketExpiringSignal( KerberosTicketExpiringCallback callback) override; KerberosClient::TestInterface* GetTestInterface() override; @@ -119,9 +119,6 @@ // The simulated number of network failures on |AcquireKerberosTgt()| (for // testing). int simulated_number_of_network_failures_ = 0; - - KerberosFilesChangedCallback kerberos_files_changed_callback_; - KerberosTicketExpiringCallback kerberos_ticket_expiring_callback_; }; } // namespace ash
diff --git a/chromeos/ash/components/dbus/kerberos/kerberos_client.cc b/chromeos/ash/components/dbus/kerberos/kerberos_client.cc index 0bd90c0..3260c0c 100644 --- a/chromeos/ash/components/dbus/kerberos/kerberos_client.cc +++ b/chromeos/ash/components/dbus/kerberos/kerberos_client.cc
@@ -6,6 +6,7 @@ #include <utility> #include "base/bind.h" +#include "base/callback_list.h" #include "base/location.h" #include "base/logging.h" #include "base/memory/weak_ptr.h" @@ -48,7 +49,7 @@ } // "Real" implementation of KerberosClient talking to the Kerberos daemon on -// the Chrome OS side. +// the ChromeOS side. class KerberosClientImpl : public KerberosClient { public: KerberosClientImpl() = default; @@ -112,28 +113,26 @@ std::move(callback)); } - void ConnectToKerberosFileChangedSignal( + base::CallbackListSubscription SubscribeToKerberosFileChangedSignal( KerberosFilesChangedCallback callback) override { - DCHECK(callback); - kerberos_files_changed_callback_ = callback; - proxy_->ConnectToSignal( kerberos::kKerberosInterface, kerberos::kKerberosFilesChangedSignal, base::BindRepeating(&KerberosClientImpl::OnKerberosFilesChanged, weak_factory_.GetWeakPtr()), base::BindOnce(&OnSignalConnected)); + + return kerberos_files_changed_callback_list_.Add(callback); } - void ConnectToKerberosTicketExpiringSignal( + base::CallbackListSubscription SubscribeToKerberosTicketExpiringSignal( KerberosTicketExpiringCallback callback) override { - DCHECK(callback); - kerberos_ticket_expiring_callback_ = callback; - proxy_->ConnectToSignal( kerberos::kKerberosInterface, kerberos::kKerberosTicketExpiringSignal, base::BindRepeating(&KerberosClientImpl::OnKerberosTicketExpiring, weak_factory_.GetWeakPtr()), base::BindOnce(&OnSignalConnected)); + + return kerberos_ticket_expiring_callback_list_.Add(callback); } void OnKerberosFilesChanged(dbus::Signal* signal) { @@ -148,8 +147,8 @@ return; } - DCHECK(kerberos_files_changed_callback_); - kerberos_files_changed_callback_.Run(principal_name); + DCHECK(!kerberos_files_changed_callback_list_.empty()); + kerberos_files_changed_callback_list_.Notify(principal_name); } void OnKerberosTicketExpiring(dbus::Signal* signal) { @@ -164,8 +163,8 @@ return; } - DCHECK(kerberos_ticket_expiring_callback_); - kerberos_ticket_expiring_callback_.Run(principal_name); + DCHECK(!kerberos_ticket_expiring_callback_list_.empty()); + kerberos_ticket_expiring_callback_list_.Notify(principal_name); } void Init(dbus::Bus* bus) { @@ -175,6 +174,11 @@ } private: + using KerberosFilesChangedCallbackList = + base::RepeatingCallbackList<PrincipalNameFunc>; + using KerberosTicketExpiringCallbackList = + base::RepeatingCallbackList<PrincipalNameFunc>; + TestInterface* GetTestInterface() override { return nullptr; } // Calls kerberosd's |method_name| method, passing in |request| as input. Once @@ -227,9 +231,9 @@ // D-Bus proxy for the Kerberos daemon, not owned. dbus::ObjectProxy* proxy_ = nullptr; - // Signal callbacks. - KerberosFilesChangedCallback kerberos_files_changed_callback_; - KerberosTicketExpiringCallback kerberos_ticket_expiring_callback_; + // Signal callback lists. + KerberosFilesChangedCallbackList kerberos_files_changed_callback_list_; + KerberosFilesChangedCallbackList kerberos_ticket_expiring_callback_list_; base::WeakPtrFactory<KerberosClientImpl> weak_factory_{this}; };
diff --git a/chromeos/ash/components/dbus/kerberos/kerberos_client.h b/chromeos/ash/components/dbus/kerberos/kerberos_client.h index 6cad360..6e4aaa6 100644 --- a/chromeos/ash/components/dbus/kerberos/kerberos_client.h +++ b/chromeos/ash/components/dbus/kerberos/kerberos_client.h
@@ -6,6 +6,7 @@ #define CHROMEOS_ASH_COMPONENTS_DBUS_KERBEROS_KERBEROS_CLIENT_H_ #include "base/callback.h" +#include "base/callback_list.h" #include "base/component_export.h" #include "chromeos/ash/components/dbus/kerberos/kerberos_service.pb.h" #include "dbus/object_proxy.h" @@ -37,10 +38,11 @@ const kerberos::AcquireKerberosTgtResponse& response)>; using GetKerberosFilesCallback = base::OnceCallback<void( const kerberos::GetKerberosFilesResponse& response)>; + using PrincipalNameFunc = void(const std::string& principal_name); using KerberosFilesChangedCallback = - base::RepeatingCallback<void(const std::string& principal_name)>; + base::RepeatingCallback<PrincipalNameFunc>; using KerberosTicketExpiringCallback = - base::RepeatingCallback<void(const std::string& principal_name)>; + base::RepeatingCallback<PrincipalNameFunc>; // Interface with testing functionality. Accessed through GetTestInterface(), // only implemented in the fake implementation. @@ -67,7 +69,7 @@ int number_of_failures) = 0; protected: - virtual ~TestInterface() {} + virtual ~TestInterface() = default; }; // Creates and initializes the global instance. |bus| must not be null. @@ -115,10 +117,11 @@ const kerberos::GetKerberosFilesRequest& request, GetKerberosFilesCallback callback) = 0; - virtual void ConnectToKerberosFileChangedSignal( + virtual base::CallbackListSubscription SubscribeToKerberosFileChangedSignal( KerberosFilesChangedCallback callback) = 0; - virtual void ConnectToKerberosTicketExpiringSignal( + virtual base::CallbackListSubscription + SubscribeToKerberosTicketExpiringSignal( KerberosTicketExpiringCallback callback) = 0; // Returns an interface for testing (fake only), or returns nullptr.
diff --git a/chromeos/ash/components/network/DEPS b/chromeos/ash/components/network/DEPS index f417a6b..2cfd9b4 100644 --- a/chromeos/ash/components/network/DEPS +++ b/chromeos/ash/components/network/DEPS
@@ -30,9 +30,20 @@ "+net", "+services/preferences/public/cpp", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api", "+url", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ] specific_include_rules = {
diff --git a/chromeos/ash/components/network/onc/onc_translator_onc_to_shill.cc b/chromeos/ash/components/network/onc/onc_translator_onc_to_shill.cc index 408b52b76..508aebc 100644 --- a/chromeos/ash/components/network/onc/onc_translator_onc_to_shill.cc +++ b/chromeos/ash/components/network/onc/onc_translator_onc_to_shill.cc
@@ -69,7 +69,8 @@ if (pkcs11_id.empty()) { // If the cert type is PKCS11 but the pkcs11 id is empty, set empty // properties to indicate 'no certificate'. - client_cert::SetEmptyShillProperties(config_type, shill_dictionary); + client_cert::SetEmptyShillProperties(config_type, + shill_dictionary->GetDict()); return; } @@ -77,7 +78,7 @@ std::string cert_id = client_cert::GetPkcs11AndSlotIdFromEapCertId(pkcs11_id, &slot_id); client_cert::SetShillProperties(config_type, slot_id, cert_id, - shill_dictionary); + shill_dictionary->GetDict()); } // This class is responsible to translate the local fields of the given
diff --git a/chromeos/components/onc/DEPS b/chromeos/components/onc/DEPS index d858bd02..183e84631 100644 --- a/chromeos/components/onc/DEPS +++ b/chromeos/components/onc/DEPS
@@ -8,5 +8,16 @@ "+crypto", "+net", "+testing", - "+third_party/abseil-cpp/absl", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/chromeos/crosapi/cpp/gurl_os_handler_utils.cc b/chromeos/crosapi/cpp/gurl_os_handler_utils.cc index 3052036b..85f63dbe 100644 --- a/chromeos/crosapi/cpp/gurl_os_handler_utils.cc +++ b/chromeos/crosapi/cpp/gurl_os_handler_utils.cc
@@ -139,7 +139,7 @@ } bool IsAshOsAsciiScheme(const base::StringPiece& scheme) { - return base::LowerCaseEqualsASCII(scheme, kOsScheme); + return base::EqualsCaseInsensitiveASCII(scheme, kOsScheme); } std::string AshOsUrlHost(const GURL& url) {
diff --git a/chromeos/dbus/DEPS b/chromeos/dbus/DEPS index 1712b665..820f194 100644 --- a/chromeos/dbus/DEPS +++ b/chromeos/dbus/DEPS
@@ -9,7 +9,18 @@ "+dbus", "+net", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api", "+url", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/chromeos/network/BUILD.gn b/chromeos/network/BUILD.gn index 8c7bdcc..5b5e8222 100644 --- a/chromeos/network/BUILD.gn +++ b/chromeos/network/BUILD.gn
@@ -292,6 +292,7 @@ "cellular_utils_unittest.cc", "certificate_helper_unittest.cc", "client_cert_resolver_unittest.cc", + "client_cert_util_unittest.cc", "device_state_unittest.cc", "fast_transition_observer_unittest.cc", "firewall_hole_unittest.cc",
diff --git a/chromeos/network/DEPS b/chromeos/network/DEPS index 36339956..867805d1 100644 --- a/chromeos/network/DEPS +++ b/chromeos/network/DEPS
@@ -30,9 +30,20 @@ "+net", "+services/preferences/public/cpp", "+testing", - "+third_party/abseil-cpp/absl", "+third_party/cros_system_api", "+url", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ] specific_include_rules = {
diff --git a/chromeos/network/client_cert_resolver.cc b/chromeos/network/client_cert_resolver.cc index 2e38af03..1e2445f4 100644 --- a/chromeos/network/client_cert_resolver.cc +++ b/chromeos/network/client_cert_resolver.cc
@@ -557,7 +557,8 @@ if (cert_it == client_cert_and_issuers.end()) { VLOG(1) << "Couldn't find a matching client cert"; - client_cert::SetEmptyShillProperties(client_cert_type, shill_properties); + client_cert::SetEmptyShillProperties(client_cert_type, + shill_properties->GetDict()); return false; } @@ -570,8 +571,8 @@ // the worst case the user can remove the problematic cert. return false; } - client_cert::SetShillProperties( - client_cert_type, slot_id, pkcs11_id, shill_properties); + client_cert::SetShillProperties(client_cert_type, slot_id, pkcs11_id, + shill_properties->GetDict()); return true; } @@ -721,7 +722,7 @@ VLOG(2) << "Inspecting network " << network->path(); client_cert::ClientCertConfig cert_config; - OncToClientCertConfig(onc_source, *policy, &cert_config); + OncToClientCertConfig(onc_source, policy->GetDict(), &cert_config); // Skip networks that don't have a ClientCertPattern or ClientCertRef. if (!ShouldResolveCert(cert_config)) @@ -817,7 +818,7 @@ const MatchingCert& matching_cert = match.matching_cert.value(); client_cert::SetShillProperties( match.cert_config_type, matching_cert.key_slot_id, - matching_cert.pkcs11_id, &shill_properties); + matching_cert.pkcs11_id, shill_properties.GetDict()); resolved_networks_info.push_back(GetNetworkIdWithGuid(network_state) + ":match,identity='" + matching_cert.identity + "'"); @@ -829,7 +830,7 @@ resolved_networks_info.push_back(GetNetworkIdWithGuid(network_state) + ":no_match"); client_cert::SetEmptyShillProperties(match.cert_config_type, - &shill_properties); + shill_properties.GetDict()); } ShillServiceClient::Get()->SetProperties( dbus::ObjectPath(match.service_path), shill_properties,
diff --git a/chromeos/network/client_cert_util.cc b/chromeos/network/client_cert_util.cc index d49c71d..e8ae7f7 100644 --- a/chromeos/network/client_cert_util.cc +++ b/chromeos/network/client_cert_util.cc
@@ -35,25 +35,25 @@ // or provisioning profile id) of a ONC-specified client certificate // specification for a network // (|dict_with_client_cert|) and stores it in |cert_config|. -void GetClientCertTypeAndDescriptor(onc::ONCSource onc_source, - const base::Value& dict_with_client_cert, - ClientCertConfig* cert_config) { +void GetClientCertTypeAndDescriptor( + onc::ONCSource onc_source, + const base::Value::Dict& dict_with_client_cert, + ClientCertConfig* cert_config) { cert_config->onc_source = onc_source; const std::string* identity = - dict_with_client_cert.FindStringKey(::onc::eap::kIdentity); + dict_with_client_cert.FindString(::onc::eap::kIdentity); if (identity) cert_config->policy_identity = *identity; const std::string* client_cert_type = - dict_with_client_cert.FindStringKey(::onc::client_cert::kClientCertType); + dict_with_client_cert.FindString(::onc::client_cert::kClientCertType); if (client_cert_type) cert_config->client_cert_type = *client_cert_type; if (cert_config->client_cert_type == ::onc::client_cert::kPattern) { const base::Value::Dict* pattern_value = - dict_with_client_cert.GetDict().FindDict( - ::onc::client_cert::kClientCertPattern); + dict_with_client_cert.FindDict(::onc::client_cert::kClientCertPattern); if (pattern_value) { absl::optional<OncCertificatePattern> pattern = OncCertificatePattern::ReadFromONCDictionary(*pattern_value); @@ -64,15 +64,14 @@ cert_config->pattern = pattern.value(); } } else if (cert_config->client_cert_type == ::onc::client_cert::kRef) { - const base::Value* client_cert_ref_key = - dict_with_client_cert.FindKeyOfType(::onc::client_cert::kClientCertRef, - base::Value::Type::STRING); + const std::string* client_cert_ref_key = + dict_with_client_cert.FindString(::onc::client_cert::kClientCertRef); if (client_cert_ref_key) - cert_config->guid = client_cert_ref_key->GetString(); + cert_config->guid = *client_cert_ref_key; } else if (cert_config->client_cert_type == ::onc::client_cert::kProvisioningProfileId) { const std::string* provisioning_profile_id = - dict_with_client_cert.FindStringKey( + dict_with_client_cert.FindString( ::onc::client_cert::kClientCertProvisioningProfileId); if (!provisioning_profile_id) { LOG(ERROR) << "ProvisioningProfileId missing"; @@ -107,7 +106,7 @@ return cert_id.substr(delimiter_pos + 1); } -void GetClientCertFromShillProperties(const base::Value& shill_properties, +void GetClientCertFromShillProperties(const base::Value::Dict& shill_properties, ConfigType* cert_config_type, int* tpm_slot, std::string* pkcs11_id) { @@ -119,14 +118,15 @@ // // VPN Provider values are read from the "Provider" dictionary, not the // "Provider.Type", etc keys (which are used only to set the values). - const base::Value* provider_properties = - shill_properties.FindDictKey(shill::kProviderProperty); + const base::Value::Dict* provider_properties = + shill_properties.FindDict(shill::kProviderProperty); if (provider_properties) { const std::string* pkcs11_id_str = nullptr; // Look for OpenVPN specific properties. + // Note: OpenVPN does not have a slot property, see crbug.com/769550. pkcs11_id_str = - provider_properties->FindStringKey(shill::kOpenVPNClientCertIdProperty); + provider_properties->FindString(shill::kOpenVPNClientCertIdProperty); if (pkcs11_id_str) { *pkcs11_id = *pkcs11_id_str; *cert_config_type = ConfigType::kOpenVpn; @@ -134,12 +134,12 @@ } // Look for L2TP-IPsec specific properties. - pkcs11_id_str = provider_properties->FindStringKey( - shill::kL2TPIPsecClientCertIdProperty); + pkcs11_id_str = + provider_properties->FindString(shill::kL2TPIPsecClientCertIdProperty); if (pkcs11_id_str) { *pkcs11_id = *pkcs11_id_str; - const std::string* cert_slot = provider_properties->FindStringKey( + const std::string* cert_slot = provider_properties->FindString( shill::kL2TPIPsecClientCertSlotProperty); if (cert_slot && !cert_slot->empty() && !base::StringToInt(*cert_slot, tpm_slot)) { @@ -152,12 +152,12 @@ // Look for IKEv2 specific properties. pkcs11_id_str = - provider_properties->FindStringKey(shill::kIKEv2ClientCertIdProperty); + provider_properties->FindString(shill::kIKEv2ClientCertIdProperty); if (pkcs11_id_str) { *pkcs11_id = *pkcs11_id_str; - const std::string* cert_slot = provider_properties->FindStringKey( - shill::kIKEv2ClientCertSlotProperty); + const std::string* cert_slot = + provider_properties->FindString(shill::kIKEv2ClientCertSlotProperty); if (cert_slot && !cert_slot->empty() && !base::StringToInt(*cert_slot, tpm_slot)) { LOG(ERROR) << "Cert slot is not an integer: " << *cert_slot << "."; @@ -172,14 +172,14 @@ // Look for EAP specific client certificate properties, which can either be // part of a WiFi or EthernetEAP configuration. const std::string* cert_id = - shill_properties.FindStringKey(shill::kEapCertIdProperty); + shill_properties.FindString(shill::kEapCertIdProperty); if (cert_id) { // Shill requires both CertID and KeyID for TLS connections, despite the // fact that by convention they are the same ID, because one identifies // the certificate and the other the private key. std::string key_id; const std::string* key_id_str = - shill_properties.FindStringKey(shill::kEapKeyIdProperty); + shill_properties.FindString(shill::kEapKeyIdProperty); if (key_id_str) key_id = *key_id_str; // Assume the configuration to be invalid, if the two IDs are not identical. @@ -195,90 +195,78 @@ void SetShillProperties(const ConfigType cert_config_type, const int tpm_slot, const std::string& pkcs11_id, - base::Value* properties) { + base::Value::Dict& properties) { switch (cert_config_type) { case ConfigType::kNone: { return; } case ConfigType::kOpenVpn: { - properties->SetKey(shill::kOpenVPNPinProperty, - base::Value(kDefaultTPMPin)); + properties.Set(shill::kOpenVPNPinProperty, kDefaultTPMPin); // Note: OpenVPN does not have a slot property, see crbug.com/769550. - properties->SetKey(shill::kOpenVPNClientCertIdProperty, - base::Value(pkcs11_id)); + properties.Set(shill::kOpenVPNClientCertIdProperty, pkcs11_id); break; } case ConfigType::kL2tpIpsec: { - properties->SetKey(shill::kL2TPIPsecPinProperty, - base::Value(kDefaultTPMPin)); - properties->SetKey(shill::kL2TPIPsecClientCertSlotProperty, - base::Value(base::NumberToString(tpm_slot))); - properties->SetKey(shill::kL2TPIPsecClientCertIdProperty, - base::Value(pkcs11_id)); + properties.Set(shill::kL2TPIPsecPinProperty, kDefaultTPMPin); + properties.Set(shill::kL2TPIPsecClientCertSlotProperty, + base::NumberToString(tpm_slot)); + properties.Set(shill::kL2TPIPsecClientCertIdProperty, pkcs11_id); break; } case ConfigType::kIkev2: { // PIN property is not used by shill for a IKEv2 service since it is a // fixed value. - properties->SetKey(shill::kIKEv2ClientCertSlotProperty, - base::Value(base::NumberToString(tpm_slot))); - properties->SetKey(shill::kIKEv2ClientCertIdProperty, - base::Value(pkcs11_id)); + properties.Set(shill::kIKEv2ClientCertSlotProperty, + base::NumberToString(tpm_slot)); + properties.Set(shill::kIKEv2ClientCertIdProperty, pkcs11_id); break; } case ConfigType::kEap: { - properties->SetKey(shill::kEapPinProperty, base::Value(kDefaultTPMPin)); + properties.Set(shill::kEapPinProperty, kDefaultTPMPin); std::string key_id = base::StringPrintf("%i:%s", tpm_slot, pkcs11_id.c_str()); // Shill requires both CertID and KeyID for TLS connections, despite the // fact that by convention they are the same ID, because one identifies // the certificate and the other the private key. - properties->SetKey(shill::kEapCertIdProperty, base::Value(key_id)); - properties->SetKey(shill::kEapKeyIdProperty, base::Value(key_id)); + properties.Set(shill::kEapCertIdProperty, key_id); + properties.Set(shill::kEapKeyIdProperty, key_id); break; } } } void SetEmptyShillProperties(const ConfigType cert_config_type, - base::Value* properties) { + base::Value::Dict& properties) { switch (cert_config_type) { case ConfigType::kNone: { return; } case ConfigType::kOpenVpn: { - properties->SetKey(shill::kOpenVPNPinProperty, - base::Value(std::string())); - properties->SetKey(shill::kOpenVPNClientCertIdProperty, - base::Value(std::string())); + properties.Set(shill::kOpenVPNPinProperty, std::string()); + properties.Set(shill::kOpenVPNClientCertIdProperty, std::string()); break; } case ConfigType::kL2tpIpsec: { - properties->SetKey(shill::kL2TPIPsecPinProperty, - base::Value(std::string())); - properties->SetKey(shill::kL2TPIPsecClientCertSlotProperty, - base::Value(std::string())); - properties->SetKey(shill::kL2TPIPsecClientCertIdProperty, - base::Value(std::string())); + properties.Set(shill::kL2TPIPsecPinProperty, std::string()); + properties.Set(shill::kL2TPIPsecClientCertSlotProperty, std::string()); + properties.Set(shill::kL2TPIPsecClientCertIdProperty, std::string()); break; } case ConfigType::kIkev2: { // PIN property is not used by shill for a IKEv2 service since it is a // fixed value. - properties->SetKey(shill::kIKEv2ClientCertSlotProperty, - base::Value(std::string())); - properties->SetKey(shill::kIKEv2ClientCertIdProperty, - base::Value(std::string())); + properties.Set(shill::kIKEv2ClientCertSlotProperty, std::string()); + properties.Set(shill::kIKEv2ClientCertIdProperty, std::string()); break; } case ConfigType::kEap: { - properties->SetKey(shill::kEapPinProperty, base::Value(std::string())); + properties.Set(shill::kEapPinProperty, std::string()); // Shill requires both CertID and KeyID for TLS connections, despite the // fact that by convention they are the same ID, because one identifies // the certificate and the other the private key. - properties->SetKey(shill::kEapCertIdProperty, base::Value(std::string())); - properties->SetKey(shill::kEapKeyIdProperty, base::Value(std::string())); + properties.Set(shill::kEapCertIdProperty, std::string()); + properties.Set(shill::kEapKeyIdProperty, std::string()); break; } } @@ -293,16 +281,16 @@ ClientCertConfig::~ClientCertConfig() = default; void OncToClientCertConfig(::onc::ONCSource onc_source, - const base::Value& network_config, + const base::Value::Dict& network_config, ClientCertConfig* cert_config) { *cert_config = ClientCertConfig(); - const base::Value* dict_with_client_cert = nullptr; + const base::Value::Dict* dict_with_client_cert = nullptr; - const base::Value* wifi = - network_config.FindDictKey(::onc::network_config::kWiFi); + const base::Value::Dict* wifi = + network_config.FindDict(::onc::network_config::kWiFi); if (wifi) { - const base::Value* eap = wifi->FindDictKey(::onc::wifi::kEAP); + const base::Value::Dict* eap = wifi->FindDict(::onc::wifi::kEAP); if (!eap) return; @@ -310,12 +298,12 @@ cert_config->location = ConfigType::kEap; } - const base::Value* vpn = - network_config.FindDictKey(::onc::network_config::kVPN); + const base::Value::Dict* vpn = + network_config.FindDict(::onc::network_config::kVPN); if (vpn) { - const base::Value* openvpn = vpn->FindDictKey(::onc::vpn::kOpenVPN); - const base::Value* ipsec = vpn->FindDictKey(::onc::vpn::kIPsec); - const base::Value* l2tp = vpn->FindDictKey(::onc::vpn::kL2TP); + const base::Value::Dict* openvpn = vpn->FindDict(::onc::vpn::kOpenVPN); + const base::Value::Dict* ipsec = vpn->FindDict(::onc::vpn::kIPsec); + const base::Value::Dict* l2tp = vpn->FindDict(::onc::vpn::kL2TP); if (openvpn) { dict_with_client_cert = openvpn; cert_config->location = ConfigType::kOpenVpn; @@ -332,10 +320,10 @@ } } - const base::Value* ethernet = - network_config.FindDictKey(::onc::network_config::kEthernet); + const base::Value::Dict* ethernet = + network_config.FindDict(::onc::network_config::kEthernet); if (ethernet) { - const base::Value* eap = ethernet->FindDictKey(::onc::wifi::kEAP); + const base::Value::Dict* eap = ethernet->FindDict(::onc::wifi::kEAP); if (!eap) return; dict_with_client_cert = eap;
diff --git a/chromeos/network/client_cert_util.h b/chromeos/network/client_cert_util.h index b4f241e..e0d6968 100644 --- a/chromeos/network/client_cert_util.h +++ b/chromeos/network/client_cert_util.h
@@ -83,7 +83,7 @@ // will be set to ConfigType::kNone, |tpm_slot| to -1 and |pkcs11_id| to the // empty string. COMPONENT_EXPORT(CHROMEOS_NETWORK) -void GetClientCertFromShillProperties(const base::Value& shill_properties, +void GetClientCertFromShillProperties(const base::Value::Dict& shill_properties, ConfigType* cert_config_type, int* tpm_slot, std::string* pkcs11_id); @@ -94,19 +94,19 @@ void SetShillProperties(const ConfigType cert_config_type, const int tpm_slot, const std::string& pkcs11_id, - base::Value* properties); + base::Value::Dict& properties); // Like SetShillProperties but instead sets the properties to empty strings. // This should be used to clear previously set client certificate properties. COMPONENT_EXPORT(CHROMEOS_NETWORK) void SetEmptyShillProperties(const ConfigType cert_config_type, - base::Value* properties); + base::Value::Dict& properties); // Determines the type of the OncCertificatePattern configuration, i.e. is it a // pattern within an EAP, IPsec or OpenVPN configuration. COMPONENT_EXPORT(CHROMEOS_NETWORK) void OncToClientCertConfig(::onc::ONCSource onc_source, - const base::Value& network_config, + const base::Value::Dict& network_config, ClientCertConfig* cert_config); } // namespace client_cert
diff --git a/chromeos/network/client_cert_util_unittest.cc b/chromeos/network/client_cert_util_unittest.cc new file mode 100644 index 0000000..badfcac --- /dev/null +++ b/chromeos/network/client_cert_util_unittest.cc
@@ -0,0 +1,518 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromeos/network/client_cert_util.h" + +#include "base/test/values_test_util.h" +#include "base/values.h" +#include "components/onc/onc_constants.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos::client_cert { + +TEST(ClientCertUtilTest, GetPkcs11AndSlotIdFromEapCertId_Ok) { + int slot_id = -1000; + EXPECT_EQ(GetPkcs11AndSlotIdFromEapCertId("2:abcd1234", &slot_id), + "abcd1234"); + EXPECT_EQ(slot_id, 2); +} + +TEST(ClientCertUtilTest, GetPkcs11AndSlotIdFromEapCertId_WrongFormat) { + int slot_id = -1000; + EXPECT_EQ(GetPkcs11AndSlotIdFromEapCertId("", &slot_id), std::string()); + EXPECT_EQ(slot_id, -1); +} + +TEST(ClientCertUtilTest, GetPkcs11AndSlotIdFromEapCertId_EmptyPkcs11Id) { + int slot_id = -1000; + EXPECT_EQ(GetPkcs11AndSlotIdFromEapCertId("2:", &slot_id), std::string()); + EXPECT_EQ(slot_id, -1); +} + +TEST(ClientCertUtilTest, GetPkcs11AndSlotIdFromEapCertId_BadSlotId) { + int slot_id = -1000; + EXPECT_EQ(GetPkcs11AndSlotIdFromEapCertId("a:abcd1234", &slot_id), + "abcd1234"); + EXPECT_EQ(slot_id, -1); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_OpenVPN) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "OpenVPN.Pkcs11.ID": "abcd1234" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kOpenVpn); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, -1); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_L2TPIPsec) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "L2TPIPsec.ClientCertID": "abcd1234", + "L2TPIPsec.ClientCertSlot": "2" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kL2tpIpsec); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, 2); +} + +TEST(ClientCertUtilTest, + GetClientCertFromShillProperties_L2TPIPsec_MissingSlot) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "L2TPIPsec.ClientCertID": "abcd1234" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kL2tpIpsec); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, -1); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_L2TPIPsec_EmptySlot) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "L2TPIPsec.ClientCertID": "abcd1234", + "L2TPIPsec.ClientCertSlot": "" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kL2tpIpsec); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, -1); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_L2TPIPsec_BadSlot) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "L2TPIPsec.ClientCertID": "abcd1234", + "L2TPIPsec.ClientCertSlot": "not_an_integer" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kNone); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_IKEv2) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "IKEv2.ClientCertID": "abcd1234", + "IKEv2.ClientCertSlot": "2" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kIkev2); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, 2); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_IKEv2_MissingSlot) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "IKEv2.ClientCertID": "abcd1234" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kIkev2); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, -1); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_IKEv2_EmptySlot) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "IKEv2.ClientCertID": "abcd1234", + "IKEv2.ClientCertSlot": "" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kIkev2); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, -1); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_IKEv2_BadSlot) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "Provider": { + "IKEv2.ClientCertID": "abcd1234", + "IKEv2.ClientCertSlot": "not_an_integer" + } + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kNone); +} + +TEST(ClientCertUtilTest, GetClientCertFromShillProperties_EAP) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "EAP.CertID": "2:abcd1234", + "EAP.KeyID": "2:abcd1234" + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kEap); + EXPECT_EQ(pkcs11_id, "abcd1234"); + EXPECT_EQ(tpm_slot, 2); +} + +TEST(ClientCertUtilTest, + GetClientCertFromShillProperties_EAP_KeyCertIdMismatch) { + ConfigType cert_config_type = ConfigType::kNone; + int tpm_slot = -1; + std::string pkcs11_id; + + base::Value shill_properties = base::test::ParseJson( + R"({ + "EAP.CertID": "2:abcd1234", + "EAP.KeyID": "3:edfg5678" + })"); + GetClientCertFromShillProperties(shill_properties.GetDict(), + &cert_config_type, &tpm_slot, &pkcs11_id); + EXPECT_EQ(cert_config_type, ConfigType::kNone); +} + +TEST(ClientCertUtilTest, SetShillProperties_OpenVPN) { + base::Value::Dict shill_properties; + SetShillProperties(ConfigType::kOpenVpn, 2, "abcd1234", shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "OpenVPN.Pkcs11.PIN": "111111", + "OpenVPN.Pkcs11.ID": "abcd1234" + })")); +} + +TEST(ClientCertUtilTest, SetShillProperties_L2TPIPsec) { + base::Value::Dict shill_properties; + SetShillProperties(ConfigType::kL2tpIpsec, 2, "abcd1234", shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "L2TPIPsec.PIN": "111111", + "L2TPIPsec.ClientCertID": "abcd1234", + "L2TPIPsec.ClientCertSlot": "2" + })")); +} + +TEST(ClientCertUtilTest, SetShillProperties_IKEv2) { + base::Value::Dict shill_properties; + SetShillProperties(ConfigType::kIkev2, 2, "abcd1234", shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "IKEv2.ClientCertID": "abcd1234", + "IKEv2.ClientCertSlot": "2" + })")); +} + +TEST(ClientCertUtilTest, SetShillProperties_EAP) { + base::Value::Dict shill_properties; + SetShillProperties(ConfigType::kEap, 2, "abcd1234", shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "EAP.PIN": "111111", + "EAP.CertID": "2:abcd1234", + "EAP.KeyID": "2:abcd1234" + })")); +} + +TEST(ClientCertUtilTest, SetEmptyShillProperties_OpenVPN) { + base::Value::Dict shill_properties; + SetEmptyShillProperties(ConfigType::kOpenVpn, shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "OpenVPN.Pkcs11.PIN": "", + "OpenVPN.Pkcs11.ID": "" + })")); +} + +TEST(ClientCertUtilTest, SetEmptyShillProperties_L2TPIPsec) { + base::Value::Dict shill_properties; + SetEmptyShillProperties(ConfigType::kL2tpIpsec, shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "L2TPIPsec.PIN": "", + "L2TPIPsec.ClientCertID": "", + "L2TPIPsec.ClientCertSlot": "" + })")); +} + +TEST(ClientCertUtilTest, SetEmptyShillProperties_IKEv2) { + base::Value::Dict shill_properties; + SetEmptyShillProperties(ConfigType::kIkev2, shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "IKEv2.ClientCertID": "", + "IKEv2.ClientCertSlot": "" + })")); +} + +TEST(ClientCertUtilTest, SetEmptyShillProperties_EAP) { + base::Value::Dict shill_properties; + SetEmptyShillProperties(ConfigType::kEap, shill_properties); + + EXPECT_THAT(base::Value(std::move(shill_properties)), base::test::IsJson( + R"({ + "EAP.PIN": "", + "EAP.CertID": "", + "EAP.KeyID": "" + })")); +} + +TEST(ClientCertUtilTest, OncToClientCertConfig_Empty) { + base::Value::Dict network_config; + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_NONE, network_config, &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kNone); +} + +// The actual tests for various client cert config types are implemented for +// wifi and not repeated for other client cert config locations (such as +// Ethernet, OpenVPN, ...) because the client cert config fields are the same. + +TEST(ClientCertUtilTest, OncToClientCertConfig_Wifi_Pattern) { + base::Value network_config = base::test::ParseJson( + R"({ + "WiFi": { + "EAP": { + "Identity": "identity_value", + "ClientCertType": "Pattern", + "ClientCertPattern": { + "Issuer": { + "CommonName": "common_name_value" + } + } + } + } + })"); + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_USER_POLICY, network_config.GetDict(), + &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kEap); + EXPECT_EQ(cert_config.client_cert_type, ::onc::client_cert::kPattern); + EXPECT_EQ(cert_config.guid, std::string()); + EXPECT_EQ(cert_config.provisioning_profile_id, std::string()); + EXPECT_EQ(cert_config.policy_identity, "identity_value"); + EXPECT_EQ(cert_config.onc_source, ::onc::ONC_SOURCE_USER_POLICY); +} + +TEST(ClientCertUtilTest, OncToClientCertConfig_Wifi_Ref) { + base::Value network_config = base::test::ParseJson( + R"({ + "WiFi": { + "EAP": { + "Identity": "identity_value", + "ClientCertType": "Ref", + "ClientCertRef": "guid" + } + } + })"); + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_USER_POLICY, network_config.GetDict(), + &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kEap); + EXPECT_EQ(cert_config.client_cert_type, ::onc::client_cert::kRef); + EXPECT_EQ(cert_config.guid, "guid"); + EXPECT_EQ(cert_config.provisioning_profile_id, std::string()); + EXPECT_EQ(cert_config.policy_identity, "identity_value"); + EXPECT_EQ(cert_config.onc_source, ::onc::ONC_SOURCE_USER_POLICY); +} + +TEST(ClientCertUtilTest, OncToClientCertConfig_Wifi_ProvisioningProfileId) { + base::Value network_config = base::test::ParseJson( + R"({ + "WiFi": { + "EAP": { + "Identity": "identity_value", + "ClientCertType": "ProvisioningProfileId", + "ClientCertProvisioningProfileId": "profile_id" + } + } + })"); + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_USER_POLICY, network_config.GetDict(), + &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kEap); + EXPECT_EQ(cert_config.client_cert_type, + ::onc::client_cert::kProvisioningProfileId); + EXPECT_EQ(cert_config.guid, std::string()); + EXPECT_EQ(cert_config.provisioning_profile_id, "profile_id"); + EXPECT_EQ(cert_config.policy_identity, "identity_value"); + EXPECT_EQ(cert_config.onc_source, ::onc::ONC_SOURCE_USER_POLICY); +} + +// The tests for the other network types (Ethernet, OpenVPN, ...) are performed +// just for provisioning profile id as an example. + +TEST(ClientCertUtilTest, OncToClientCertConfig_Ethernet_ProvisioningProfileId) { + base::Value network_config = base::test::ParseJson( + R"({ + "Ethernet": { + "EAP": { + "Identity": "identity_value", + "ClientCertType": "ProvisioningProfileId", + "ClientCertProvisioningProfileId": "profile_id" + } + } + })"); + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_USER_POLICY, network_config.GetDict(), + &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kEap); + EXPECT_EQ(cert_config.client_cert_type, + ::onc::client_cert::kProvisioningProfileId); + EXPECT_EQ(cert_config.guid, std::string()); + EXPECT_EQ(cert_config.provisioning_profile_id, "profile_id"); + EXPECT_EQ(cert_config.policy_identity, "identity_value"); + EXPECT_EQ(cert_config.onc_source, ::onc::ONC_SOURCE_USER_POLICY); +} + +TEST(ClientCertUtilTest, OncToClientCertConfig_OpenVPN_ProvisioningProfileId) { + base::Value network_config = base::test::ParseJson( + R"({ + "VPN": { + "OpenVPN": { + "Identity": "identity_value", + "ClientCertType": "ProvisioningProfileId", + "ClientCertProvisioningProfileId": "profile_id" + } + } + })"); + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_USER_POLICY, network_config.GetDict(), + &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kOpenVpn); + EXPECT_EQ(cert_config.client_cert_type, + ::onc::client_cert::kProvisioningProfileId); + EXPECT_EQ(cert_config.guid, std::string()); + EXPECT_EQ(cert_config.provisioning_profile_id, "profile_id"); + EXPECT_EQ(cert_config.policy_identity, "identity_value"); + EXPECT_EQ(cert_config.onc_source, ::onc::ONC_SOURCE_USER_POLICY); +} + +TEST(ClientCertUtilTest, + OncToClientCertConfig_L2TPIPsec_ProvisioningProfileId) { + base::Value network_config = base::test::ParseJson( + R"({ + "VPN": { + "L2TP": { }, + "IPsec": { + "Identity": "identity_value", + "ClientCertType": "ProvisioningProfileId", + "ClientCertProvisioningProfileId": "profile_id" + } + } + })"); + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_USER_POLICY, network_config.GetDict(), + &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kL2tpIpsec); + EXPECT_EQ(cert_config.client_cert_type, + ::onc::client_cert::kProvisioningProfileId); + EXPECT_EQ(cert_config.guid, std::string()); + EXPECT_EQ(cert_config.provisioning_profile_id, "profile_id"); + EXPECT_EQ(cert_config.policy_identity, "identity_value"); + EXPECT_EQ(cert_config.onc_source, ::onc::ONC_SOURCE_USER_POLICY); +} + +TEST(ClientCertUtilTest, OncToClientCertConfig_IKEv2_ProvisioningProfileId) { + base::Value network_config = base::test::ParseJson( + R"({ + "VPN": { + "IPsec": { + "Identity": "identity_value", + "ClientCertType": "ProvisioningProfileId", + "ClientCertProvisioningProfileId": "profile_id" + } + } + })"); + ClientCertConfig cert_config; + OncToClientCertConfig(::onc::ONC_SOURCE_USER_POLICY, network_config.GetDict(), + &cert_config); + + EXPECT_EQ(cert_config.location, ConfigType::kIkev2); + EXPECT_EQ(cert_config.client_cert_type, + ::onc::client_cert::kProvisioningProfileId); + EXPECT_EQ(cert_config.guid, std::string()); + EXPECT_EQ(cert_config.provisioning_profile_id, "profile_id"); + EXPECT_EQ(cert_config.policy_identity, "identity_value"); + EXPECT_EQ(cert_config.onc_source, ::onc::ONC_SOURCE_USER_POLICY); +} + +} // namespace chromeos::client_cert
diff --git a/chromeos/network/network_cert_migrator.cc b/chromeos/network/network_cert_migrator.cc index ef6c0ed1..e18f82d 100644 --- a/chromeos/network/network_cert_migrator.cc +++ b/chromeos/network/network_cert_migrator.cc
@@ -97,7 +97,7 @@ chromeos::client_cert::ConfigType config_type = chromeos::client_cert::ConfigType::kNone; chromeos::client_cert::GetClientCertFromShillProperties( - properties, &config_type, &configured_slot_id, &pkcs11_id); + properties.GetDict(), &config_type, &configured_slot_id, &pkcs11_id); if (config_type == chromeos::client_cert::ConfigType::kNone || pkcs11_id.empty()) { return result; @@ -113,7 +113,8 @@ if (!cert) { LOG(WARNING) << "No matching cert found, removing the certificate " "configuration from network " << service_path; - chromeos::client_cert::SetEmptyShillProperties(config_type, &result); + chromeos::client_cert::SetEmptyShillProperties(config_type, + result.GetDict()); return result; } if (real_slot_id == -1) { @@ -125,7 +126,7 @@ VLOG(1) << "Network " << service_path << " is configured with no or an incorrect slot id."; chromeos::client_cert::SetShillProperties(config_type, real_slot_id, - pkcs11_id, &result); + pkcs11_id, result.GetDict()); } return result; }
diff --git a/chromeos/network/network_connection_handler_impl.cc b/chromeos/network/network_connection_handler_impl.cc index 9b2eb08..54986611 100644 --- a/chromeos/network/network_connection_handler_impl.cc +++ b/chromeos/network/network_connection_handler_impl.cc
@@ -697,7 +697,7 @@ client_cert::ClientCertConfig cert_config_from_policy; if (policy) { - client_cert::OncToClientCertConfig(onc_source, *policy, + client_cert::OncToClientCertConfig(onc_source, policy->GetDict(), &cert_config_from_policy); }
diff --git a/components/background_sync/background_sync_permission_context.cc b/components/background_sync/background_sync_permission_context.cc index db27694..ce22734 100644 --- a/components/background_sync/background_sync_permission_context.cc +++ b/components/background_sync/background_sync_permission_context.cc
@@ -16,7 +16,6 @@ } void BackgroundSyncPermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/components/background_sync/background_sync_permission_context.h b/components/background_sync/background_sync_permission_context.h index c1c60fd2..350118c8 100644 --- a/components/background_sync/background_sync_permission_context.h +++ b/components/background_sync/background_sync_permission_context.h
@@ -29,7 +29,6 @@ private: // PermissionContextBase: void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/components/background_sync/background_sync_permission_context_unittest.cc b/components/background_sync/background_sync_permission_context_unittest.cc index 5f19279..198fade 100644 --- a/components/background_sync/background_sync_permission_context_unittest.cc +++ b/components/background_sync/background_sync_permission_context_unittest.cc
@@ -47,7 +47,7 @@ web_contents()->GetMainFrame()->GetRoutingID(), permissions::PermissionRequestID::RequestLocalId()); permission_context->RequestPermission( - web_contents(), id, url, /* user_gesture= */ false, + id, url, /* user_gesture= */ false, base::BindOnce( &BackgroundSyncPermissionContextTest::TrackPermissionDecision, base::Unretained(this), run_loop.QuitClosure()));
diff --git a/components/certificate_transparency/data/log_list.json b/components/certificate_transparency/data/log_list.json index 9a94433..5219bdb 100644 --- a/components/certificate_transparency/data/log_list.json +++ b/components/certificate_transparency/data/log_list.json
@@ -1,6 +1,6 @@ { - "version": "9.24", - "log_list_timestamp": "2022-05-26T12:54:06Z", + "version": "9.25", + "log_list_timestamp": "2022-05-27T12:55:13Z", "operators": [ { "name": "Google",
diff --git a/components/exo/wayland/clients/client_base.cc b/components/exo/wayland/clients/client_base.cc index 7b97fe0..e5f4e2aa 100644 --- a/components/exo/wayland/clients/client_base.cc +++ b/components/exo/wayland/clients/client_base.cc
@@ -533,7 +533,7 @@ return false; } // We can't actually use the virtual GEM, so discard it like we do in CrOS - if (base::LowerCaseEqualsASCII("vgem", drm_version->name)) + if (base::EqualsCaseInsensitiveASCII("vgem", drm_version->name)) continue; if (strstr(drm_version->name, params.use_drm_value.c_str())) { drm_fd_ = std::move(drm_fd);
diff --git a/components/feed/content/renderer/rss_link_reader.cc b/components/feed/content/renderer/rss_link_reader.cc index 42c18fb..338e73d5 100644 --- a/components/feed/content/renderer/rss_link_reader.cc +++ b/components/feed/content/renderer/rss_link_reader.cc
@@ -37,14 +37,14 @@ if (!web_type.ContainsOnlyASCII() || !web_rel.ContainsOnlyASCII()) return GURL(); std::string type = web_type.Ascii(); - if (!(base::LowerCaseEqualsASCII(type, "application/rss+xml") || - base::LowerCaseEqualsASCII(type, "application/rss+atom") || - base::LowerCaseEqualsASCII(type, "application/atom+xml"))) { + if (!(base::EqualsCaseInsensitiveASCII(type, "application/rss+xml") || + base::EqualsCaseInsensitiveASCII(type, "application/rss+atom") || + base::EqualsCaseInsensitiveASCII(type, "application/atom+xml"))) { return GURL(); } std::string rel = web_rel.Ascii(); - if (!(base::LowerCaseEqualsASCII(rel, "alternate") || - base::LowerCaseEqualsASCII(rel, "service.feed"))) { + if (!(base::EqualsCaseInsensitiveASCII(rel, "alternate") || + base::EqualsCaseInsensitiveASCII(rel, "service.feed"))) { return GURL(); } blink::WebURL url =
diff --git a/components/language/core/common/language_experiments.cc b/components/language/core/common/language_experiments.cc index 8086c23..e9d99ac 100644 --- a/components/language/core/common/language_experiments.cc +++ b/components/language/core/common/language_experiments.cc
@@ -28,8 +28,6 @@ "NotifySyncOnLanguageDetermined", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kDetailedLanguageSettings{"DetailedLanguageSettings", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kDesktopRestructuredLanguageSettings{ - "DesktopRestructuredLanguageSettings", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kDesktopDetailedLanguageSettings{ "DesktopDetailedLanguageSettings", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kTranslateAssistContent{"TranslateAssistContent",
diff --git a/components/language/core/common/language_experiments.h b/components/language/core/common/language_experiments.h index 9bf8464..839f7015 100644 --- a/components/language/core/common/language_experiments.h +++ b/components/language/core/common/language_experiments.h
@@ -42,10 +42,6 @@ // This feature enables setting the application language on Android. extern const base::Feature kDetailedLanguageSettings; -// This feature enables the desktop version's redesigned language settings -// layout. -extern const base::Feature kDesktopRestructuredLanguageSettings; - // This feature enables setting the application language on Desktop. extern const base::Feature kDesktopDetailedLanguageSettings;
diff --git a/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.cc b/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.cc index e9250ec..7046fc1 100644 --- a/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.cc +++ b/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.cc
@@ -55,7 +55,6 @@ } void CameraPanTiltZoomPermissionContext::RequestPermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_frame_origin, bool user_gesture, @@ -63,8 +62,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (HasAvailableCameraPtzDevices()) { - PermissionContextBase::RequestPermission(web_contents, id, - requesting_frame_origin, + PermissionContextBase::RequestPermission(id, requesting_frame_origin, user_gesture, std::move(callback)); return; } @@ -80,7 +78,7 @@ std::move(callback).Run(CONTENT_SETTING_BLOCK); return; } - web_contents->GetBrowserContext() + render_frame_host->GetBrowserContext() ->GetPermissionController() ->RequestPermissionFromCurrentDocument( blink::PermissionType::VIDEO_CAPTURE, render_frame_host, user_gesture,
diff --git a/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.h b/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.h index 61d15ac..6f25187 100644 --- a/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.h +++ b/components/permissions/contexts/camera_pan_tilt_zoom_permission_context.h
@@ -53,7 +53,6 @@ private: // PermissionContextBase void RequestPermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_frame_origin, bool user_gesture,
diff --git a/components/permissions/contexts/geolocation_permission_context.cc b/components/permissions/contexts/geolocation_permission_context.cc index 54b1737..d0c8fdd 100644 --- a/components/permissions/contexts/geolocation_permission_context.cc +++ b/components/permissions/contexts/geolocation_permission_context.cc
@@ -28,7 +28,6 @@ GeolocationPermissionContext::~GeolocationPermissionContext() = default; void GeolocationPermissionContext::DecidePermission( - content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, @@ -36,10 +35,10 @@ BrowserPermissionCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!delegate_->DecidePermission(web_contents, id, requesting_origin, - user_gesture, &callback, this)) { + if (!delegate_->DecidePermission(id, requesting_origin, user_gesture, + &callback, this)) { DCHECK(callback); - PermissionContextBase::DecidePermission(web_contents, id, requesting_origin, + PermissionContextBase::DecidePermission(id, requesting_origin, embedding_origin, user_gesture, std::move(callback)); }
diff --git a/components/permissions/contexts/geolocation_permission_context.h b/components/permissions/contexts/geolocation_permission_context.h index 7463e47..bbc7ba56 100644 --- a/components/permissions/contexts/geolocation_permission_context.h +++ b/components/permissions/contexts/geolocation_permission_context.h
@@ -33,8 +33,7 @@ // Allows the delegate to override the context's DecidePermission() logic. // If this returns true, the base context's DecidePermission() will not be // called. - virtual bool DecidePermission(content::WebContents* web_contents, - const PermissionRequestID& id, + virtual bool DecidePermission(const PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture, BrowserPermissionCallback* callback, @@ -62,8 +61,7 @@ ~GeolocationPermissionContext() override; - void DecidePermission(content::WebContents* web_contents, - const PermissionRequestID& id, + void DecidePermission(const PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, bool user_gesture,
diff --git a/components/permissions/contexts/geolocation_permission_context_android.cc b/components/permissions/contexts/geolocation_permission_context_android.cc index 8b4fe96b..4bf702d7 100644 --- a/components/permissions/contexts/geolocation_permission_context_android.cc +++ b/components/permissions/contexts/geolocation_permission_context_android.cc
@@ -94,7 +94,6 @@ } void GeolocationPermissionContextAndroid::RequestPermission( - content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame_origin, bool user_gesture, @@ -102,6 +101,9 @@ content::RenderFrameHost* const render_frame_host = content::RenderFrameHost::FromID(id.render_process_id(), id.render_frame_id()); + + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(render_frame_host); const GURL embedding_origin = PermissionUtil::GetLastCommittedOriginAsURL( render_frame_host->GetMainFrame()); @@ -133,8 +135,7 @@ } GeolocationPermissionContext::RequestPermission( - web_contents, id, requesting_frame_origin, user_gesture, - std::move(callback)); + id, requesting_frame_origin, user_gesture, std::move(callback)); } void GeolocationPermissionContextAndroid::UserMadePermissionDecision(
diff --git a/components/permissions/contexts/geolocation_permission_context_android.h b/components/permissions/contexts/geolocation_permission_context_android.h index ec31701..f469555 100644 --- a/components/permissions/contexts/geolocation_permission_context_android.h +++ b/components/permissions/contexts/geolocation_permission_context_android.h
@@ -72,8 +72,7 @@ private: // GeolocationPermissionContext: - void RequestPermission(content::WebContents* web_contents, - const PermissionRequestID& id, + void RequestPermission(const PermissionRequestID& id, const GURL& requesting_frame_origin, bool user_gesture, BrowserPermissionCallback callback) override;
diff --git a/components/permissions/contexts/geolocation_permission_context_unittest.cc b/components/permissions/contexts/geolocation_permission_context_unittest.cc index a0f8e5e..b434616 100644 --- a/components/permissions/contexts/geolocation_permission_context_unittest.cc +++ b/components/permissions/contexts/geolocation_permission_context_unittest.cc
@@ -91,8 +91,7 @@ #endif } - bool DecidePermission(content::WebContents* web_contents, - const PermissionRequestID& id, + bool DecidePermission(const PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture, BrowserPermissionCallback* callback, @@ -140,8 +139,7 @@ PermissionRequestID RequestID(int request_id); PermissionRequestID RequestIDForTab(int tab, int request_id); - void RequestGeolocationPermission(content::WebContents* web_contents, - const PermissionRequestID& id, + void RequestGeolocationPermission(const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture); @@ -226,12 +224,11 @@ } void GeolocationPermissionContextTests::RequestGeolocationPermission( - content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture) { geolocation_permission_context_->RequestPermission( - web_contents, id, requesting_frame, user_gesture, + id, requesting_frame, user_gesture, base::BindOnce(&GeolocationPermissionContextTests::PermissionResponse, base::Unretained(this), id)); content::RunAllTasksUntilIdle(); @@ -398,7 +395,7 @@ NavigateAndCommit(origin); RequestManagerDocumentLoadCompleted(); MockLocationSettings::ClearHasShownLocationSettingsDialog(); - RequestGeolocationPermission(web_contents(), RequestID(0), origin, true); + RequestGeolocationPermission(RequestID(0), origin, true); return MockLocationSettings::HasShownLocationSettingsDialog(); } @@ -408,7 +405,7 @@ NavigateAndCommit(origin); RequestManagerDocumentLoadCompleted(); MockLocationSettings::ClearHasShownLocationSettingsDialog(); - RequestGeolocationPermission(web_contents(), RequestID(0), origin, true); + RequestGeolocationPermission(RequestID(0), origin, true); EXPECT_TRUE(HasActivePrompt()); AcceptPrompt(); @@ -507,8 +504,7 @@ RequestManagerDocumentLoadCompleted(); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); } @@ -519,8 +515,7 @@ RequestManagerDocumentLoadCompleted(); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); ASSERT_FALSE(HasActivePrompt()); } @@ -534,8 +529,7 @@ MockLocationSettings::SetLocationStatus(true /* android */, true /* system */); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); EXPECT_TRUE(HasActivePrompt()); histograms.ExpectTotalCount("Permissions.Action.Geolocation", 0); @@ -546,8 +540,7 @@ true /* system */); MockLocationSettings::SetCanPromptForAndroidPermission(false); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); histograms.ExpectUniqueSample("Permissions.Action.Geolocation", static_cast<int>(PermissionAction::IGNORED), 1); EXPECT_FALSE(HasActivePrompt()); @@ -560,8 +553,7 @@ MockLocationSettings::SetLocationStatus(false /* android */, true /* system */); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); @@ -576,8 +568,7 @@ true /* system */); MockLocationSettings::SetCanPromptForAndroidPermission(false); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); EXPECT_FALSE(HasActivePrompt()); } @@ -588,8 +579,7 @@ MockLocationSettings::SetLocationStatus(true /* android */, false /* system */); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); EXPECT_FALSE(HasActivePrompt()); EXPECT_FALSE(MockLocationSettings::HasShownLocationSettingsDialog()); } @@ -599,8 +589,7 @@ NavigateAndCommit(requesting_frame); RequestManagerDocumentLoadCompleted(); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); @@ -619,8 +608,7 @@ MockLocationSettings::SetLocationSettingsDialogStatus(true /* enabled */, GRANTED); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); @@ -643,8 +631,7 @@ MockLocationSettings::SetLocationSettingsDialogStatus(true /* enabled */, DENIED); EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_BLOCK); @@ -931,8 +918,7 @@ // Check permission is requested. ASSERT_FALSE(HasActivePrompt()); const bool user_gesture = true; - RequestGeolocationPermission(web_contents(), RequestID(0), url_a, - user_gesture); + RequestGeolocationPermission(RequestID(0), url_a, user_gesture); ASSERT_TRUE(HasActivePrompt()); // Change the hash, we'll still be on the same page. @@ -955,8 +941,7 @@ // Check permission is requested. ASSERT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); EXPECT_TRUE(HasActivePrompt()); // Accept the frame. @@ -979,7 +964,7 @@ ASSERT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), frame_0, true); + RequestGeolocationPermission(RequestID(0), frame_0, true); ASSERT_TRUE(HasActivePrompt()); std::u16string text_0 = GetPromptText(); @@ -1002,8 +987,7 @@ // Nothing should be displayed. EXPECT_FALSE(HasActivePrompt()); - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - true); + RequestGeolocationPermission(RequestID(0), requesting_frame, true); EXPECT_FALSE(HasActivePrompt()); CheckPermissionMessageSent(0, false); } @@ -1019,11 +1003,9 @@ RequestManagerDocumentLoadCompleted(extra_tabs_[1].get()); // Request permission in all three tabs. - RequestGeolocationPermission(web_contents(), RequestID(0), url_a, true); - RequestGeolocationPermission(extra_tabs_[0].get(), RequestIDForTab(0, 0), - url_b, true); - RequestGeolocationPermission(extra_tabs_[1].get(), RequestIDForTab(1, 0), - url_a, true); + RequestGeolocationPermission(RequestID(0), url_a, true); + RequestGeolocationPermission(RequestIDForTab(0, 0), url_b, true); + RequestGeolocationPermission(RequestIDForTab(1, 0), url_a, true); ASSERT_TRUE(HasActivePrompt()); // For A0. ASSERT_TRUE(HasActivePrompt(extra_tabs_[0].get())); ASSERT_TRUE(HasActivePrompt(extra_tabs_[1].get())); @@ -1048,8 +1030,7 @@ RequestManagerDocumentLoadCompleted(); // Request permission for two frames. - RequestGeolocationPermission(web_contents(), RequestID(0), requesting_frame, - false); + RequestGeolocationPermission(RequestID(0), requesting_frame, false); ASSERT_TRUE(HasActivePrompt()); EXPECT_EQ(CONTENT_SETTING_ASK,
diff --git a/components/permissions/contexts/midi_sysex_permission_context_unittest.cc b/components/permissions/contexts/midi_sysex_permission_context_unittest.cc index 49c853050..900680f 100644 --- a/components/permissions/contexts/midi_sysex_permission_context_unittest.cc +++ b/components/permissions/contexts/midi_sysex_permission_context_unittest.cc
@@ -80,7 +80,7 @@ web_contents()->GetMainFrame()->GetRoutingID(), permissions::PermissionRequestID::RequestLocalId()); permission_context.RequestPermission( - web_contents(), id, url, true, + id, url, true, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context)));
diff --git a/components/permissions/contexts/nfc_permission_context.cc b/components/permissions/contexts/nfc_permission_context.cc index efda925..9a2937e 100644 --- a/components/permissions/contexts/nfc_permission_context.cc +++ b/components/permissions/contexts/nfc_permission_context.cc
@@ -31,7 +31,6 @@ #endif void NfcPermissionContext::DecidePermission( - content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, @@ -42,7 +41,7 @@ return; } permissions::PermissionContextBase::DecidePermission( - web_contents, id, requesting_origin, embedding_origin, user_gesture, + id, requesting_origin, embedding_origin, user_gesture, std::move(callback)); }
diff --git a/components/permissions/contexts/nfc_permission_context.h b/components/permissions/contexts/nfc_permission_context.h index 8c52b53..a965187 100644 --- a/components/permissions/contexts/nfc_permission_context.h +++ b/components/permissions/contexts/nfc_permission_context.h
@@ -42,8 +42,7 @@ const GURL& requesting_origin, const GURL& embedding_origin) const override; #endif - void DecidePermission(content::WebContents* web_contents, - const PermissionRequestID& id, + void DecidePermission(const PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, bool user_gesture,
diff --git a/components/permissions/contexts/nfc_permission_context_unittest.cc b/components/permissions/contexts/nfc_permission_context_unittest.cc index e5762016..b8383c50 100644 --- a/components/permissions/contexts/nfc_permission_context_unittest.cc +++ b/components/permissions/contexts/nfc_permission_context_unittest.cc
@@ -46,8 +46,7 @@ PermissionRequestID RequestID(int request_id); - void RequestNfcPermission(content::WebContents* web_contents, - const PermissionRequestID& id, + void RequestNfcPermission(const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture); @@ -90,12 +89,11 @@ } void NfcPermissionContextTests::RequestNfcPermission( - content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture) { nfc_permission_context_->RequestPermission( - web_contents, id, requesting_frame, user_gesture, + id, requesting_frame, user_gesture, base::BindOnce(&NfcPermissionContextTests::PermissionResponse, base::Unretained(this), id)); content::RunAllTasksUntilIdle(); @@ -231,8 +229,7 @@ RequestManagerDocumentLoadCompleted(); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, - true /* user_gesture */); + RequestNfcPermission(RequestID(0), requesting_frame, true /* user_gesture */); #if BUILDFLAG(IS_ANDROID) ASSERT_TRUE(HasActivePrompt()); @@ -247,7 +244,7 @@ RequestManagerDocumentLoadCompleted(); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_FALSE(HasActivePrompt()); } @@ -260,7 +257,7 @@ RequestManagerDocumentLoadCompleted(); MockNfcSystemLevelSetting::SetNfcSystemLevelSettingEnabled(false); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); ASSERT_FALSE(MockNfcSystemLevelSetting::HasShownNfcSettingPrompt()); AcceptPrompt(); @@ -275,7 +272,7 @@ RequestManagerDocumentLoadCompleted(); MockNfcSystemLevelSetting::SetNfcSystemLevelSettingEnabled(false); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); ASSERT_FALSE(MockNfcSystemLevelSetting::HasShownNfcSettingPrompt()); DenyPrompt(); @@ -292,7 +289,7 @@ RequestManagerDocumentLoadCompleted(); MockNfcSystemLevelSetting::SetNfcSystemLevelSettingEnabled(false); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_FALSE(HasActivePrompt()); ASSERT_TRUE(MockNfcSystemLevelSetting::HasShownNfcSettingPrompt()); } @@ -305,7 +302,7 @@ NavigateAndCommit(requesting_frame); RequestManagerDocumentLoadCompleted(); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_FALSE(HasActivePrompt()); ASSERT_FALSE(MockNfcSystemLevelSetting::HasShownNfcSettingPrompt()); } @@ -318,7 +315,7 @@ MockNfcSystemLevelSetting::SetNfcSystemLevelSettingEnabled(false); MockNfcSystemLevelSetting::SetNfcAccessIsPossible(false); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); ASSERT_FALSE(MockNfcSystemLevelSetting::HasShownNfcSettingPrompt()); AcceptPrompt(); @@ -335,7 +332,7 @@ MockNfcSystemLevelSetting::SetNfcSystemLevelSettingEnabled(false); MockNfcSystemLevelSetting::SetNfcAccessIsPossible(false); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt()); ASSERT_FALSE(MockNfcSystemLevelSetting::HasShownNfcSettingPrompt()); DenyPrompt(); @@ -354,7 +351,7 @@ MockNfcSystemLevelSetting::SetNfcSystemLevelSettingEnabled(false); MockNfcSystemLevelSetting::SetNfcAccessIsPossible(false); EXPECT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_FALSE(HasActivePrompt()); ASSERT_FALSE(MockNfcSystemLevelSetting::HasShownNfcSettingPrompt()); CheckPermissionMessageSent(0 /* request _id */, true /* allowed */); @@ -370,7 +367,7 @@ ASSERT_FALSE(HasActivePrompt()); - RequestNfcPermission(web_contents(), RequestID(0), requesting_frame, true); + RequestNfcPermission(RequestID(0), requesting_frame, true); ASSERT_TRUE(HasActivePrompt());
diff --git a/components/permissions/contexts/payment_handler_permission_context.cc b/components/permissions/contexts/payment_handler_permission_context.cc index ae16592c..0257a74 100644 --- a/components/permissions/contexts/payment_handler_permission_context.cc +++ b/components/permissions/contexts/payment_handler_permission_context.cc
@@ -23,7 +23,6 @@ PaymentHandlerPermissionContext::~PaymentHandlerPermissionContext() {} void PaymentHandlerPermissionContext::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/components/permissions/contexts/payment_handler_permission_context.h b/components/permissions/contexts/payment_handler_permission_context.h index cdbab62..6b38df85 100644 --- a/components/permissions/contexts/payment_handler_permission_context.h +++ b/components/permissions/contexts/payment_handler_permission_context.h
@@ -35,7 +35,6 @@ private: // PermissionContextBase void DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin,
diff --git a/components/permissions/permission_context_base.cc b/components/permissions/permission_context_base.cc index c2c6fc7..3699474 100644 --- a/components/permissions/permission_context_base.cc +++ b/components/permissions/permission_context_base.cc
@@ -120,7 +120,6 @@ } void PermissionContextBase::RequestPermission( - content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture, @@ -129,6 +128,13 @@ content::RenderFrameHost* const rfh = content::RenderFrameHost::FromID( id.render_process_id(), id.render_frame_id()); + + if (!rfh) { + // Permission request is not allowed without a valid RenderFrameHost. + std::move(callback).Run(CONTENT_SETTING_ASK); + return; + } + const GURL requesting_origin = requesting_frame.DeprecatedGetOriginAsURL(); const GURL embedding_origin = PermissionUtil::GetLastCommittedOriginAsURL(rfh->GetMainFrame()); @@ -220,8 +226,8 @@ PermissionUmaUtil::RecordEmbargoPromptSuppression( PermissionEmbargoStatus::NOT_EMBARGOED); - DecidePermission(web_contents, id, requesting_origin, embedding_origin, - user_gesture, std::move(callback)); + DecidePermission(id, requesting_origin, embedding_origin, user_gesture, + std::move(callback)); } void PermissionContextBase::UserMadePermissionDecision( @@ -379,7 +385,6 @@ } void PermissionContextBase::DecidePermission( - content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, @@ -396,6 +401,12 @@ requesting_origin == embedding_origin || content_settings_type_ == ContentSettingsType::STORAGE_ACCESS); + content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( + id.render_process_id(), id.render_frame_id()); + DCHECK(rfh); + + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(rfh); PermissionRequestManager* permission_request_manager = PermissionRequestManager::FromWebContents(web_contents); // TODO(felt): sometimes |permission_request_manager| is null. This check is @@ -418,15 +429,6 @@ .second; DCHECK(inserted) << "Duplicate id " << id.ToString(); - content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( - id.render_process_id(), id.render_frame_id()); - - if (!rfh) { - request->Cancelled(); - request->RequestFinished(); - return; - } - permission_request_manager->AddRequest(rfh, request); }
diff --git a/components/permissions/permission_context_base.h b/components/permissions/permission_context_base.h index 9266ced..60c8efd 100644 --- a/components/permissions/permission_context_base.h +++ b/components/permissions/permission_context_base.h
@@ -88,8 +88,7 @@ // |callback| is called upon resolution of the request, but not if a prompt // is shown and ignored. - virtual void RequestPermission(content::WebContents* web_contents, - const PermissionRequestID& id, + virtual void RequestPermission(const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture, BrowserPermissionCallback callback); @@ -134,8 +133,7 @@ // Called if generic checks (existing content setting, embargo, etc.) fail to // resolve a permission request. The default implementation prompts the user. - virtual void DecidePermission(content::WebContents* web_contents, - const PermissionRequestID& id, + virtual void DecidePermission(const PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, bool user_gesture,
diff --git a/components/permissions/permission_context_base_unittest.cc b/components/permissions/permission_context_base_unittest.cc index 4b08004f..733b4ae2 100644 --- a/components/permissions/permission_context_base_unittest.cc +++ b/components/permissions/permission_context_base_unittest.cc
@@ -88,26 +88,23 @@ content_settings_type()); } - void RequestPermission(content::WebContents* web_contents, - const PermissionRequestID& id, + void RequestPermission(const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture, BrowserPermissionCallback callback) override { base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); - PermissionContextBase::RequestPermission(web_contents, id, requesting_frame, - true /* user_gesture */, - std::move(callback)); + PermissionContextBase::RequestPermission( + id, requesting_frame, true /* user_gesture */, std::move(callback)); run_loop.Run(); } - void DecidePermission(content::WebContents* web_contents, - const PermissionRequestID& id, + void DecidePermission(const PermissionRequestID& id, const GURL& requesting_origin, const GURL& embedding_origin, bool user_gesture, BrowserPermissionCallback callback) override { - PermissionContextBase::DecidePermission(web_contents, id, requesting_origin, + PermissionContextBase::DecidePermission(id, requesting_origin, embedding_origin, user_gesture, std::move(callback)); if (respond_permission_) { @@ -238,7 +235,7 @@ &PermissionContextBaseTests::RespondToPermission, base::Unretained(this), &permission_context, id, url, decision)); permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, + id, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); ASSERT_EQ(1u, permission_context.decisions().size()); @@ -341,7 +338,7 @@ CONTENT_SETTING_ASK)); permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, + id, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); histograms.ExpectTotalCount( @@ -394,7 +391,7 @@ CONTENT_SETTING_ASK)); permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, + id, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); @@ -433,7 +430,7 @@ base::Unretained(this), &permission_context, id, url, CONTENT_SETTING_ASK)); permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, + id, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); histograms.ExpectTotalCount( @@ -507,7 +504,7 @@ base::Unretained(this), &permission_context, id, url, CONTENT_SETTING_ASK)); permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, + id, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); @@ -565,7 +562,7 @@ web_contents()->GetMainFrame()->GetRoutingID(), PermissionRequestID::RequestLocalId()); permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, + id, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); @@ -595,7 +592,7 @@ CONTENT_SETTING_ALLOW)); permission_context.RequestPermission( - web_contents(), id, url, true /* user_gesture */, + id, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); @@ -679,7 +676,7 @@ // Request a permission without setting the callback to DecidePermission. permission_context.RequestPermission( - web_contents(), id1, url, true /* user_gesture */, + id1, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context))); @@ -690,7 +687,7 @@ &PermissionContextBaseTests::RespondToPermission, base::Unretained(this), &permission_context, id1, url, response)); permission_context.RequestPermission( - web_contents(), id2, url, true /* user_gesture */, + id2, url, true /* user_gesture */, base::BindOnce(&TestPermissionContext::TrackPermissionDecision, base::Unretained(&permission_context)));
diff --git a/components/permissions/permission_manager.cc b/components/permissions/permission_manager.cc index 698d7a5d..96d7af03 100644 --- a/components/permissions/permission_manager.cc +++ b/components/permissions/permission_manager.cc
@@ -426,7 +426,6 @@ DCHECK(context); context->RequestPermission( - content::WebContents::FromRenderFrameHost(render_frame_host), request_id, canonical_requesting_origin, user_gesture, base::BindOnce( &PermissionResponseCallback::OnPermissionsRequestResponseStatus,
diff --git a/components/policy/core/common/features.cc b/components/policy/core/common/features.cc index 7282c13c..a82f2e2d 100644 --- a/components/policy/core/common/features.cc +++ b/components/policy/core/common/features.cc
@@ -25,7 +25,7 @@ const base::Feature kActivateMetricsReportingEnabledPolicyAndroid{ "ActivateMetricsReportingEnabledPolicyAndroid", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kEnableCachedManagementStatus{ "EnableCachedManagementStatus", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/components/policy/resources/webui/policy.js b/components/policy/resources/webui/policy.js index f400fe1..e745cc8 100644 --- a/components/policy/resources/webui/policy.js +++ b/components/policy/resources/webui/policy.js
@@ -10,3 +10,41 @@ document.addEventListener('DOMContentLoaded', () => { page.initialize(); }); + +// Functions for tests that directly inject JS to access certain UI elements. +function getPolicyFieldsets() { + const statusSection = document.querySelector('#status-section'); + return statusSection.querySelectorAll('fieldset'); +} + +function getAllPolicyTables() { + return document.querySelector('#policy-ui').querySelectorAll('.policy-table'); +} + +function getAllPolicyRows(policyTable) { + return policyTable.querySelectorAll('.policy.row'); +} + +function getAllPolicyRowDivs(policyRow) { + return policyRow.querySelectorAll('div'); +} + +function getPrecedenceRowValue() { + const precedenceRow = + document.querySelector('#policy-ui') + .querySelector('.policy-table .precedence.row > .value'); + return precedenceRow; +} + +function getRefreshIntervalEl() { + return document.querySelector('#status-box-container .refresh-interval'); +} + +Object.assign(window, { + getPolicyFieldsets, + getAllPolicyTables, + getAllPolicyRows, + getAllPolicyRowDivs, + getPrecedenceRowValue, + getRefreshIntervalEl, +});
diff --git a/components/reporting/proto/synced/metric_data.proto b/components/reporting/proto/synced/metric_data.proto index 1ef585c..adb4317 100644 --- a/components/reporting/proto/synced/metric_data.proto +++ b/components/reporting/proto/synced/metric_data.proto
@@ -110,6 +110,8 @@ optional int64 link_quality = 13; // Wifi power management enabled optional bool power_management_enabled = 14; + // Signal strength for wireless networks in dBm. + optional int32 signal_strength_dbm = 15; } // Configured networks telemetry data.
diff --git a/components/safe_browsing/content/browser/threat_details_cache.cc b/components/safe_browsing/content/browser/threat_details_cache.cc index 1f0a5b14..bd28ab4 100644 --- a/components/safe_browsing/content/browser/threat_details_cache.cc +++ b/components/safe_browsing/content/browser/threat_details_cache.cc
@@ -191,7 +191,7 @@ std::string name, value; while (headers->EnumerateHeaderLines(&iter, &name, &value)) { // Strip any Set-Cookie headers. - if (base::LowerCaseEqualsASCII(name, "set-cookie")) + if (base::EqualsCaseInsensitiveASCII(name, "set-cookie")) continue; ClientSafeBrowsingReportRequest::HTTPHeader* pb_header = pb_response->add_headers();
diff --git a/components/thin_webview/internal/compositor_view_impl.cc b/components/thin_webview/internal/compositor_view_impl.cc index 08ce986..e1d39c9 100644 --- a/components/thin_webview/internal/compositor_view_impl.cc +++ b/components/thin_webview/internal/compositor_view_impl.cc
@@ -58,7 +58,9 @@ root_layer_->SetIsDrawable(true); absl::optional<SkColor> background_color = ui::JavaColorToOptionalSkColor(java_background_color); - root_layer_->SetBackgroundColor(background_color.value()); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + root_layer_->SetBackgroundColor( + SkColor4f::FromColor(background_color.value())); } CompositorViewImpl::~CompositorViewImpl() = default;
diff --git a/components/user_education/views/help_bubble_view.cc b/components/user_education/views/help_bubble_view.cc index bea56fab..f8b01175 100644 --- a/components/user_education/views/help_bubble_view.cc +++ b/components/user_education/views/help_bubble_view.cc
@@ -301,6 +301,8 @@ views::BubbleBorder::STANDARD_SHADOW), delegate_(delegate), force_anchor_rect_(anchor_rect) { + // The anchor for promo bubbles should not highlight. + set_highlight_button_when_shown(false); DCHECK(anchor_view) << "A bubble that closes on blur must be initially focused."; UseCompactMargins();
diff --git a/components/user_education/views/help_bubble_view.h b/components/user_education/views/help_bubble_view.h index 8199397..d1d1915 100644 --- a/components/user_education/views/help_bubble_view.h +++ b/components/user_education/views/help_bubble_view.h
@@ -63,9 +63,6 @@ // BubbleDialogDelegateView: bool OnMousePressed(const ui::MouseEvent& event) override; std::u16string GetAccessibleWindowTitle() const override; - void UpdateHighlightedButton(bool highlighted) override { - // Do nothing: the anchor for promo bubbles should not highlight. - } void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnThemeChanged() override; gfx::Size CalculatePreferredSize() const override;
diff --git a/components/viz/host/hit_test/hit_test_query.cc b/components/viz/host/hit_test/hit_test_query.cc index e703c39..e01a3e63 100644 --- a/components/viz/host/hit_test/hit_test_query.cc +++ b/components/viz/host/hit_test/hit_test_query.cc
@@ -9,7 +9,6 @@ #include <utility> #include "base/containers/stack.h" -#include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "components/viz/common/features.h" #include "components/viz/common/hit_test/hit_test_region_list.h" @@ -194,9 +193,6 @@ target->frame_sink_id = hit_test_data_[region_index].frame_sink_id; target->location_in_target = gfx::PointF(); target->flags = HitTestRegionFlags::kHitTestAsk; - RecordSlowPathHitTestReasons( - AsyncHitTestReasons::kPerspectiveTransform | - hit_test_data_[region_index].async_hit_test_reasons); return true; } @@ -243,8 +239,6 @@ target->frame_sink_id = hit_test_data_[region_index].frame_sink_id; target->location_in_target = location_in_target; target->flags = flags; - RecordSlowPathHitTestReasons( - hit_test_data_[region_index].async_hit_test_reasons); return true; } @@ -273,18 +267,14 @@ !(flags & HitTestRegionFlags::kHitTestIgnore)) { target->frame_sink_id = hit_test_data_[region_index].frame_sink_id; target->location_in_target = location_in_target; - uint32_t async_hit_test_reasons = - hit_test_data_[region_index].async_hit_test_reasons; uint32_t target_flags = flags; if (root_view_overlapped) { DCHECK_EQ(hit_test_data_[region_index].async_hit_test_reasons, AsyncHitTestReasons::kOverlappedRegion); target_flags &= ~HitTestRegionFlags::kHitTestAsk; - async_hit_test_reasons = AsyncHitTestReasons::kNotAsyncHitTest; } target->flags = target_flags; // We record fast path hit testing instances with reason kNotAsyncHitTest. - RecordSlowPathHitTestReasons(async_hit_test_reasons); return true; } return false; @@ -365,27 +355,6 @@ return false; } -void HitTestQuery::RecordSlowPathHitTestReasons(uint32_t reasons) const { - static const char* kAsyncHitTestReasonsHistogramName = - "Event.VizHitTest.AsyncHitTestReasons"; - if (reasons == AsyncHitTestReasons::kNotAsyncHitTest) { - UMA_HISTOGRAM_ENUMERATION( - kAsyncHitTestReasonsHistogramName, - AsyncHitTestReasons::kNotAsyncHitTest, - AsyncHitTestReasons::kAsyncHitTestReasonCount + 1); - return; - } - - for (uint32_t i = 0; i < AsyncHitTestReasons::kAsyncHitTestReasonCount; ++i) { - unsigned val = 1 << i; - if (reasons & val) { - UMA_HISTOGRAM_ENUMERATION( - kAsyncHitTestReasonsHistogramName, i + 1, - AsyncHitTestReasons::kAsyncHitTestReasonCount + 1); - } - } -} - std::string HitTestQuery::PrintHitTestData() const { std::ostringstream oss; base::stack<uint32_t> parents;
diff --git a/components/viz/host/hit_test/hit_test_query.h b/components/viz/host/hit_test/hit_test_query.h index c6c6f12..8451940 100644 --- a/components/viz/host/hit_test/hit_test_query.h +++ b/components/viz/host/hit_test/hit_test_query.h
@@ -5,6 +5,7 @@ #ifndef COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_QUERY_H_ #define COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_QUERY_H_ +#include <string> #include <vector> #include "base/callback.h" @@ -153,8 +154,6 @@ size_t region_index, gfx::Transform* transform) const; - void RecordSlowPathHitTestReasons(uint32_t) const; - std::vector<AggregatedHitTestRegion> hit_test_data_; };
diff --git a/content/browser/accessibility/browser_accessibility_android.cc b/content/browser/accessibility/browser_accessibility_android.cc index 5fa2ddb..29a058e7 100644 --- a/content/browser/accessibility/browser_accessibility_android.cc +++ b/content/browser/accessibility/browser_accessibility_android.cc
@@ -481,7 +481,7 @@ // On Android, contenteditable needs to be handled the same as any // other text field. role = ax::mojom::Role::kTextField; - } else if (IsAndroidTextView()) { + } else if (ui::IsAndroidTextViewCandidate(role) && HasOnlyTextChildren()) { // On Android, we want to report some extra nodes as TextViews. For example, // a <div> that only contains text, or a <p> that only contains text. role = ax::mojom::Role::kStaticText; @@ -490,10 +490,6 @@ return ui::AXRoleToAndroidClassName(role, PlatformGetParent() != nullptr); } -bool BrowserAccessibilityAndroid::IsAndroidTextView() const { - return ui::IsAndroidTextViewCandidate(GetRole()) && HasOnlyTextChildren(); -} - bool BrowserAccessibilityAndroid::IsChildOfLeaf() const { BrowserAccessibility* ancestor = InternalGetParent(); @@ -1928,6 +1924,19 @@ auto* manager = static_cast<BrowserAccessibilityManagerAndroid*>(this->manager()); manager->ClearNodeInfoCacheForGivenId(unique_id()); + + // For any nodes that are the children of a leaf, we also want to invalidate + // the cache for the ancestry chain up until the first non-leaf node. + if (IsChildOfLeaf()) { + BrowserAccessibilityAndroid* parent = + static_cast<BrowserAccessibilityAndroid*>(PlatformGetParent()); + + while (parent != nullptr && (parent->IsChildOfLeaf() || parent->IsLeaf())) { + manager->ClearNodeInfoCacheForGivenId(parent->unique_id()); + parent = static_cast<BrowserAccessibilityAndroid*>( + parent->PlatformGetParent()); + } + } } int BrowserAccessibilityAndroid::CountChildrenWithRole(
diff --git a/content/browser/accessibility/browser_accessibility_android.h b/content/browser/accessibility/browser_accessibility_android.h index 372fc00..3441934 100644 --- a/content/browser/accessibility/browser_accessibility_android.h +++ b/content/browser/accessibility/browser_accessibility_android.h
@@ -37,7 +37,6 @@ std::u16string GetLocalizedStringForImageAnnotationStatus( ax::mojom::ImageAnnotationStatus status) const override; - bool IsAndroidTextView() const; bool IsCheckable() const; bool IsChecked() const; bool IsClickable() const override;
diff --git a/content/browser/accessibility/browser_accessibility_manager_android.cc b/content/browser/accessibility/browser_accessibility_manager_android.cc index 357ee15..7db2cbd 100644 --- a/content/browser/accessibility/browser_accessibility_manager_android.cc +++ b/content/browser/accessibility/browser_accessibility_manager_android.cc
@@ -263,17 +263,6 @@ wcax->AnnounceLiveRegionText(text); break; } - case ui::AXEventGenerator::Event::NAME_CHANGED: { - // Clear node from cache whenever the name changes to ensure fresh data. - wcax->ClearNodeInfoCacheForGivenId(android_node->unique_id()); - - // If this is a simple text element, also send an event to the framework. - if (ui::IsText(android_node->GetRole()) || - android_node->IsAndroidTextView()) { - wcax->HandleTextContentChanged(android_node->unique_id()); - } - break; - } case ui::AXEventGenerator::Event::RANGE_VALUE_CHANGED: DCHECK(android_node->GetData().IsRangeValueSupported()); if (android_node->IsSlider()) @@ -347,6 +336,7 @@ case ui::AXEventGenerator::Event::MENU_ITEM_SELECTED: case ui::AXEventGenerator::Event::MULTILINE_STATE_CHANGED: case ui::AXEventGenerator::Event::MULTISELECTABLE_STATE_CHANGED: + case ui::AXEventGenerator::Event::NAME_CHANGED: case ui::AXEventGenerator::Event::OBJECT_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::OTHER_ATTRIBUTE_CHANGED: case ui::AXEventGenerator::Event::PARENT_CHANGED:
diff --git a/content/browser/accessibility/dump_accessibility_browsertest_base.cc b/content/browser/accessibility/dump_accessibility_browsertest_base.cc index 39e3808..289243b 100644 --- a/content/browser/accessibility/dump_accessibility_browsertest_base.cc +++ b/content/browser/accessibility/dump_accessibility_browsertest_base.cc
@@ -311,7 +311,7 @@ if (!expected_file.empty()) { expected_lines = test_helper_.LoadExpectationFile(expected_file); } -#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) +#if BUILDFLAG(IS_WIN) else { LOG(INFO) << "No expectation file present, ignoring test on this " "platform.";
diff --git a/content/browser/accessibility/hit_testing_browsertest.cc b/content/browser/accessibility/hit_testing_browsertest.cc index f83226f..f40ad0e1 100644 --- a/content/browser/accessibility/hit_testing_browsertest.cc +++ b/content/browser/accessibility/hit_testing_browsertest.cc
@@ -682,7 +682,7 @@ } } -#if defined(THREAD_SANITIZER) +#if defined(THREAD_SANITIZER) || BUILDFLAG(IS_LINUX) // TODO(https://crbug.com/1224978): Times out flakily on TSAN builds. #define MAYBE_HitTest_WithPinchZoom DISABLED_HitTest_WithPinchZoom #else
diff --git a/content/browser/accessibility/web_contents_accessibility_android.cc b/content/browser/accessibility/web_contents_accessibility_android.cc index 3cca1fc..23bc1fa 100644 --- a/content/browser/accessibility/web_contents_accessibility_android.cc +++ b/content/browser/accessibility/web_contents_accessibility_android.cc
@@ -445,16 +445,6 @@ env, obj, base::android::ConvertUTF16ToJavaString(env, text)); } -void WebContentsAccessibilityAndroid::HandleTextContentChanged( - int32_t unique_id) { - JNIEnv* env = AttachCurrentThread(); - ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); - if (obj.is_null()) - return; - Java_WebContentsAccessibilityImpl_handleTextContentChanged(env, obj, - unique_id); -} - void WebContentsAccessibilityAndroid::HandleTextSelectionChanged( int32_t unique_id) { JNIEnv* env = AttachCurrentThread();
diff --git a/content/browser/accessibility/web_contents_accessibility_android.h b/content/browser/accessibility/web_contents_accessibility_android.h index 47915ce8..905910cf 100644 --- a/content/browser/accessibility/web_contents_accessibility_android.h +++ b/content/browser/accessibility/web_contents_accessibility_android.h
@@ -385,7 +385,6 @@ void HandleScrolledToAnchor(int32_t unique_id); void HandleDialogModalOpened(int32_t unique_id); void AnnounceLiveRegionText(const std::u16string& text); - void HandleTextContentChanged(int32_t unique_id); void HandleTextSelectionChanged(int32_t unique_id); void HandleEditableTextChanged(int32_t unique_id); void HandleSliderChanged(int32_t unique_id);
diff --git a/content/browser/attribution_reporting/attribution_internals.mojom b/content/browser/attribution_reporting/attribution_internals.mojom index 0b8dd807..c24a99d 100644 --- a/content/browser/attribution_reporting/attribution_internals.mojom +++ b/content/browser/attribution_reporting/attribution_internals.mojom
@@ -156,6 +156,7 @@ kDeduplicated, kLowPriority, kNoised, + kNoMatchingConfigurations, // Aggregatable statuses: kNoHistograms,
diff --git a/content/browser/attribution_reporting/attribution_internals_handler_impl.cc b/content/browser/attribution_reporting/attribution_internals_handler_impl.cc index 56ff971b..9f8ec68 100644 --- a/content/browser/attribution_reporting/attribution_internals_handler_impl.cc +++ b/content/browser/attribution_reporting/attribution_internals_handler_impl.cc
@@ -375,6 +375,8 @@ return WebUITriggerStatus::kNoMatchingSourceFilterData; case EventLevelStatus::kProhibitedByBrowserPolicy: return WebUITriggerStatus::kProhibitedByBrowserPolicy; + case EventLevelStatus::kNoMatchingConfigurations: + return WebUITriggerStatus::kNoMatchingConfigurations; } }
diff --git a/content/browser/attribution_reporting/attribution_manager_impl.cc b/content/browser/attribution_reporting/attribution_manager_impl.cc index 8fc90b8..9b899ec 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl.cc +++ b/content/browser/attribution_reporting/attribution_manager_impl.cc
@@ -94,9 +94,9 @@ void RecordCreateReportStatus(CreateReportResult result) { static_assert( AttributionTrigger::EventLevelResult::kMaxValue == - AttributionTrigger::EventLevelResult::kProhibitedByBrowserPolicy, - "Bump version of Conversions.CreateReportStatus2 histogram."); - base::UmaHistogramEnumeration("Conversions.CreateReportStatus2", + AttributionTrigger::EventLevelResult::kNoMatchingConfigurations, + "Bump version of Conversions.CreateReportStatus3 histogram."); + base::UmaHistogramEnumeration("Conversions.CreateReportStatus3", result.event_level_status()); base::UmaHistogramEnumeration( "Conversions.AggregatableReport.CreateReportStatus2",
diff --git a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc index 4e7c819..9279610 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc +++ b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc
@@ -1047,7 +1047,7 @@ attribution_manager_->HandleTrigger(DefaultTrigger()); EXPECT_THAT(StoredReports(), IsEmpty()); histograms.ExpectUniqueSample( - "Conversions.CreateReportStatus2", + "Conversions.CreateReportStatus3", AttributionTrigger::EventLevelResult::kNoMatchingImpressions, 1); histograms.ExpectUniqueSample( "Conversions.AggregatableReport.CreateReportStatus2",
diff --git a/content/browser/attribution_reporting/attribution_storage_sql.cc b/content/browser/attribution_reporting/attribution_storage_sql.cc index 6f6cf6c..a89f81f3 100644 --- a/content/browser/attribution_reporting/attribution_storage_sql.cc +++ b/content/browser/attribution_reporting/attribution_storage_sql.cc
@@ -1009,9 +1009,6 @@ const AttributionSourceType source_type = common_info.source_type(); - uint64_t trigger_data = 0; - int64_t priority = 0; - auto event_trigger = base::ranges::find_if( trigger.event_triggers(), [&](const AttributionTrigger::EventTriggerData& event_trigger) { @@ -1020,16 +1017,11 @@ event_trigger.not_filters); }); - // If there's a match, use its data. Otherwise use default values instead of - // returning an error so that a report is still sent. - // TODO(apaseltiner): Consider recording a metric for no match. - if (event_trigger != trigger.event_triggers().end()) { - trigger_data = event_trigger->data; - priority = event_trigger->priority; - dedup_key = event_trigger->dedup_key; - } + if (event_trigger == trigger.event_triggers().end()) + return EventLevelResult::kNoMatchingConfigurations; - switch (ReportAlreadyStored(attribution_info.source.source_id(), dedup_key)) { + switch (ReportAlreadyStored(attribution_info.source.source_id(), + event_trigger->dedup_key)) { case ReportAlreadyStoredStatus::kNotStored: break; case ReportAlreadyStoredStatus::kStored: @@ -1069,10 +1061,12 @@ report = AttributionReport( attribution_info, report_time, delegate_->NewReportID(), AttributionReport::EventLevelData( - delegate_->SanitizeTriggerData(trigger_data, source_type), priority, - randomized_response_rate, + delegate_->SanitizeTriggerData(event_trigger->data, source_type), + event_trigger->priority, randomized_response_rate, AttributionReport::EventLevelData::Id(kUnsetReportId))); + dedup_key = event_trigger->dedup_key; + return EventLevelResult::kSuccess; }
diff --git a/content/browser/attribution_reporting/attribution_storage_unittest.cc b/content/browser/attribution_reporting/attribution_storage_unittest.cc index 105c373..6e097adb 100644 --- a/content/browser/attribution_reporting/attribution_storage_unittest.cc +++ b/content/browser/attribution_reporting/attribution_storage_unittest.cc
@@ -2242,7 +2242,7 @@ })))); } -TEST_F(AttributionStorageTest, NoMatchingTriggerData_UsesDefaultData) { +TEST_F(AttributionStorageTest, NoMatchingTriggerData_ReturnsError) { const auto origin = url::Origin::Create(GURL("https://r.test")); storage()->StoreSource(SourceBuilder() @@ -2251,7 +2251,7 @@ .SetReportingOrigin(origin) .Build()); - EXPECT_EQ(AttributionTrigger::EventLevelResult::kSuccess, + EXPECT_EQ(AttributionTrigger::EventLevelResult::kNoMatchingConfigurations, MaybeCreateAndStoreEventLevelReport(AttributionTrigger( origin, origin, /*filters=*/AttributionFilterData(), @@ -2266,9 +2266,7 @@ /*not_filters=*/AttributionFilterData())}, AttributionAggregatableTrigger()))); - EXPECT_THAT(storage()->GetAttributionReports(base::Time::Max()), - ElementsAre(EventLevelDataIs( - AllOf(TriggerDataIs(0), TriggerPriorityIs(0))))); + EXPECT_THAT(storage()->GetAttributionReports(base::Time::Max()), IsEmpty()); EXPECT_THAT(storage()->GetActiveSources(), ElementsAre(DedupKeysAre(IsEmpty()))); @@ -2407,11 +2405,13 @@ CreateReportAggregatableStatusIs( AttributionTrigger::AggregatableResult:: kNoMatchingSourceFilterData))); - EXPECT_THAT(storage()->MaybeCreateAndStoreReport(trigger2), - AllOf(CreateReportEventLevelStatusIs( - AttributionTrigger::EventLevelResult::kSuccess), - CreateReportAggregatableStatusIs( - AttributionTrigger::AggregatableResult::kSuccess))); + EXPECT_THAT( + storage()->MaybeCreateAndStoreReport(trigger2), + AllOf( + CreateReportEventLevelStatusIs( + AttributionTrigger::EventLevelResult::kNoMatchingConfigurations), + CreateReportAggregatableStatusIs( + AttributionTrigger::AggregatableResult::kSuccess))); } TEST_F(AttributionStorageTest,
diff --git a/content/browser/attribution_reporting/attribution_test_utils.cc b/content/browser/attribution_reporting/attribution_test_utils.cc index 8aa1f41..65744e6 100644 --- a/content/browser/attribution_reporting/attribution_test_utils.cc +++ b/content/browser/attribution_reporting/attribution_test_utils.cc
@@ -919,6 +919,9 @@ case AttributionTrigger::EventLevelResult::kProhibitedByBrowserPolicy: out << "prohibitedByBrowserPolicy"; break; + case AttributionTrigger::EventLevelResult::kNoMatchingConfigurations: + out << "noMatchingConfigurations"; + break; } return out; }
diff --git a/content/browser/attribution_reporting/attribution_trigger.h b/content/browser/attribution_reporting/attribution_trigger.h index 697fe0b..d2b8851 100644 --- a/content/browser/attribution_reporting/attribution_trigger.h +++ b/content/browser/attribution_reporting/attribution_trigger.h
@@ -41,7 +41,8 @@ kExcessiveReportingOrigins = 9, kNoMatchingSourceFilterData = 10, kProhibitedByBrowserPolicy = 11, - kMaxValue = kProhibitedByBrowserPolicy, + kNoMatchingConfigurations = 12, + kMaxValue = kNoMatchingConfigurations, }; // Represents the potential aggregatable outcomes from attempting to register
diff --git a/content/browser/buckets/bucket_manager.cc b/content/browser/buckets/bucket_manager.cc index 347dd31323..85ffc34 100644 --- a/content/browser/buckets/bucket_manager.cc +++ b/content/browser/buckets/bucket_manager.cc
@@ -25,9 +25,8 @@ auto permission_decision = base::BindRepeating( [](GlobalRenderFrameHostId id, blink::PermissionType permission_type) { auto* rfh = RenderFrameHost::FromID(id); - // The callback will be invoked in the handler for a mojo message from - // the renderer so the rfh should still exist. - DCHECK(rfh); + if (!rfh) + return blink::mojom::PermissionStatus::DENIED; return rfh->GetBrowserContext() ->GetPermissionController() ->GetPermissionStatusForCurrentDocument(permission_type, rfh); @@ -49,9 +48,8 @@ [](int render_process_id, const url::Origin& origin, blink::PermissionType permission_type) { RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id); - // The callback will be invoked in the handler for a mojo message from - // the renderer so the rph should still exist. - DCHECK(rph); + if (!rph) + return blink::mojom::PermissionStatus::DENIED; return rph->GetBrowserContext() ->GetPermissionController() ->GetPermissionStatusForWorker(permission_type, rph, origin);
diff --git a/content/browser/devtools/browser_devtools_agent_host.cc b/content/browser/devtools/browser_devtools_agent_host.cc index 80177d9..614098a 100644 --- a/content/browser/devtools/browser_devtools_agent_host.cc +++ b/content/browser/devtools/browser_devtools_agent_host.cc
@@ -177,34 +177,33 @@ return false; session->SetBrowserOnly(true); - session->AddHandler(std::make_unique<protocol::TargetHandler>( + session->CreateAndAddHandler<protocol::TargetHandler>( protocol::TargetHandler::AccessMode::kBrowser, GetId(), - auto_attacher_.get(), session->GetRootSession())); + auto_attacher_.get(), session->GetRootSession()); if (only_discovery_) return true; - session->AddHandler(std::make_unique<protocol::BrowserHandler>( - session->GetClient()->MayWriteLocalFiles())); + session->CreateAndAddHandler<protocol::BrowserHandler>( + session->GetClient()->MayWriteLocalFiles()); #if BUILDFLAG(USE_VIZ_DEBUGGER) - session->AddHandler(std::make_unique<protocol::VisualDebuggerHandler>()); + session->CreateAndAddHandler<protocol::VisualDebuggerHandler>(); #endif - session->AddHandler(std::make_unique<protocol::IOHandler>(GetIOContext())); - session->AddHandler(std::make_unique<protocol::FetchHandler>( + session->CreateAndAddHandler<protocol::IOHandler>(GetIOContext()); + session->CreateAndAddHandler<protocol::FetchHandler>( GetIOContext(), - base::BindRepeating([](base::OnceClosure cb) { std::move(cb).Run(); }))); - session->AddHandler(std::make_unique<protocol::MemoryHandler>()); - session->AddHandler(std::make_unique<protocol::SecurityHandler>()); - session->AddHandler(std::make_unique<protocol::StorageHandler>()); - session->AddHandler(std::make_unique<protocol::SystemInfoHandler>()); + base::BindRepeating([](base::OnceClosure cb) { std::move(cb).Run(); })); + session->CreateAndAddHandler<protocol::MemoryHandler>(); + session->CreateAndAddHandler<protocol::SecurityHandler>(); + session->CreateAndAddHandler<protocol::StorageHandler>(); + session->CreateAndAddHandler<protocol::SystemInfoHandler>(); if (tethering_task_runner_) { - session->AddHandler(std::make_unique<protocol::TetheringHandler>( - socket_callback_, tethering_task_runner_)); + session->CreateAndAddHandler<protocol::TetheringHandler>( + socket_callback_, tethering_task_runner_); } - session->AddHandler( - std::make_unique<protocol::TracingHandler>(GetIOContext())); + session->CreateAndAddHandler<protocol::TracingHandler>(GetIOContext()); #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX) && BUILDFLAG(CLANG_PGO) - session->AddHandler(std::make_unique<protocol::NativeProfilingHandler>()); + session->CreateAndAddHandler<protocol::NativeProfilingHandler>(); #endif return true;
diff --git a/content/browser/devtools/devtools_session.h b/content/browser/devtools/devtools_session.h index ff3b03d..accad006 100644 --- a/content/browser/devtools/devtools_session.h +++ b/content/browser/devtools/devtools_session.h
@@ -9,6 +9,7 @@ #include <map> #include <memory> #include <string> +#include <type_traits> #include "base/containers/flat_map.h" #include "base/containers/span.h" @@ -29,6 +30,21 @@ namespace protocol { class DevToolsDomainHandler; +class AuditsHandler; +class DOMHandler; +class EmulationHandler; +class InputHandler; +class InspectorHandler; +class IOHandler; +class OverlayHandler; +class NetworkHandler; +class FetchHandler; +class StorageHandler; +class TargetHandler; +class PageHandler; +class TracingHandler; +class LogHandler; +class WebAuthnHandler; } class DevToolsSession : public protocol::FrontendChannel, @@ -54,7 +70,18 @@ // Browser-only sessions do not talk to mojom::DevToolsAgent, but instead // handle all protocol messages locally in the browser process. void SetBrowserOnly(bool browser_only); - void AddHandler(std::unique_ptr<protocol::DevToolsDomainHandler> handler); + template <typename Handler, typename... Args> + Handler* CreateAndAddHandler(Args&&... args) { + if (!IsDomainAvailableToUntrustedClient<Handler>() && + !client_->IsTrusted()) { + return nullptr; + } + auto handler = std::make_unique<Handler>(std::forward<Args>(args)...); + Handler* handler_ptr = handler.get(); + AddHandler(std::move(handler)); + return handler_ptr; + } + void TurnIntoExternalProxy(DevToolsExternalAgentProxyDelegate* delegate); void AttachToAgent(blink::mojom::DevToolsAgent* agent, @@ -130,6 +157,26 @@ // Merges the |updates| received from the renderer into session_state_cookie_. void ApplySessionStateUpdates(blink::mojom::DevToolsSessionStatePtr updates); + template <typename T> + bool IsDomainAvailableToUntrustedClient() { + return std::disjunction_v<std::is_same<T, protocol::AuditsHandler>, + std::is_same<T, protocol::DOMHandler>, + std::is_same<T, protocol::EmulationHandler>, + std::is_same<T, protocol::InputHandler>, + std::is_same<T, protocol::InspectorHandler>, + std::is_same<T, protocol::IOHandler>, + std::is_same<T, protocol::OverlayHandler>, + std::is_same<T, protocol::NetworkHandler>, + std::is_same<T, protocol::FetchHandler>, + std::is_same<T, protocol::StorageHandler>, + std::is_same<T, protocol::TargetHandler>, + std::is_same<T, protocol::PageHandler>, + std::is_same<T, protocol::TracingHandler>, + std::is_same<T, protocol::LogHandler>, + std::is_same<T, protocol::WebAuthnHandler>>; + } + void AddHandler(std::unique_ptr<protocol::DevToolsDomainHandler> handler); + mojo::AssociatedReceiver<blink::mojom::DevToolsSessionHost> receiver_{this}; mojo::AssociatedRemote<blink::mojom::DevToolsSession> session_; mojo::Remote<blink::mojom::DevToolsSession> io_session_;
diff --git a/content/browser/devtools/protocol/page_handler.cc b/content/browser/devtools/protocol/page_handler.cc index 0e30606..aa7b51d 100644 --- a/content/browser/devtools/protocol/page_handler.cc +++ b/content/browser/devtools/protocol/page_handler.cc
@@ -1050,6 +1050,8 @@ Response response = AssureTopLevelActiveFrame(host_); if (response.IsError()) return response; + if (!browser_handler_) + return Response::ServerError("Cannot not access browser-level commands"); return browser_handler_->DoSetDownloadBehavior(behavior, browser_context, std::move(download_path)); }
diff --git a/content/browser/devtools/render_frame_devtools_agent_host.cc b/content/browser/devtools/render_frame_devtools_agent_host.cc index 9e565ba..9d6491d 100644 --- a/content/browser/devtools/render_frame_devtools_agent_host.cc +++ b/content/browser/devtools/render_frame_devtools_agent_host.cc
@@ -300,31 +300,27 @@ frame_host_->DidAccessInitialMainDocument(); } - auto emulation_handler = std::make_unique<protocol::EmulationHandler>(); - protocol::EmulationHandler* emulation_handler_ptr = emulation_handler.get(); - - session->AddHandler(std::make_unique<protocol::AuditsHandler>()); - session->AddHandler(std::make_unique<protocol::BackgroundServiceHandler>()); - auto browser_handler = std::make_unique<protocol::BrowserHandler>( - session->GetClient()->MayWriteLocalFiles()); - auto* browser_handler_ptr = browser_handler.get(); - session->AddHandler(std::move(browser_handler)); - session->AddHandler(std::make_unique<protocol::DOMHandler>( - session->GetClient()->MayReadLocalFiles())); - session->AddHandler(std::move(emulation_handler)); - auto input_handler = std::make_unique<protocol::InputHandler>( + session->CreateAndAddHandler<protocol::AuditsHandler>(); + session->CreateAndAddHandler<protocol::BackgroundServiceHandler>(); + auto* browser_handler = + session->CreateAndAddHandler<protocol::BrowserHandler>( + session->GetClient()->MayWriteLocalFiles()); + session->CreateAndAddHandler<protocol::DOMHandler>( + session->GetClient()->MayReadLocalFiles()); + auto* emulation_handler = + session->CreateAndAddHandler<protocol::EmulationHandler>(); + session->CreateAndAddHandler<protocol::InputHandler>( session->GetClient()->MayReadLocalFiles(), session->GetClient()->IsTrusted()); - session->AddHandler(std::move(input_handler)); - session->AddHandler(std::make_unique<protocol::InspectorHandler>()); - session->AddHandler(std::make_unique<protocol::IOHandler>(GetIOContext())); - session->AddHandler(std::make_unique<protocol::MemoryHandler>()); + session->CreateAndAddHandler<protocol::InspectorHandler>(); + session->CreateAndAddHandler<protocol::IOHandler>(GetIOContext()); + session->CreateAndAddHandler<protocol::MemoryHandler>(); #if BUILDFLAG(USE_VIZ_DEBUGGER) - session->AddHandler(std::make_unique<protocol::VisualDebuggerHandler>()); + session->CreateAndAddHandler<protocol::VisualDebuggerHandler>(); #endif if (!frame_tree_node_ || !frame_tree_node_->parent()) - session->AddHandler(std::make_unique<protocol::OverlayHandler>()); - session->AddHandler(std::make_unique<protocol::NetworkHandler>( + session->CreateAndAddHandler<protocol::OverlayHandler>(); + session->CreateAndAddHandler<protocol::NetworkHandler>( GetId(), frame_tree_node_ ? frame_tree_node_->devtools_frame_token() : base::UnguessableToken(), @@ -332,38 +328,37 @@ base::BindRepeating( &RenderFrameDevToolsAgentHost::UpdateResourceLoaderFactories, base::Unretained(this)), - session->GetClient()->MayReadLocalFiles())); - session->AddHandler(std::make_unique<protocol::FetchHandler>( + session->GetClient()->MayReadLocalFiles()); + session->CreateAndAddHandler<protocol::FetchHandler>( GetIOContext(), base::BindRepeating( [](RenderFrameDevToolsAgentHost* self, base::OnceClosure done_callback) { self->UpdateResourceLoaderFactories(); std::move(done_callback).Run(); }, - base::Unretained(this)))); - session->AddHandler(std::make_unique<protocol::SchemaHandler>()); + base::Unretained(this))); + session->CreateAndAddHandler<protocol::SchemaHandler>(); const bool may_attach_to_brower = session->GetClient()->IsTrusted(); - session->AddHandler(std::make_unique<protocol::ServiceWorkerHandler>( - /* allow_inspect_worker= */ may_attach_to_brower)); - session->AddHandler(std::make_unique<protocol::StorageHandler>()); - session->AddHandler(std::make_unique<protocol::TargetHandler>( + session->CreateAndAddHandler<protocol::ServiceWorkerHandler>( + /* allow_inspect_worker= */ may_attach_to_brower); + session->CreateAndAddHandler<protocol::StorageHandler>(); + session->CreateAndAddHandler<protocol::TargetHandler>( may_attach_to_brower ? protocol::TargetHandler::AccessMode::kRegular : protocol::TargetHandler::AccessMode::kAutoAttachOnly, - GetId(), auto_attacher_.get(), session->GetRootSession())); - session->AddHandler(std::make_unique<protocol::PageHandler>( - emulation_handler_ptr, browser_handler_ptr, + GetId(), auto_attacher_.get(), session->GetRootSession()); + session->CreateAndAddHandler<protocol::PageHandler>( + emulation_handler, browser_handler, session->GetClient()->AllowUnsafeOperations(), session->GetClient()->IsTrusted(), - session->GetClient()->GetNavigationInitiatorOrigin())); - session->AddHandler(std::make_unique<protocol::SecurityHandler>()); + session->GetClient()->GetNavigationInitiatorOrigin()); + session->CreateAndAddHandler<protocol::SecurityHandler>(); if (!frame_tree_node_ || !frame_tree_node_->parent()) { - session->AddHandler( - std::make_unique<protocol::TracingHandler>(GetIOContext())); + session->CreateAndAddHandler<protocol::TracingHandler>(GetIOContext()); } - session->AddHandler(std::make_unique<protocol::LogHandler>()); + session->CreateAndAddHandler<protocol::LogHandler>(); #if !BUILDFLAG(IS_ANDROID) - session->AddHandler(std::make_unique<protocol::WebAuthnHandler>()); + session->CreateAndAddHandler<protocol::WebAuthnHandler>(); #endif // !BUILDFLAG(IS_ANDROID) if (sessions().empty()) {
diff --git a/content/browser/devtools/service_worker_devtools_agent_host.cc b/content/browser/devtools/service_worker_devtools_agent_host.cc index c1895858..74f6f55 100644 --- a/content/browser/devtools/service_worker_devtools_agent_host.cc +++ b/content/browser/devtools/service_worker_devtools_agent_host.cc
@@ -226,24 +226,24 @@ bool ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session, bool acquire_wake_lock) { - session->AddHandler(std::make_unique<protocol::IOHandler>(GetIOContext())); - session->AddHandler(std::make_unique<protocol::InspectorHandler>()); - session->AddHandler(std::make_unique<protocol::NetworkHandler>( + session->CreateAndAddHandler<protocol::IOHandler>(GetIOContext()); + session->CreateAndAddHandler<protocol::InspectorHandler>(); + session->CreateAndAddHandler<protocol::NetworkHandler>( GetId(), devtools_worker_token_, GetIOContext(), base::DoNothing(), - session->GetClient()->MayReadLocalFiles())); + session->GetClient()->MayReadLocalFiles()); - session->AddHandler(std::make_unique<protocol::FetchHandler>( + session->CreateAndAddHandler<protocol::FetchHandler>( GetIOContext(), base::BindRepeating( &ServiceWorkerDevToolsAgentHost::UpdateLoaderFactories, - base::Unretained(this)))); - session->AddHandler(std::make_unique<protocol::SchemaHandler>()); + base::Unretained(this))); + session->CreateAndAddHandler<protocol::SchemaHandler>(); - auto target_handler = std::make_unique<protocol::TargetHandler>( + auto* target_handler = session->CreateAndAddHandler<protocol::TargetHandler>( protocol::TargetHandler::AccessMode::kAutoAttachOnly, GetId(), auto_attacher_.get(), session->GetRootSession()); + DCHECK(target_handler); target_handler->DisableAutoAttachOfServiceWorkers(); - session->AddHandler(std::move(target_handler)); if (state_ == WORKER_READY && sessions().empty()) UpdateIsAttached(true);
diff --git a/content/browser/devtools/shared_worker_devtools_agent_host.cc b/content/browser/devtools/shared_worker_devtools_agent_host.cc index 539d032..6749790 100644 --- a/content/browser/devtools/shared_worker_devtools_agent_host.cc +++ b/content/browser/devtools/shared_worker_devtools_agent_host.cc
@@ -87,20 +87,20 @@ bool SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session, bool acquire_wake_lock) { - session->AddHandler(std::make_unique<protocol::IOHandler>(GetIOContext())); - session->AddHandler(std::make_unique<protocol::InspectorHandler>()); - session->AddHandler(std::make_unique<protocol::NetworkHandler>( + session->CreateAndAddHandler<protocol::IOHandler>(GetIOContext()); + session->CreateAndAddHandler<protocol::InspectorHandler>(); + session->CreateAndAddHandler<protocol::NetworkHandler>( GetId(), devtools_worker_token_, GetIOContext(), - base::BindRepeating([] {}), session->GetClient()->MayReadLocalFiles())); + base::BindRepeating([] {}), session->GetClient()->MayReadLocalFiles()); // TODO(crbug.com/1143100): support pushing updated loader factories down to // renderer. - session->AddHandler(std::make_unique<protocol::FetchHandler>( + session->CreateAndAddHandler<protocol::FetchHandler>( GetIOContext(), - base::BindRepeating([](base::OnceClosure cb) { std::move(cb).Run(); }))); - session->AddHandler(std::make_unique<protocol::SchemaHandler>()); - session->AddHandler(std::make_unique<protocol::TargetHandler>( + base::BindRepeating([](base::OnceClosure cb) { std::move(cb).Run(); })); + session->CreateAndAddHandler<protocol::SchemaHandler>(); + session->CreateAndAddHandler<protocol::TargetHandler>( protocol::TargetHandler::AccessMode::kAutoAttachOnly, GetId(), - auto_attacher_.get(), session->GetRootSession())); + auto_attacher_.get(), session->GetRootSession()); return true; }
diff --git a/content/browser/devtools/worker_devtools_agent_host.cc b/content/browser/devtools/worker_devtools_agent_host.cc index dec63fe8..ed17e0f 100644 --- a/content/browser/devtools/worker_devtools_agent_host.cc +++ b/content/browser/devtools/worker_devtools_agent_host.cc
@@ -131,13 +131,13 @@ bool WorkerDevToolsAgentHost::AttachSession(DevToolsSession* session, bool acquire_wake_lock) { - session->AddHandler(std::make_unique<protocol::IOHandler>(GetIOContext())); - session->AddHandler(std::make_unique<protocol::TargetHandler>( + session->CreateAndAddHandler<protocol::IOHandler>(GetIOContext()); + session->CreateAndAddHandler<protocol::TargetHandler>( protocol::TargetHandler::AccessMode::kAutoAttachOnly, GetId(), - auto_attacher_.get(), session->GetRootSession())); - session->AddHandler(std::make_unique<protocol::NetworkHandler>( + auto_attacher_.get(), session->GetRootSession()); + session->CreateAndAddHandler<protocol::NetworkHandler>( GetId(), devtools_worker_token_, GetIOContext(), base::DoNothing(), - session->GetClient()->MayReadLocalFiles())); + session->GetClient()->MayReadLocalFiles()); return true; }
diff --git a/content/browser/net/reporting_service_proxy.cc b/content/browser/net/reporting_service_proxy.cc index 5868b2d..08c579fc 100644 --- a/content/browser/net/reporting_service_proxy.cc +++ b/content/browser/net/reporting_service_proxy.cc
@@ -52,16 +52,17 @@ const absl::optional<std::string>& source_file, int line_number, int column_number) override { - auto body = std::make_unique<base::DictionaryValue>(); - body->SetString("id", id); - body->SetString("message", message); + base::Value::Dict body; + body.Set("id", id); + body.Set("message", message); if (source_file) - body->SetString("sourceFile", *source_file); + body.Set("sourceFile", *source_file); if (line_number) - body->SetInteger("lineNumber", line_number); + body.Set("lineNumber", line_number); if (column_number) - body->SetInteger("columnNumber", column_number); - QueueReport(url, "default", "intervention", std::move(body)); + body.Set("columnNumber", column_number); + QueueReport(url, "default", "intervention", + std::make_unique<base::Value>(std::move(body))); } void QueueDeprecationReport(const GURL& url, @@ -71,19 +72,21 @@ const absl::optional<std::string>& source_file, int line_number, int column_number) override { - auto body = std::make_unique<base::DictionaryValue>(); - body->SetString("id", id); - if (anticipated_removal) - body->SetDouble("anticipatedRemoval", - anticipated_removal->ToJsTimeIgnoringNull()); - body->SetString("message", message); + base::Value::Dict body; + body.Set("id", id); + if (anticipated_removal) { + body.Set("anticipatedRemoval", + anticipated_removal->ToJsTimeIgnoringNull()); + } + body.Set("message", message); if (source_file) - body->SetString("sourceFile", *source_file); + body.Set("sourceFile", *source_file); if (line_number) - body->SetInteger("lineNumber", line_number); + body.Set("lineNumber", line_number); if (column_number) - body->SetInteger("columnNumber", column_number); - QueueReport(url, "default", "deprecation", std::move(body)); + body.Set("columnNumber", column_number); + QueueReport(url, "default", "deprecation", + std::make_unique<base::Value>(std::move(body))); } void QueueCspViolationReport(const GURL& url, @@ -99,25 +102,26 @@ uint16_t status_code, int line_number, int column_number) override { - auto body = std::make_unique<base::DictionaryValue>(); - body->SetString("documentURL", document_url); + base::Value::Dict body; + body.Set("documentURL", document_url); if (referrer) - body->SetString("referrer", *referrer); + body.Set("referrer", *referrer); if (blocked_url) - body->SetString("blockedURL", *blocked_url); - body->SetString("effectiveDirective", effective_directive); - body->SetString("originalPolicy", original_policy); + body.Set("blockedURL", *blocked_url); + body.Set("effectiveDirective", effective_directive); + body.Set("originalPolicy", original_policy); if (source_file) - body->SetString("sourceFile", *source_file); + body.Set("sourceFile", *source_file); if (script_sample) - body->SetString("sample", *script_sample); - body->SetString("disposition", disposition); - body->SetInteger("statusCode", status_code); + body.Set("sample", *script_sample); + body.Set("disposition", disposition); + body.Set("statusCode", status_code); if (line_number) - body->SetInteger("lineNumber", line_number); + body.Set("lineNumber", line_number); if (column_number) - body->SetInteger("columnNumber", column_number); - QueueReport(url, group, "csp-violation", std::move(body)); + body.Set("columnNumber", column_number); + QueueReport(url, group, "csp-violation", + std::make_unique<base::Value>(std::move(body))); } void QueuePermissionsPolicyViolationReport( @@ -128,19 +132,19 @@ const absl::optional<std::string>& source_file, int line_number, int column_number) override { - auto body = std::make_unique<base::DictionaryValue>(); - body->SetString("policyId", policy_id); - body->SetString("disposition", disposition); + base::Value::Dict body; + body.Set("policyId", policy_id); + body.Set("disposition", disposition); if (message) - body->SetString("message", *message); + body.Set("message", *message); if (source_file) - body->SetString("sourceFile", *source_file); + body.Set("sourceFile", *source_file); if (line_number) - body->SetInteger("lineNumber", line_number); + body.Set("lineNumber", line_number); if (column_number) - body->SetInteger("columnNumber", column_number); + body.Set("columnNumber", column_number); QueueReport(url, "default", "permissions-policy-violation", - std::move(body)); + std::make_unique<base::Value>(std::move(body))); } void QueueDocumentPolicyViolationReport( @@ -152,18 +156,19 @@ const absl::optional<std::string>& source_file, int line_number, int column_number) override { - auto body = std::make_unique<base::DictionaryValue>(); - body->SetString("policyId", policy_id); - body->SetString("disposition", disposition); + base::Value::Dict body; + body.Set("policyId", policy_id); + body.Set("disposition", disposition); if (message) - body->SetString("message", *message); + body.Set("message", *message); if (source_file) - body->SetString("sourceFile", *source_file); + body.Set("sourceFile", *source_file); if (line_number) - body->SetInteger("lineNumber", line_number); + body.Set("lineNumber", line_number); if (column_number) - body->SetInteger("columnNumber", column_number); - QueueReport(url, group, "document-policy-violation", std::move(body)); + body.Set("columnNumber", column_number); + QueueReport(url, group, "document-policy-violation", + std::make_unique<base::Value>(std::move(body))); } int render_process_id() const { return render_process_id_; }
diff --git a/content/browser/network_service_instance_impl.cc b/content/browser/network_service_instance_impl.cc index 3ce5bf5c..e030850 100644 --- a/content/browser/network_service_instance_impl.cc +++ b/content/browser/network_service_instance_impl.cc
@@ -826,10 +826,37 @@ } #if BUILDFLAG(IS_ANDROID) + // On Android, if a cookie_manager pending receiver was passed then migration + // should not be attempted as the cookie file is already being accessed by the + // browser instance. + if (params->cookie_manager) { + if (params->file_paths) { + // No migration should ever be attempted under this configuration. + DCHECK(!params->file_paths->unsandboxed_data_path); + } + CreateNetworkContextInternal( + std::move(context), std::move(params), + SandboxGrantResult::kDidNotAttemptToGrantSandboxAccess); + return; + } + + // Note: This logic is duplicated from MaybeGrantAccessToDataPath to this fast + // path. This should be kept in sync if there are any changes to the logic. + SandboxGrantResult grant_result = SandboxGrantResult::kNoMigrationRequested; + if (!params->file_paths) { + // No file paths (e.g. in-memory context) so nothing to do. + grant_result = SandboxGrantResult::kDidNotAttemptToGrantSandboxAccess; + } else { + // If no `unsandboxed_data_path` is supplied, it means this is network + // context has been created by Android Webview, which does not understand + // the concept of `unsandboxed_data_path`. In this case, `data_directory` + // should always be used, if present. + if (!params->file_paths->unsandboxed_data_path) + grant_result = SandboxGrantResult::kDidNotAttemptToGrantSandboxAccess; + } // Create network context immediately without thread hops. - CreateNetworkContextInternal( - std::move(context), std::move(params), - SandboxGrantResult::kDidNotAttemptToGrantSandboxAccess); + CreateNetworkContextInternal(std::move(context), std::move(params), + grant_result); #else // Restrict disk access to a certain path (on another thread) and continue // with network context creation.
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index f4fc156..6f7e468 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -1751,9 +1751,6 @@ void RenderWidgetHostViewAuraTest::RunTimerBasedWheelEventPhaseInfoTest( bool percent_based_scrolling_enabled) { - // TODO(clchambers): consolidate into one header along with other declarations - // of this constant - const float kScrollPercentPerLineOrChar = 0.05f; InitViewForFrame(nullptr); view_->Show(); sink_->ClearMessages(); @@ -1786,11 +1783,11 @@ EXPECT_EQ(WebInputEvent::Type::kGestureScrollUpdate, gesture_event->GetType()); EXPECT_EQ(0U, gesture_event->data.scroll_update.delta_x); - EXPECT_EQ( - percent_based_scrolling_enabled - ? 5 * kScrollPercentPerLineOrChar / ui::MouseWheelEvent::kWheelDelta - : 5U, - gesture_event->data.scroll_update.delta_y); + EXPECT_EQ(percent_based_scrolling_enabled + ? 5 * ui::kScrollPercentPerLineOrChar / + ui::MouseWheelEvent::kWheelDelta + : 5U, + gesture_event->data.scroll_update.delta_y); events[1]->ToEvent()->CallCallback( blink::mojom::InputEventResultState::kConsumed);
diff --git a/content/browser/renderer_host/render_widget_targeter.cc b/content/browser/renderer_host/render_widget_targeter.cc index 0fdf7c4..efaea402 100644 --- a/content/browser/renderer_host/render_widget_targeter.cc +++ b/content/browser/renderer_host/render_widget_targeter.cc
@@ -13,7 +13,6 @@ #include "base/rand_util.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" -#include "content/public/browser/site_isolation_policy.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "ui/events/blink/blink_event_util.h" @@ -245,7 +244,6 @@ request_target_location); } RenderWidgetHostViewBase* target = result.view; - async_depth_ = 0; if (!is_autoscroll_in_progress_ && result.should_query_view) { TRACE_EVENT_WITH_FLOW2( "viz,benchmark", "Event.Pipeline", TRACE_ID_GLOBAL(trace_id_), @@ -263,8 +261,7 @@ QueryClient(request_target, request_target_location, nullptr, gfx::PointF(), std::move(request)); } else { - FoundTarget(target, result.target_location, result.latched_target, - &request); + FoundTarget(target, result.target_location, &request); } } @@ -300,14 +297,13 @@ // understand why this happens. https://crbug.com/859492. // We do not verify hit testing result under this circumstance. if (!target_client.is_bound() || !target_client.is_connected()) { - FoundTarget(target, target_location, false, &request); + FoundTarget(target, target_location, &request); return; } const gfx::PointF location = request.GetLocation(); request_in_flight_ = std::move(request); - async_depth_++; TracingUmaTracker tracker("Event.AsyncTargeting.ResponseTime"); async_hit_test_timeout_.Start( @@ -406,7 +402,7 @@ middle_click_result_ = {view, false, transformed_location, false}; } - FoundTarget(view, transformed_location, false, &request); + FoundTarget(view, transformed_location, &request); } else { QueryClient(view, transformed_location, target.get(), target_location, std::move(request)); @@ -416,16 +412,8 @@ void RenderWidgetTargeter::FoundTarget( RenderWidgetHostViewBase* target, const absl::optional<gfx::PointF>& target_location, - bool latched_target, TargetingRequest* request) { DCHECK(request); - - if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites() && - !latched_target) { - UMA_HISTOGRAM_COUNTS_100("Event.AsyncTargeting.AsyncClientDepth", - async_depth_); - } - // RenderWidgetHostViewMac can be deleted asynchronously, in which case the // View will be valid but there will no longer be a RenderWidgetHostImpl. if (!request->GetRootView() || !request->GetRootView()->GetRenderWidgetHost()) @@ -469,11 +457,10 @@ // When a request to the top-level frame times out then the event gets // sent there anyway. It will trigger the hung renderer dialog if the // renderer fails to process it. - FoundTarget(current_request_target.get(), current_target_location, false, + FoundTarget(current_request_target.get(), current_target_location, &request); } else { - FoundTarget(last_request_target.get(), last_target_location, false, - &request); + FoundTarget(last_request_target.get(), last_target_location, &request); } } @@ -489,7 +476,7 @@ // Since we couldn't find the target frame among the child-frames // we process the event in the current frame. - FoundTarget(target.get(), location, false, &request); + FoundTarget(target.get(), location, &request); } } // namespace content
diff --git a/content/browser/renderer_host/render_widget_targeter.h b/content/browser/renderer_host/render_widget_targeter.h index d5a7512..c321e556 100644 --- a/content/browser/renderer_host/render_widget_targeter.h +++ b/content/browser/renderer_host/render_widget_targeter.h
@@ -208,12 +208,9 @@ const gfx::PointF& transformed_location); // |target_location|, if - // set, is the location in |target|'s coordinate space. If |latched_target| is - // false, we explicitly did hit-testing for this event, instead of using a - // known target. + // set, is the location in |target|'s coordinate space. void FoundTarget(RenderWidgetHostViewBase* target, const absl::optional<gfx::PointF>& target_location, - bool latched_target, TargetingRequest* request); // Callback when the hit testing timer fires, to resume event processing @@ -241,10 +238,6 @@ std::unordered_set<RenderWidgetHostViewBase*> unresponsive_views_; - // This value keeps track of the number of clients we have asked in order to - // do async hit-testing. - uint32_t async_depth_ = 0; - // Target to send events to if autoscroll is in progress RenderWidgetTargetResult middle_click_result_;
diff --git a/content/browser/resources/attribution_reporting/attribution_internals.ts b/content/browser/resources/attribution_reporting/attribution_internals.ts index de4bbbb..08e9cc1 100644 --- a/content/browser/resources/attribution_reporting/attribution_internals.ts +++ b/content/browser/resources/attribution_reporting/attribution_internals.ts
@@ -717,6 +717,8 @@ return 'Failure: No aggregatable data present'; case WebUITrigger_Status.kProhibitedByBrowserPolicy: return 'Failure: Prohibited by browser policy'; + case WebUITrigger_Status.kNoMatchingConfigurations: + return 'Rejected: no matching event-level configurations'; default: return status.toString(); }
diff --git a/content/common/font_list_unittest.cc b/content/common/font_list_unittest.cc index 548dca9..d06a8ba7 100644 --- a/content/common/font_list_unittest.cc +++ b/content/common/font_list_unittest.cc
@@ -88,7 +88,7 @@ const std::string& font_id = font_names[0].GetString(); // The checks are inspired by Gecko's gfxMacPlatformFontList::AddFamily. - EXPECT_FALSE(base::LowerCaseEqualsASCII(font_id, "lastresort")) + EXPECT_FALSE(base::EqualsCaseInsensitiveASCII(font_id, "lastresort")) << font_id << " seems to be LastResort, which should be filtered"; EXPECT_FALSE(font_id[0] == '.') << font_id << " seems like a hidden font, which should be filtered";
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java index 1e7de52..eb267ba9 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/BrowserAccessibilityState.java
@@ -4,6 +4,8 @@ package org.chromium.content.browser.accessibility; +import static org.chromium.content.browser.accessibility.WebContentsAccessibilityImpl.TAG; + import android.accessibilityservice.AccessibilityServiceInfo; import android.content.ComponentName; import android.content.ContentResolver; @@ -44,8 +46,6 @@ public void onBrowserAccessibilityStateChanged(boolean newScreenReaderEnabledState); } - private static final String TAG = "ClankAccessibility"; - // Analysis of the most popular accessibility services on Android suggests // that any service that requests any of these three events is a screen reader // or other complete assistive technology. If none of these events are requested,
diff --git a/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java b/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java index 247205d..3d3c819 100644 --- a/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/accessibility/WebContentsAccessibilityImpl.java
@@ -81,6 +81,7 @@ import androidx.core.view.accessibility.AccessibilityNodeProviderCompat; import org.chromium.base.ContextUtils; +import org.chromium.base.Log; import org.chromium.base.UserData; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; @@ -121,6 +122,9 @@ public class WebContentsAccessibilityImpl extends AccessibilityNodeProviderCompat implements AccessibilityStateChangeListener, WebContentsAccessibility, WindowEventObserver, UserData, BrowserAccessibilityState.Listener { + // Public catch-all TAG for logging in the accessibility component. + public static final String TAG = "ClankAccessibility"; + // The following constants have been hard coded so we can support actions newer than our // minimum SDK without having to break methods into a series of subclasses. // TODO(mschillaci): Remove these once they are added to the AccessibilityNodeInfoCompat class. @@ -400,14 +404,22 @@ // actually requested. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { - AutofillManager autofillManager = mContext.getSystemService(AutofillManager.class); - if (autofillManager != null && autofillManager.isEnabled()) { - // Native accessibility is usually initialized when getAccessibilityNodeProvider is - // called, but the Autofill compatibility bridge only calls that method after it has - // received the first accessibility events. To solve the chicken-and-egg problem, - // always initialize the native parts when the user has an Autofill service enabled. - refreshState(); - getAccessibilityNodeProvider(); + // The system service call for AutofillManager can timeout and throws an Exception. + // This is treated differently in each version of Android, so we must catch a + // generic Exception. (refer to crbug.com/1186406 or AutofillManagerWrapper ctor). + try { + AutofillManager autofillManager = mContext.getSystemService(AutofillManager.class); + if (autofillManager != null && autofillManager.isEnabled()) { + // Native accessibility is usually initialized when getAccessibilityNodeProvider + // is called, but the Autofill compatibility bridge only calls that method after + // it has received the first accessibility events. To solve the chicken-and-egg + // problem, always initialize the native parts when the user has an Autofill + // service enabled. + refreshState(); + getAccessibilityNodeProvider(); + } + } catch (Exception e) { + Log.e(TAG, "AutofillManager did not resolve before time limit."); } } } @@ -1660,16 +1672,6 @@ } @CalledByNative - private void handleTextContentChanged(int id) { - AccessibilityEvent event = - buildAccessibilityEvent(id, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); - if (event != null) { - event.setContentChangeTypes(AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT); - requestSendAccessibilityEvent(event); - } - } - - @CalledByNative private void handleEditableTextChanged(int id) { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); }
diff --git a/content/shell/browser/shell_content_browser_client.cc b/content/shell/browser/shell_content_browser_client.cc index 151e170..86d34f9 100644 --- a/content/shell/browser/shell_content_browser_client.cc +++ b/content/shell/browser/shell_content_browser_client.cc
@@ -73,6 +73,7 @@ #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" +#include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-shared.h" #include "ui/base/ui_base_features.h" #include "ui/base/ui_base_switches.h" #include "url/gurl.h" @@ -744,4 +745,14 @@ } } +blink::ParsedPermissionsPolicy +ShellContentBrowserClient::GetPermissionsPolicyForIsolatedApp( + content::BrowserContext* browser_context, + const url::Origin& app_origin) { + blink::ParsedPermissionsPolicyDeclaration decl( + blink::mojom::PermissionsPolicyFeature::kDirectSockets, {app_origin}, + /*matches_all_origins=*/false, /*matches_opaque_src=*/false); + return {decl}; +} + } // namespace content
diff --git a/content/shell/browser/shell_content_browser_client.h b/content/shell/browser/shell_content_browser_client.h index 0532d35e..1f92afd 100644 --- a/content/shell/browser/shell_content_browser_client.h +++ b/content/shell/browser/shell_content_browser_client.h
@@ -140,6 +140,12 @@ void OnNetworkServiceCreated( network::mojom::NetworkService* network_service) override; + // Turns on features via permissions policy for Isolated App + // Web Platform Tests. + blink::ParsedPermissionsPolicy GetPermissionsPolicyForIsolatedApp( + content::BrowserContext* browser_context, + const url::Origin& app_origin) override; + void CreateFeatureListAndFieldTrials(); ShellBrowserContext* browser_context();
diff --git a/content/test/attribution_simulator_impl.cc b/content/test/attribution_simulator_impl.cc index e00eb254..ba6b8686 100644 --- a/content/test/attribution_simulator_impl.cc +++ b/content/test/attribution_simulator_impl.cc
@@ -386,6 +386,7 @@ case AttributionTrigger::EventLevelResult::kExcessiveReportingOrigins: case AttributionTrigger::EventLevelResult::kNoMatchingSourceFilterData: case AttributionTrigger::EventLevelResult::kProhibitedByBrowserPolicy: + case AttributionTrigger::EventLevelResult::kNoMatchingConfigurations: event_level_reason << result.event_level_status(); break; }
diff --git a/content/test/data/attribution_reporting/simulator/rejected_triggers.input.json b/content/test/data/attribution_reporting/simulator/rejected_triggers.input.json index 42275a9..cce2d6d 100644 --- a/content/test/data/attribution_reporting/simulator/rejected_triggers.input.json +++ b/content/test/data/attribution_reporting/simulator/rejected_triggers.input.json
@@ -102,6 +102,12 @@ "b": 123 } } + }, + { + "timestamp": "1643235579000", + "reporting_origin": "https://r.test", + "destination_origin": "https://d.test", + "Attribution-Reporting-Register-Trigger": {} } ] }
diff --git a/content/test/data/attribution_reporting/simulator/rejected_triggers.output.json b/content/test/data/attribution_reporting/simulator/rejected_triggers.output.json index db2b9a8..b61b8c8 100644 --- a/content/test/data/attribution_reporting/simulator/rejected_triggers.output.json +++ b/content/test/data/attribution_reporting/simulator/rejected_triggers.output.json
@@ -55,6 +55,15 @@ } } } + }, + { + "event_level_reason": "noMatchingConfigurations", + "trigger": { + "timestamp": "1643235579000", + "reporting_origin": "https://r.test", + "destination_origin": "https://d.test", + "Attribution-Reporting-Register-Trigger": {} + } } ], "event_level_reports": [
diff --git a/content/web_test/browser/web_test_browser_main_runner.cc b/content/web_test/browser/web_test_browser_main_runner.cc index 823bfa0..d6c78e64 100644 --- a/content/web_test/browser/web_test_browser_main_runner.cc +++ b/content/web_test/browser/web_test_browser_main_runner.cc
@@ -178,6 +178,7 @@ command_line.AppendSwitchASCII(network::switches::kHostResolverRules, "MAP nonexistent.*.test ~NOTFOUND," + "MAP web-platform.test:443 127.0.0.1:8444," "MAP *.test. 127.0.0.1," "MAP *.test 127.0.0.1");
diff --git a/docs/enterprise/description_guidelines.md b/docs/enterprise/description_guidelines.md index f21363a..43e0411 100644 --- a/docs/enterprise/description_guidelines.md +++ b/docs/enterprise/description_guidelines.md
@@ -13,6 +13,7 @@ * Google Cast: `<ph name="PRODUCT_NAME">Google Cast</ph>` * Google Cloud Print: `<ph name="CLOUD_PRINT_NAME">Google Cloud Print</ph>` * Google Drive: `<ph name="GOOGLE_DRIVE_NAME">Google Drive</ph>` +* Google Update: `<ph name="GOOGLE_UPDATE_NAME">Google Update</ph>` * Google Workspace: `<ph name="GOOGLE_WORKSPACE_PRODUCT_NAME">Google Workspace</ph>` * Lacros: `<ph name="LACROS_NAME">Lacros</ph>` * Android: `<ph name="ANDROID_NAME">Android</ph>`
diff --git a/docs/frame_trees.md b/docs/frame_trees.md new file mode 100644 index 0000000..26e9b62e1 --- /dev/null +++ b/docs/frame_trees.md
@@ -0,0 +1,81 @@ +# Demystifying FrameTree Concepts + +## What are Frame Trees? + +There are two representations of FrameTrees used in rendering Web Pages. +- Blink's [FrameTrees](../third_party/blink/renderer/core/page/frame_tree.h) +- Content's [FrameTrees](../content/browser/renderer_host/frame_tree.h) + +These concepts are very similar, however on the content side a placeholder +[FrameTreeNode](../content/browser/renderer_host/frame_tree_node.h) can +be placed in the FrameTree to hold another frame tree. This `FrameTreeNode`'s +current RenderFrameHost will have a valid +`RenderFrameHostImpl::inner_tree_main_frame_tree_node_id` frame tree node +ID. + +The renderer side (Blink) will have no notion of this placeholder in the +frame tree and its frame tree appears as it would for the web exposed +[window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window/frames) + +## What are Outermost Main Frames? + +Building on the concept above that a `FrameTree` can have an embedded +`FrameTree` (and many nesting levels of them), there is the concept of +the `OutermostMainFrame`. The OutermostMainFrame is the main frame (root) +of a FrameTree that is not embedded in other FrameTrees.[^1] + +So that does mean there can be __multiple main frames__ in a displayed +tab to the user. For features like `fencedframes` the inner `FrameTree` +has a main frame but it will not be an `OutermostMainFrame`. + +To determine whether something is a main frame `RenderFrameHost::GetParent` +is typically used. Likewise there is a `RenderFrameHost::GetParentOrOuterDocument` to determine if something is an `OutermostMainFrame`. + +Example Frame Tree: + A + B (iframe) + C (fenced frame - placeholder frame)[^2] + C* (main frame in fenced frame). + + C* GetParent returns null. + C* GetParentOrOuterDocument returns A. + C GetParent & GetParentOrOuterDocument returns A. + B GetParent & GetParentOrOuterDocument returns A. + A GetParent & GetParentOrOuterDocument returns nullptr. + +## Can I have multiple outermost main frames? + +Prerender and back/forward cache are features where there can be +other outermost main frame present in a `WebContents`. + +## What are Pages? + +Pages can be an overloaded term so we will clarify what we mean by the +class concepts: +- Blink's [Page](../third_party/blink/renderer/core/page/page.h) +- Content's [Page](../content/public/browser/page.h) + +The two usages are very similar, they effectively are an object representing +the state of a `FrameTree`. Since frames can be hosted in different renderers +(for isolation) there may be a number of Blink `Page` objects, one for each +renderer that participates in the rendering of a single `Page` in content. + +## What is the Primary Page? + +There is only ever one Primary Page for a given `WebContents`. The primary +page is defined by the fact that the main frame is the `OutermostMainFrame` +and being actively displayed in the tab. + +The primary page can change over time (see +`WebContentsObserver::PrimaryPageChanged`). The primary page can change when +navigating, a `Page` is restored from the `BackForwardCache` or from the +prendering pages. + +[^1] GuestViews (embedding of a WebContents inside another WebContents) are +considered embedded FrameTrees as well. However for consideration of +OutermostMainFrames (ie. GetParentOrOuterDocument, Primary page) they do not +escape the WebContents boundary because of the logical embedding boundary. + +[^2] The placeholder RenderFrameHost is generally not exposed outside +of the content boundary. Iteration APIs such as ForEachRenderFrameHost +do not visit this node.
diff --git a/docs/fuchsia/README.md b/docs/fuchsia/README.md index a9e682c..056b001 100644 --- a/docs/fuchsia/README.md +++ b/docs/fuchsia/README.md
@@ -41,7 +41,7 @@ * [Running Telemetry Benchmarks on Fuchsia](telemetry.md) ## Fuchsia WebEngine and Runners -See [Fuchsia WebEngine and Runners](../../fuchsia_webengine/README.md). +See [Fuchsia WebEngine and Runners](../../fuchsia_web/README.md). ## Resources for developers working on Chromium for Fuchsia
diff --git a/docs/updater/functional_spec.md b/docs/updater/functional_spec.md index 5c1c1a5..2f03680 100644 --- a/docs/updater/functional_spec.md +++ b/docs/updater/functional_spec.md
@@ -121,12 +121,12 @@ * --crash-handler * Starts a crash handler for the parent process. * --server - * Launch the updater RPC server. The server will answer RPC messages on + * Launch the updater RPC server. The server answers RPC messages on the UpdateService interface only. * --service=update|update-internal - * If `update`, the server will answer RPC messages on the + * If `update`, the server answers RPC messages on the UpdateService interface only. - * If `update-internal`, the server will answer RPC messages on the + * If `update-internal`, the server answers RPC messages on the UpdateServiceInternal interface only. * --windows-service * This switch starts the Windows service. This switch is invoked by the @@ -159,7 +159,7 @@ * --healthcheck * Exit immediately with no error. -If none of the above arguments are set, the updater will exit with an error. +If none of the above arguments are set, the updater exits with an error. Additionally, the mode may be modified by combining it with: * --system @@ -170,14 +170,60 @@ The updater communicates with update servers using the [Omaha Protocol](protocol_3_1.md). +#### Security +It is not possible to MITM the updater even if the network (including TLS) is +compromised. The integrity of the client-server communication is guaranteed +by the [Client Update Protocol (CUP)](cup.md). + +#### Retries +The updater does not retry an update check that transacted with the backend, +even if the response was erroneous (misformatted or unparsable), until the +next normally scheduled update check. + +#### DOS Mitigation +The updater sends DoS mitigation headers in requests to the server. + +When the server responds with an `X-Retry-After header`, the client does not +issue another update check until the specified period has passed (maximum 24 +hours). + +* The updater distinguishes between foreground and background priority: if an + `X-Retry-After` was received in the background case, a foreground update is + still permitted (but not if it was received in response to a foreground + update). + +#### Load Smoothing +TODO(crbug.com/1329868) - implement the algorithm. +The updater scatters its routine updates: +* Two updaters installed in identical situations and at the same time, after + some period of time, do not have synchronized times at which they check + for updates. + * For example, the updater may randomly choose to wait 6 hours instead of 5 to + perform the next check. The probability of choosing 6 hours is .1. + * The change only applies to users who have not overridden their + `UpdateCheckMs` feature. + * For testing purposes, the feature can be disabled by creating an + DWORD value `DisableUpdateAppsHourlyJitter` in `UpdateDev`. + * For testing purposes, an `UpdateDev` value can set the jitter time to a + constant value, in the same [0, 60) seconds range. The name of the value is + `AutoUpdateJitterMs` and it represents the time to wait before an update + check is made in milliseconds. +* The global load from updaters is scattered among the minutes of the hour, the + seconds of the minute, and the milliseconds of the second. + * For example, load spikes on the first minute of the hour, or + the first second of every minute, or even the first millisecond of every + second are undesirable. + +#### Usage Counts +TODO(crbug.com/1329328) - document the client responsibilities. + ### Update Formats -The updater accepts updates packaged as CRX₃ files. All files must be signed -with a publisher key. The corresponding public key is hardcoded into the -updater. +The updater accepts updates packaged as CRX₃ files. All files are signed with a +publisher key. The corresponding public key is hardcoded into the updater. ### Installation -The updater must handle the installation of new applications. The updater can +The updater handles the installation of new applications. The updater can download, install, and update an applications when the application is running. One or more applications can be installed at once, as a bundle. @@ -204,8 +250,8 @@ This type of installs is done with a [standalone/offline installer] (#Standalone-Installer). This is an installer which embeds all data required to install the application, including the payload and various configuration data -needed by the application setup. Such an install must be able to complete when -a network connection is not available. +needed by the application setup. Such an install completes even if a network +connection is not available. There are a couple of scenarios where the standalone/offline installer is used: @@ -241,7 +287,7 @@ TODO(crbug.com/1327491) - is this needed? If yes, document the algorithm. #### Installer APIs -As part of installing or updating an application, the updater will execute the +As part of installing or updating an application, the updater executes the application's installer. The API for the application installer is platform- specific. @@ -487,7 +533,7 @@ {"logging":{"verbose":true}} ``` -The updater client will now create a temporary file, say `c:\my +The updater client creates a temporary file, say `c:\my path\temporaryfile.dat` (assuming the application installer is running from `c:\my path\YesExe.exe`), with the following file contents: ``` @@ -501,14 +547,14 @@ * Notice above that the temp file contents are prefixed with an UTF-8 Byte Order Mark of `EF BB BF`. -* For MSI installers, a property will passed to the installer: +* For MSI installers, a property is passed to the installer: `INSTALLERDATA="pathtofile"`. -* For exe-based installers, as shown above, a command line parameter will be +* For exe-based installers, as shown above, a command line parameter is passed to the installer: `--installerdata="pathtofile"`. -* For Mac installers, an environment variable will be set: +* For Mac installers, an environment variable is set: `INSTALLERDATA="pathtofile"`. * Ownership of the temp file is the responsibility of the application installer. -The updater will not delete this file. +The updater does not delete this file. * This installerdata is not persisted anywhere else, and it is not sent as a part of pings to the update server. @@ -551,7 +597,9 @@ request, the priority, whether a same-version update (repair) is permitted, and callbacks to monitor the progress and completion of the operation. -Regardless of the normal update check timing, the update check will be attempted +The interface provides the version of the update, if an update is available. + +Regardless of the normal update check timing, the update check is attempted immediately. ### App Registration @@ -559,22 +607,21 @@ the updater. Unlike on-demand updates, cross-user application registration is not permitted. -If the application is already installed, it should be registered with the -version present on disk. If it has not yet been installed, a version of 0 -should be used. +If the application is already installed, it is registered with the version +present on disk. If it has not yet been installed, a version of `0` is used. ### App Activity Reporting Applications can report whether they are actively used or not through the updater. Update servers can then aggregate this information to produce user counts. -Windows: +#### Windows: * When active, the application sets HKCU\SOFTWARE\{Company}\Update\ClientState\{AppID} → dr (REG_SZ): 1. * Note: both user-scoped and system-scoped updaters use HKCU. -* When reporting active use, the updater will reset the value to 0. +* When reporting active use, the updater resets the value to 0. -macOS: +#### macOS: * The application touches ~/Library/{Company}/{Company}SoftwareUpdate/Actives/{APPID}. * The updater deletes the file when reporting active use. @@ -590,7 +637,7 @@ The updater may upload its crash reports and send usage stats if and only if any piece of software it manages is permitted to send usage stats. -Windows: +#### Windows: * Applications enable usage stats by writing: `HKCU\SOFTWARE\{Company}\Update\ClientState\{APPID}` → usagestats (DWORD): 1 or @@ -598,28 +645,31 @@ (DWORD): 1 * Applications rescind this permission by writing a value of 0. -macOS: +#### macOS: * Application enable usage stats by setting `IsUploadEnabled` to true for a crashpad database maintained in a "Crashpad" subdirectory of their application data directory. -* The updater will search the file system for Crashpad directories belonging +* The updater searches the file system for Crashpad directories belonging to {Company}. ### Enterprise Policies TODO(crbug.com/1035895): Document relevant enterprise policies. +#### Windows +ADMX templates are provided. + ### Telemetry -When the updater installs an application (an installer is run) it will send an +When the updater installs an application (an installer is run) it sends an event with `"eventtype": 2` indicating the outcome of installation. The updater does not send such a ping for its own installation. -When the updater updates an application (including itself) it will send an +When the updater updates an application (including itself) it sends an event with `"eventtype": 3` indicating the outcome of update operation. -When the updater detects the uninstallation of an application, it will send an +When the updater detects the uninstallation of an application, it sends an event with `"eventtype": 4` to notify the server of the uninstallation. -When the updater attempts to download a file, it will send an event with +When the updater attempts to download a file, it sends an event with `"eventtype": 14` describing the parameters and outcome of the download. Multiple events associated with an update session are bundled together into a @@ -645,8 +695,8 @@ applications). `{params}` is optional and can also include replaceable parameters substituted at runtime. -The program path must always be an absolute path. Additionally, for system -applications, the program path must also be a child of %ProgramFiles% or +The program path is always an absolute path. Additionally, for system +applications, the program path is also a child of %ProgramFiles% or %ProgramFiles(x86)%. For instance: * `c:\path-to-exe\exe.exe` is an invalid path. * `"c:\Program Files\subdir\exe.exe"` is a valid path. @@ -705,8 +755,8 @@ ``` Parameters placeholders (`%1-%9`) are filled by the numbered parameters in -`IAppCommandWeb::execute`. Placeholders without corresponding parameters will -cause execution to fail. +`IAppCommandWeb::execute`. Placeholders without corresponding parameters +cause the execution to fail. Clients may poll for the execution status of commands that they have invoked by using the `status` method of `IAppCommandWeb`. When the status is @@ -714,11 +764,11 @@ exit code. #### Command-Line Format -* for system applications, the executable path must be in a secure location such -as `%ProgramFiles%` for security, since it will be run elevated. +* for system applications, the executable path is in a secure location such +as `%ProgramFiles%` for security, since it runs elevated. * placeholders are not permitted in the executable path. * placeholders take the form of a percent character `%` followed by a digit. -Literal `%` characters must be escaped by doubling them. +Literal `%` characters are escaped by doubling them. For example, if parameters to `IAppCommandWeb::execute` are `AA` and `BB` respectively, a command format of: @@ -729,21 +779,20 @@ ## Uninstallation On Mac and Linux, if the application was registered with an existence path checker and no file at that path exists (or if the file at that path is owned -by another user), the updater will consider the application uninstalled, send -the ping, and cease trying to keep it up to date. +by another user), the updater considers the application uninstalled, sends +the ping, and stops trying to keep it up to date. On Windows, if the ClientState entry for for the application is deleted, the app is considered uninstalled. -On Windows, the updater registers a "UninstallCmdLine" under the -`Software\{Company}\Updater` key. This command line can be invoked by -application uninstallers to cause the updater to immediately update its -registrations. The updater will also check for uninstallations in every periodic -task execution. +On Windows, the updater registers a "UninstallCmdLine" under the `Software\ +{Company}\Updater` key. This command line can be invoked by application +uninstallers to cause the updater to update its registrations. The updater +also checks for uninstallations in every periodic task execution. -When the last registered application is uninstalled, the updater will uninstall -itself. The updater will also uninstall itself if it has started 24 times but -never had a product (besides itself) registered for updates. +When the last registered application is uninstalled, the updater uninstalls +itself immediately. The updater also uninstalls itself if it has started +24 times but never had a product (besides itself) registered for updates. The updater uninstaller removes all updater files, registry keys, RPC hooks, scheduled tasks, and so forth from the file system, except that it leaves a
diff --git a/extensions/browser/api/web_request/web_request_api_helpers.cc b/extensions/browser/api/web_request/web_request_api_helpers.cc index 4ecfcdd..51ee8d1 100644 --- a/extensions/browser/api/web_request/web_request_api_helpers.cc +++ b/extensions/browser/api/web_request/web_request_api_helpers.cc
@@ -818,10 +818,9 @@ continue; if (ShouldHideResponseHeader(extra_info_spec, name)) continue; - std::string name_lowercase = base::ToLowerASCII(name); bool header_found = false; for (const auto& i : *new_response_headers) { - if (base::LowerCaseEqualsASCII(i.first, name_lowercase) && + if (base::EqualsCaseInsensitiveASCII(i.first, name) && value == i.second) { header_found = true; break; @@ -839,13 +838,12 @@ continue; if (ShouldHideResponseHeader(extra_info_spec, i.first)) continue; - std::string name_lowercase = base::ToLowerASCII(i.first); size_t iter = 0; std::string name; std::string value; bool header_found = false; while (old_response_headers->EnumerateHeaderLines(&iter, &name, &value)) { - if (base::LowerCaseEqualsASCII(name, name_lowercase) && + if (base::EqualsCaseInsensitiveASCII(name, i.first) && value == i.second) { header_found = true; break; @@ -1741,7 +1739,7 @@ bool ShouldHideResponseHeader(int extra_info_spec, const std::string& name) { return !(extra_info_spec & ExtraInfoSpec::EXTRA_HEADERS) && - base::LowerCaseEqualsASCII(name, "set-cookie"); + base::EqualsCaseInsensitiveASCII(name, "set-cookie"); } bool ArePublicSessionRestrictionsEnabled() {
diff --git a/fuchsia_web/BUILD.gn b/fuchsia_web/BUILD.gn new file mode 100644 index 0000000..b5cb091 --- /dev/null +++ b/fuchsia_web/BUILD.gn
@@ -0,0 +1,19 @@ +# Copyright 2022 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. + +assert(is_fuchsia) + +visibility = [ "//:gn_all" ] + +# Ensures every target within this directory is reachable. +# Used by "//:gn_all". +# TODO(crbug.com/1081525): Update these to targets within this directory as +# they are moved. +group("gn_all") { + deps = [ + "//fuchsia/engine:web_engine", + "//fuchsia/runners:cast_runner", + "//fuchsia/runners:web_runner", + ] +}
diff --git a/fuchsia_webengine/DEPS b/fuchsia_web/DEPS similarity index 75% rename from fuchsia_webengine/DEPS rename to fuchsia_web/DEPS index a8d5dde..e64f359 100644 --- a/fuchsia_webengine/DEPS +++ b/fuchsia_web/DEPS
@@ -1,4 +1,4 @@ include_rules = [ # Require explicit include rules for sub-directories. - "-fuchsia_webengine", + "-fuchsia_web", ] \ No newline at end of file
diff --git a/fuchsia_webengine/DIR_METADATA b/fuchsia_web/DIR_METADATA similarity index 100% rename from fuchsia_webengine/DIR_METADATA rename to fuchsia_web/DIR_METADATA
diff --git a/fuchsia_webengine/OWNERS b/fuchsia_web/OWNERS similarity index 100% rename from fuchsia_webengine/OWNERS rename to fuchsia_web/OWNERS
diff --git a/fuchsia_webengine/README.md b/fuchsia_web/README.md similarity index 76% rename from fuchsia_webengine/README.md rename to fuchsia_web/README.md index 1a03734..10c71b82 100644 --- a/fuchsia_webengine/README.md +++ b/fuchsia_web/README.md
@@ -1,7 +1,9 @@ -# Fuchsia WebEngine and Runners +# `fuchsia.web` - Fuchsia WebEngine and Runners -This directory contains implementation code for Fuchsia WebEngine and code -specifically related to it, including the Runners that use it. Code in this +This directory contains code related to the +[`fuchsia.web`](https://fuchsia.dev/reference/fidl/fuchsia.web) FIDL API. +Specifically, it contains the implementation of Fuchsia WebEngine and code +related to it, including the Runners that use it. Code in this directory must not be used outside it and its subdirectories. General information about Chromium on Fuchsia is @@ -12,11 +14,19 @@ ## Code organization Each of the following subdirectories contain code for a specific Fuchsia service: -* `./engine` contains the WebEngine implementation. WebEngine enables -Fuchsia applications to embed Chromium frames for rendering web content. +* `./common` contains code shared by both WebEngine and Runners. * `./runners`contains implementations of Fuchsia `sys.runner`. * `./runners/cast` Enables the Fuchsia system to launch Cast applications. * `./runners/web` Enables the Fuchsia system to launch HTTP or HTTPS URLs. +* `./shell` contains WebEngineShell, a simple wrapper for launching URLs in +WebEngine from the command line. +* `./webengine` contains the WebEngine implementation. WebEngine is an +implementation of +[`fuchsia.web`](https://fuchsia.dev/reference/fidl/fuchsia.web) that enables +Fuchsia Components to render web content using Chrome's Content layer. +* `./webinstance_host` contains code for WebEngine clients to directly +instantiate a WebInstance Component (`web_instance.cm`) using the WebEngine +package. ### Test code @@ -27,8 +37,8 @@ code is run inside the browser process, allowing for full access to the browser code - but not other processes. * Integration tests: Exercise the published FIDL API of a Fuchsia Component. For - instance, `//fuchsia_webengine/engine:web_engine_integration_tests` make use - of the `//fuchsia_webengine/engine:web_engine` component. The test code runs + instance, `//fuchsia_web/webengine:web_engine_integration_tests` make use + of the `//fuchsia_web/webengine:web_engine` component. The test code runs in a separate process in a separate Fuchsia Component, allowing only access to the published API of the component under test. @@ -41,9 +51,9 @@ `*_unittest.cc`, `*_ browsertest.cc` or `*_integration_test.cc`. Test code that is shared across Components should live in `a dedicated ``test` -directory. For example, the `//fuchsia_webengine/engine/test` directory, which +directory. For example, the `//fuchsia_web/webengine/test` directory, which contains code shared by all browser tests, and -`//fuchsia_webengine/common/test`, which contains code shared by tests for both +`//fuchsia_web/common/test`, which contains code shared by tests for both WebEngine and Runners. ## Building and deploying the WebRunner service
diff --git a/headless/lib/browser/protocol/headless_devtools_session.cc b/headless/lib/browser/protocol/headless_devtools_session.cc index ca9bfee..8978d9b 100644 --- a/headless/lib/browser/protocol/headless_devtools_session.cc +++ b/headless/lib/browser/protocol/headless_devtools_session.cc
@@ -22,6 +22,8 @@ base::WeakPtr<HeadlessBrowserImpl> browser, content::DevToolsAgentHostClientChannel* channel) : browser_(browser), dispatcher_(this), client_channel_(channel) { + CHECK(client_channel_->GetClient()->IsTrusted()) + << "Connection to headless requires a trusted client"; content::DevToolsAgentHost* agent_host = channel->GetAgentHost(); if (agent_host->GetWebContents() && agent_host->GetType() == content::DevToolsAgentHost::kTypePage) { @@ -30,10 +32,8 @@ AddHandler(std::make_unique<PageHandler>(agent_host, agent_host->GetWebContents())); } - if (channel->GetClient()->IsTrusted()) { - AddHandler( - std::make_unique<BrowserHandler>(browser_.get(), agent_host->GetId())); - } + AddHandler( + std::make_unique<BrowserHandler>(browser_.get(), agent_host->GetId())); AddHandler(std::make_unique<TargetHandler>(browser_.get())); }
diff --git a/infra/config/generated/builders/ci/ios-asan/properties.json b/infra/config/generated/builders/ci/ios-asan/properties.json index 01b24c91..de9c888e 100644 --- a/infra/config/generated/builders/ci/ios-asan/properties.json +++ b/infra/config/generated/builders/ci/ios-asan/properties.json
@@ -1,6 +1,5 @@ { "$build/goma": { - "enable_ats": true, "rpc_extra_params": "?prod", "server_host": "goma.chromium.org", "use_luci_auth": true @@ -21,5 +20,6 @@ "recipe": "chromium", "sheriff_rotations": [ "ios" - ] + ], + "xcode_build_version": "13c100" } \ No newline at end of file
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index 65f0064..ae1be59 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -12701,7 +12701,7 @@ ' "led_builder_is_bootstrapped": true,' ' "recipe": "chromium"' '}' - execution_timeout_secs: 43200 + execution_timeout_secs: 50400 build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments { @@ -29514,12 +29514,10 @@ builders { name: "ios-asan" swarming_host: "chromium-swarm.appspot.com" - dimensions: "builderless:1" - dimensions: "cores:8" + dimensions: "builder:ios-asan" dimensions: "cpu:x86-64" - dimensions: "os:Ubuntu-18.04" + dimensions: "os:Mac-11" dimensions: "pool:luci.chromium.ci" - dimensions: "ssd:0" exe { cipd_package: "infra/chromium/bootstrapper/${platform}" cipd_version: "latest" @@ -29554,6 +29552,10 @@ ' ]' '}' execution_timeout_secs: 10800 + caches { + name: "xcode_ios_13c100" + path: "xcode_ios_13c100.app" + } build_numbers: YES service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" experiments {
diff --git a/infra/config/subprojects/chromium/ci/chromium.fyi.star b/infra/config/subprojects/chromium/ci/chromium.fyi.star index dc1af2ff..65f8c36 100644 --- a/infra/config/subprojects/chromium/ci/chromium.fyi.star +++ b/infra/config/subprojects/chromium/ci/chromium.fyi.star
@@ -1010,7 +1010,7 @@ reclient_rewrapper_env = {"RBE_compare": "true"}, reclient_ensure_verified = True, description_html = "verify artifacts. should be removed after the migration. crbug.com/1260232", - execution_timeout = 12 * time.hour, + execution_timeout = 14 * time.hour, ) fyi_mac_builder(
diff --git a/infra/config/subprojects/chromium/ci/chromium.memory.star b/infra/config/subprojects/chromium/ci/chromium.memory.star index af94a9b3..14fde13 100644 --- a/infra/config/subprojects/chromium/ci/chromium.memory.star +++ b/infra/config/subprojects/chromium/ci/chromium.memory.star
@@ -6,7 +6,7 @@ load("//lib/args.star", "args") load("//lib/branches.star", "branches") load("//lib/builder_config.star", "builder_config") -load("//lib/builders.star", "goma", "os", "sheriff_rotations") +load("//lib/builders.star", "goma", "os", "sheriff_rotations", "xcode") load("//lib/ci.star", "ci", "rbe_instance", "rbe_jobs") load("//lib/consoles.star", "consoles") @@ -594,4 +594,7 @@ ), goma_backend = goma.backend.RBE_PROD, sheriff_rotations = args.ignore_default(sheriff_rotations.IOS), + cores = None, + os = os.MAC_11, + xcode = xcode.x13main, )
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm index 638dd4de..793f4c1 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm
@@ -138,8 +138,6 @@ CGFloat pinnedOffsetY = [self.headerController pinnedOffsetY]; self.collectionShiftingOffset = MAX(-self.additionalOffset, pinnedOffsetY - [self adjustedOffset].y); - - self.collectionController.scrolledToMinimumHeight = YES; self.shouldAnimateHeader = YES; __weak __typeof(self) weakSelf = self; @@ -148,8 +146,9 @@ initWithDuration:kShiftTilesUpAnimationDuration curve:UIViewAnimationCurveEaseInOut animations:^{ - if (!weakSelf) + if (!weakSelf) { return; + } __typeof(weakSelf) strongSelf = weakSelf; if (strongSelf.collectionView.contentOffset.y < @@ -168,14 +167,19 @@ }]; [self.animator addCompletion:^(UIViewAnimatingPosition finalPosition) { - if (!weakSelf) + ContentSuggestionsHeaderSynchronizer* strongSelf = weakSelf; + if (!strongSelf) { return; + } - if (finalPosition == UIViewAnimatingPositionEnd) - weakSelf.shouldAnimateHeader = NO; + if (finalPosition == UIViewAnimatingPositionEnd) { + strongSelf.shouldAnimateHeader = NO; + } - if (completion) + strongSelf.collectionController.scrolledToMinimumHeight = YES; + if (completion) { completion(finalPosition); + } }]; self.animator.interruptible = YES;
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer_unittest.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer_unittest.mm index 37943d3..0c04ffd 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer_unittest.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer_unittest.mm
@@ -6,6 +6,8 @@ #include <memory> +#include "base/run_loop.h" +#include "base/test/task_environment.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_controlling.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_controlling.h" #import "ios/testing/scoped_block_swizzler.h" @@ -45,6 +47,7 @@ } private: + base::test::TaskEnvironment task_environment_; ContentSuggestionsHeaderSynchronizer* synchronizer_; id header_controller_; id collection_controller_; @@ -59,6 +62,7 @@ // Action. [Synchronizer() shiftTilesUpWithAnimations:nil completion:nil]; + base::RunLoop().RunUntilIdle(); // Tests. EXPECT_OCMOCK_VERIFY(collectionController);
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm index 567fc27..704c2e92 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm
@@ -346,17 +346,16 @@ UIViewController* parentViewController = self.isFeedVisible ? self.discoverFeedWrapperViewController.discoverFeed : self.discoverFeedWrapperViewController; - [self addViewController:[self contentSuggestionsViewController] - toParentViewController:parentViewController]; - if (!IsContentSuggestionsUIViewControllerMigrationEnabled()) { - self.contentSuggestionsLayout.parentCollectionView = self.collectionView; - } - // Configures the feed header in the view hierarchy if it is visible. if (self.feedHeaderViewController) { [self addViewController:self.feedHeaderViewController toParentViewController:parentViewController]; } + [self addViewController:[self contentSuggestionsViewController] + toParentViewController:parentViewController]; + if (!IsContentSuggestionsUIViewControllerMigrationEnabled()) { + self.contentSuggestionsLayout.parentCollectionView = self.collectionView; + } // Adds the feed top section to the view hierarchy if it exists. if (IsDiscoverFeedTopSyncPromoEnabled() &&
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/BUILD.gn b/ios/chrome/browser/ui/popup_menu/overflow_menu/BUILD.gn index 0826a8b..755c999 100644 --- a/ios/chrome/browser/ui/popup_menu/overflow_menu/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/BUILD.gn
@@ -15,8 +15,6 @@ source_set("overflow_menu") { configs += [ "//build/config/compiler:enable_arc" ] sources = [ - "destination_usage_history.h", - "destination_usage_history.mm", "overflow_menu_mediator.h", "overflow_menu_mediator.mm", ] @@ -94,6 +92,7 @@ "//ios/chrome/browser/ui/ntp:metrics", "//ios/chrome/browser/ui/popup_menu:constants", "//ios/chrome/browser/ui/popup_menu:metrics_protocols", + "//ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history", "//ios/chrome/browser/ui/util", "//ios/chrome/browser/web", "//ios/chrome/browser/web/font_size", @@ -157,10 +156,7 @@ source_set("unit_tests") { testonly = true - sources = [ - "destination_usage_history_unittest.mm", - "overflow_menu_mediator_unittest.mm", - ] + sources = [ "overflow_menu_mediator_unittest.mm" ] deps = [ ":overflow_menu", "//base",
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.mm b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.mm deleted file mode 100644 index d01c435e..0000000 --- a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.mm +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.h" - -#include "base/json/json_writer.h" -#include "base/mac/foundation_util.h" -#include "base/strings/sys_string_conversions.h" -#include "components/prefs/pref_service.h" -#import "ios/chrome/browser/pref_names.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -namespace { - -// Converts base::Value::Dict* to NSDictionary. -NSDictionary* NSDictionaryFromDictionaryValue(const base::Value::Dict* value) { - std::string JSON; - const bool success = base::JSONWriter::Write(*value, &JSON); - DCHECK(success) << "Failed to convert base::Value::Dict to JSON"; - NSString* JSONString = @(JSON.c_str()); - NSData* JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding]; - NSDictionary* dictionary = base::mac::ObjCCastStrict<NSDictionary>( - [NSJSONSerialization JSONObjectWithData:JSONData - options:kNilOptions - error:nil]); - DCHECK(dictionary) << "Failed to convert JSON to NSDictionary"; - - return dictionary; -} - -} // namespace - -@interface DestinationUsageHistory () - -// Dictionary that tracks the total number of times a given destination was -// clicked in a given day. -@property(nonatomic, readwrite, strong) NSDictionary* history; - -@end - -@implementation DestinationUsageHistory - -- (instancetype)initWithPrefService:(PrefService*)prefService { - if (self = [super init]) { - _prefService = prefService; - - if (_prefService) { - const base::Value::Dict* locallyStoredHistory = - _prefService - ->GetDictionary(prefs::kOverflowMenuDestinationUsageHistory) - ->GetIfDict(); - - if (!locallyStoredHistory || locallyStoredHistory->empty()) { - // User's first time tracking destination usage history, so a new - // dictionary should be created. - _history = [[NSDictionary alloc] init]; - } else { - _history = NSDictionaryFromDictionaryValue(locallyStoredHistory); - } - } - } - - return self; -} - -#pragma mark - Public - -- (void)trackDestinationClick:(NSString*)destinationName { - if (self.prefService) { - base::Value::Dict dict; - dict.Set("lastClicked", base::SysNSStringToUTF8(destinationName)); - - self.prefService->SetDict(prefs::kOverflowMenuDestinationUsageHistory, - std::move(dict)); - } -} - -@end
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/BUILD.gn b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/BUILD.gn new file mode 100644 index 0000000..e6429d4 --- /dev/null +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/BUILD.gn
@@ -0,0 +1,29 @@ +source_set("destination_usage_history") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "destination_usage_history.h", + "destination_usage_history.mm", + ] + frameworks = [ "Foundation.framework" ] + deps = [ + "//base", + "//components/prefs", + "//ios/chrome/browser:pref_names", + "//ios/chrome/browser/ui/popup_menu/overflow_menu:overflow_menu_constants", + ] +} + +source_set("unit_tests") { + testonly = true + sources = [ "destination_usage_history_unittest.mm" ] + deps = [ + ":destination_usage_history", + "//base", + "//components/prefs", + "//components/prefs:test_support", + "//ios/chrome/browser:pref_names", + "//ios/chrome/browser/ui/popup_menu/overflow_menu:overflow_menu_constants", + "//testing/gtest", + ] + configs += [ "//build/config/compiler:enable_arc" ] +}
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.h b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.h similarity index 65% rename from ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.h rename to ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.h index a8ac991f..fa35bff 100644 --- a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.h +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.h
@@ -2,23 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_DESTINATION_USAGE_HISTORY_H_ -#define IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_DESTINATION_USAGE_HISTORY_H_ +#ifndef IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_DESTINATION_USAGE_HISTORY_DESTINATION_USAGE_HISTORY_H_ +#define IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_DESTINATION_USAGE_HISTORY_DESTINATION_USAGE_HISTORY_H_ #import <UIKit/UIKit.h> +#import "ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.h" + class PrefService; // Maintains a history of which items from the new overflow menu carousel the -// user clicks. Additionally, suggests a sorted order (based on usage frecency) -// for carousel menu items. +// user clicks and suggests a sorted order for carousel menu items (based on +// usage frecency). @interface DestinationUsageHistory : NSObject -// Pref service to retrieve preference values. +// Pref service to retrieve/store preference values. @property(nonatomic, assign) PrefService* prefService; // Records a destination click from the overflow menu carousel. -- (void)trackDestinationClick:(NSString*)destinationName; +- (void)trackDestinationClick:(overflow_menu::Destination)destination; // Designated initializer. Initializes with |prefService|. - (instancetype)initWithPrefService:(PrefService*)prefService @@ -28,4 +30,4 @@ @end -#endif // IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_DESTINATION_USAGE_HISTORY_H_ +#endif // IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_DESTINATION_USAGE_HISTORY_DESTINATION_USAGE_HISTORY_H_
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.mm b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.mm new file mode 100644 index 0000000..c8bd089 --- /dev/null +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.mm
@@ -0,0 +1,69 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.h" + +#include "base/strings/string_number_conversions.h" +#include "base/time/time.h" +#include "components/prefs/pref_service.h" +#include "components/prefs/scoped_user_pref_update.h" +#import "ios/chrome/browser/pref_names.h" +#import "ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace { + +// The number of days since the Unix epoch; one day, in this context, runs from +// UTC midnight to UTC midnight. +int TodaysDay() { + return (base::Time::Now() - base::Time::UnixEpoch()).InDays(); +} + +// Creates a path of the form "<day>.<destination>", where "." indexes +// into the next DictionaryValue down. +const std::string DottedPath(int day, overflow_menu::Destination destination) { + std::string destination_name = + overflow_menu::StringNameForDestination(destination); + + return base::NumberToString(day) + "." + destination_name; +} + +} // namespace + +@implementation DestinationUsageHistory + +- (instancetype)initWithPrefService:(PrefService*)prefService { + if (self = [super init]) { + _prefService = prefService; + } + + return self; +} + +#pragma mark - Public + +// Track click for |destination| and associate it with TodaysDay(). +- (void)trackDestinationClick:(overflow_menu::Destination)destination { + DCHECK(_prefService); + // Exit early if there's no pref service; this is not expected to happen. + if (!_prefService) + return; + + const base::Value* pref = + _prefService->GetDictionary(prefs::kOverflowMenuDestinationUsageHistory); + const base::Value::Dict* history = pref->GetIfDict(); + const std::string path = DottedPath(TodaysDay(), destination); + + absl::optional<int> prevNumClicks = history->FindIntByDottedPath(path); + int numClicks = prevNumClicks.value_or(0) + 1; + + DictionaryPrefUpdate update(_prefService, + prefs::kOverflowMenuDestinationUsageHistory); + update->SetIntPath(path, numClicks); +} + +@end
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history_unittest.mm b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history_unittest.mm new file mode 100644 index 0000000..2a60d105 --- /dev/null +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history_unittest.mm
@@ -0,0 +1,173 @@ +// Copyright 2022 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.h" +#include "base/strings/string_number_conversions.h" +#include "base/time/time.h" +#include "base/values.h" +#include "components/prefs/pref_registry_simple.h" +#include "components/prefs/testing_pref_service.h" +#import "ios/chrome/browser/pref_names.h" +#import "ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.h" +#include "testing/platform_test.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace { + +// The number of days since the Unix epoch; one day, in this context, runs from +// UTC midnight to UTC midnight. +int TodaysDay() { + return (base::Time::Now() - base::Time::UnixEpoch()).InDays(); +} + +} // namespace + +class DestinationUsageHistoryTest : public PlatformTest { + public: + DestinationUsageHistoryTest() {} + + protected: + DestinationUsageHistory* CreateDestinationUsageHistory() { + CreatePrefs(); + + destination_usage_history_ = + [[DestinationUsageHistory alloc] initWithPrefService:prefs_.get()]; + + return destination_usage_history_; + } + + DestinationUsageHistory* CreatePopulatedDestinationUsageHistory() { + CreatePrefsWithInitialData(); + destination_usage_history_ = + [[DestinationUsageHistory alloc] initWithPrefService:prefs_.get()]; + return destination_usage_history_; + } + + void CreatePrefs() { + prefs_ = std::make_unique<TestingPrefServiceSimple>(); + prefs_->registry()->RegisterDictionaryPref( + prefs::kOverflowMenuDestinationUsageHistory, PrefRegistry::LOSSY_PREF); + } + + void CreatePrefsWithInitialData() { + CreatePrefs(); + base::Value::Dict history; + base::Value::Dict day_history; + day_history.Set(overflow_menu::StringNameForDestination( + overflow_menu::Destination::Bookmarks), + 3); + history.Set(base::NumberToString(TodaysDay()), std::move(day_history)); + prefs_->SetDict(prefs::kOverflowMenuDestinationUsageHistory, + std::move(history)); + } + + std::string DottedPath(std::string day, std::string destination_name) { + return day + "." + destination_name; + } + + std::unique_ptr<TestingPrefServiceSimple> prefs_; + DestinationUsageHistory* destination_usage_history_; +}; + +// Tests the initializer correctly creates a DestinationUsageHistory* with the +// specified Pref service. +TEST_F(DestinationUsageHistoryTest, InitWithPrefService) { + CreateDestinationUsageHistory(); + + PrefService* pref_service = destination_usage_history_.prefService; + + EXPECT_NE( + pref_service->FindPreference(prefs::kOverflowMenuDestinationUsageHistory), + nullptr); + EXPECT_FALSE( + pref_service->HasPrefPath(prefs::kOverflowMenuDestinationUsageHistory)); +} + +// Tests the initializer correctly creates a DestinationUsageHistory* with the +// specified Pref service, when the prefs have existing data. +TEST_F(DestinationUsageHistoryTest, InitWithPrefServiceForDirtyPrefs) { + CreatePopulatedDestinationUsageHistory(); + + PrefService* pref_service = destination_usage_history_.prefService; + + EXPECT_NE( + pref_service->FindPreference(prefs::kOverflowMenuDestinationUsageHistory), + nullptr); + EXPECT_TRUE( + pref_service->HasPrefPath(prefs::kOverflowMenuDestinationUsageHistory)); +} + +// Tests that a new destination click is incremented and written to Chrome +// Prefs. +TEST_F(DestinationUsageHistoryTest, HandlesNewDestinationClickAndAddToPrefs) { + DestinationUsageHistory* destination_usage_history = + CreateDestinationUsageHistory(); + + // Click bookmarks destination. + [destination_usage_history + trackDestinationClick:overflow_menu::Destination::Bookmarks]; + + // Fetch saved destination usage history. + const base::Value* history = + destination_usage_history_.prefService->GetDictionary( + prefs::kOverflowMenuDestinationUsageHistory); + ASSERT_NE(history, nullptr); + ASSERT_TRUE(history->is_dict()); + + const base::Value::Dict* history_dict = history->GetIfDict(); + ASSERT_NE(history, nullptr); + + std::string today = base::NumberToString(TodaysDay()); + std::string destination = overflow_menu::StringNameForDestination( + overflow_menu::Destination::Bookmarks); + std::string dotted_path = DottedPath(today, destination); + + // Query saved usage history for Bookmarks entry for |today|. + const base::Value* target = history_dict->FindByDottedPath(dotted_path); + + // Verify bookmarks entry exists and has been clicked once. + ASSERT_NE(target, nullptr); + EXPECT_TRUE(destination_usage_history_.prefService->HasPrefPath( + prefs::kOverflowMenuDestinationUsageHistory)); + EXPECT_EQ(1, target->GetInt()); +} + +// Tests that an existing destination click is incremented and written to Chrome +// Prefs. +TEST_F(DestinationUsageHistoryTest, + HandlesExistingDestinationClickAndAddToPrefs) { + DestinationUsageHistory* destination_usage_history = + CreatePopulatedDestinationUsageHistory(); + + // Click bookmarks destination. + [destination_usage_history + trackDestinationClick:overflow_menu::Destination::Bookmarks]; + + // Fetch saved destination usage history. + const base::Value* history = + destination_usage_history_.prefService->GetDictionary( + prefs::kOverflowMenuDestinationUsageHistory); + ASSERT_NE(history, nullptr); + ASSERT_TRUE(history->is_dict()); + + const base::Value::Dict* history_dict = history->GetIfDict(); + ASSERT_NE(history, nullptr); + + std::string today = base::NumberToString(TodaysDay()); + std::string destination = overflow_menu::StringNameForDestination( + overflow_menu::Destination::Bookmarks); + std::string dotted_path = DottedPath(today, destination); + + // Query saved usage history for Bookmarks entry for |today|. + const base::Value* target = history_dict->FindByDottedPath(dotted_path); + + // Verify bookmarks entry exists and has been clicked once. + ASSERT_NE(target, nullptr); + EXPECT_TRUE(destination_usage_history_.prefService->HasPrefPath( + prefs::kOverflowMenuDestinationUsageHistory)); + EXPECT_EQ(4, target->GetInt()); +}
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history_unittest.mm b/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history_unittest.mm deleted file mode 100644 index a5b1603..0000000 --- a/ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history_unittest.mm +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2022 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.h" - -#include "base/values.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/testing_pref_service.h" -#import "ios/chrome/browser/pref_names.h" -#include "testing/platform_test.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -class DestinationUsageHistoryTest : public PlatformTest { - public: - DestinationUsageHistoryTest() {} - - protected: - DestinationUsageHistory* CreateDestinationUsageHistory() { - // Destination Usage History must be created with a Pref service. - CreatePrefs(); - - destination_usage_history_ = - [[DestinationUsageHistory alloc] initWithPrefService:prefs_.get()]; - - return destination_usage_history_; - } - - void CreatePrefs() { - prefs_ = std::make_unique<TestingPrefServiceSimple>(); - prefs_->registry()->RegisterDictionaryPref( - prefs::kOverflowMenuDestinationUsageHistory, PrefRegistry::LOSSY_PREF); - } - - std::unique_ptr<TestingPrefServiceSimple> prefs_; - DestinationUsageHistory* destination_usage_history_; -}; - -// Tests the initializer correctly creates a DestinationUsageHistory* with the -// specified Pref service. -TEST_F(DestinationUsageHistoryTest, InitWithPrefService) { - CreateDestinationUsageHistory(); - - PrefService* pref_service = destination_usage_history_.prefService; - - EXPECT_NE( - pref_service->FindPreference(prefs::kOverflowMenuDestinationUsageHistory), - nullptr); - EXPECT_FALSE( - pref_service->HasPrefPath(prefs::kOverflowMenuDestinationUsageHistory)); -} - -// Tests that a destination click is written to Chrome Prefs. -TEST_F(DestinationUsageHistoryTest, AddsBookmarksClickToPrefs) { - DestinationUsageHistory* destination_usage_history = - CreateDestinationUsageHistory(); - [destination_usage_history trackDestinationClick:@"bookmarks"]; - - PrefService* pref_service = destination_usage_history_.prefService; - - const base::Value* dictionary = - pref_service->GetDictionary(prefs::kOverflowMenuDestinationUsageHistory); - ASSERT_NE(dictionary, nullptr); - - const base::Value* dictionary_value = - dictionary->FindKeyOfType("lastClicked", base::Value::Type::STRING); - ASSERT_NE(dictionary_value, nullptr); - - EXPECT_TRUE( - pref_service->HasPrefPath(prefs::kOverflowMenuDestinationUsageHistory)); - EXPECT_EQ("bookmarks", dictionary_value->GetString()); -}
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.cc b/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.cc index 051cb57..d651f57 100644 --- a/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.cc +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.cc
@@ -9,7 +9,6 @@ #include "base/notreached.h" namespace overflow_menu { - // WARNING - PLEASE READ: Sadly, we cannot switch over strings in C++, so be // very careful when updating this method to ensure all enums are accounted for. Destination DestinationForStringName(std::string destination) {
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator.mm b/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator.mm index 805fd64..98901ecd 100644 --- a/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator.mm +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator.mm
@@ -49,7 +49,7 @@ #import "ios/chrome/browser/ui/icons/action_icon.h" #import "ios/chrome/browser/ui/icons/chrome_symbol.h" #import "ios/chrome/browser/ui/ntp/feed_metrics_recorder.h" -#import "ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history.h" +#import "ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history/destination_usage_history.h" #import "ios/chrome/browser/ui/popup_menu/overflow_menu/feature_flags.h" #import "ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_constants.h" #import "ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_swift.h" @@ -801,8 +801,7 @@ overflow_menu::RecordUmaActionForDestination(destination); if (IsSmartSortingNewOverflowMenuEnabled()) { - // NOTE: swapping name for destination coming in subsequent CL very soon! - [weakSelf.destinationUsageHistory trackDestinationClick:name]; + [weakSelf.destinationUsageHistory trackDestinationClick:destination]; } handler();
diff --git a/ios/chrome/test/BUILD.gn b/ios/chrome/test/BUILD.gn index 8e55e6c..4e56f08 100644 --- a/ios/chrome/test/BUILD.gn +++ b/ios/chrome/test/BUILD.gn
@@ -330,6 +330,7 @@ "//ios/chrome/browser/ui/page_info:unit_tests", "//ios/chrome/browser/ui/popup_menu:unit_tests", "//ios/chrome/browser/ui/popup_menu/overflow_menu:unit_tests", + "//ios/chrome/browser/ui/popup_menu/overflow_menu/destination_usage_history:unit_tests", "//ios/chrome/browser/ui/presenters:unit_tests", "//ios/chrome/browser/ui/qr_generator:unit_tests", "//ios/chrome/browser/ui/reading_list:unit_tests",
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 index 437dcb1..ce7b03af 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -af58dd1dc9688f4db1b427d5bdb9c99e1be269e8 \ No newline at end of file +6dedb3e74f8ffc9430c3540089736fa6968cfa2f \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 index d4b38262..1e3ea42 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -61e95def2aee7046aca1c602c1e44cbe48af588b \ No newline at end of file +24091cb273ec8775a2d6f35fd4ad85e1a2acbc9a \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 index 92e48b6..95f9d1a9 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -351d30c386f60f886511c069382b709af2281f57 \ No newline at end of file +3313c844ef1b6ea25b609180bb52b7d16874de08 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 index 1e55f8c5..9c00720 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -65bd6c607e47f59159018ce21bbf95dd3996e64b \ No newline at end of file +d3d718661c066491dd6975301600ae9ec930d35b \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 index b57f0fd..4654599 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -b1924a005a4e9593562815c9ce3ae11bdcc995a7 \ No newline at end of file +553d0de85469519c7d0b5beb54dfdc53184ddfbe \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 index 658e3b0..0c7bbdf 100644 --- a/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_dogfood_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -aed930aecc71603ddf1d15c4437e3ec5d4390f8b \ No newline at end of file +d3b854cd9f60a6801dc858a6faf04d485b95077d \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 index 51b6e83..9294f50 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -c3fbaa396c68c05d2aac8ab2518acd45038c68bc \ No newline at end of file +9806e83e47abc8cbaa7d3daf8c0f220041b58698 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 index ddf1429e..f5e7c60f 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -c57c75f9db526d72547603a7e87a3cd00aa89503 \ No newline at end of file +1df8de7c044505ccadfd044cb3a6e426fe25d129 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 index 26d8e2d..db4f783 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -708539b7db243840e48ba7588caaf06a42a7e4ae \ No newline at end of file +f1fa0556e078d5c6b0117c44e53c7161b18a4eb4 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 index 8d9a413d..89b7734 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -3b5beeb8de6acac3220a84461f2aa31d34e14e5f \ No newline at end of file +010ac88e03cb848472de012c67ba676dcbef1a4d \ No newline at end of file
diff --git a/ios/third_party/webkit/BUILD.gn b/ios/third_party/webkit/BUILD.gn index 4a650bf..a4c160a4 100644 --- a/ios/third_party/webkit/BUILD.gn +++ b/ios/third_party/webkit/BUILD.gn
@@ -113,14 +113,14 @@ args = invoker.args - # TODO(crbug.com/934252): "-j 4" restricts xcodebuild to four simultaneous + # TODO(crbug.com/1329824): "-j 8" restricts xcodebuild to eight simultaneous # jobs. This is intended to prevent overloading the machine, because ninja # will already be spawning a large number of jobs in parallel with # xcodebuild, but it causes the webkit build to run very slowly. Find a way # to increase the parallelism here. args += [ "-j", - "4", + "8", "-quiet", ] }
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 072a9a7..c395add 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -540,6 +540,7 @@ "//ios/web/test:mojo_bindings", "//ios/web/test:test_constants", "//ios/web/test:test_support", + "//ios/web/test/fakes", "//ios/web/web_state:web_state_impl_header", "//ios/web/webui", "//net:test_support",
diff --git a/ios/web/favicon/BUILD.gn b/ios/web/favicon/BUILD.gn index afd866e..83a84065 100644 --- a/ios/web/favicon/BUILD.gn +++ b/ios/web/favicon/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//ios/build/config.gni") +import("//ios/web/public/js_messaging/compile_ts.gni") import("//ios/web/public/js_messaging/optimize_js.gni") source_set("favicon") { @@ -24,18 +25,35 @@ ] } +compile_ts("compile_typescript") { + sources = [ + "//ios/web/public/js_messaging/resources/utils.ts", + "resources/favicon.ts", + "resources/favicon_event_listeners.ts", + "resources/favicon_utils.ts", + ] +} + optimize_js("favicon_js") { visibility = [ ":favicon" ] - primary_script = "resources/favicon.js" - sources = [ "resources/favicon.js" ] + _script = filter_include(get_target_outputs(":compile_typescript"), + [ "*favicon.js" ]) + primary_script = _script[0] + sources = _script + + deps = [ ":compile_typescript" ] } optimize_js("favicon_event_listeners_js") { visibility = [ ":favicon" ] - primary_script = "resources/favicon_event_listeners.js" - sources = [ "resources/favicon_event_listeners.js" ] + _script = filter_include(get_target_outputs(":compile_typescript"), + [ "*favicon_event_listeners.js" ]) + primary_script = _script[0] + sources = _script + + deps = [ ":compile_typescript" ] } source_set("unittests") {
diff --git a/ios/web/favicon/resources/favicon.js b/ios/web/favicon/resources/favicon.js deleted file mode 100644 index f9531da..0000000 --- a/ios/web/favicon/resources/favicon.js +++ /dev/null
@@ -1,47 +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. - -/** - * @fileoverview Gets and returns favicons in main frame. This script should be - * injected only into main frame when it's loaded. - */ - -// Requires functions from common.js - -// Store namespace object in a global __gCrWeb object referenced by a string, so -// it does not get renamed by closure compiler during the minification. -__gCrWeb.favicon = {}; -__gCrWeb['favicon'] = __gCrWeb.favicon; - -/** - * Retrieves favicon information. - * - * @return {Object} Object containing favicon data. - */ -function getFavicons() { - var favicons = []; - delete favicons.toJSON; // Never inherit Array.prototype.toJSON. - var links = document.getElementsByTagName('link'); - var linkCount = links.length; - for (var i = 0; i < linkCount; ++i) { - if (links[i].rel) { - var rel = links[i].rel.toLowerCase(); - if (rel == 'shortcut icon' || rel == 'icon' || - rel == 'apple-touch-icon' || rel == 'apple-touch-icon-precomposed') { - var favicon = {rel: links[i].rel.toLowerCase(), href: links[i].href}; - if (links[i].sizes && links[i].sizes.value) { - favicon.sizes = links[i].sizes.value; - } - favicons.push(favicon); - } - } - } - return favicons; -} - -__gCrWeb.favicon.sendFaviconUrls = function() { - __gCrWeb.common.sendWebKitMessage('FaviconUrlsHandler', getFavicons() ); -}; - -__gCrWeb.favicon.sendFaviconUrls();
diff --git a/ios/web/favicon/resources/favicon.ts b/ios/web/favicon/resources/favicon.ts new file mode 100644 index 0000000..09a2995b --- /dev/null +++ b/ios/web/favicon/resources/favicon.ts
@@ -0,0 +1,12 @@ +// Copyright 2022 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. + +/** + * @fileoverview Gets and returns favicons in main frame. This script + * should be injected only into the main frame when it's loaded. + */ + +import { sendFaviconUrls } from "//ios/web/favicon/resources/favicon_utils.js"; + +sendFaviconUrls(); \ No newline at end of file
diff --git a/ios/web/favicon/resources/favicon_event_listeners.js b/ios/web/favicon/resources/favicon_event_listeners.js deleted file mode 100644 index bf158375..0000000 --- a/ios/web/favicon/resources/favicon_event_listeners.js +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2021 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. - -// Requires functions from favicon.js - -window.addEventListener('hashchange', function(evt) { - // Hash changes don't trigger __gCrWeb.didFinishNavigation, so fetch favicons - // for the new page manually. - __gCrWeb.favicon.sendFaviconUrls(); -});
diff --git a/ios/web/favicon/resources/favicon_event_listeners.ts b/ios/web/favicon/resources/favicon_event_listeners.ts new file mode 100644 index 0000000..bd71213 --- /dev/null +++ b/ios/web/favicon/resources/favicon_event_listeners.ts
@@ -0,0 +1,12 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import { sendFaviconUrls } from "//ios/web/favicon/resources/favicon_utils.js"; + +window.addEventListener('hashchange', () => { + // Manually update favicons because hash changes do not trigger + // a reload of injected scripts. + // (Script injection is the only time when favicon.ts send favicons.) + sendFaviconUrls(); +}); \ No newline at end of file
diff --git a/ios/web/favicon/resources/favicon_utils.ts b/ios/web/favicon/resources/favicon_utils.ts new file mode 100644 index 0000000..ade7016 --- /dev/null +++ b/ios/web/favicon/resources/favicon_utils.ts
@@ -0,0 +1,52 @@ +// 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. + +/** + * @fileoverview Provides a function which collects favicon + * details from the current document + */ + +import { sendWebKitMessage } from '//ios/web/public/js_messaging/resources/utils.js' + +declare interface FaviconData { + rel: string, + href: string | undefined, + sizes?: string +} + +/** + * Retrieves favicon information. + * + * @return {FaviconData[]} An array of objects containing favicon data. + */ +function getFavicons(): FaviconData[] { + let favicons: FaviconData[] = []; + let links = document.getElementsByTagName('link'); + let linkCount = links.length; + for (var i = 0; i < linkCount; ++i) { + let link = links[i]; + let rel = link?.rel.toLowerCase(); + + if (rel === 'shortcut icon' || + rel === 'icon' || + rel === 'apple-touch-icon' || + rel === 'apple-touch-icon-precomposed') { + let favicon: FaviconData = + {rel: rel, href: link?.href}; + let size_value = link?.sizes?.value; + + if (size_value) { + favicon.sizes = size_value; + } + favicons.push(favicon); + } + } + return favicons; +} + +function sendFaviconUrls(): void { + sendWebKitMessage('FaviconUrlsHandler', getFavicons()); +} + +export {sendFaviconUrls} \ No newline at end of file
diff --git a/ios/web/public/webui/url_data_source_ios.h b/ios/web/public/webui/url_data_source_ios.h index 4387df2..1924902 100644 --- a/ios/web/public/webui/url_data_source_ios.h +++ b/ios/web/public/webui/url_data_source_ios.h
@@ -67,6 +67,10 @@ // TODO: nuke this and convert all callers to not replace. virtual bool ShouldReplaceExistingSource() const; + // Returns true if i18n replacemenents should be performed in JS files. Needed + // by UIs that use Web Components. + virtual bool ShouldReplaceI18nInJS() const; + // Returns true if responses from this URLDataSourceIOS can be cached. virtual bool AllowCaching() const;
diff --git a/ios/web/public/webui/web_ui_ios_data_source.h b/ios/web/public/webui/web_ui_ios_data_source.h index b9394c45..b8cee35c 100644 --- a/ios/web/public/webui/web_ui_ios_data_source.h +++ b/ios/web/public/webui/web_ui_ios_data_source.h
@@ -54,6 +54,10 @@ // URL that provides translations and dynamic data when requested. virtual void UseStringsJs() = 0; + // Call this to enable i18n replacements in JS files (needed by Web UIs that + // use Web Components). + virtual void EnableReplaceI18nInJS() = 0; + // Adds a mapping between a path name and a resource to return. virtual void AddResourcePath(const std::string& path, int resource_id) = 0;
diff --git a/ios/web/webui/mojo_facade.mm b/ios/web/webui/mojo_facade.mm index 02b033b..b97386a1 100644 --- a/ios/web/webui/mojo_facade.mm +++ b/ios/web/webui/mojo_facade.mm
@@ -19,6 +19,8 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include "base/values.h" +#include "ios/web/public/js_messaging/web_frame.h" +#import "ios/web/public/js_messaging/web_frame_util.h" #include "ios/web/public/thread/web_thread.h" #import "ios/web/public/web_state.h" #include "mojo/public/cpp/bindings/generic_pending_receiver.h" @@ -213,7 +215,10 @@ stringWithFormat: @"Mojo.internal.watchCallbacksHolder.callCallback(%d, %d)", callback_id, result]; - web_state_->ExecuteJavaScript(base::SysNSStringToUTF16(script)); + web::WebFrame* main_frame = web::GetMainFrame(web_state_); + if (main_frame) { + main_frame->ExecuteJavaScript(base::SysNSStringToUTF16(script)); + } }, *callback_id); auto watcher = std::make_unique<mojo::SimpleWatcher>(
diff --git a/ios/web/webui/mojo_facade_unittest.mm b/ios/web/webui/mojo_facade_unittest.mm index 84082e1..7a6aa71 100644 --- a/ios/web/webui/mojo_facade_unittest.mm +++ b/ios/web/webui/mojo_facade_unittest.mm
@@ -11,8 +11,10 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #import "base/test/ios/wait_util.h" +#import "ios/web/public/test/fakes/fake_web_frames_manager.h" #import "ios/web/public/test/fakes/fake_web_state.h" #include "ios/web/public/test/web_test.h" +#import "ios/web/test/fakes/fake_web_frame_impl.h" #include "ios/web/test/mojo_test.mojom.h" #include "ios/web/web_state/web_state_impl.h" #import "testing/gtest_mac.h" @@ -47,14 +49,28 @@ error:nil]; } -class FakeWebStateWithMojoFacade : public FakeWebState { +class FakeWebStateWithInterfaceBinder : public FakeWebState { public: + InterfaceBinder* GetInterfaceBinderForMainFrame() override { + return &interface_binder_; + } + + private: + InterfaceBinder interface_binder_{this}; +}; + +class FakeWebFrameWithMojoFacade : public FakeWebFrameImpl { + public: + FakeWebFrameWithMojoFacade() + : FakeWebFrameImpl(kMainFakeFrameId, /*is_main_frame=*/true, GURL()) {} + void SetWatchId(int watch_id) { watch_id_ = watch_id; } void SetFacade(MojoFacade* facade) { facade_ = facade; } - void ExecuteJavaScript(const std::u16string& javascript) override { - FakeWebState::ExecuteJavaScript(javascript); + bool ExecuteJavaScript(const std::u16string& javascript) override { + bool success = FakeWebFrameImpl::ExecuteJavaScript(javascript); + // Cancel the watch immediately to ensure there are no additional // notifications. // NOTE: This must be done as a side effect of executing the JavaScript. @@ -65,16 +81,13 @@ }, }; EXPECT_TRUE(facade_->HandleMojoMessage(GetJson(cancel_watch)).empty()); - } - InterfaceBinder* GetInterfaceBinderForMainFrame() override { - return &interface_binder_; + return success; } private: int watch_id_; MojoFacade* facade_; // weak - InterfaceBinder interface_binder_{this}; }; } // namespace @@ -84,10 +97,18 @@ protected: MojoFacadeTest() { facade_ = std::make_unique<MojoFacade>(&web_state_); - web_state_.SetFacade(facade_.get()); + + auto web_frames_manager = std::make_unique<web::FakeWebFramesManager>(); + frames_manager_ = web_frames_manager.get(); + web_state_.SetWebFramesManager(std::move(web_frames_manager)); + + auto main_frame = std::make_unique<FakeWebFrameWithMojoFacade>(); + main_frame->SetFacade(facade_.get()); + main_frame_ = main_frame.get(); + frames_manager_->AddWebFrame(std::move(main_frame)); } - FakeWebStateWithMojoFacade* web_state() { return &web_state_; } + FakeWebFrameWithMojoFacade* main_frame() { return main_frame_; } MojoFacade* facade() { return facade_.get(); } void CreateMessagePipe(uint32_t* handle0, uint32_t* handle1) { @@ -119,7 +140,9 @@ } private: - FakeWebStateWithMojoFacade web_state_; + FakeWebStateWithInterfaceBinder web_state_; + web::FakeWebFramesManager* frames_manager_; + FakeWebFrameWithMojoFacade* main_frame_; std::unique_ptr<MojoFacade> facade_; }; @@ -173,7 +196,7 @@ int watch_id = 0; EXPECT_TRUE(base::StringToInt(watch_id_as_string, &watch_id)); - web_state()->SetWatchId(watch_id); + main_frame()->SetWatchId(watch_id); // Write to the other end of the pipe. NSDictionary* write = @{ @@ -189,7 +212,7 @@ EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForJSCompletionTimeout, ^bool { base::RunLoop().RunUntilIdle(); - return !web_state()->GetLastExecutedJavascript().empty(); + return !main_frame()->GetLastJavaScriptCall().empty(); })); NSString* expected_script = @@ -198,7 +221,7 @@ callback_id, MOJO_RESULT_OK]; EXPECT_EQ(base::SysNSStringToUTF16(expected_script), - web_state()->GetLastExecutedJavascript()); + main_frame()->GetLastJavaScriptCall()); CloseHandle(handle0); CloseHandle(handle1);
diff --git a/ios/web/webui/url_data_manager_ios_backend.mm b/ios/web/webui/url_data_manager_ios_backend.mm index 5fe5b55..4619e08 100644 --- a/ios/web/webui/url_data_manager_ios_backend.mm +++ b/ios/web/webui/url_data_manager_ios_backend.mm
@@ -332,8 +332,10 @@ const std::string& mime_type) { set_mime_type(mime_type); - if (mime_type == "text/html") + if (mime_type == "text/html" || (mime_type == "application/javascript" && + source->ShouldReplaceI18nInJS())) { set_source(source); + } NotifyHeadersComplete(); }
diff --git a/ios/web/webui/url_data_source_ios.mm b/ios/web/webui/url_data_source_ios.mm index 5b975d1..f448f82a 100644 --- a/ios/web/webui/url_data_source_ios.mm +++ b/ios/web/webui/url_data_source_ios.mm
@@ -39,4 +39,8 @@ return GetWebClient()->IsAppSpecificURL(url); } +bool URLDataSourceIOS::ShouldReplaceI18nInJS() const { + return false; +} + } // namespace web
diff --git a/ios/web/webui/url_data_source_ios_impl.cc b/ios/web/webui/url_data_source_ios_impl.cc index a8609f4..fef8d8f3 100644 --- a/ios/web/webui/url_data_source_ios_impl.cc +++ b/ios/web/webui/url_data_source_ios_impl.cc
@@ -58,4 +58,8 @@ return nullptr; } +bool URLDataSourceIOSImpl::ShouldReplaceI18nInJS() const { + return false; +} + } // namespace web
diff --git a/ios/web/webui/url_data_source_ios_impl.h b/ios/web/webui/url_data_source_ios_impl.h index 4977888..2526acd 100644 --- a/ios/web/webui/url_data_source_ios_impl.h +++ b/ios/web/webui/url_data_source_ios_impl.h
@@ -68,6 +68,10 @@ // Replacements for i18n or null if no replacements are desired. virtual const ui::TemplateReplacements* GetReplacements() const; + // Whether to perform i18n replacements in JS files (needed by WebUIs that are + // using Web Components). + virtual bool ShouldReplaceI18nInJS() const; + protected: virtual ~URLDataSourceIOSImpl();
diff --git a/ios/web/webui/web_ui_ios_data_source_impl.h b/ios/web/webui/web_ui_ios_data_source_impl.h index e51d584..675d84d6 100644 --- a/ios/web/webui/web_ui_ios_data_source_impl.h +++ b/ios/web/webui/web_ui_ios_data_source_impl.h
@@ -34,6 +34,8 @@ base::span<const webui::LocalizedString> strings) override; void AddBoolean(const std::string& name, bool value) override; void UseStringsJs() override; + void EnableReplaceI18nInJS() override; + bool ShouldReplaceI18nInJS() const override; void AddResourcePath(const std::string& path, int resource_id) override; void SetDefaultResource(int resource_id) override; void DisableDenyXFrameOptions() override; @@ -82,6 +84,7 @@ bool deny_xframe_options_; bool load_time_data_defaults_added_; bool replace_existing_source_; + bool should_replace_i18n_in_js_; }; } // web
diff --git a/ios/web/webui/web_ui_ios_data_source_impl.mm b/ios/web/webui/web_ui_ios_data_source_impl.mm index 4b322c7..b26fc7f2 100644 --- a/ios/web/webui/web_ui_ios_data_source_impl.mm +++ b/ios/web/webui/web_ui_ios_data_source_impl.mm
@@ -51,6 +51,9 @@ bool ShouldReplaceExistingSource() const override { return parent_->replace_existing_source_; } + bool ShouldReplaceI18nInJS() const override { + return parent_->ShouldReplaceI18nInJS(); + } bool AllowCaching() const override { return false; } bool ShouldDenyXFrameOptions() const override { return parent_->deny_xframe_options_; @@ -66,7 +69,8 @@ default_resource_(-1), deny_xframe_options_(true), load_time_data_defaults_added_(false), - replace_existing_source_(true) {} + replace_existing_source_(true), + should_replace_i18n_in_js_(false) {} WebUIIOSDataSourceImpl::~WebUIIOSDataSourceImpl() {} @@ -112,6 +116,14 @@ use_strings_js_ = true; } +void WebUIIOSDataSourceImpl::EnableReplaceI18nInJS() { + should_replace_i18n_in_js_ = true; +} + +bool WebUIIOSDataSourceImpl::ShouldReplaceI18nInJS() const { + return should_replace_i18n_in_js_; +} + void WebUIIOSDataSourceImpl::AddResourcePath(const std::string& path, int resource_id) { path_to_idr_map_[path] = resource_id;
diff --git a/ios/web/webui/web_ui_ios_impl.mm b/ios/web/webui/web_ui_ios_impl.mm index edf67e76..d72ea439 100644 --- a/ios/web/webui/web_ui_ios_impl.mm +++ b/ios/web/webui/web_ui_ios_impl.mm
@@ -12,6 +12,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "ios/web/public/js_messaging/web_frame.h" +#import "ios/web/public/js_messaging/web_frame_util.h" #import "ios/web/public/web_client.h" #include "ios/web/public/webui/web_ui_ios_controller.h" #include "ios/web/public/webui/web_ui_ios_controller_factory.h" @@ -180,7 +181,12 @@ } void WebUIIOSImpl::ExecuteJavascript(const std::u16string& javascript) { - web_state_->ExecuteJavaScript(javascript); + web::WebFrame* main_frame = web::GetMainFrame(web_state_); + if (!main_frame) { + return; + } + + main_frame->ExecuteJavaScript(javascript); } } // namespace web
diff --git a/media/gpu/chromeos/platform_video_frame_utils.cc b/media/gpu/chromeos/platform_video_frame_utils.cc index 96133de..3b5fdac 100644 --- a/media/gpu/chromeos/platform_video_frame_utils.cc +++ b/media/gpu/chromeos/platform_video_frame_utils.cc
@@ -125,7 +125,7 @@ version->name, base::checked_cast<std::string::size_type>(version->name_len)); drmFreeVersion(version); - if (base::LowerCaseEqualsASCII(version_name, "vgem")) + if (base::EqualsCaseInsensitiveASCII(version_name, "vgem")) continue; gbm_device_ = ui::CreateGbmDevice(render_node_file_.GetPlatformFile()); if (gbm_device_)
diff --git a/media/gpu/vaapi/vaapi_unittest.cc b/media/gpu/vaapi/vaapi_unittest.cc index 3f3d6e75..56c2d8b 100644 --- a/media/gpu/vaapi/vaapi_unittest.cc +++ b/media/gpu/vaapi/vaapi_unittest.cc
@@ -785,7 +785,7 @@ version->name, base::checked_cast<std::string::size_type>(version->name_len)); drmFreeVersion(version); - if (base::LowerCaseEqualsASCII(version_name, "vgem")) + if (base::EqualsCaseInsensitiveASCII(version_name, "vgem")) continue; gbm = gbm_create_device(drm_fd.GetPlatformFile());
diff --git a/media/gpu/vaapi/vaapi_wrapper.cc b/media/gpu/vaapi/vaapi_wrapper.cc index 1173321d..355b5f929 100644 --- a/media/gpu/vaapi/vaapi_wrapper.cc +++ b/media/gpu/vaapi/vaapi_wrapper.cc
@@ -577,7 +577,7 @@ version->name, base::checked_cast<std::string::size_type>(version->name_len)); drmFreeVersion(version); - if (base::LowerCaseEqualsASCII(version_name, "vgem")) + if (base::EqualsCaseInsensitiveASCII(version_name, "vgem")) continue; VADisplayState::Get()->SetDrmFd(drm_file.GetPlatformFile()); return;
diff --git a/net/base/network_isolation_key.cc b/net/base/network_isolation_key.cc index 8f138c4..e6fc03ba 100644 --- a/net/base/network_isolation_key.cc +++ b/net/base/network_isolation_key.cc
@@ -165,6 +165,12 @@ if (!frame_site || frame_site->opaque()) return false; + if (base::FeatureList::IsEnabled( + net::features::kForceIsolationInfoFrameOriginToTopLevelFrame) && + frame_site != top_frame_site) { + return false; + } + *network_isolation_key = NetworkIsolationKey(std::move(*top_frame_site), std::move(*frame_site)); return true;
diff --git a/net/base/network_isolation_key_unittest.cc b/net/base/network_isolation_key_unittest.cc index 0a6c7a8..6f05b842 100644 --- a/net/base/network_isolation_key_unittest.cc +++ b/net/base/network_isolation_key_unittest.cc
@@ -284,6 +284,21 @@ // Write the value on failure. EXPECT_FALSE(NetworkIsolationKey::FromValue(test_case, &key)) << test_case; } + + base::Value::ListStorage triple_key_list; + triple_key_list.emplace_back(base::Value("http://www.triple.com")); + triple_key_list.emplace_back(base::Value("http://www.key.com")); + NetworkIsolationKey key; + const auto triple_key_case = base::Value(std::move(triple_key_list)); + + // When double key is enabled top_level_site must equal frame_site. + bool expect_fail_on_different_sites = + ForceIsolationInfoFrameOriginToTopLevelFrameEnabled(); + + if (expect_fail_on_different_sites) { + EXPECT_FALSE(NetworkIsolationKey::FromValue(triple_key_case, &key)) + << triple_key_case; + } } TEST_P(NetworkIsolationKeyTest, WithFrameSite) {
diff --git a/net/http/http_auth_handler_basic.cc b/net/http/http_auth_handler_basic.cc index 009f847d..1b18763 100644 --- a/net/http/http_auth_handler_basic.cc +++ b/net/http/http_auth_handler_basic.cc
@@ -45,7 +45,7 @@ realm->clear(); HttpUtil::NameValuePairsIterator parameters = tokenizer.param_pairs(); while (parameters.GetNext()) { - if (!base::LowerCaseEqualsASCII(parameters.name_piece(), "realm")) + if (!base::EqualsCaseInsensitiveASCII(parameters.name_piece(), "realm")) continue; if (!ConvertToUtf8AndNormalize(parameters.value_piece(), kCharsetLatin1,
diff --git a/net/http/http_auth_handler_digest.cc b/net/http/http_auth_handler_digest.cc index a8018dc..c0a0905 100644 --- a/net/http/http_auth_handler_digest.cc +++ b/net/http/http_auth_handler_digest.cc
@@ -153,10 +153,11 @@ // for the new challenge. std::string original_realm; while (parameters.GetNext()) { - if (base::LowerCaseEqualsASCII(parameters.name_piece(), "stale")) { - if (base::LowerCaseEqualsASCII(parameters.value_piece(), "true")) + if (base::EqualsCaseInsensitiveASCII(parameters.name_piece(), "stale")) { + if (base::EqualsCaseInsensitiveASCII(parameters.value_piece(), "true")) return HttpAuth::AUTHORIZATION_RESULT_STALE; - } else if (base::LowerCaseEqualsASCII(parameters.name_piece(), "realm")) { + } else if (base::EqualsCaseInsensitiveASCII(parameters.name_piece(), + "realm")) { original_realm = parameters.value(); } } @@ -234,32 +235,32 @@ bool HttpAuthHandlerDigest::ParseChallengeProperty(base::StringPiece name, base::StringPiece value) { - if (base::LowerCaseEqualsASCII(name, "realm")) { + if (base::EqualsCaseInsensitiveASCII(name, "realm")) { std::string realm; if (!ConvertToUtf8AndNormalize(value, kCharsetLatin1, &realm)) return false; realm_ = realm; original_realm_ = std::string(value); - } else if (base::LowerCaseEqualsASCII(name, "nonce")) { + } else if (base::EqualsCaseInsensitiveASCII(name, "nonce")) { nonce_ = std::string(value); - } else if (base::LowerCaseEqualsASCII(name, "domain")) { + } else if (base::EqualsCaseInsensitiveASCII(name, "domain")) { domain_ = std::string(value); - } else if (base::LowerCaseEqualsASCII(name, "opaque")) { + } else if (base::EqualsCaseInsensitiveASCII(name, "opaque")) { opaque_ = std::string(value); - } else if (base::LowerCaseEqualsASCII(name, "stale")) { + } else if (base::EqualsCaseInsensitiveASCII(name, "stale")) { // Parse the stale boolean. - stale_ = base::LowerCaseEqualsASCII(value, "true"); - } else if (base::LowerCaseEqualsASCII(name, "algorithm")) { + stale_ = base::EqualsCaseInsensitiveASCII(value, "true"); + } else if (base::EqualsCaseInsensitiveASCII(name, "algorithm")) { // Parse the algorithm. - if (base::LowerCaseEqualsASCII(value, "md5")) { + if (base::EqualsCaseInsensitiveASCII(value, "md5")) { algorithm_ = ALGORITHM_MD5; - } else if (base::LowerCaseEqualsASCII(value, "md5-sess")) { + } else if (base::EqualsCaseInsensitiveASCII(value, "md5-sess")) { algorithm_ = ALGORITHM_MD5_SESS; } else { DVLOG(1) << "Unknown value of algorithm"; return false; // FAIL -- unsupported value of algorithm. } - } else if (base::LowerCaseEqualsASCII(name, "qop")) { + } else if (base::EqualsCaseInsensitiveASCII(name, "qop")) { // Parse the comma separated list of qops. // auth is the only supported qop, and all other values are ignored. // @@ -270,7 +271,7 @@ ','); qop_ = QOP_UNSPECIFIED; while (qop_values.GetNext()) { - if (base::LowerCaseEqualsASCII(qop_values.value_piece(), "auth")) { + if (base::EqualsCaseInsensitiveASCII(qop_values.value_piece(), "auth")) { qop_ = QOP_AUTH; break; }
diff --git a/net/http/http_cache_transaction.cc b/net/http/http_cache_transaction.cc index d675b12..e89c745 100644 --- a/net/http/http_cache_transaction.cc +++ b/net/http/http_cache_transaction.cc
@@ -28,7 +28,7 @@ #include "base/power_monitor/power_monitor.h" #include "base/strings/string_number_conversions.h" // For HexEncode. #include "base/strings/string_piece.h" -#include "base/strings/string_util.h" // For LowerCaseEqualsASCII. +#include "base/strings/string_util.h" // For EqualsCaseInsensitiveASCII. #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/clock.h" @@ -150,7 +150,7 @@ HttpUtil::ValuesIterator v(header_value.begin(), header_value.end(), ','); while (v.GetNext()) { - if (base::LowerCaseEqualsASCII(v.value_piece(), search->value)) + if (base::EqualsCaseInsensitiveASCII(v.value_piece(), search->value)) return true; } }
diff --git a/net/http/http_content_disposition.cc b/net/http/http_content_disposition.cc index 11b1db94..459e7ed 100644 --- a/net/http/http_content_disposition.cc +++ b/net/http/http_content_disposition.cc
@@ -360,9 +360,9 @@ DCHECK(type.find('=') == base::StringPiece::npos); - if (base::LowerCaseEqualsASCII(type, "inline")) { + if (base::EqualsCaseInsensitiveASCII(type, "inline")) { type_ = INLINE; - } else if (base::LowerCaseEqualsASCII(type, "attachment")) { + } else if (base::EqualsCaseInsensitiveASCII(type, "attachment")) { type_ = ATTACHMENT; } else { parse_result_flags_ |= HAS_UNKNOWN_DISPOSITION_TYPE; @@ -404,7 +404,7 @@ HttpUtil::NameValuePairsIterator iter(pos, end, ';'); while (iter.GetNext()) { if (filename.empty() && - base::LowerCaseEqualsASCII(iter.name_piece(), "filename")) { + base::EqualsCaseInsensitiveASCII(iter.name_piece(), "filename")) { DecodeFilenameValue(iter.value(), referrer_charset, &filename, &parse_result_flags_); if (!filename.empty()) { @@ -412,8 +412,8 @@ if (filename[0] == '\'') parse_result_flags_ |= HAS_SINGLE_QUOTED_FILENAME; } - } else if (ext_filename.empty() && - base::LowerCaseEqualsASCII(iter.name_piece(), "filename*")) { + } else if (ext_filename.empty() && base::EqualsCaseInsensitiveASCII( + iter.name_piece(), "filename*")) { DecodeExtValue(iter.raw_value(), &ext_filename); if (!ext_filename.empty()) parse_result_flags_ |= HAS_EXT_FILENAME;
diff --git a/net/http/http_response_headers.cc b/net/http/http_response_headers.cc index 0821f596..3c164476 100644 --- a/net/http/http_response_headers.cc +++ b/net/http/http_response_headers.cc
@@ -110,7 +110,7 @@ bool ShouldUpdateHeader(base::StringPiece name) { for (size_t i = 0; i < std::size(kNonUpdatedHeaders); ++i) { - if (base::LowerCaseEqualsASCII(name, kNonUpdatedHeaders[i])) + if (base::EqualsCaseInsensitiveASCII(name, kNonUpdatedHeaders[i])) return false; } for (size_t i = 0; i < std::size(kNonUpdatedHeaderPrefixes); ++i) { @@ -1293,7 +1293,7 @@ std::string token; while (EnumerateHeader(&iterator, header, &token)) { for (const KeepAliveToken& keep_alive_token : kKeepAliveTokens) { - if (base::LowerCaseEqualsASCII(token, keep_alive_token.token)) + if (base::EqualsCaseInsensitiveASCII(token, keep_alive_token.token)) return keep_alive_token.keep_alive; } }
diff --git a/net/http/http_security_headers.cc b/net/http/http_security_headers.cc index 39eb8191..15defb9 100644 --- a/net/http/http_security_headers.cc +++ b/net/http/http_security_headers.cc
@@ -102,10 +102,11 @@ case DIRECTIVE_END: if (base::IsAsciiWhitespace(token[0])) continue; - if (base::LowerCaseEqualsASCII(token, "max-age")) { + if (base::EqualsCaseInsensitiveASCII(token, "max-age")) { state = AFTER_MAX_AGE_LABEL; max_age_observed++; - } else if (base::LowerCaseEqualsASCII(token, "includesubdomains")) { + } else if (base::EqualsCaseInsensitiveASCII(token, + "includesubdomains")) { state = AFTER_INCLUDE_SUBDOMAINS; include_subdomains_observed++; include_subdomains_candidate = true; @@ -198,7 +199,7 @@ while (name_value_pairs.GetNext()) { base::StringPiece name = name_value_pairs.name_piece(); - if (base::LowerCaseEqualsASCII(name, "max-age")) { + if (base::EqualsCaseInsensitiveASCII(name, "max-age")) { // "A given directive MUST NOT appear more than once in a given header // field." if (parsed_max_age) @@ -208,7 +209,7 @@ return false; } parsed_max_age = true; - } else if (base::LowerCaseEqualsASCII(name, "enforce")) { + } else if (base::EqualsCaseInsensitiveASCII(name, "enforce")) { // "A given directive MUST NOT appear more than once in a given header // field." if (enforce_candidate) @@ -216,7 +217,7 @@ if (!name_value_pairs.value_piece().empty()) return false; enforce_candidate = true; - } else if (base::LowerCaseEqualsASCII(name, "report-uri")) { + } else if (base::EqualsCaseInsensitiveASCII(name, "report-uri")) { // "A given directive MUST NOT appear more than once in a given header // field." if (has_report_uri)
diff --git a/net/http/http_stream_factory_job.cc b/net/http/http_stream_factory_job.cc index c60650b23..550fdf12b 100644 --- a/net/http/http_stream_factory_job.cc +++ b/net/http/http_stream_factory_job.cc
@@ -168,8 +168,10 @@ stream_type_(HttpStreamRequest::BIDIRECTIONAL_STREAM), init_connection_already_resumed_(false) { // Websocket `destination` schemes should be converted to HTTP(S). - DCHECK(base::LowerCaseEqualsASCII(destination_.scheme(), url::kHttpScheme) || - base::LowerCaseEqualsASCII(destination_.scheme(), url::kHttpsScheme)); + DCHECK(base::EqualsCaseInsensitiveASCII(destination_.scheme(), + url::kHttpScheme) || + base::EqualsCaseInsensitiveASCII(destination_.scheme(), + url::kHttpsScheme)); // This class is specific to a single `ProxyServer`, so `proxy_info_` must be // non-empty. Entries beyond the first are ignored. It should simply take a @@ -362,7 +364,8 @@ base::Contains(quic_params->origins_to_force_quic_on, HostPortPair::FromSchemeHostPort(destination))) && proxy_info.is_direct() && - base::LowerCaseEqualsASCII(destination.scheme(), url::kHttpsScheme); + base::EqualsCaseInsensitiveASCII(destination.scheme(), + url::kHttpsScheme); } // static
diff --git a/net/http/http_stream_parser.cc b/net/http/http_stream_parser.cc index 76d3fce..e9cfa31 100644 --- a/net/http/http_stream_parser.cc +++ b/net/http/http_stream_parser.cc
@@ -1019,7 +1019,7 @@ // See // https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/qS63pYso4P0 if (read_buf_->offset() < 3 || scheme != "http" || - !base::LowerCaseEqualsASCII( + !base::EqualsCaseInsensitiveASCII( base::StringPiece(read_buf_->StartOfBuffer(), 3), "icy")) { return ERR_INVALID_HTTP_RESPONSE; }
diff --git a/net/http/http_util.cc b/net/http/http_util.cc index 0116a45..3029855 100644 --- a/net/http/http_util.cc +++ b/net/http/http_util.cc
@@ -114,14 +114,14 @@ // Trim LWS from param value, ParseMimeType() leaves WS for quoted-string. // TODO(mmenke): Check that name has only valid characters. if (!type_has_charset && - base::LowerCaseEqualsASCII(param.first, "charset")) { + base::EqualsCaseInsensitiveASCII(param.first, "charset")) { type_has_charset = true; charset_value = std::string(HttpUtil::TrimLWS(param.second)); continue; } if (boundary && !type_has_boundary && - base::LowerCaseEqualsASCII(param.first, "boundary")) { + base::EqualsCaseInsensitiveASCII(param.first, "boundary")) { type_has_boundary = true; *boundary = std::string(HttpUtil::TrimLWS(param.second)); continue; @@ -154,7 +154,7 @@ // "bytes" unit identifier is not found. bytes_unit = TrimLWS(bytes_unit); - if (!base::LowerCaseEqualsASCII(bytes_unit, "bytes")) { + if (!base::EqualsCaseInsensitiveASCII(bytes_unit, "bytes")) { return false; } @@ -227,7 +227,7 @@ return false; // Invalid header if it doesn't contain "bytes-unit". - if (!base::LowerCaseEqualsASCII( + if (!base::EqualsCaseInsensitiveASCII( TrimLWS(content_range_spec.substr(0, space_position)), "bytes")) { return false; } @@ -332,7 +332,7 @@ return false; for (const char* field : kForbiddenHeaderFields) { - if (base::LowerCaseEqualsASCII(name, field)) + if (base::EqualsCaseInsensitiveASCII(name, field)) return false; } return true; @@ -375,7 +375,7 @@ }; for (const char* header : kNonCoalescingHeaders) { - if (base::LowerCaseEqualsASCII(name, header)) { + if (base::EqualsCaseInsensitiveASCII(name, header)) { return true; } } @@ -518,8 +518,8 @@ if (buf_len >= http_len) { size_t i_max = std::min(buf_len - http_len, slop); for (size_t i = 0; i <= i_max; ++i) { - if (base::LowerCaseEqualsASCII(base::StringPiece(buf + i, http_len), - "http")) + if (base::EqualsCaseInsensitiveASCII(base::StringPiece(buf + i, http_len), + "http")) return i; } } @@ -751,7 +751,7 @@ std::string::const_iterator i = etag_header.begin(); std::string::const_iterator j = etag_header.begin() + slash; TrimLWS(&i, &j); - if (!base::LowerCaseEqualsASCII(base::MakeStringPiece(i, j), "w")) + if (!base::EqualsCaseInsensitiveASCII(base::MakeStringPiece(i, j), "w")) return true; } @@ -870,7 +870,7 @@ << "the header name must be in all lower case"; while (GetNext()) { - if (base::LowerCaseEqualsASCII( + if (base::EqualsCaseInsensitiveASCII( base::MakeStringPiece(name_begin_, name_end_), name)) { return true; } @@ -1049,7 +1049,7 @@ return false; base::StringPiece param_name = params.substr(0, equals_pos); param_name = TrimLWS(param_name); - if (!base::LowerCaseEqualsASCII(param_name, "q")) + if (!base::EqualsCaseInsensitiveASCII(param_name, "q")) return false; base::StringPiece qvalue = params.substr(equals_pos + 1); qvalue = TrimLWS(qvalue);
diff --git a/net/quic/platform/impl/DEPS b/net/quic/platform/impl/DEPS deleted file mode 100644 index 2c12fec5..0000000 --- a/net/quic/platform/impl/DEPS +++ /dev/null
@@ -1,4 +0,0 @@ -include_rules = [ - # Allow string_view.h since absl::string_view is widely used in QUICHE API. - "+third_party/abseil-cpp/absl/strings", -]
diff --git a/net/reporting/reporting_browsing_data_remover_unittest.cc b/net/reporting/reporting_browsing_data_remover_unittest.cc index d7c81ac..86e19da8 100644 --- a/net/reporting/reporting_browsing_data_remover_unittest.cc +++ b/net/reporting/reporting_browsing_data_remover_unittest.cc
@@ -45,8 +45,8 @@ void AddReport(const GURL& url) { cache()->AddReport(absl::nullopt, NetworkIsolationKey(), url, kUserAgent_, kGroup_, kType_, - std::make_unique<base::DictionaryValue>(), 0, - tick_clock()->NowTicks(), 0); + std::make_unique<base::Value>(base::Value::Type::DICT), + 0, tick_clock()->NowTicks(), 0); } // TODO(chlily): Take NIK.
diff --git a/net/reporting/reporting_cache_impl.cc b/net/reporting/reporting_cache_impl.cc index 0bfc777..cff87d8 100644 --- a/net/reporting/reporting_cache_impl.cc +++ b/net/reporting/reporting_cache_impl.cc
@@ -101,35 +101,33 @@ std::vector<base::Value> report_list; for (const ReportingReport* report : sorted_reports) { - base::Value report_dict(base::Value::Type::DICTIONARY); - report_dict.SetKey( - "network_isolation_key", - base::Value(report->network_isolation_key.ToDebugString())); - report_dict.SetKey("url", base::Value(report->url.spec())); - report_dict.SetKey("group", base::Value(report->group)); - report_dict.SetKey("type", base::Value(report->type)); - report_dict.SetKey("depth", base::Value(report->depth)); - report_dict.SetKey("queued", - base::Value(NetLog::TickCountToString(report->queued))); - report_dict.SetKey("attempts", base::Value(report->attempts)); + base::Value::Dict report_dict; + report_dict.Set("network_isolation_key", + report->network_isolation_key.ToDebugString()); + report_dict.Set("url", report->url.spec()); + report_dict.Set("group", report->group); + report_dict.Set("type", report->type); + report_dict.Set("depth", report->depth); + report_dict.Set("queued", NetLog::TickCountToString(report->queued)); + report_dict.Set("attempts", report->attempts); if (report->body) { - report_dict.SetKey("body", report->body->Clone()); + report_dict.Set("body", report->body->Clone()); } switch (report->status) { case ReportingReport::Status::DOOMED: - report_dict.SetKey("status", base::Value("doomed")); + report_dict.Set("status", "doomed"); break; case ReportingReport::Status::PENDING: - report_dict.SetKey("status", base::Value("pending")); + report_dict.Set("status", "pending"); break; case ReportingReport::Status::QUEUED: - report_dict.SetKey("status", base::Value("queued")); + report_dict.Set("status", "queued"); break; case ReportingReport::Status::SUCCESS: - report_dict.SetKey("status", base::Value("success")); + report_dict.Set("status", "success"); break; } - report_list.push_back(std::move(report_dict)); + report_list.emplace_back(base::Value(std::move(report_dict))); } return base::Value(std::move(report_list)); } @@ -1599,10 +1597,10 @@ } base::Value ReportingCacheImpl::GetClientAsValue(const Client& client) const { - base::Value client_dict(base::Value::Type::DICTIONARY); - client_dict.SetKey("network_isolation_key", - base::Value(client.network_isolation_key.ToDebugString())); - client_dict.SetKey("origin", base::Value(client.origin.Serialize())); + base::Value::Dict client_dict; + client_dict.Set("network_isolation_key", + client.network_isolation_key.ToDebugString()); + client_dict.Set("origin", client.origin.Serialize()); std::vector<base::Value> group_list; for (const std::string& group_name : client.endpoint_group_names) { @@ -1612,20 +1610,18 @@ group_list.push_back(GetEndpointGroupAsValue(group)); } - client_dict.SetKey("groups", base::Value(std::move(group_list))); + client_dict.Set("groups", base::Value(std::move(group_list))); - return client_dict; + return base::Value(std::move(client_dict)); } base::Value ReportingCacheImpl::GetEndpointGroupAsValue( const CachedReportingEndpointGroup& group) const { - base::Value group_dict(base::Value::Type::DICTIONARY); - group_dict.SetKey("name", base::Value(group.group_key.group_name)); - group_dict.SetKey("expires", - base::Value(NetLog::TimeToString(group.expires))); - group_dict.SetKey( - "includeSubdomains", - base::Value(group.include_subdomains == OriginSubdomains::INCLUDE)); + base::Value::Dict group_dict; + group_dict.Set("name", group.group_key.group_name); + group_dict.Set("expires", NetLog::TimeToString(group.expires)); + group_dict.Set("includeSubdomains", + group.include_subdomains == OriginSubdomains::INCLUDE); std::vector<base::Value> endpoint_list; @@ -1635,31 +1631,32 @@ endpoint_list.push_back(GetEndpointAsValue(endpoint)); } - group_dict.SetKey("endpoints", base::Value(std::move(endpoint_list))); + group_dict.Set("endpoints", base::Value(std::move(endpoint_list))); - return group_dict; + return base::Value(std::move(group_dict)); } base::Value ReportingCacheImpl::GetEndpointAsValue( const ReportingEndpoint& endpoint) const { - base::Value endpoint_dict(base::Value::Type::DICTIONARY); - endpoint_dict.SetKey("url", base::Value(endpoint.info.url.spec())); - endpoint_dict.SetKey("priority", base::Value(endpoint.info.priority)); - endpoint_dict.SetKey("weight", base::Value(endpoint.info.weight)); + base::Value::Dict endpoint_dict; + endpoint_dict.Set("url", endpoint.info.url.spec()); + endpoint_dict.Set("priority", endpoint.info.priority); + endpoint_dict.Set("weight", endpoint.info.weight); const ReportingEndpoint::Statistics& stats = endpoint.stats; - base::Value successful_dict(base::Value::Type::DICTIONARY); - successful_dict.SetKey("uploads", base::Value(stats.successful_uploads)); - successful_dict.SetKey("reports", base::Value(stats.successful_reports)); - endpoint_dict.SetKey("successful", std::move(successful_dict)); - base::Value failed_dict(base::Value::Type::DICTIONARY); - failed_dict.SetKey("uploads", base::Value(stats.attempted_uploads - - stats.successful_uploads)); - failed_dict.SetKey("reports", base::Value(stats.attempted_reports - - stats.successful_reports)); - endpoint_dict.SetKey("failed", std::move(failed_dict)); + base::Value::Dict successful_dict; + successful_dict.Set("uploads", stats.successful_uploads); + successful_dict.Set("reports", stats.successful_reports); + endpoint_dict.Set("successful", std::move(successful_dict)); - return endpoint_dict; + base::Value::Dict failed_dict; + failed_dict.Set("uploads", + stats.attempted_uploads - stats.successful_uploads); + failed_dict.Set("reports", + stats.attempted_reports - stats.successful_reports); + endpoint_dict.Set("failed", std::move(failed_dict)); + + return base::Value(std::move(endpoint_dict)); } } // namespace net
diff --git a/net/reporting/reporting_cache_unittest.cc b/net/reporting/reporting_cache_unittest.cc index 604b506..03db767 100644 --- a/net/reporting/reporting_cache_unittest.cc +++ b/net/reporting/reporting_cache_unittest.cc
@@ -244,9 +244,9 @@ cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); - cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, - kNowTicks_, 0); + cache()->AddReport( + kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); EXPECT_EQ(1, observer()->cached_reports_update_count()); cache()->GetReports(&reports); @@ -283,12 +283,12 @@ TEST_P(ReportingCacheTest, RemoveAllReports) { LoadReportingClients(); - cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, - kNowTicks_, 0); - cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, - kNowTicks_, 0); + cache()->AddReport( + kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); + cache()->AddReport( + kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); EXPECT_EQ(2, observer()->cached_reports_update_count()); std::vector<const ReportingReport*> reports; @@ -305,9 +305,9 @@ TEST_P(ReportingCacheTest, RemovePendingReports) { LoadReportingClients(); - cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, - kNowTicks_, 0); + cache()->AddReport( + kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); EXPECT_EQ(1, observer()->cached_reports_update_count()); std::vector<const ReportingReport*> reports; @@ -343,9 +343,9 @@ TEST_P(ReportingCacheTest, RemoveAllPendingReports) { LoadReportingClients(); - cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, - kNowTicks_, 0); + cache()->AddReport( + kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); EXPECT_EQ(1, observer()->cached_reports_update_count()); std::vector<const ReportingReport*> reports; @@ -385,12 +385,12 @@ const base::TimeTicks now = base::TimeTicks(); const ReportingReport* report1 = AddAndReturnReport(kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, - std::make_unique<base::DictionaryValue>(), 0, - now + base::Seconds(200), 0); + std::make_unique<base::Value>(base::Value::Type::DICT), + 0, now + base::Seconds(200), 0); const ReportingReport* report2 = AddAndReturnReport(kOtherNik_, kUrl1_, kUserAgent_, kGroup2_, kType_, - std::make_unique<base::DictionaryValue>(), 0, - now + base::Seconds(100), 1); + std::make_unique<base::Value>(base::Value::Type::DICT), + 0, now + base::Seconds(100), 1); // Mark report1 and report2 as pending. EXPECT_THAT(cache()->GetReportsToDeliver(), ::testing::UnorderedElementsAre(report1, report2)); @@ -431,12 +431,12 @@ // Add two new reports that will show up as "queued". const ReportingReport* report3 = AddAndReturnReport(kNik_, kUrl2_, kUserAgent_, kGroup1_, kType_, - std::make_unique<base::DictionaryValue>(), 2, - now + base::Seconds(200), 0); + std::make_unique<base::Value>(base::Value::Type::DICT), + 2, now + base::Seconds(200), 0); const ReportingReport* report4 = AddAndReturnReport(kOtherNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, - std::make_unique<base::DictionaryValue>(), 0, - now + base::Seconds(300), 0); + std::make_unique<base::Value>(base::Value::Type::DICT), + 0, now + base::Seconds(300), 0); actual = cache()->GetReportsAsValue(); expected = base::test::ParseJson(base::StringPrintf( R"json( @@ -505,14 +505,14 @@ // Queue a V1 report for each of these sources, and a V0 report (with a null // source) for the same URL. cache()->AddReport(source1, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, - std::make_unique<base::DictionaryValue>(), 0, kNowTicks_, - 0); - cache()->AddReport(source2, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, - std::make_unique<base::DictionaryValue>(), 0, kNowTicks_, - 0); - cache()->AddReport(absl::nullopt, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); + cache()->AddReport(source2, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, + kNowTicks_, 0); + cache()->AddReport( + absl::nullopt, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); EXPECT_EQ(3, observer()->cached_reports_update_count()); std::vector<const ReportingReport*> reports; @@ -1449,15 +1449,17 @@ // Enqueue the maximum number of reports, spaced apart in time. for (size_t i = 0; i < max_report_count; ++i) { cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, - tick_clock()->NowTicks(), 0); + kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), + 0, tick_clock()->NowTicks(), 0); tick_clock()->Advance(base::Minutes(1)); } EXPECT_EQ(max_report_count, report_count()); // Add one more report to force the cache to evict one. cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, + kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); // Make sure the cache evicted a report to make room for the new one, and make @@ -1480,10 +1482,10 @@ // Enqueue the maximum number of reports, spaced apart in time. std::vector<const ReportingReport*> reports; for (size_t i = 0; i < max_report_count; ++i) { - reports.push_back( - AddAndReturnReport(kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, - std::make_unique<base::DictionaryValue>(), 0, - tick_clock()->NowTicks(), 0)); + reports.push_back(AddAndReturnReport( + kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, + tick_clock()->NowTicks(), 0)); tick_clock()->Advance(base::Minutes(1)); } EXPECT_EQ(max_report_count, report_count()); @@ -1494,9 +1496,9 @@ // Add one more report to force the cache to evict one. Since the cache has // only pending reports, it will be forced to evict the *new* report! - cache()->AddReport(kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, - kType_, std::make_unique<base::DictionaryValue>(), 0, - kNowTicks_, 0); + cache()->AddReport( + kReportingSource_, kNik_, kUrl1_, kUserAgent_, kGroup1_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, kNowTicks_, 0); // Make sure the cache evicted a report, and make sure the report evicted was // the new, non-pending one.
diff --git a/net/reporting/reporting_delivery_agent_unittest.cc b/net/reporting/reporting_delivery_agent_unittest.cc index 341d8b7..270c9403 100644 --- a/net/reporting/reporting_delivery_agent_unittest.cc +++ b/net/reporting/reporting_delivery_agent_unittest.cc
@@ -53,7 +53,7 @@ policy.endpoint_backoff_policy.entry_lifetime_ms = 0; policy.endpoint_backoff_policy.always_use_initial_delay = false; UsePolicy(policy); - report_body_.SetStringKey("key", "value"); + report_body_.GetDict().Set("key", "value"); } void AddReport(const absl::optional<base::UnguessableToken>& reporting_source, @@ -108,7 +108,7 @@ base::test::ScopedFeatureList feature_list_; - base::Value report_body_{base::Value::Type::DICTIONARY}; + base::Value report_body_{base::Value::Type::DICT}; const GURL kUrl_ = GURL("https://origin/path"); const GURL kOtherUrl_ = GURL("https://other-origin/path"); const GURL kSubdomainUrl_ = GURL("https://sub.origin/path"); @@ -158,18 +158,18 @@ auto value = pending_uploads()[0]->GetValue(); ASSERT_TRUE(value->is_list()); - ASSERT_EQ(1u, value->GetListDeprecated().size()); + ASSERT_EQ(1u, value->GetList().size()); - base::Value& report = value->GetListDeprecated()[0]; + base::Value& report = value->GetList()[0]; ASSERT_TRUE(report.is_dict()); - EXPECT_EQ(5u, report.DictSize()); + EXPECT_EQ(5u, report.GetDict().size()); ExpectDictIntegerValue(0, report, "age"); ExpectDictStringValue(kType_, report, "type"); ExpectDictStringValue(kUrl_.spec(), report, "url"); ExpectDictStringValue(kUserAgent_, report, "user_agent"); - base::Value* body = report.FindDictKey("body"); - EXPECT_EQ("value", *body->FindStringKey("key")); + const base::Value::Dict* body = report.GetDict().FindDict("body"); + EXPECT_EQ("value", *body->FindString("key")); } pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); @@ -234,17 +234,17 @@ const auto value = pending_uploads()[0]->GetValue(); ASSERT_TRUE(value->is_list()); - ASSERT_EQ(1u, value->GetListDeprecated().size()); + ASSERT_EQ(1u, value->GetList().size()); - const base::Value& report = value->GetListDeprecated()[0]; + const base::Value& report = value->GetList()[0]; ASSERT_TRUE(report.is_dict()); ExpectDictIntegerValue(0, report, "age"); ExpectDictStringValue(kType_, report, "type"); ExpectDictStringValue(kUrl_.spec(), report, "url"); ExpectDictStringValue(kUserAgent_, report, "user_agent"); - const base::Value* body = report.FindDictKey("body"); - EXPECT_EQ("value", *body->FindStringKey("key")); + const base::Value::Dict* body = report.GetDict().FindDict("body"); + EXPECT_EQ("value", *body->FindString("key")); } pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); @@ -312,18 +312,18 @@ auto value = pending_uploads()[0]->GetValue(); ASSERT_TRUE(value->is_list()); - ASSERT_EQ(1u, value->GetListDeprecated().size()); + ASSERT_EQ(1u, value->GetList().size()); - base::Value& report = value->GetListDeprecated()[0]; + base::Value& report = value->GetList()[0]; ASSERT_TRUE(report.is_dict()); - EXPECT_EQ(5u, report.DictSize()); + EXPECT_EQ(5u, report.GetDict().size()); ExpectDictIntegerValue(0, report, "age"); ExpectDictStringValue(kType_, report, "type"); ExpectDictStringValue(kSubdomainUrl_.spec(), report, "url"); ExpectDictStringValue(kUserAgent_, report, "user_agent"); - base::Value* body = report.FindDictKey("body"); - EXPECT_EQ("value", *body->FindStringKey("key")); + const base::Value::Dict* body = report.GetDict().FindDict("body"); + EXPECT_EQ("value", *body->FindString("key")); } pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); @@ -391,18 +391,18 @@ auto value = pending_uploads()[0]->GetValue(); ASSERT_TRUE(value->is_list()); - ASSERT_EQ(1u, value->GetListDeprecated().size()); + ASSERT_EQ(1u, value->GetList().size()); - base::Value& report = value->GetListDeprecated()[0]; + base::Value& report = value->GetList()[0]; ASSERT_TRUE(report.is_dict()); - EXPECT_EQ(5u, report.DictSize()); + EXPECT_EQ(5u, report.GetDict().size()); ExpectDictIntegerValue(0, report, "age"); ExpectDictStringValue(kType_, report, "type"); ExpectDictStringValue(kUrl_.spec(), report, "url"); ExpectDictStringValue(kUserAgent_, report, "user_agent"); - base::Value* body = report.FindDictKey("body"); - EXPECT_EQ("value", *body->FindStringKey("key")); + const base::Value::Dict* body = report.GetDict().FindDict("body"); + EXPECT_EQ("value", *body->FindString("key")); } pending_uploads()[0]->Complete(ReportingUploader::Outcome::SUCCESS); @@ -472,9 +472,6 @@ static const int kAgeMillis = 12345; - base::DictionaryValue body; - body.SetString("key", "value"); - ASSERT_TRUE(SetEndpointInCache(kGroupKey_, kEndpoint_, kExpires_)); AddReport(kEmptyReportingSource_, kNik_, kUrl_, kGroup_);
diff --git a/net/reporting/reporting_garbage_collector_unittest.cc b/net/reporting/reporting_garbage_collector_unittest.cc index aa27ee9..17de3c1 100644 --- a/net/reporting/reporting_garbage_collector_unittest.cc +++ b/net/reporting/reporting_garbage_collector_unittest.cc
@@ -49,7 +49,7 @@ EXPECT_FALSE(garbage_collection_timer()->IsRunning()); cache()->AddReport(absl::nullopt, kNik_, kUrl_, kUserAgent_, kGroup_, kType_, - std::make_unique<base::DictionaryValue>(), 0, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); EXPECT_TRUE(garbage_collection_timer()->IsRunning()); @@ -61,7 +61,7 @@ TEST_F(ReportingGarbageCollectorTest, Report) { cache()->AddReport(absl::nullopt, kNik_, kUrl_, kUserAgent_, kGroup_, kType_, - std::make_unique<base::DictionaryValue>(), 0, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); garbage_collection_timer()->Fire(); @@ -70,7 +70,7 @@ TEST_F(ReportingGarbageCollectorTest, ExpiredReport) { cache()->AddReport(absl::nullopt, kNik_, kUrl_, kUserAgent_, kGroup_, kType_, - std::make_unique<base::DictionaryValue>(), 0, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); tick_clock()->Advance(2 * policy().max_report_age); garbage_collection_timer()->Fire(); @@ -80,7 +80,7 @@ TEST_F(ReportingGarbageCollectorTest, FailedReport) { cache()->AddReport(absl::nullopt, kNik_, kUrl_, kUserAgent_, kGroup_, kType_, - std::make_unique<base::DictionaryValue>(), 0, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); std::vector<const ReportingReport*> reports; @@ -120,7 +120,8 @@ cache()->SetV1EndpointForTesting(group_key, *kReportingSource_, kIsolationInfo_, kUrl_); cache()->AddReport(kReportingSource_, kNik_, kUrl_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0, + kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); // Mark the source as expired. The source data should be removed as soon as // all reports are delivered.
diff --git a/net/reporting/reporting_header_parser.cc b/net/reporting/reporting_header_parser.cc index 968006c..ceb5879 100644 --- a/net/reporting/reporting_header_parser.cc +++ b/net/reporting/reporting_header_parser.cc
@@ -166,7 +166,7 @@ std::vector<ReportingEndpoint::EndpointInfo> endpoints; - for (const base::Value& endpoint : endpoint_list->GetListDeprecated()) { + for (const base::Value& endpoint : endpoint_list->GetList()) { ReportingEndpoint::EndpointInfo parsed_endpoint; if (ProcessEndpoint(delegate, group_key, endpoint, &parsed_endpoint)) endpoints.push_back(std::move(parsed_endpoint)); @@ -286,8 +286,7 @@ std::vector<ReportingEndpointGroup> parsed_header; - for (size_t i = 0; i < value->GetListDeprecated().size(); i++) { - const base::Value& group_value = value->GetListDeprecated()[i]; + for (const auto& group_value : value->GetList()) { ReportingEndpointGroup parsed_endpoint_group; if (ProcessEndpointGroup(delegate, cache, network_isolation_key, origin, group_value, &parsed_endpoint_group)) { @@ -295,7 +294,7 @@ } } - if (parsed_header.empty() && value->GetListDeprecated().size() > 0) { + if (parsed_header.empty() && value->GetList().size() > 0) { RecordReportingHeaderType(ReportingHeaderType::kReportToInvalid); }
diff --git a/net/reporting/reporting_network_change_observer_unittest.cc b/net/reporting/reporting_network_change_observer_unittest.cc index 913b4415..92370ce 100644 --- a/net/reporting/reporting_network_change_observer_unittest.cc +++ b/net/reporting/reporting_network_change_observer_unittest.cc
@@ -64,7 +64,8 @@ UsePolicy(new_policy); cache()->AddReport(kReportingSource_, kNik_, kUrl_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0, + kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); SetEndpoint(); ASSERT_EQ(1u, report_count()); @@ -83,7 +84,8 @@ UsePolicy(new_policy); cache()->AddReport(kReportingSource_, kNik_, kUrl_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0, + kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); SetEndpoint(); ASSERT_EQ(1u, report_count()); @@ -102,7 +104,8 @@ UsePolicy(new_policy); cache()->AddReport(kReportingSource_, kNik_, kUrl_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0, + kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); SetEndpoint(); ASSERT_EQ(1u, report_count()); @@ -121,7 +124,8 @@ UsePolicy(new_policy); cache()->AddReport(kReportingSource_, kNik_, kUrl_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0, + kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0, tick_clock()->NowTicks(), 0); SetEndpoint(); ASSERT_EQ(1u, report_count());
diff --git a/net/reporting/reporting_service.cc b/net/reporting/reporting_service.cc index ac9f499c9..b8665609 100644 --- a/net/reporting/reporting_service.cc +++ b/net/reporting/reporting_service.cc
@@ -157,11 +157,11 @@ } base::Value StatusAsValue() const override { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("reportingEnabled", base::Value(true)); - dict.SetKey("clients", context_->cache()->GetClientsAsValue()); - dict.SetKey("reports", context_->cache()->GetReportsAsValue()); - return dict; + base::Value::Dict dict; + dict.Set("reportingEnabled", true); + dict.Set("clients", context_->cache()->GetClientsAsValue()); + dict.Set("reports", context_->cache()->GetReportsAsValue()); + return base::Value(std::move(dict)); } std::vector<const ReportingReport*> GetReports() const override {
diff --git a/net/reporting/reporting_service_unittest.cc b/net/reporting/reporting_service_unittest.cc index 6b30051..6d40b21 100644 --- a/net/reporting/reporting_service_unittest.cc +++ b/net/reporting/reporting_service_unittest.cc
@@ -112,8 +112,9 @@ }; TEST_P(ReportingServiceTest, QueueReport) { - service()->QueueReport(kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); FinishLoading(true /* load_success */); std::vector<const ReportingReport*> reports; @@ -129,8 +130,9 @@ TEST_P(ReportingServiceTest, QueueReportSanitizeUrl) { // Same as kUrl_ but with username, password, and fragment. GURL url = GURL("https://username:password@origin/path#fragment"); - service()->QueueReport(url, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + url, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); FinishLoading(true /* load_success */); std::vector<const ReportingReport*> reports; @@ -147,8 +149,9 @@ GURL url = GURL("https://"); // This does not trigger an attempt to load from the store because the url // is immediately rejected as invalid. - service()->QueueReport(url, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + url, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); std::vector<const ReportingReport*> reports; context()->cache()->GetReports(&reports); @@ -163,8 +166,9 @@ // Re-create the store, so it reads the new feature value. Init(); - service()->QueueReport(kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); FinishLoading(true /* load_success */); std::vector<const ReportingReport*> reports; @@ -256,8 +260,9 @@ service()->SetDocumentReportingEndpoints(*kReportingSource_, kOrigin_, kIsolationInfo_, *parsed_header); // This report should be sent immediately, starting the delivery agent timer. - service()->QueueReport(kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); FinishLoading(true /* load_success */); @@ -291,8 +296,9 @@ service()->SetDocumentReportingEndpoints(*kReportingSource_, kOrigin_, kIsolationInfo_, *parsed_header); // This report should be sent immediately, starting the delivery agent timer. - service()->QueueReport(kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); FinishLoading(true /* load_success */); @@ -305,8 +311,9 @@ ReportingReport::Status::PENDING)); // Queue another report, which should remain queued. - service()->QueueReport(kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); EXPECT_EQ(1u, context()->cache()->GetReportCountWithStatusForTesting( ReportingReport::Status::QUEUED)); EXPECT_EQ(1u, context()->cache()->GetReportCountWithStatusForTesting( @@ -460,8 +467,9 @@ EXPECT_THAT(store()->GetAllCommands(), testing::UnorderedElementsAreArray(expected_commands)); - service()->QueueReport(kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); expected_commands.emplace_back( CommandType::UPDATE_REPORTING_ENDPOINT_GROUP_ACCESS_TIME, kGroupKey_); EXPECT_THAT(store()->GetAllCommands(), @@ -521,8 +529,9 @@ EXPECT_THAT(store()->GetAllCommands(), testing::UnorderedElementsAreArray(expected_commands)); - service()->QueueReport(kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, - kType_, std::make_unique<base::DictionaryValue>(), 0); + service()->QueueReport( + kUrl_, kReportingSource_, kNik_, kUserAgent_, kGroup_, kType_, + std::make_unique<base::Value>(base::Value::Type::DICT), 0); EXPECT_THAT(store()->GetAllCommands(), testing::UnorderedElementsAreArray(expected_commands));
diff --git a/services/device/geolocation/network_location_provider_unittest.cc b/services/device/geolocation/network_location_provider_unittest.cc index 59a96b3..3c102053 100644 --- a/services/device/geolocation/network_location_provider_unittest.cc +++ b/services/device/geolocation/network_location_provider_unittest.cc
@@ -19,6 +19,8 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/bind.h" +#include "base/test/repeating_test_future.h" #include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" @@ -40,6 +42,8 @@ namespace device { +using ::base::test::RepeatingTestFuture; + // Records the most recent position update and counts the number of times // OnLocationUpdate is called. struct LocationUpdateListener { @@ -440,6 +444,8 @@ mojom::Geoposition position = provider->GetPosition(); EXPECT_FALSE(ValidateGeoposition(position)); + EXPECT_EQ("Did not provide a good position fix", position.error_message); + EXPECT_TRUE(position.error_technical.empty()); // 2. Now wifi data arrives -- SetData will notify listeners. const int kFirstScanAps = 6; @@ -503,6 +509,12 @@ // Error means we now no longer have a fix. position = provider->GetPosition(); EXPECT_FALSE(ValidateGeoposition(position)); + EXPECT_EQ("Network error. Check DevTools console for more information.", + position.error_message); + EXPECT_EQ( + "Network location provider at 'https://www.googleapis.com/' : " + "ERR_FAILED.", + position.error_technical); // 7. Wifi scan returns to original set: should be serviced from cache. wifi_data_provider_->SetData(CreateReferenceWifiScanData(kFirstScanAps)); @@ -579,6 +591,57 @@ CheckRequestIsValid(kScanCount, 0); } +TEST_F(GeolocationNetworkProviderTest, NetworkRequestServiceBadRequest) { + std::unique_ptr<LocationProvider> provider(CreateProvider(true)); + provider->StartProvider(false); + ASSERT_EQ(1, test_url_loader_factory_.NumPending()); + + RepeatingTestFuture<mojom::GeopositionPtr> future; + provider->SetUpdateCallback( + base::BindLambdaForTesting([&future](const LocationProvider* provider, + const mojom::Geoposition& position) { + future.AddValue(position.Clone()); + })); + const std::string& request_url = + test_url_loader_factory_.pending_requests()->back().request.url.spec(); + test_url_loader_factory_.AddResponse(request_url, std::string(), + net::HTTP_BAD_REQUEST); + + auto position = future.Take(); + EXPECT_EQ( + "Failed to query location from network service. Check the DevTools " + "console for more information.", + position->error_message); + EXPECT_EQ( + "Network location provider at 'https://www.googleapis.com/' : Returned " + "error code 400.", + position->error_technical); +} + +TEST_F(GeolocationNetworkProviderTest, NetworkRequestResponseMalformed) { + std::unique_ptr<LocationProvider> provider(CreateProvider(true)); + provider->StartProvider(false); + ASSERT_EQ(1, test_url_loader_factory_.NumPending()); + + RepeatingTestFuture<mojom::GeopositionPtr> future; + provider->SetUpdateCallback( + base::BindLambdaForTesting([&future](const LocationProvider* provider, + const mojom::Geoposition& position) { + future.AddValue(position.Clone()); + })); + const std::string& request_url = + test_url_loader_factory_.pending_requests()->back().request.url.spec(); + const char* kMalformedResponse = + "{" + " \"status MALFORMED\"" + "}"; + test_url_loader_factory_.AddResponse(request_url, kMalformedResponse); + + auto position = future.Take(); + EXPECT_EQ("Response was malformed", position->error_message); + EXPECT_TRUE(position->error_technical.empty()); +} + #if BUILDFLAG(IS_MAC) // Tests that, callbacks and network requests are never made until we have // system location permission.
diff --git a/services/device/geolocation/network_location_request.cc b/services/device/geolocation/network_location_request.cc index 033091c..8b6032b4 100644 --- a/services/device/geolocation/network_location_request.cc +++ b/services/device/geolocation/network_location_request.cc
@@ -166,6 +166,7 @@ url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); + url_loader_->SetAllowHttpErrorResults(true); std::string upload_data; FormUploadData(wifi_data, wifi_timestamp, &upload_data); @@ -290,16 +291,22 @@ } void FormatPositionError(const GURL& server_url, - const std::string& message, + const std::string& error_message, + const std::string& error_technical, mojom::Geoposition* position) { position->error_code = mojom::Geoposition::ErrorCode::POSITION_UNAVAILABLE; - position->error_message = "Network location provider at '"; - position->error_message += server_url.DeprecatedGetOriginAsURL().spec(); - position->error_message += "' : "; - position->error_message += message; - position->error_message += "."; + position->error_message = error_message; VLOG(1) << "NetworkLocationRequest::GetLocationFromResponse() : " << position->error_message; + if (!error_technical.empty()) { + position->error_technical = "Network location provider at '"; + position->error_technical += server_url.DeprecatedGetOriginAsURL().spec(); + position->error_technical += "' : "; + position->error_technical += error_technical; + position->error_technical += "."; + VLOG(1) << "NetworkLocationRequest::GetLocationFromResponse() : " + << position->error_technical; + } } void GetLocationFromResponse(int net_error, @@ -312,8 +319,10 @@ // HttpPost can fail for a number of reasons. Most likely this is because // we're offline, or there was no response. if (net_error != net::OK) { - FormatPositionError(server_url, net::ErrorToShortString(net_error), - position); + FormatPositionError(server_url, + "Network error. Check " + "DevTools console for more information.", + net::ErrorToShortString(net_error), position); RecordUmaEvent(NETWORK_LOCATION_REQUEST_EVENT_RESPONSE_EMPTY); RecordUmaNetError(net_error); return; @@ -322,7 +331,10 @@ if (status_code != 200) { // HTTP OK. std::string message = "Returned error code "; message += base::NumberToString(status_code); - FormatPositionError(server_url, message, position); + FormatPositionError(server_url, + "Failed to query location from network service. Check " + "the DevTools console for more information.", + message, position); RecordUmaEvent(NETWORK_LOCATION_REQUEST_EVENT_RESPONSE_NOT_OK); return; } @@ -331,8 +343,8 @@ // this position fix. DCHECK(response_body); if (!ParseServerResponse(*response_body, wifi_timestamp, position)) { - // We failed to parse the repsonse. - FormatPositionError(server_url, "Response was malformed", position); + // We failed to parse the response. + FormatPositionError(server_url, "Response was malformed", "", position); RecordUmaEvent(NETWORK_LOCATION_REQUEST_EVENT_RESPONSE_MALFORMED); return; } @@ -340,7 +352,7 @@ // The response was successfully parsed, but it may not be a valid // position fix. if (!ValidateGeoposition(*position)) { - FormatPositionError(server_url, "Did not provide a good position fix", + FormatPositionError(server_url, "Did not provide a good position fix", "", position); RecordUmaEvent(NETWORK_LOCATION_REQUEST_EVENT_RESPONSE_INVALID_FIX); return;
diff --git a/services/device/public/mojom/geoposition.mojom b/services/device/public/mojom/geoposition.mojom index 0fd5b0c..4301423 100644 --- a/services/device/public/mojom/geoposition.mojom +++ b/services/device/public/mojom/geoposition.mojom
@@ -57,4 +57,6 @@ ErrorCode error_code = NONE; // Human-readable error message. string error_message; + // Technical detail of the error. + string error_technical; };
diff --git a/storage/browser/file_system/file_system_url.cc b/storage/browser/file_system/file_system_url.cc index f30c964..95603ba 100644 --- a/storage/browser/file_system/file_system_url.cc +++ b/storage/browser/file_system/file_system_url.cc
@@ -162,6 +162,9 @@ ss << path_.value(); } ss << ", storage key: " << storage_key_.GetDebugString(); + if (bucket_.has_value()) { + ss << ", bucket id: " << bucket_->id; + } ss << " }"; return ss.str(); } @@ -172,7 +175,7 @@ bool FileSystemURL::IsInSameFileSystem(const FileSystemURL& other) const { return origin() == other.origin() && type() == other.type() && - filesystem_id() == other.filesystem_id(); + filesystem_id() == other.filesystem_id() && bucket() == other.bucket(); } bool FileSystemURL::operator==(const FileSystemURL& that) const { @@ -181,7 +184,7 @@ } else { return storage_key() == that.storage_key() && type_ == that.type_ && path_ == that.path_ && filesystem_id_ == that.filesystem_id_ && - is_valid_ == that.is_valid_; + is_valid_ == that.is_valid_ && bucket_ == that.bucket_; } } @@ -194,6 +197,8 @@ return lhs.type_ < rhs.type_; if (lhs.filesystem_id_ != rhs.filesystem_id_) return lhs.filesystem_id_ < rhs.filesystem_id_; + if (lhs.bucket_ != rhs.bucket_) + return lhs.bucket_ < rhs.bucket_; return lhs.path_ < rhs.path_; }
diff --git a/storage/browser/file_system/file_system_url_unittest.cc b/storage/browser/file_system/file_system_url_unittest.cc index 3a818c4..561e0fef 100644 --- a/storage/browser/file_system/file_system_url_unittest.cc +++ b/storage/browser/file_system/file_system_url_unittest.cc
@@ -9,6 +9,7 @@ #include <utility> #include "base/files/file_path.h" +#include "base/strings/string_number_conversions.h" #include "storage/common/file_system/file_system_types.h" #include "storage/common/file_system/file_system_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -23,6 +24,8 @@ #define DRIVE FPL("/a/") #endif +constexpr int kBucketId = 1; + namespace storage { namespace { @@ -38,6 +41,13 @@ return path.NormalizePathSeparators().AsUTF8Unsafe(); } +BucketLocator CreateNonDefaultBucket() { + return BucketLocator( + BucketId::FromUnsafeValue(kBucketId), + blink::StorageKey::CreateFromStringForTesting("http://www.example.com/"), + blink::mojom::StorageType::kTemporary, /*is_default=*/false); +} + } // namespace TEST(FileSystemURLTest, ParsePersistent) { @@ -119,12 +129,25 @@ } } - const FileSystemURL a = CreateFileSystemURL( + FileSystemURL a = CreateFileSystemURL( "filesystem:http://chromium.org/temporary/dir a/file a"); - const FileSystemURL b = CreateFileSystemURL( + FileSystemURL b = CreateFileSystemURL( "filesystem:http://chromium.org/persistent/dir a/file a"); EXPECT_EQ(a.type() < b.type(), compare(a, b)); EXPECT_EQ(b.type() < a.type(), compare(b, a)); + + // Testing comparison between FileSystemURLs that have a non-empty, + // non-default bucket value set. + BucketLocator bucket = CreateNonDefaultBucket(); + a.SetBucket(bucket); + b.SetBucket(bucket); + // An identical bucket added to each URL does not alter type mismatch. + EXPECT_EQ(a.type() < b.type(), compare(a, b)); + // c is a copy of a, just without a bucket value set. + const FileSystemURL c = CreateFileSystemURL( + "filesystem:http://chromium.org/temporary/dir a/file a"); + // Ensure that buckets are taken into consideration for comparison. + EXPECT_EQ(a.bucket() < c.bucket(), compare(a, c)); } TEST(FileSystemURLTest, IsParent) { @@ -196,6 +219,15 @@ EXPECT_EQ("{ path: " + NormalizedUTF8Path(kPath) + ", storage key: " + kURL1.storage_key().GetDebugString() + " }", kURL2.DebugString()); + FileSystemURL kURL3 = FileSystemURL::CreateForTest( + blink::StorageKey::CreateFromStringForTesting("http://example.com"), + kFileSystemTypeTemporary, kPath); + kURL3.SetBucket(CreateNonDefaultBucket()); + EXPECT_EQ("{ uri: filesystem:http://example.com/temporary/" + + NormalizedUTF8Path(kPath) + + ", storage key: " + kURL3.storage_key().GetDebugString() + + ", bucket id: " + base::NumberToString(kBucketId) + " }", + kURL3.DebugString()); } TEST(FileSystemURLTest, IsInSameFileSystem) { @@ -220,6 +252,18 @@ EXPECT_FALSE(url_foo_temp_a.IsInSameFileSystem(url_foo_perm_a)); EXPECT_FALSE(url_foo_temp_a.IsInSameFileSystem(url_bar_temp_a)); EXPECT_FALSE(url_foo_temp_a.IsInSameFileSystem(url_bar_perm_a)); + + // Test that non-empty, non-default bucket values are taken into account when + // determining of two URLs are in the same FileSystem. + BucketLocator bucket = CreateNonDefaultBucket(); + url_foo_temp_a.SetBucket(bucket); + url_foo_temp_b.SetBucket(bucket); + EXPECT_TRUE(url_foo_temp_a.IsInSameFileSystem(url_foo_temp_b)); + // url_foo_temp_c is identical to url_foo_temp_a but without a bucket value. + FileSystemURL url_foo_temp_c = FileSystemURL::CreateForTest( + blink::StorageKey::CreateFromStringForTesting("http://foo"), + kFileSystemTypeTemporary, base::FilePath::FromUTF8Unsafe("a")); + EXPECT_FALSE(url_foo_temp_a.IsInSameFileSystem(url_foo_temp_c)); } TEST(FileSystemURLTest, ValidAfterMoves) {
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 3e3c2bf7..9546fd0 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -5865,21 +5865,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5086.0", + "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -5892,7 +5892,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "isolate_profile_data": true, @@ -6030,21 +6030,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -6056,7 +6056,7 @@ }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "args": [ @@ -6176,21 +6176,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -6202,7 +6202,7 @@ }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "isolate_profile_data": true,
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 8a75feaa..82eb5e2 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -88037,21 +88037,21 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5086.0", + "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", @@ -88059,7 +88059,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "isolate_profile_data": true, @@ -88172,28 +88172,28 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "args": [ @@ -88293,28 +88293,28 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "isolate_profile_data": true, "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "isolate_profile_data": true, @@ -89652,20 +89652,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5086.0", + "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -89679,7 +89679,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "merge": { @@ -89817,20 +89817,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -89843,7 +89843,7 @@ }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "args": [ @@ -89963,20 +89963,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -89989,7 +89989,7 @@ }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "merge": { @@ -91485,20 +91485,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5086.0", + "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -91512,7 +91512,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "merge": { @@ -91650,20 +91650,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -91676,7 +91676,7 @@ }, "test": "lacros_chrome_browsertests", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "args": [ @@ -91796,20 +91796,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5086.0", + "name": "lacros_chrome_browsertests_run_in_series Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -91822,7 +91822,7 @@ }, "test": "lacros_chrome_browsertests_run_in_series", "test_id_prefix": "ninja://chrome/test:lacros_chrome_browsertests_run_in_series/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" }, { "merge": { @@ -92557,20 +92557,20 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome" ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" }, - "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5086.0", + "name": "interactive_ui_tests Lacros version skew testing ash 104.0.5087.0", "swarming": { "can_use_on_swarming_builders": true, "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v104.0.5086.0", - "revision": "version:104.0.5086.0" + "location": "lacros_version_skew_tests_v104.0.5087.0", + "revision": "version:104.0.5087.0" } ], "dimension_sets": [ @@ -92583,7 +92583,7 @@ }, "test": "interactive_ui_tests", "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/", - "variant_id": "Lacros version skew testing ash 104.0.5086.0" + "variant_id": "Lacros version skew testing ash 104.0.5087.0" } ] },
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index ce65c18e..d319d40 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -22,15 +22,15 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5086.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v104.0.5087.0/test_ash_chrome', ], - 'identifier': 'Lacros version skew testing ash 104.0.5086.0', + 'identifier': 'Lacros version skew testing ash 104.0.5087.0', 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v104.0.5086.0', - 'revision': 'version:104.0.5086.0', + 'location': 'lacros_version_skew_tests_v104.0.5087.0', + 'revision': 'version:104.0.5087.0', }, ], },
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index fe7426a..4cde762 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -3009,7 +3009,7 @@ ], "experiments": [ { - "name": "RecipeTasksRuleBasedDiscountDriveManagedUsersPhotos_Enabled", + "name": "RecipeTasksRuleBasedDiscountDriveManagedUsersCartOptimizeRecipeTasksSAPIV2Fre_Enabled", "params": { "NtpChromeCartModuleAbandonedCartDiscountParam": "true", "NtpChromeCartModuleAbandonedCartDiscountUseUtmParam": "true", @@ -3017,8 +3017,8 @@ "NtpDriveModuleExperimentGroupParam": "foo:bar", "NtpDriveModuleManagedUsersOnlyParam": "true", "NtpModulesLoadTimeoutMillisecondsParam": "3000", - "NtpModulesOrderParam": "", - "discount-fetch-delay": "1h" + "discount-fetch-delay": "1h", + "use_sapi_v2": "true" }, "enable_features": [ "NtpChromeCartModule", @@ -3047,6 +3047,7 @@ "NtpChromeCartModule", "NtpDriveModule", "NtpModules", + "NtpModulesFirstRunExperience", "NtpRecipeTasksModule" ], "disable_features": [ @@ -6324,25 +6325,6 @@ ] } ], - "PerProcessReclaimArcVmOnFirstMemoryPressure": [ - { - "platforms": [ - "chromeos" - ], - "experiments": [ - { - "name": "EnabledGroupB_DropCachesOnly_20220513", - "params": { - "OnlyDropCachesOnFirstMemoryPressureAfterArcVmBoot": "true", - "TrimArcVmOnFirstMemoryPressureAfterArcVmBoot": "true" - }, - "enable_features": [ - "TrimArcVmOnMemoryPressure" - ] - } - ] - } - ], "PercentDroppedFramesSlidingWindow": [ { "platforms": [
diff --git a/third_party/blink/common/web_package/web_package_request_matcher.cc b/third_party/blink/common/web_package/web_package_request_matcher.cc index 2d1b9a6..d119713f 100644 --- a/third_party/blink/common/web_package/web_package_request_matcher.cc +++ b/third_party/blink/common/web_package/web_package_request_matcher.cc
@@ -71,7 +71,8 @@ item.value = name_value_pairs.name(); item.weight = 1.0; while (name_value_pairs.GetNext()) { - if (base::LowerCaseEqualsASCII(name_value_pairs.name_piece(), "q")) { + if (base::EqualsCaseInsensitiveASCII(name_value_pairs.name_piece(), + "q")) { if (auto value = GetQValue(name_value_pairs.value())) item.weight = *value; } else {
diff --git a/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc b/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc index 13316fd..5f08567b 100644 --- a/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc +++ b/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc
@@ -118,14 +118,14 @@ const CSSValue* value = CSSParser::ParseSingleValue( CSSPropertyID::kGridTemplateColumns, "repeat(1000000, 10%)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1000000); } TEST(CSSPropertyParserTest, GridTrackLimit4) { const CSSValue* value = CSSParser::ParseSingleValue( CSSPropertyID::kGridTemplateRows, "repeat(1000000, 10%)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1000000); } TEST(CSSPropertyParserTest, GridTrackLimit5) { @@ -133,7 +133,7 @@ CSSPropertyID::kGridTemplateColumns, "repeat(1000000, [first] min-content [last])", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1000000); } TEST(CSSPropertyParserTest, GridTrackLimit6) { @@ -141,21 +141,21 @@ CSSPropertyID::kGridTemplateRows, "repeat(1000000, [first] min-content [last])", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1000000); } TEST(CSSPropertyParserTest, GridTrackLimit7) { const CSSValue* value = CSSParser::ParseSingleValue( CSSPropertyID::kGridTemplateColumns, "repeat(1000001, auto)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1000001); } TEST(CSSPropertyParserTest, GridTrackLimit8) { const CSSValue* value = CSSParser::ParseSingleValue( CSSPropertyID::kGridTemplateRows, "repeat(1000001, auto)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1000001); } TEST(CSSPropertyParserTest, GridTrackLimit9) { @@ -163,7 +163,7 @@ CSSPropertyID::kGridTemplateColumns, "repeat(400000, 2em minmax(10px, max-content) 0.5fr)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 99999); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1200000); } TEST(CSSPropertyParserTest, GridTrackLimit10) { @@ -171,7 +171,7 @@ CSSPropertyID::kGridTemplateRows, "repeat(400000, 2em minmax(10px, max-content) 0.5fr)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 99999); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 1200000); } TEST(CSSPropertyParserTest, GridTrackLimit11) { @@ -179,7 +179,7 @@ CSSPropertyID::kGridTemplateColumns, "repeat(600000, [first] 3vh 10% 2fr [nav] 10px auto 1fr 6em [last])", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 99995); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 4200000); } TEST(CSSPropertyParserTest, GridTrackLimit12) { @@ -187,7 +187,7 @@ CSSPropertyID::kGridTemplateRows, "repeat(600000, [first] 3vh 10% 2fr [nav] 10px auto 1fr 6em [last])", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 99995); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 4200000); } TEST(CSSPropertyParserTest, GridTrackLimit13) { @@ -195,7 +195,7 @@ CSSPropertyID::kGridTemplateColumns, "repeat(100000000000000000000, 10% 1fr)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), INT_MAX - 1); } TEST(CSSPropertyParserTest, GridTrackLimit14) { @@ -203,7 +203,7 @@ CSSPropertyID::kGridTemplateRows, "repeat(100000000000000000000, 10% 1fr)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 100000); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), INT_MAX - 1); } TEST(CSSPropertyParserTest, GridTrackLimit15) { @@ -211,7 +211,7 @@ CSSPropertyID::kGridTemplateColumns, "repeat(100000000000000000000, 10% 5em 1fr auto auto 15px min-content)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 99995); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), INT_MAX - 1); } TEST(CSSPropertyParserTest, GridTrackLimit16) { @@ -219,7 +219,7 @@ CSSPropertyID::kGridTemplateRows, "repeat(100000000000000000000, 10% 5em 1fr auto auto 15px min-content)", StrictCSSParserContext(SecureContextMode::kSecureContext)); - EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), 99995); + EXPECT_EQ(ComputeNumberOfTracks(To<CSSValueList>(value)), INT_MAX - 1); } static int GetGridPositionInteger(const CSSValue& value) { @@ -243,7 +243,7 @@ CSSPropertyID::kGridColumnEnd, "1000000", StrictCSSParserContext(SecureContextMode::kSecureContext)); DCHECK(value); - EXPECT_EQ(GetGridPositionInteger(*value), 100000); + EXPECT_EQ(GetGridPositionInteger(*value), 1000000); } TEST(CSSPropertyParserTest, GridPositionLimit3) { @@ -251,7 +251,7 @@ CSSPropertyID::kGridRowStart, "1000001", StrictCSSParserContext(SecureContextMode::kSecureContext)); DCHECK(value); - EXPECT_EQ(GetGridPositionInteger(*value), 100000); + EXPECT_EQ(GetGridPositionInteger(*value), 1000001); } TEST(CSSPropertyParserTest, GridPositionLimit4) { @@ -259,7 +259,7 @@ CSSPropertyID::kGridRowEnd, "5000000000", StrictCSSParserContext(SecureContextMode::kSecureContext)); DCHECK(value); - EXPECT_EQ(GetGridPositionInteger(*value), 100000); + EXPECT_EQ(GetGridPositionInteger(*value), INT_MAX - 1); } TEST(CSSPropertyParserTest, GridPositionLimit5) { @@ -275,7 +275,7 @@ CSSPropertyID::kGridColumnEnd, "-1000000", StrictCSSParserContext(SecureContextMode::kSecureContext)); DCHECK(value); - EXPECT_EQ(GetGridPositionInteger(*value), -100000); + EXPECT_EQ(GetGridPositionInteger(*value), -1000000); } TEST(CSSPropertyParserTest, GridPositionLimit7) { @@ -283,7 +283,7 @@ CSSPropertyID::kGridRowStart, "-1000001", StrictCSSParserContext(SecureContextMode::kSecureContext)); DCHECK(value); - EXPECT_EQ(GetGridPositionInteger(*value), -100000); + EXPECT_EQ(GetGridPositionInteger(*value), -1000001); } TEST(CSSPropertyParserTest, GridPositionLimit8) { @@ -291,7 +291,7 @@ CSSPropertyID::kGridRowEnd, "-5000000000", StrictCSSParserContext(SecureContextMode::kSecureContext)); DCHECK(value); - EXPECT_EQ(GetGridPositionInteger(*value), -100000); + EXPECT_EQ(GetGridPositionInteger(*value), 1 - INT_MAX); } TEST(CSSPropertyParserTest, ColorFunction) {
diff --git a/third_party/blink/renderer/core/css/pending_sheet_type.cc b/third_party/blink/renderer/core/css/pending_sheet_type.cc index d5c99c29..5d4bfee90 100644 --- a/third_party/blink/renderer/core/css/pending_sheet_type.cc +++ b/third_party/blink/renderer/core/css/pending_sheet_type.cc
@@ -28,11 +28,11 @@ ? RenderBlockingBehavior::kInBodyParserBlocking : RenderBlockingBehavior::kBlocking); } - bool has_render_blocking_attr = + bool potentially_render_blocking = RuntimeEnabledFeatures::BlockingAttributeEnabled() && - BlockingAttribute::IsExplicitlyRenderBlocking( - sheet_owner.FastGetAttribute(html_names::kBlockingAttr)); - return has_render_blocking_attr + IsA<HTMLElement>(sheet_owner) && + To<HTMLElement>(sheet_owner).IsPotentiallyRenderBlocking(); + return potentially_render_blocking ? std::make_pair(PendingSheetType::kDynamicRenderBlocking, RenderBlockingBehavior::kBlocking) : std::make_pair(PendingSheetType::kNonBlocking,
diff --git a/third_party/blink/renderer/core/css/style_element.cc b/third_party/blink/renderer/core/css/style_element.cc index 2954647a..e16433c7 100644 --- a/third_party/blink/renderer/core/css/style_element.cc +++ b/third_party/blink/renderer/core/css/style_element.cc
@@ -235,8 +235,10 @@ // rendering. if (pending_sheet_type_ != PendingSheetType::kDynamicRenderBlocking) return; - if (blocking() && blocking()->IsExplicitlyRenderBlocking()) + if (!IsA<HTMLElement>(element) || + To<HTMLElement>(element).IsPotentiallyRenderBlocking()) { return; + } element.GetDocument().GetStyleEngine().RemovePendingBlockingSheet( element, pending_sheet_type_); pending_sheet_type_ = PendingSheetType::kNonBlocking;
diff --git a/third_party/blink/renderer/core/css/style_element.h b/third_party/blink/renderer/core/css/style_element.h index f4e51e41..87ed914 100644 --- a/third_party/blink/renderer/core/css/style_element.h +++ b/third_party/blink/renderer/core/css/style_element.h
@@ -29,7 +29,6 @@ namespace blink { -class BlockingAttribute; class ContainerNode; class Document; class Element; @@ -46,7 +45,6 @@ virtual const AtomicString& type() const = 0; virtual const AtomicString& media() const = 0; - virtual BlockingAttribute* blocking() const = 0; // Returns whether |this| and |node| are the same object. Helps us verify // parameter validity in certain member functions with an Element parameter @@ -67,6 +65,9 @@ Member<CSSStyleSheet> sheet_; + protected: + bool CreatedByParser() const { return created_by_parser_; } + private: ProcessingResult CreateSheet(Element&, const String& text = String()); ProcessingResult Process(Element&);
diff --git a/third_party/blink/renderer/core/css/style_rule_import.cc b/third_party/blink/renderer/core/css/style_rule_import.cc index cca81540..1ea0dbb 100644 --- a/third_party/blink/renderer/core/css/style_rule_import.cc +++ b/third_party/blink/renderer/core/css/style_rule_import.cc
@@ -156,7 +156,7 @@ DCHECK(!style_sheet_client_->GetResource()); params.SetRenderBlockingBehavior(root_sheet->GetRenderBlockingBehavior()); - // TODO(yoav): Set defer status based on the IsExplicitlyRenderBlocking flag. + // TODO(yoav): Set defer status based on the IsRenderBlocking flag. // https://bugs.chromium.org/p/chromium/issues/detail?id=1001078 CSSStyleSheetResource::Fetch(params, fetcher, style_sheet_client_); if (loading_) {
diff --git a/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc b/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc index 2bbec6d2..7eb0301 100644 --- a/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc +++ b/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc
@@ -219,75 +219,63 @@ session->ConnectToV8(main_thread_debugger->GetV8Inspector(), context_group_id); - InspectorDOMAgent* dom_agent = MakeGarbageCollected<InspectorDOMAgent>( + InspectorDOMAgent* dom_agent = session->CreateAndAppend<InspectorDOMAgent>( isolate, inspected_frames, session->V8Session()); - session->Append(dom_agent); - auto* layer_tree_agent = - MakeGarbageCollected<InspectorLayerTreeAgent>(inspected_frames, this); - session->Append(layer_tree_agent); + session->CreateAndAppend<InspectorLayerTreeAgent>(inspected_frames, this); InspectorNetworkAgent* network_agent = - MakeGarbageCollected<InspectorNetworkAgent>(inspected_frames, nullptr, - session->V8Session()); - session->Append(network_agent); + session->CreateAndAppend<InspectorNetworkAgent>(inspected_frames, nullptr, + session->V8Session()); - auto* css_agent = MakeGarbageCollected<InspectorCSSAgent>( + auto* css_agent = session->CreateAndAppend<InspectorCSSAgent>( dom_agent, inspected_frames, network_agent, resource_content_loader_.Get(), resource_container_.Get()); - session->Append(css_agent); InspectorDOMDebuggerAgent* dom_debugger_agent = - MakeGarbageCollected<InspectorDOMDebuggerAgent>(isolate, dom_agent, - session->V8Session()); - session->Append(dom_debugger_agent); + session->CreateAndAppend<InspectorDOMDebuggerAgent>(isolate, dom_agent, + session->V8Session()); - InspectorPerformanceAgent* performance_agent = - MakeGarbageCollected<InspectorPerformanceAgent>(inspected_frames); - session->Append(performance_agent); + session->CreateAndAppend<InspectorPerformanceAgent>(inspected_frames); - session->Append(MakeGarbageCollected<InspectorDOMSnapshotAgent>( - inspected_frames, dom_debugger_agent)); + session->CreateAndAppend<InspectorDOMSnapshotAgent>(inspected_frames, + dom_debugger_agent); - session->Append(MakeGarbageCollected<InspectorAnimationAgent>( - inspected_frames, css_agent, session->V8Session())); + session->CreateAndAppend<InspectorAnimationAgent>(inspected_frames, css_agent, + session->V8Session()); - session->Append(MakeGarbageCollected<InspectorMemoryAgent>(inspected_frames)); + session->CreateAndAppend<InspectorMemoryAgent>(inspected_frames); - auto* page_agent = MakeGarbageCollected<InspectorPageAgent>( + auto* page_agent = session->CreateAndAppend<InspectorPageAgent>( inspected_frames, this, resource_content_loader_.Get(), session->V8Session()); - session->Append(page_agent); - session->Append(MakeGarbageCollected<InspectorLogAgent>( + session->CreateAndAppend<InspectorLogAgent>( &inspected_frames->Root()->GetPage()->GetConsoleMessageStorage(), - inspected_frames->Root()->GetPerformanceMonitor(), session->V8Session())); + inspected_frames->Root()->GetPerformanceMonitor(), session->V8Session()); InspectorOverlayAgent* overlay_agent = - MakeGarbageCollected<InspectorOverlayAgent>( + session->CreateAndAppend<InspectorOverlayAgent>( web_local_frame_impl_.Get(), inspected_frames, session->V8Session(), dom_agent); - session->Append(overlay_agent); - session->Append( - MakeGarbageCollected<InspectorIOAgent>(isolate, session->V8Session())); + session->CreateAndAppend<InspectorIOAgent>(isolate, session->V8Session()); - session->Append(MakeGarbageCollected<InspectorAuditsAgent>( + session->CreateAndAppend<InspectorAuditsAgent>( network_agent, &inspected_frames->Root()->GetPage()->GetInspectorIssueStorage(), - inspected_frames)); + inspected_frames); - session->Append(MakeGarbageCollected<InspectorMediaAgent>( - inspected_frames, /*worker_global_scope=*/nullptr)); + session->CreateAndAppend<InspectorMediaAgent>( + inspected_frames, /*worker_global_scope=*/nullptr); // TODO(dgozman): we should actually pass the view instead of frame, but // during remote->local transition we cannot access mainFrameImpl() yet, so // we have to store the frame which will become the main frame later. - session->Append(MakeGarbageCollected<InspectorEmulationAgent>( - web_local_frame_impl_.Get())); + session->CreateAndAppend<InspectorEmulationAgent>( + web_local_frame_impl_.Get()); - session->Append(MakeGarbageCollected<InspectorPerformanceTimelineAgent>( - inspected_frames)); + session->CreateAndAppend<InspectorPerformanceTimelineAgent>(inspected_frames); // Call session init callbacks registered from higher layers. CoreInitializer::GetInstance().InitInspectorAgentSession(
diff --git a/third_party/blink/renderer/core/frame/child_frame_compositing_helper.cc b/third_party/blink/renderer/core/frame/child_frame_compositing_helper.cc index ca8c8fa9..09e16d1 100644 --- a/third_party/blink/renderer/core/frame/child_frame_compositing_helper.cc +++ b/third_party/blink/renderer/core/frame/child_frame_compositing_helper.cc
@@ -55,7 +55,7 @@ surface_layer_ = cc::SurfaceLayer::Create(); surface_layer_->SetMasksToBounds(true); surface_layer_->SetSurfaceHitTestable(true); - surface_layer_->SetBackgroundColor(SK_ColorTRANSPARENT); + surface_layer_->SetBackgroundColor(SkColors::kTransparent); // If we're synchronizing surfaces, then use an infinite deadline to ensure // everything is synchronized.
diff --git a/third_party/blink/renderer/core/frame/frame.cc b/third_party/blink/renderer/core/frame/frame.cc index f370d23..c058355d 100644 --- a/third_party/blink/renderer/core/frame/frame.cc +++ b/third_party/blink/renderer/core/frame/frame.cc
@@ -358,10 +358,11 @@ bool Frame::IsInFencedFrameTree() const { DCHECK(!IsDetached()); - if (!blink::features::IsFencedFramesEnabled()) + auto ff_impl = GetPage()->FencedFramesImplementationType(); + if (!ff_impl) return false; - switch (blink::features::kFencedFramesImplementationTypeParam.Get()) { + switch (ff_impl.value()) { case blink::features::FencedFramesImplementationType::kMPArch: return GetPage() && GetPage()->IsMainFrameFencedFrameRoot(); case blink::features::FencedFramesImplementationType::kShadowDOM: @@ -373,10 +374,12 @@ } bool Frame::IsFencedFrameRoot() const { - if (!blink::features::IsFencedFramesEnabled()) + DCHECK(!IsDetached()); + auto ff_impl = GetPage()->FencedFramesImplementationType(); + if (!ff_impl) return false; - switch (blink::features::kFencedFramesImplementationTypeParam.Get()) { + switch (ff_impl.value()) { case blink::features::FencedFramesImplementationType::kMPArch: return IsInFencedFrameTree() && IsMainFrame(); case blink::features::FencedFramesImplementationType::kShadowDOM: @@ -391,13 +394,14 @@ const { DCHECK(!IsDetached()); - if (!blink::features::IsFencedFramesEnabled()) + auto ff_impl = GetPage()->FencedFramesImplementationType(); + if (!ff_impl) return absl::nullopt; if (!IsInFencedFrameTree()) return absl::nullopt; - switch (blink::features::kFencedFramesImplementationTypeParam.Get()) { + switch (ff_impl.value()) { case blink::features::FencedFramesImplementationType::kMPArch: return GetPage()->FencedFrameMode(); case blink::features::FencedFramesImplementationType::kShadowDOM: @@ -411,10 +415,11 @@ } bool Frame::IsInShadowDOMOpaqueAdsFencedFrameTree() const { - if (!blink::features::IsFencedFramesEnabled()) + auto ff_impl = GetPage()->FencedFramesImplementationType(); + if (!ff_impl) return false; - switch (blink::features::kFencedFramesImplementationTypeParam.Get()) { + switch (ff_impl.value()) { case blink::features::FencedFramesImplementationType::kMPArch: return false; case blink::features::FencedFramesImplementationType::kShadowDOM: { @@ -428,10 +433,11 @@ } bool Frame::IsInMPArchOpaqueAdsFencedFrameTree() const { - if (!blink::features::IsFencedFramesEnabled()) + auto ff_impl = GetPage()->FencedFramesImplementationType(); + if (!ff_impl) return false; - switch (blink::features::kFencedFramesImplementationTypeParam.Get()) { + switch (ff_impl.value()) { case blink::features::FencedFramesImplementationType::kMPArch: return GetPage() && GetPage()->FencedFrameMode() == mojom::blink::FencedFrameMode::kOpaqueAds; @@ -652,13 +658,19 @@ } Frame* Frame::Parent(FrameTreeBoundary frame_tree_boundary) const { + // |parent_| will be null if detached, return early before accessing + // Page. + if (!parent_) + return nullptr; + // TODO(crbug.com/1123606): Remove this once we use MPArch as the underlying // fenced frames implementation, instead of the // `FencedFrameShadowDOMDelegate`. if (frame_tree_boundary == FrameTreeBoundary::kFenced && Owner() && Owner()->GetFramePolicy().is_fenced && - features::IsFencedFramesEnabled() && - features::IsFencedFramesShadowDOMBased()) { + GetPage()->FencedFramesImplementationType().has_value() && + GetPage()->FencedFramesImplementationType().value() == + features::FencedFramesImplementationType::kShadowDOM) { return nullptr; } @@ -726,10 +738,11 @@ } bool Frame::ShouldAllowScriptFocus() { - if (!features::IsFencedFramesEnabled()) + auto ff_impl = GetPage()->FencedFramesImplementationType(); + if (!ff_impl) return true; - switch (blink::features::kFencedFramesImplementationTypeParam.Get()) { + switch (ff_impl.value()) { case blink::features::FencedFramesImplementationType::kMPArch: // For a newly-loaded page, no page will have focus. We allow a non-fenced // frame to get the first focus before enforcing if a page already has
diff --git a/third_party/blink/renderer/core/frame/local_dom_window.cc b/third_party/blink/renderer/core/frame/local_dom_window.cc index 1651fc9a..98e4b66 100644 --- a/third_party/blink/renderer/core/frame/local_dom_window.cc +++ b/third_party/blink/renderer/core/frame/local_dom_window.cc
@@ -2066,19 +2066,22 @@ ExceptionState& exception_state) { LocalDOMWindow* entered_window = EnteredDOMWindow(isolate); + if (!IsCurrentlyDisplayedInFrame()) + return nullptr; + // If the bindings implementation is 100% correct, the current realm and the // entered realm should be same origin-domain. However, to be on the safe // side and add some defense in depth, we'll check against the entry realm // as well here. if (!BindingSecurity::ShouldAllowAccessTo(entered_window, this, exception_state)) { + // Trigger DCHECK() failure, while gracefully failing on release builds. + NOTREACHED(); UseCounter::Count(GetExecutionContext(), WebFeature::kWindowOpenRealmMismatch); return nullptr; } - if (!IsCurrentlyDisplayedInFrame()) - return nullptr; if (!entered_window->GetFrame()) return nullptr; @@ -2184,19 +2187,22 @@ LocalDOMWindow* entered_window = EnteredDOMWindow(isolate); DCHECK(isSecureContext()); + if (!IsCurrentlyDisplayedInFrame()) + return nullptr; + // If the bindings implementation is 100% correct, the current realm and the // entered realm should be same origin-domain. However, to be on the safe // side and add some defense in depth, we'll check against the entry realm // as well here. if (!BindingSecurity::ShouldAllowAccessTo(entered_window, this, exception_state)) { + // Trigger DCHECK() failure, while gracefully failing on release builds. + NOTREACHED(); UseCounter::Count(GetExecutionContext(), WebFeature::kWindowOpenRealmMismatch); return nullptr; } - if (!IsCurrentlyDisplayedInFrame()) - return nullptr; if (!entered_window->GetFrame()) return nullptr;
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 5e05718..6f9c5ac 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -361,12 +361,10 @@ if (Frame* frame = portal->GetFrame()) function(*frame->View()); } - if (features::IsFencedFramesMPArchBased()) { - for (HTMLFencedFrameElement* fenced_frame : - DocumentFencedFrames::From(*document).GetFencedFrames()) { - if (Frame* frame = fenced_frame->ContentFrame()) - function(*frame->View()); - } + for (HTMLFencedFrameElement* fenced_frame : + DocumentFencedFrames::From(*document).GetFencedFrames()) { + if (Frame* frame = fenced_frame->ContentFrame()) + function(*frame->View()); } } } @@ -442,14 +440,11 @@ function(*view); } } - if (features::IsFencedFramesMPArchBased()) { - for (HTMLFencedFrameElement* fenced_frame : - DocumentFencedFrames::From(*document).GetFencedFrames()) { - if (RemoteFrame* frame = - To<RemoteFrame>(fenced_frame->ContentFrame())) { - if (RemoteFrameView* view = frame->View()) - function(*view); - } + for (HTMLFencedFrameElement* fenced_frame : + DocumentFencedFrames::From(*document).GetFencedFrames()) { + if (RemoteFrame* frame = To<RemoteFrame>(fenced_frame->ContentFrame())) { + if (RemoteFrameView* view = frame->View()) + function(*view); } } } @@ -4302,14 +4297,12 @@ } } - if (features::IsFencedFramesMPArchBased()) { - for (HTMLFencedFrameElement* fenced_frame : - DocumentFencedFrames::From(*frame_->GetDocument()).GetFencedFrames()) { - if (Frame* frame = fenced_frame->ContentFrame()) { - needs_occlusion_tracking |= - frame->View()->UpdateViewportIntersectionsForSubtree( - flags, monotonic_time); - } + for (HTMLFencedFrameElement* fenced_frame : + DocumentFencedFrames::From(*frame_->GetDocument()).GetFencedFrames()) { + if (Frame* frame = fenced_frame->ContentFrame()) { + needs_occlusion_tracking |= + frame->View()->UpdateViewportIntersectionsForSubtree(flags, + monotonic_time); } } return needs_occlusion_tracking;
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc index 6d8071c6..e3db4855 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
@@ -201,11 +201,9 @@ callback.Run(remote_frame); } // Iterate on any fenced frames owned by a local frame. - if (features::IsFencedFramesMPArchBased()) { - for (HTMLFencedFrameElement* fenced_frame : - DocumentFencedFrames::From(*document).GetFencedFrames()) { - callback.Run(To<RemoteFrame>(fenced_frame->ContentFrame())); - } + for (HTMLFencedFrameElement* fenced_frame : + DocumentFencedFrames::From(*document).GetFencedFrames()) { + callback.Run(To<RemoteFrame>(fenced_frame->ContentFrame())); } } }
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_test.cc b/third_party/blink/renderer/core/frame/web_frame_widget_test.cc index 650a8cc..f566679 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_test.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_test.cc
@@ -490,7 +490,7 @@ color_layer->SetBounds(gfx::Size(100, 100)); cc::CopyProperties(root_layer, color_layer.get()); root_layer->SetChildLayerList(cc::LayerList({color_layer})); - color_layer->SetBackgroundColor(SK_ColorRED); + color_layer->SetBackgroundColor(SkColors::kRed); } WebFrameWidgetImpl* FrameWidgetBase() {
diff --git a/third_party/blink/renderer/core/html/blocking_attribute.cc b/third_party/blink/renderer/core/html/blocking_attribute.cc index 09e13a4..5ffd0b8 100644 --- a/third_party/blink/renderer/core/html/blocking_attribute.cc +++ b/third_party/blink/renderer/core/html/blocking_attribute.cc
@@ -28,8 +28,7 @@ } // static -bool BlockingAttribute::IsExplicitlyRenderBlocking( - const String& attribute_value) { +bool BlockingAttribute::HasRenderToken(const String& attribute_value) { if (!RuntimeEnabledFeatures::BlockingAttributeEnabled()) return false; if (attribute_value.IsEmpty())
diff --git a/third_party/blink/renderer/core/html/blocking_attribute.h b/third_party/blink/renderer/core/html/blocking_attribute.h index c357c8ef..5b0ad023 100644 --- a/third_party/blink/renderer/core/html/blocking_attribute.h +++ b/third_party/blink/renderer/core/html/blocking_attribute.h
@@ -20,9 +20,8 @@ explicit BlockingAttribute(Element* element) : DOMTokenList(*element, html_names::kBlockingAttr) {} - // https://html.spec.whatwg.org/C/#explicitly-render-blocking - static bool IsExplicitlyRenderBlocking(const String& attribute_value); - bool IsExplicitlyRenderBlocking() const { return contains(kRenderToken); } + static bool HasRenderToken(const String& attribute_value); + bool HasRenderToken() const { return contains(kRenderToken); } void CountTokenUsage();
diff --git a/third_party/blink/renderer/core/html/fenced_frame/document_fenced_frames.cc b/third_party/blink/renderer/core/html/fenced_frame/document_fenced_frames.cc index dc9b411ed..26f0b32 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/document_fenced_frames.cc +++ b/third_party/blink/renderer/core/html/fenced_frame/document_fenced_frames.cc
@@ -32,31 +32,29 @@ void DocumentFencedFrames::RegisterFencedFrame( HTMLFencedFrameElement* fenced_frame) { + DCHECK(features::IsFencedFramesMPArchBased()); fenced_frames_.push_back(fenced_frame); - if (features::IsFencedFramesMPArchBased()) { - LocalFrame* frame = GetSupplementable()->GetFrame(); - if (!frame) - return; - if (Page* page = frame->GetPage()) - page->IncrementSubframeCount(); - } + LocalFrame* frame = GetSupplementable()->GetFrame(); + if (!frame) + return; + if (Page* page = frame->GetPage()) + page->IncrementSubframeCount(); } void DocumentFencedFrames::DeregisterFencedFrame( HTMLFencedFrameElement* fenced_frame) { + DCHECK(features::IsFencedFramesMPArchBased()); wtf_size_t index = fenced_frames_.Find(fenced_frame); if (index != WTF::kNotFound) { fenced_frames_.EraseAt(index); } - if (features::IsFencedFramesMPArchBased()) { - LocalFrame* frame = GetSupplementable()->GetFrame(); - if (!frame) - return; - if (Page* page = frame->GetPage()) { - page->DecrementSubframeCount(); - } + LocalFrame* frame = GetSupplementable()->GetFrame(); + if (!frame) + return; + if (Page* page = frame->GetPage()) { + page->DecrementSubframeCount(); } }
diff --git a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.cc b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.cc index a8e5ebe5..419770b 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.cc +++ b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.cc
@@ -11,6 +11,8 @@ #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/frame/remote_frame.h" #include "third_party/blink/renderer/core/html/fenced_frame/document_fenced_frames.h" +#include "third_party/blink/renderer/core/layout/layout_object.h" +#include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink { @@ -18,7 +20,11 @@ FencedFrameMPArchDelegate::FencedFrameMPArchDelegate( HTMLFencedFrameElement* outer_element) : HTMLFencedFrameElement::FencedFrameDelegate(outer_element) { - DCHECK_EQ(features::kFencedFramesImplementationTypeParam.Get(), + DCHECK_EQ(outer_element->GetDocument() + .GetFrame() + ->GetPage() + ->FencedFramesImplementationType() + .value(), features::FencedFramesImplementationType::kMPArch); DocumentFencedFrames::From(GetElement().GetDocument()) @@ -47,4 +53,27 @@ .DeregisterFencedFrame(&GetElement()); } +void FencedFrameMPArchDelegate::AttachLayoutTree() { + if (GetElement().GetLayoutEmbeddedContent() && GetElement().ContentFrame()) { + GetElement().SetEmbeddedContentView(GetElement().ContentFrame()->View()); + } +} + +bool FencedFrameMPArchDelegate::SupportsFocus() { + return true; +} + +void FencedFrameMPArchDelegate::FreezeFrameSize() { + // With MPArch, mark the layout as stale. Do this unconditionally because + // we are rounding the size. + GetElement().GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation( + "Froze MPArch fenced frame"); + + // Stop the `ResizeObserver`. It is needed only to compute the + // frozen size in MPArch. ShadowDOM stays subscribed in order to + // update the CSS on the inner iframe element as the outer container's + // size changes. + GetElement().StopResizeObserver(); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.h b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.h index 0efac9eb..1349a72 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.h +++ b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_mparch_delegate.h
@@ -26,6 +26,9 @@ void Navigate(const KURL&) override; void Dispose() override; + void AttachLayoutTree() override; + bool SupportsFocus() override; + void FreezeFrameSize() override; private: mojo::AssociatedRemote<mojom::blink::FencedFrameOwnerHost> remote_;
diff --git a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.cc b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.cc index effa0c88..7dafe46 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.cc +++ b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.cc
@@ -6,9 +6,11 @@ #include "third_party/blink/public/common/features.h" #include "third_party/blink/renderer/core/dom/shadow_root.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/html/html_collection.h" #include "third_party/blink/renderer/core/html/html_iframe_element.h" #include "third_party/blink/renderer/core/html/html_style_element.h" +#include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink { @@ -16,7 +18,11 @@ FencedFrameShadowDOMDelegate::FencedFrameShadowDOMDelegate( HTMLFencedFrameElement* outer_element) : HTMLFencedFrameElement::FencedFrameDelegate(outer_element) { - DCHECK_EQ(features::kFencedFramesImplementationTypeParam.Get(), + DCHECK_EQ(outer_element->GetDocument() + .GetFrame() + ->GetPage() + ->FencedFramesImplementationType() + .value(), features::FencedFramesImplementationType::kShadowDOM); GetElement().EnsureUserAgentShadowRoot(); @@ -61,4 +67,10 @@ internal_iframe->setAttribute(html_names::kSrcAttr, url_string); } +void FencedFrameShadowDOMDelegate::FreezeFrameSize() { + // With Shadow DOM, update the CSS `transform` property whenever + // |content_rect_| or |frozen_frame_size_| change. + GetElement().UpdateInnerStyleOnFrozenInternalFrame(); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.h b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.h index 3dcdd72..83726f4 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.h +++ b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate.h
@@ -23,6 +23,7 @@ explicit FencedFrameShadowDOMDelegate(HTMLFencedFrameElement* outer_element); void Navigate(const KURL&) override; + void FreezeFrameSize() override; private: void AddUserAgentShadowContent(ShadowRoot&);
diff --git a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate_test.cc b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate_test.cc index 9c8c477..fed6b04 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate_test.cc +++ b/third_party/blink/renderer/core/html/fenced_frame/fenced_frame_shadow_dom_delegate_test.cc
@@ -27,16 +27,16 @@ public: FencedFrameShadowDOMDelegateTest() : ScopedFencedFramesForTest(true), - RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {} + RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) { + enabled_feature_list_.InitWithFeaturesAndParameters( + {{blink::features::kFencedFrames, + {{"implementation_type", "shadow_dom"}}}}, + {/* disabled_features */}); + } protected: void SetUp() override { RenderingTest::SetUp(); - base::FieldTrialParams params; - params["implementation_type"] = "shadow_dom"; - enabled_feature_list_.InitAndEnableFeatureWithParameters( - features::kFencedFrames, params); - SecurityContext& security_context = GetDocument().GetFrame()->DomWindow()->GetSecurityContext(); security_context.SetSecurityOriginForTesting(nullptr);
diff --git a/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.cc b/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.cc index 542a8afb..909df5a 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.cc +++ b/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.cc
@@ -64,8 +64,9 @@ bool HasDifferentModeThanParent(HTMLFencedFrameElement& outer_element) { mojom::blink::FencedFrameMode current_mode = outer_element.GetMode(); + Page* ancestor_page = outer_element.GetDocument().GetFrame()->GetPage(); - if (features::kFencedFramesImplementationTypeParam.Get() == + if (ancestor_page->FencedFramesImplementationType() == features::FencedFramesImplementationType::kShadowDOM) { // ShadowDOM check. if (Frame* ancestor = outer_element.GetDocument().GetFrame()) { @@ -101,7 +102,6 @@ return false; } // MPArch check. - Page* ancestor_page = outer_element.GetDocument().GetFrame()->GetPage(); return ancestor_page->IsMainFrameFencedFrameRoot() && ancestor_page->FencedFrameMode() != current_mode; } @@ -256,9 +256,11 @@ // of this function. DCHECK(outer_element->GetDocument().GetFrame()); + Page* ancestor_page = outer_element->GetDocument().GetFrame()->GetPage(); + if (HasDifferentModeThanParent(*outer_element)) { mojom::blink::FencedFrameMode parent_mode = - features::kFencedFramesImplementationTypeParam.Get() == + ancestor_page->FencedFramesImplementationType() == features::FencedFramesImplementationType::kShadowDOM ? outer_element->GetDocument() .GetFrame() @@ -278,7 +280,7 @@ return nullptr; } - if (features::kFencedFramesImplementationTypeParam.Get() == + if (ancestor_page->FencedFramesImplementationType() == features::FencedFramesImplementationType::kShadowDOM) { return MakeGarbageCollected<FencedFrameShadowDOMDelegate>(outer_element); } @@ -448,11 +450,8 @@ void HTMLFencedFrameElement::AttachLayoutTree(AttachContext& context) { HTMLFrameOwnerElement::AttachLayoutTree(context); - if (features::IsFencedFramesMPArchBased()) { - if (GetLayoutEmbeddedContent() && ContentFrame()) { - SetEmbeddedContentView(ContentFrame()->View()); - } - } + if (frame_delegate_) + frame_delegate_->AttachLayoutTree(); } bool HTMLFencedFrameElement::LayoutObjectIsNeeded( @@ -464,7 +463,10 @@ LayoutObject* HTMLFencedFrameElement::CreateLayoutObject( const ComputedStyle& style, LegacyLayout legacy_layout) { - if (features::IsFencedFramesMPArchBased()) { + Page* page = GetDocument().GetFrame()->GetPage(); + + if (page->FencedFramesImplementationType() == + features::FencedFramesImplementationType::kMPArch) { return MakeGarbageCollected<LayoutIFrame>(this); } @@ -472,7 +474,7 @@ } bool HTMLFencedFrameElement::SupportsFocus() const { - return features::IsFencedFramesMPArchBased(); + return frame_delegate_->SupportsFocus(); } PhysicalSize HTMLFencedFrameElement::CoerceFrameSize( @@ -624,22 +626,7 @@ // from here to during FLEDGE/SharedStorage. frozen_frame_size_ = CoerceFrameSize(size); - if (features::IsFencedFramesMPArchBased()) { - // With MPArch, mark the layout as stale. Do this unconditionally because - // we are rounding the size. - GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation( - "Froze MPArch fenced frame"); - - // Stop the `ResizeObserver`. It is needed only to compute the - // frozen size in MPArch. ShadowDOM stays subscribed in order to - // update the CSS on the inner iframe element as the outer container's - // size changes. - StopResizeObserver(); - } else { - // With Shadow DOM, update the CSS `transform` property whenever - // |content_rect_| or |frozen_frame_size_| change. - UpdateInnerStyleOnFrozenInternalFrame(); - } + frame_delegate_->FreezeFrameSize(); } void HTMLFencedFrameElement::StartResizeObserver() { @@ -678,8 +665,12 @@ FreezeFrameSize(content_rect_->size); return; } - if (frozen_frame_size_ && !features::IsFencedFramesMPArchBased()) + Page* page = GetDocument().GetFrame()->GetPage(); + if (frozen_frame_size_ && + page->FencedFramesImplementationType() == + features::FencedFramesImplementationType::kShadowDOM) { UpdateInnerStyleOnFrozenInternalFrame(); + } } void HTMLFencedFrameElement::UpdateInnerStyleOnFrozenInternalFrame() {
diff --git a/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.h b/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.h index 09003bf..05c835b 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.h +++ b/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.h
@@ -53,6 +53,10 @@ // collection. virtual void Dispose() {} + virtual void AttachLayoutTree() {} + virtual bool SupportsFocus() { return false; } + virtual void FreezeFrameSize() {} + protected: HTMLFencedFrameElement& GetElement() const { return *outer_element_; } @@ -165,6 +169,8 @@ mojom::blink::FencedFrameMode mode_ = mojom::blink::FencedFrameMode::kDefault; bool freeze_mode_attribute_ = false; + friend class FencedFrameMPArchDelegate; + friend class FencedFrameShadowDOMDelegate; friend class ResizeObserverDelegate; FRIEND_TEST_ALL_PREFIXES(HTMLFencedFrameElementTest, FreezeSizePageZoomFactor);
diff --git a/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element_test.cc b/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element_test.cc index 95c93bb..a7c01d8 100644 --- a/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element_test.cc +++ b/third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element_test.cc
@@ -23,16 +23,16 @@ public: HTMLFencedFrameElementTest() : ScopedFencedFramesForTest(true), - RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {} + RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) { + enabled_feature_list_.InitWithFeaturesAndParameters( + {{blink::features::kFencedFrames, + {{"implementation_type", "shadow_dom"}}}}, + {/* disabled_features */}); + } protected: void SetUp() override { RenderingTest::SetUp(); - base::FieldTrialParams params; - params["implementation_type"] = GetParam(); - enabled_feature_list_.InitAndEnableFeatureWithParameters( - features::kFencedFrames, params); - SecurityContext& security_context = GetDocument().GetFrame()->DomWindow()->GetSecurityContext(); security_context.SetSecurityOriginForTesting(nullptr);
diff --git a/third_party/blink/renderer/core/html/forms/select_type.cc b/third_party/blink/renderer/core/html/forms/select_type.cc index 7b6ccbc4..ef859edf 100644 --- a/third_party/blink/renderer/core/html/forms/select_type.cc +++ b/third_party/blink/renderer/core/html/forms/select_type.cc
@@ -498,8 +498,8 @@ cloned_style->SetUnicodeBidi(option_style->GetUnicodeBidi()); cloned_style->SetTextAlign(option_style->GetTextAlign(true)); if (auto* inner_layout = inner_element.GetLayoutObject()) { - inner_layout->SetStyle(std::move(cloned_style), - LayoutObject::ApplyStyleChanges::kYes); + inner_layout->SetModifiedStyleOutsideStyleRecalc( + std::move(cloned_style), LayoutObject::ApplyStyleChanges::kYes); } else { inner_element.SetComputedStyle(std::move(cloned_style)); }
diff --git a/third_party/blink/renderer/core/html/html_element.h b/third_party/blink/renderer/core/html/html_element.h index 61f54ee..5522413 100644 --- a/third_party/blink/renderer/core/html/html_element.h +++ b/third_party/blink/renderer/core/html/html_element.h
@@ -177,6 +177,9 @@ V8UnionBooleanOrStringOrUnrestrictedDouble* hidden() const; void setHidden(const V8UnionBooleanOrStringOrUnrestrictedDouble*); + // https://html.spec.whatwg.org/C/#potentially-render-blocking + virtual bool IsPotentiallyRenderBlocking() const { return false; } + protected: enum AllowPercentage { kDontAllowPercentageValues, kAllowPercentageValues }; enum AllowZero { kDontAllowZeroValues, kAllowZeroValues };
diff --git a/third_party/blink/renderer/core/html/html_link_element.cc b/third_party/blink/renderer/core/html/html_link_element.cc index 13ba31c0..e7320b96 100644 --- a/third_party/blink/renderer/core/html/html_link_element.cc +++ b/third_party/blink/renderer/core/html/html_link_element.cc
@@ -85,7 +85,7 @@ RuntimeEnabledFeatures::BlockingAttributeEnabled()) { blocking_attribute_->DidUpdateAttributeValue(params.old_value, value); blocking_attribute_->CountTokenUsage(); - if (!IsRenderBlocking()) { + if (!IsPotentiallyRenderBlocking()) { if (GetLinkStyle() && GetLinkStyle()->StyleSheetIsLoading()) GetLinkStyle()->UnblockRenderingForPendingSheet(); } @@ -334,13 +334,9 @@ GetLinkStyle()->SetToPendingState(); } -bool HTMLLinkElement::IsImplicitlyRenderBlocking() const { - return IsCreatedByParser() && rel_attribute_.IsStyleSheet(); -} - -bool HTMLLinkElement::IsRenderBlocking() const { - return blocking_attribute_->IsExplicitlyRenderBlocking() || - IsImplicitlyRenderBlocking(); +bool HTMLLinkElement::IsPotentiallyRenderBlocking() const { + return blocking_attribute_->HasRenderToken() || + (IsCreatedByParser() && rel_attribute_.IsStyleSheet()); } bool HTMLLinkElement::IsURLAttribute(const Attribute& attribute) const {
diff --git a/third_party/blink/renderer/core/html/html_link_element.h b/third_party/blink/renderer/core/html/html_link_element.h index 52b8ecb5..4a07749 100644 --- a/third_party/blink/renderer/core/html/html_link_element.h +++ b/third_party/blink/renderer/core/html/html_link_element.h
@@ -144,16 +144,12 @@ void SetToPendingState() override; void FinishParsingChildren() override; bool HasActivationBehavior() const override; + bool IsPotentiallyRenderBlocking() const override; // From LinkLoaderClient void LinkLoaded() override; void LinkLoadingErrored() override; - // https://html.spec.whatwg.org/C/#implicitly-render-blocking - bool IsImplicitlyRenderBlocking() const; - // https://html.spec.whatwg.org/C/#render-blocking - bool IsRenderBlocking() const; - Member<LinkResource> link_; Member<LinkLoader> link_loader_;
diff --git a/third_party/blink/renderer/core/html/html_plugin_element.cc b/third_party/blink/renderer/core/html/html_plugin_element.cc index 5061e372..b8e49b6 100644 --- a/third_party/blink/renderer/core/html/html_plugin_element.cc +++ b/third_party/blink/renderer/core/html/html_plugin_element.cc
@@ -400,6 +400,8 @@ // is handled externally. Also note that it is possible to call // PluginWrapper before the plugin has gone through the update phase(see // https://crbug.com/946709). + if (!frame->Client()) + return v8::Local<v8::Object>(); plugin_wrapper_.Reset( isolate, frame->Client()->GetScriptableObject(*this, isolate)); }
diff --git a/third_party/blink/renderer/core/html/html_script_element.cc b/third_party/blink/renderer/core/html/html_script_element.cc index 4f7e637..c3085ea 100644 --- a/third_party/blink/renderer/core/html/html_script_element.cc +++ b/third_party/blink/renderer/core/html/html_script_element.cc
@@ -108,7 +108,7 @@ params.new_value); blocking_attribute_->CountTokenUsage(); if (GetDocument().GetRenderBlockingResourceManager() && - !blocking_attribute_->IsExplicitlyRenderBlocking()) { + !IsPotentiallyRenderBlocking()) { GetDocument().GetRenderBlockingResourceManager()->RemovePendingScript( *this); } @@ -334,6 +334,14 @@ return *factory.CreateElement(TagQName(), flags, IsValue()); } +bool HTMLScriptElement::IsPotentiallyRenderBlocking() const { + return blocking_attribute_->HasRenderToken() || + (loader_->IsParserInserted() && + loader_->GetScriptType() == + ScriptLoader::ScriptTypeAtPrepare::kClassic && + !AsyncAttributeValue() && !DeferAttributeValue()); +} + // static bool HTMLScriptElement::supports(ScriptState* script_state, const AtomicString& type) {
diff --git a/third_party/blink/renderer/core/html/html_script_element.h b/third_party/blink/renderer/core/html/html_script_element.h index ff13a429..81ee3c52 100644 --- a/third_party/blink/renderer/core/html/html_script_element.h +++ b/third_party/blink/renderer/core/html/html_script_element.h
@@ -79,6 +79,8 @@ void FinishParsingChildren() override; + bool IsPotentiallyRenderBlocking() const override; + private: void ParseAttribute(const AttributeModificationParams&) override; InsertionNotificationRequest InsertedInto(ContainerNode&) override; @@ -114,9 +116,6 @@ bool ElementHasDuplicateAttributes() const override { return HasDuplicateAttribute(); } - bool IsExplicitlyRenderBlocking() const override { - return blocking_attribute_->IsExplicitlyRenderBlocking(); - } bool AllowInlineScriptForCSP(const AtomicString& nonce, const WTF::OrdinalNumber&, const String& script_content) override;
diff --git a/third_party/blink/renderer/core/html/html_style_element.cc b/third_party/blink/renderer/core/html/html_style_element.cc index 9f15276..d160c68 100644 --- a/third_party/blink/renderer/core/html/html_style_element.cc +++ b/third_party/blink/renderer/core/html/html_style_element.cc
@@ -154,6 +154,10 @@ style_sheet->setDisabled(set_disabled); } +bool HTMLStyleElement::IsPotentiallyRenderBlocking() const { + return blocking_attribute_->HasRenderToken() || CreatedByParser(); +} + void HTMLStyleElement::Trace(Visitor* visitor) const { visitor->Trace(blocking_attribute_); StyleElement::Trace(visitor);
diff --git a/third_party/blink/renderer/core/html/html_style_element.h b/third_party/blink/renderer/core/html/html_style_element.h index a6efe44..602d662 100644 --- a/third_party/blink/renderer/core/html/html_style_element.h +++ b/third_party/blink/renderer/core/html/html_style_element.h
@@ -44,8 +44,7 @@ bool disabled() const; void setDisabled(bool); - - BlockingAttribute* blocking() const override { return blocking_attribute_; } + BlockingAttribute& blocking() const { return *blocking_attribute_; } void Trace(Visitor*) const override; @@ -55,11 +54,12 @@ void DispatchPendingEvent(std::unique_ptr<IncrementLoadEventDelayCount>, bool is_load_event); - // overload from HTMLElement + // override from HTMLElement void ParseAttribute(const AttributeModificationParams&) override; InsertionNotificationRequest InsertedInto(ContainerNode&) override; void RemovedFrom(ContainerNode&) override; void ChildrenChanged(const ChildrenChange&) override; + bool IsPotentiallyRenderBlocking() const override; void FinishParsingChildren() override;
diff --git a/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc b/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc index 31296e1d..590871e7 100644 --- a/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc +++ b/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc
@@ -309,8 +309,7 @@ } else if (is_script && (is_module || defer_ == FetchParameters::kLazyLoad)) { render_blocking_behavior = - BlockingAttribute::IsExplicitlyRenderBlocking( - blocking_attribute_value_) + BlockingAttribute::HasRenderToken(blocking_attribute_value_) ? RenderBlockingBehavior::kBlocking : (is_async_ ? RenderBlockingBehavior::kPotentiallyBlocking : RenderBlockingBehavior::kNonBlocking);
diff --git a/third_party/blink/renderer/core/inspector/devtools_session.cc b/third_party/blink/renderer/core/inspector/devtools_session.cc index 8640d6a9..53bac96 100644 --- a/third_party/blink/renderer/core/inspector/devtools_session.cc +++ b/third_party/blink/renderer/core/inspector/devtools_session.cc
@@ -127,6 +127,7 @@ inspector_backend_dispatcher_(new protocol::UberDispatcher(this)), session_state_(std::move(reattach_session_state)), client_expects_binary_responses_(client_expects_binary_responses), + client_is_trusted_(client_is_trusted), v8_session_state_(kV8StateKey), v8_session_state_cbor_(&v8_session_state_, /*default_value=*/{}), session_id_(session_id) { @@ -157,9 +158,11 @@ void DevToolsSession::ConnectToV8(v8_inspector::V8Inspector* inspector, int context_group_id) { const auto& cbor = v8_session_state_cbor_.Get(); - v8_session_ = - inspector->connect(context_group_id, this, - v8_inspector::StringView(cbor.data(), cbor.size())); + v8_session_ = inspector->connect( + context_group_id, this, + v8_inspector::StringView(cbor.data(), cbor.size()), + client_is_trusted_ ? v8_inspector::V8Inspector::kFullyTrusted + : v8_inspector::V8Inspector::kUntrusted); } bool DevToolsSession::IsDetached() {
diff --git a/third_party/blink/renderer/core/inspector/devtools_session.h b/third_party/blink/renderer/core/inspector/devtools_session.h index d7c7ba85..6beb623 100644 --- a/third_party/blink/renderer/core/inspector/devtools_session.h +++ b/third_party/blink/renderer/core/inspector/devtools_session.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_DEVTOOLS_SESSION_H_ #include <memory> +#include <type_traits> #include "base/callback.h" #include "mojo/public/cpp/bindings/pending_associated_receiver.h" #include "mojo/public/cpp/bindings/pending_associated_remote.h" @@ -31,6 +32,21 @@ class DocumentLoader; class InspectorAgent; class LocalFrame; +class InspectorAuditsAgent; +class InspectorCSSAgent; +class InspectorCacheStorageAgent; +class InspectorDOMAgent; +class InspectorDOMDebuggerAgent; +class InspectorDOMSnapshotAgent; +class InspectorDatabaseAgent; +class InspectorEmulationAgent; +class InspectorIOAgent; +class InspectorLogAgent; +class InspectorNetworkAgent; +class InspectorOverlayAgent; +class InspectorPageAgent; +class InspectorPerformanceAgent; +class InspectorWebAudioAgent; class CORE_EXPORT DevToolsSession : public GarbageCollected<DevToolsSession>, public mojom::blink::DevToolsSession, @@ -56,7 +72,15 @@ void ConnectToV8(v8_inspector::V8Inspector*, int context_group_id); v8_inspector::V8InspectorSession* V8Session() { return v8_session_.get(); } - void Append(InspectorAgent*); + template <typename Agent, typename... Args> + Agent* CreateAndAppend(Args&&... args) { + if (!IsDomainAvailableToUntrustedClient<Agent>() && !client_is_trusted_) { + return nullptr; + } + auto agent = MakeGarbageCollected<Agent>(std::forward<Args>(args)...); + Append(agent); + return agent; + } void Detach(); void Trace(Visitor*) const; @@ -106,6 +130,26 @@ blink::mojom::blink::DevToolsMessagePtr FinalizeMessage( std::vector<uint8_t> message) const; + template <typename T> + bool IsDomainAvailableToUntrustedClient() { + return std::disjunction_v<std::is_same<T, InspectorAuditsAgent>, + std::is_same<T, InspectorCSSAgent>, + std::is_same<T, InspectorCacheStorageAgent>, + std::is_same<T, InspectorDOMAgent>, + std::is_same<T, InspectorDOMDebuggerAgent>, + std::is_same<T, InspectorDOMSnapshotAgent>, + std::is_same<T, InspectorDatabaseAgent>, + std::is_same<T, InspectorEmulationAgent>, + std::is_same<T, InspectorIOAgent>, + std::is_same<T, InspectorLogAgent>, + std::is_same<T, InspectorNetworkAgent>, + std::is_same<T, InspectorOverlayAgent>, + std::is_same<T, InspectorPageAgent>, + std::is_same<T, InspectorPerformanceAgent>, + std::is_same<T, InspectorWebAudioAgent>>; + } + void Append(InspectorAgent*); + Member<DevToolsAgent> agent_; // DevToolsSession is not tied to ExecutionContext HeapMojoAssociatedReceiver<mojom::blink::DevToolsSession, DevToolsSession> @@ -123,6 +167,7 @@ // See https://bugs.chromium.org/p/chromium/issues/detail?id=1044989#c8 Vector<base::OnceCallback<std::vector<uint8_t>()>> notification_queue_; const bool client_expects_binary_responses_; + const bool client_is_trusted_; InspectorAgentState v8_session_state_; InspectorAgentState::Bytes v8_session_state_cbor_; const String session_id_;
diff --git a/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc b/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc index b22dd2f4..275cab7 100644 --- a/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc
@@ -65,7 +65,9 @@ v8_session_(v8_session), is_cloning_(false), enabled_(&agent_state_, /*default_value=*/false), - playback_rate_(&agent_state_, /*default_value=*/1.0) {} + playback_rate_(&agent_state_, /*default_value=*/1.0) { + DCHECK(css_agent); +} void InspectorAnimationAgent::Restore() { if (enabled_.Get()) {
diff --git a/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc b/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc index cb80778..144bf92 100644 --- a/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_audits_agent.cc
@@ -120,7 +120,9 @@ : inspector_issue_storage_(storage), enabled_(&agent_state_, false), network_agent_(network_agent), - inspected_frames_(inspected_frames) {} + inspected_frames_(inspected_frames) { + DCHECK(network_agent); +} InspectorAuditsAgent::~InspectorAuditsAgent() = default;
diff --git a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc index 10ce707..497fd470 100644 --- a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc
@@ -591,7 +591,10 @@ enable_requested_(&agent_state_, /*default_value=*/false), enable_completed_(false), coverage_enabled_(&agent_state_, /*default_value=*/false), - local_fonts_enabled_(&agent_state_, /*default_value=*/true) {} + local_fonts_enabled_(&agent_state_, /*default_value=*/true) { + DCHECK(dom_agent); + DCHECK(network_agent); +} InspectorCSSAgent::~InspectorCSSAgent() = default;
diff --git a/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc b/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc index 10ab8f52..3efbde7 100644 --- a/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc
@@ -213,7 +213,9 @@ pause_on_all_xhrs_(&agent_state_, /*default_value=*/false), xhr_breakpoints_(&agent_state_, /*default_value=*/false), event_listener_breakpoints_(&agent_state_, /*default_value*/ false), - csp_violation_breakpoints_(&agent_state_, /*default_value*/ false) {} + csp_violation_breakpoints_(&agent_state_, /*default_value*/ false) { + DCHECK(dom_agent); +} InspectorDOMDebuggerAgent::~InspectorDOMDebuggerAgent() = default;
diff --git a/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc b/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc index 146e7b9b..97a7564 100644 --- a/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc
@@ -203,7 +203,9 @@ InspectorDOMDebuggerAgent* dom_debugger_agent) : inspected_frames_(inspected_frames), dom_debugger_agent_(dom_debugger_agent), - enabled_(&agent_state_, /*default_value=*/false) {} + enabled_(&agent_state_, /*default_value=*/false) { + DCHECK(dom_debugger_agent); +} InspectorDOMSnapshotAgent::~InspectorDOMSnapshotAgent() = default;
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc index 1c71596e..c13d798 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
@@ -386,7 +386,9 @@ show_size_on_resize_(&agent_state_, false), paused_in_debugger_message_(&agent_state_, String()), inspect_mode_(&agent_state_, protocol::Overlay::InspectModeEnum::None), - inspect_mode_protocol_config_(&agent_state_, std::vector<uint8_t>()) {} + inspect_mode_protocol_config_(&agent_state_, std::vector<uint8_t>()) { + DCHECK(dom_agent); +} InspectorOverlayAgent::~InspectorOverlayAgent() { DCHECK(!overlay_page_);
diff --git a/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc b/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc index 7861042..9eef0cc 100644 --- a/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc +++ b/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc
@@ -116,17 +116,16 @@ thread_->GetWorkerBackingThread().BackingThread().AddTaskObserver(this); session->ConnectToV8(debugger_->GetV8Inspector(), debugger_->ContextGroupId(thread_)); - session->Append(MakeGarbageCollected<InspectorLogAgent>( - thread_->GetConsoleMessageStorage(), nullptr, session->V8Session())); + session->CreateAndAppend<InspectorLogAgent>( + thread_->GetConsoleMessageStorage(), nullptr, session->V8Session()); if (auto* scope = DynamicTo<WorkerGlobalScope>(thread_->GlobalScope())) { - auto* network_agent = MakeGarbageCollected<InspectorNetworkAgent>( + auto* network_agent = session->CreateAndAppend<InspectorNetworkAgent>( inspected_frames_.Get(), scope, session->V8Session()); - session->Append(network_agent); - session->Append(MakeGarbageCollected<InspectorEmulationAgent>(nullptr)); - session->Append(MakeGarbageCollected<InspectorAuditsAgent>( - network_agent, thread_->GetInspectorIssueStorage(), nullptr)); - session->Append(MakeGarbageCollected<InspectorMediaAgent>( - inspected_frames_.Get(), scope)); + session->CreateAndAppend<InspectorEmulationAgent>(nullptr); + session->CreateAndAppend<InspectorAuditsAgent>( + network_agent, thread_->GetInspectorIssueStorage(), nullptr); + session->CreateAndAppend<InspectorMediaAgent>(inspected_frames_.Get(), + scope); } ++session_count_; }
diff --git a/third_party/blink/renderer/core/layout/layout_object.cc b/third_party/blink/renderer/core/layout/layout_object.cc index f725763..195f9df2 100644 --- a/third_party/blink/renderer/core/layout/layout_object.cc +++ b/third_party/blink/renderer/core/layout/layout_object.cc
@@ -4822,7 +4822,7 @@ return outline_rects; } -void LayoutObject::SetTextAutoSizedStyle( +void LayoutObject::SetModifiedStyleOutsideStyleRecalc( scoped_refptr<const ComputedStyle> style, ApplyStyleChanges apply_changes) { NOT_DESTROYED();
diff --git a/third_party/blink/renderer/core/layout/layout_object.h b/third_party/blink/renderer/core/layout/layout_object.h index 0aaf6b5..e304a5d 100644 --- a/third_party/blink/renderer/core/layout/layout_object.h +++ b/third_party/blink/renderer/core/layout/layout_object.h
@@ -2336,8 +2336,15 @@ void SetPseudoElementStyle(scoped_refptr<const ComputedStyle>, bool match_parent_size = false); - void SetTextAutoSizedStyle(scoped_refptr<const ComputedStyle>, - ApplyStyleChanges); + // In some cases we modify the ComputedStyle after the style recalc, either + // for updating anonymous style or doing layout hacks for special elements + // where we update the ComputedStyle during layout. + // If the LayoutObject has an associated node, we will SetComputedStyle on + // that node with the new ComputedStyle. Modifying the ComputedStyle of a node + // outside of style recalc can break invariants in the style engine, so this + // function must not gain any new call sites. + void SetModifiedStyleOutsideStyleRecalc(scoped_refptr<const ComputedStyle>, + ApplyStyleChanges); // This function returns an enclosing non-anonymous LayoutBlock for this // element. This function is not always returning the containing block as
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 c1d543ccf..4c97178 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
@@ -579,7 +579,7 @@ // circumstances. This function updates |LastBaseline| in such cases. void SetLastBaselineToBlockEndMarginEdgeIfNeeded(); - void SetTableGridRect(const PhysicalRect& table_grid_rect) { + void SetTableGridRect(const LogicalRect& table_grid_rect) { table_grid_rect_ = table_grid_rect; } @@ -773,7 +773,7 @@ LayoutUnit math_italic_correction_; // Table specific types. - absl::optional<PhysicalRect> table_grid_rect_; + absl::optional<LogicalRect> table_grid_rect_; NGTableFragmentData::ColumnGeometries table_column_geometries_; scoped_refptr<const NGTableBorders> table_collapsed_borders_; std::unique_ptr<NGTableFragmentData::CollapsedBordersGeometry>
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h index a5f3f53..81d38249 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h
@@ -137,7 +137,7 @@ return absl::nullopt; } - PhysicalRect TableGridRect() const { + LogicalRect TableGridRect() const { return ComputeRareDataAddress()->table_grid_rect; } @@ -441,7 +441,7 @@ const std::unique_ptr<const NGMathMLPaintInfo> mathml_paint_info; // Table rare-data. - PhysicalRect table_grid_rect; + LogicalRect table_grid_rect; NGTableFragmentData::ColumnGeometries table_column_geometries; scoped_refptr<const NGTableBorders> table_collapsed_borders; std::unique_ptr<NGTableFragmentData::CollapsedBordersGeometry>
diff --git a/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.cc index 2088efd..634477f 100644 --- a/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.cc
@@ -761,7 +761,7 @@ const Vector<NGTableColumnLocation>& column_locations, const NGTableTypes::Rows& rows, const NGTableBorders& table_borders, - const PhysicalRect& table_grid_rect, + const LogicalRect& table_grid_rect, const LayoutUnit table_grid_block_size) { container_builder_.SetTableGridRect(table_grid_rect); container_builder_.SetTableColumnCount(column_locations.size()); @@ -1186,14 +1186,9 @@ container_builder_.SetFragmentsTotalBlockSize(block_size); - const WritingModeConverter grid_converter( - Style().GetWritingDirection(), - ToPhysicalSize(container_builder_.Size(), - table_writing_direction.GetWritingMode())); - - ComputeTableSpecificFragmentData( - grouped_children, column_locations, rows, table_borders, - grid_converter.ToPhysical(table_grid_rect), column_block_size); + ComputeTableSpecificFragmentData(grouped_children, column_locations, rows, + table_borders, table_grid_rect, + column_block_size); if (RuntimeEnabledFeatures::MathMLCoreEnabled() && Node().GetDOMNode() && Node().GetDOMNode()->HasTagName(mathml_names::kMtableTag))
diff --git a/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.h index c0450360..28b25c63a 100644 --- a/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm.h
@@ -74,7 +74,7 @@ const Vector<NGTableColumnLocation>& column_locations, const NGTableTypes::Rows& rows, const NGTableBorders& table_borders, - const PhysicalRect& table_grid_rect, + const LogicalRect& table_grid_rect, LayoutUnit table_grid_block_size); const NGLayoutResult* GenerateFragment(
diff --git a/third_party/blink/renderer/core/layout/text_autosizer.cc b/third_party/blink/renderer/core/layout/text_autosizer.cc index 0e3169a..1786e8c 100644 --- a/third_party/blink/renderer/core/layout/text_autosizer.cc +++ b/third_party/blink/renderer/core/layout/text_autosizer.cc
@@ -1258,7 +1258,7 @@ else DCHECK(false); - layout_object->SetTextAutoSizedStyle( + layout_object->SetModifiedStyleOutsideStyleRecalc( std::move(style), LayoutObject::ApplyStyleChanges::kNo); if (layout_object->IsText()) To<LayoutText>(layout_object)->AutosizingMultiplerChanged(); @@ -1270,7 +1270,7 @@ case kLayoutNeeded: DCHECK(!layouter); - layout_object->SetTextAutoSizedStyle( + layout_object->SetModifiedStyleOutsideStyleRecalc( std::move(style), LayoutObject::ApplyStyleChanges::kYes); break; }
diff --git a/third_party/blink/renderer/core/page/page.cc b/third_party/blink/renderer/core/page/page.cc index 7e627ff..e1db9ee 100644 --- a/third_party/blink/renderer/core/page/page.cc +++ b/third_party/blink/renderer/core/page/page.cc
@@ -106,6 +106,7 @@ const int kTenFrames = 10; bool g_limit_max_frames_to_ten_for_testing = false; + } // namespace // Function defined in third_party/blink/public/web/blink.h. @@ -182,6 +183,11 @@ bool is_ordinary) : SettingsDelegate(std::make_unique<Settings>()), main_frame_(nullptr), + fenced_frames_impl_( + features::IsFencedFramesEnabled() + ? absl::optional<features::FencedFramesImplementationType>( + features::kFencedFramesImplementationTypeParam.Get()) + : absl::nullopt), agent_group_scheduler_(agent_group_scheduler), animator_(MakeGarbageCollected<PageAnimator>(*this)), autoscroll_controller_(MakeGarbageCollected<AutoscrollController>(*this)), @@ -613,13 +619,11 @@ // Check the ``DocumentFencedFrames`` on every local frame beneath // the ``frame`` to get an accurate count (i.e. if an iframe embeds // a fenced frame and creates a new ``DocumentFencedFrames`` object). - if (features::IsFencedFramesMPArchBased()) { - if (auto* local_frame = DynamicTo<LocalFrame>(frame)) { - actual_frame_count += static_cast<int>( - DocumentFencedFrames::From(*local_frame->GetDocument()) - .GetFencedFrames() - .size()); - } + if (auto* local_frame = DynamicTo<LocalFrame>(frame)) { + actual_frame_count += static_cast<int>( + DocumentFencedFrames::From(*local_frame->GetDocument()) + .GetFencedFrames() + .size()); } }
diff --git a/third_party/blink/renderer/core/page/page.h b/third_party/blink/renderer/core/page/page.h index 6cd1b330..9d4f832 100644 --- a/third_party/blink/renderer/core/page/page.h +++ b/third_party/blink/renderer/core/page/page.h
@@ -28,6 +28,8 @@ #include "base/check_op.h" #include "base/dcheck_is_on.h" #include "base/types/pass_key.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/metrics/document_update_reason.h" #include "third_party/blink/public/mojom/devtools/inspector_issue.mojom-blink-forward.h" #include "third_party/blink/public/mojom/fenced_frame/fenced_frame.mojom-blink.h" @@ -221,6 +223,11 @@ return window_features_; } + absl::optional<features::FencedFramesImplementationType> + FencedFramesImplementationType() const { + return fenced_frames_impl_; + } + PageScaleConstraintsSet& GetPageScaleConstraintsSet(); const PageScaleConstraintsSet& GetPageScaleConstraintsSet() const; @@ -430,6 +437,9 @@ // longer needed. Member<Frame> main_frame_; + // The type of fenced frames being used. + absl::optional<features::FencedFramesImplementationType> fenced_frames_impl_; + scheduler::WebAgentGroupScheduler& agent_group_scheduler_; Member<PageAnimator> animator_; const Member<AutoscrollController> autoscroll_controller_;
diff --git a/third_party/blink/renderer/core/paint/background_image_geometry.cc b/third_party/blink/renderer/core/paint/background_image_geometry.cc index 20b9be5..31a83aca 100644 --- a/third_party/blink/renderer/core/paint/background_image_geometry.cc +++ b/third_party/blink/renderer/core/paint/background_image_geometry.cc
@@ -341,6 +341,39 @@ PhysicalSize(layout_viewport->VisibleContentRect().size())); } +// Computes the stitched table-grid rect relative to the current fragment. +PhysicalRect ComputeStitchedTableGridRect( + const NGPhysicalBoxFragment& fragment) { + const auto writing_direction = fragment.Style().GetWritingDirection(); + LogicalRect table_grid_rect; + LogicalRect fragment_local_grid_rect; + LayoutUnit stitched_block_size; + + for (const NGPhysicalBoxFragment& walker : + To<LayoutBox>(fragment.GetLayoutObject())->PhysicalFragments()) { + LogicalRect local_grid_rect = walker.TableGridRect(); + local_grid_rect.offset.block_offset += stitched_block_size; + if (table_grid_rect.IsEmpty()) + table_grid_rect = local_grid_rect; + else + table_grid_rect.Unite(local_grid_rect); + + if (&walker == &fragment) + fragment_local_grid_rect = local_grid_rect; + + stitched_block_size += NGFragment(writing_direction, walker).BlockSize(); + } + + // Make the rect relative to the fragment we are currently painting. + table_grid_rect.offset.block_offset -= + fragment_local_grid_rect.offset.block_offset; + + WritingModeConverter converter( + writing_direction, ToPhysicalSize(fragment_local_grid_rect.size, + writing_direction.GetWritingMode())); + return converter.ToPhysical(table_grid_rect); +} + } // Anonymous namespace BackgroundImageGeometry::BackgroundImageGeometry( @@ -400,7 +433,12 @@ To<LayoutBoxModelObject>(fragment.GetLayoutObject())) { DCHECK(box_->IsBox()); - if (!fragment.IsOnlyForNode()) { + if (fragment.IsTableNG()) { + auto stitched_background_rect = ComputeStitchedTableGridRect(fragment); + positioning_size_override_ = stitched_background_rect.size; + element_positioning_area_offset_ = -stitched_background_rect.offset; + box_has_multiple_fragments_ = !fragment.IsOnlyForNode(); + } else if (!fragment.IsOnlyForNode()) { // The element is block-fragmented. We need to calculate the correct // background offset within an imaginary box where all the fragments have // been stitched together.
diff --git a/third_party/blink/renderer/core/paint/compositing/compositing_test.cc b/third_party/blink/renderer/core/paint/compositing/compositing_test.cc index bb3bf2c6..dbbd27d 100644 --- a/third_party/blink/renderer/core/paint/compositing/compositing_test.cc +++ b/third_party/blink/renderer/core/paint/compositing/compositing_test.cc
@@ -459,8 +459,8 @@ // blending the CSS background-color of the <html> element with // LocalFrameView::BaseBackgroundColor(), which is white by default. auto* layer = CcLayersByName(RootCcLayer(), "LayoutView #document")[0]; - SkColor expected_color = SkColorSetRGB(10, 20, 30); - EXPECT_EQ(layer->background_color(), SK_ColorTRANSPARENT); + SkColor4f expected_color = SkColor4f::FromColor(SkColorSetRGB(10, 20, 30)); + EXPECT_EQ(layer->background_color(), SkColors::kTransparent); auto* scrollable_area = GetLocalFrameView()->LayoutViewport(); layer = ScrollingContentsCcLayerByScrollElementId( RootCcLayer(), scrollable_area->GetScrollElementId()); @@ -468,9 +468,9 @@ // Non-root layers set background_color based on the CSS background color of // the layer-defining element. - expected_color = SkColorSetRGB(30, 40, 50); + expected_color = SkColor4f::FromColor(SkColorSetRGB(30, 40, 50)); layer = CcLayerByDOMElementId("scroller"); - EXPECT_EQ(layer->background_color(), SK_ColorTRANSPARENT); + EXPECT_EQ(layer->background_color(), SkColors::kTransparent); scrollable_area = scroller_box->GetScrollableArea(); layer = ScrollingContentsCcLayerByScrollElementId( RootCcLayer(), scrollable_area->GetScrollElementId()); @@ -521,23 +521,24 @@ // contents layer should not checkerboard, so its background color should be // transparent. auto* layer = CcLayersByName(RootCcLayer(), "LayoutView #document")[0]; - EXPECT_EQ(layer->background_color(), SK_ColorWHITE); + EXPECT_EQ(layer->background_color(), SkColors::kWhite); auto* scrollable_area = GetLocalFrameView()->LayoutViewport(); layer = ScrollingContentsCcLayerByScrollElementId( RootCcLayer(), scrollable_area->GetScrollElementId()); - EXPECT_EQ(layer->background_color(), SK_ColorTRANSPARENT); - EXPECT_EQ(layer->SafeOpaqueBackgroundColor(), SK_ColorTRANSPARENT); + EXPECT_EQ(layer->background_color(), SkColors::kTransparent); + EXPECT_EQ(layer->SafeOpaqueBackgroundColor(), SkColors::kTransparent); // Non-root layers set background_color based on the CSS background color of // the layer-defining element. - SkColor expected_color = SkColorSetARGB(roundf(255. * 0.6), 30, 40, 50); + SkColor4f expected_color = + SkColor4f::FromColor(SkColorSetARGB(roundf(255. * 0.6), 30, 40, 50)); layer = CcLayerByDOMElementId("scroller"); EXPECT_EQ(layer->background_color(), expected_color); scrollable_area = scroller_box->GetScrollableArea(); layer = ScrollingContentsCcLayerByScrollElementId( RootCcLayer(), scrollable_area->GetScrollElementId()); - EXPECT_EQ(layer->background_color(), SK_ColorTRANSPARENT); - EXPECT_EQ(layer->SafeOpaqueBackgroundColor(), SK_ColorTRANSPARENT); + EXPECT_EQ(layer->background_color(), SkColors::kTransparent); + EXPECT_EQ(layer->SafeOpaqueBackgroundColor(), SkColors::kTransparent); } TEST_P(CompositingTest, ContainPaintLayerBounds) { @@ -1383,38 +1384,38 @@ auto* opaque_color = CcLayerByDOMElementId("opaque-color"); EXPECT_TRUE(opaque_color->contents_opaque()); - EXPECT_EQ(SK_ColorBLUE, opaque_color->background_color()); - EXPECT_EQ(SK_ColorBLUE, opaque_color->SafeOpaqueBackgroundColor()); + EXPECT_EQ(opaque_color->background_color(), SkColors::kBlue); + EXPECT_EQ(opaque_color->SafeOpaqueBackgroundColor(), SkColors::kBlue); auto* opaque_image = CcLayerByDOMElementId("opaque-image"); EXPECT_TRUE(opaque_image->contents_opaque()); - EXPECT_EQ(SK_ColorTRANSPARENT, opaque_image->background_color()); + EXPECT_EQ(opaque_image->background_color(), SkColors::kTransparent); // Fallback to use the viewport background. - EXPECT_EQ(SK_ColorYELLOW, opaque_image->SafeOpaqueBackgroundColor()); + EXPECT_EQ(opaque_image->SafeOpaqueBackgroundColor(), SkColors::kYellow); - const SkColor kTranslucentCyan = SkColorSetARGB(128, 0, 255, 255); + const SkColor4f kTranslucentCyan{0.0f, 1.0f, 1.0f, 128.0f / 255.0f}; auto* opaque_image_translucent_color = CcLayerByDOMElementId("opaque-image-translucent-color"); EXPECT_TRUE(opaque_image_translucent_color->contents_opaque()); - EXPECT_EQ(kTranslucentCyan, - opaque_image_translucent_color->background_color()); + EXPECT_EQ(opaque_image_translucent_color->background_color(), + kTranslucentCyan); // Use background_color() with the alpha channel forced to be opaque. - EXPECT_EQ(SK_ColorCYAN, - opaque_image_translucent_color->SafeOpaqueBackgroundColor()); + EXPECT_EQ(opaque_image_translucent_color->SafeOpaqueBackgroundColor(), + SkColors::kCyan); auto* partly_opaque = CcLayerByDOMElementId("partly-opaque"); EXPECT_FALSE(partly_opaque->contents_opaque()); - EXPECT_EQ(SK_ColorBLUE, partly_opaque->background_color()); + EXPECT_EQ(partly_opaque->background_color(), SkColors::kBlue); // SafeOpaqueBackgroundColor() returns SK_ColorTRANSPARENT when // background_color() is opaque and contents_opaque() is false. - EXPECT_EQ(SK_ColorTRANSPARENT, partly_opaque->SafeOpaqueBackgroundColor()); + EXPECT_EQ(partly_opaque->SafeOpaqueBackgroundColor(), SkColors::kTransparent); auto* translucent = CcLayerByDOMElementId("translucent"); EXPECT_FALSE(translucent->contents_opaque()); - EXPECT_EQ(kTranslucentCyan, translucent->background_color()); + EXPECT_EQ(translucent->background_color(), kTranslucentCyan); // SafeOpaqueBackgroundColor() returns background_color() if it's not opaque // and contents_opaque() is false. - EXPECT_EQ(kTranslucentCyan, translucent->SafeOpaqueBackgroundColor()); + EXPECT_EQ(translucent->SafeOpaqueBackgroundColor(), kTranslucentCyan); } TEST_P(CompositingSimTest, SquashingLayerSafeOpaqueBackgroundColor) { @@ -1463,10 +1464,11 @@ EXPECT_FALSE(squashing_layer->contents_opaque()); // The background color of #bottomright is used as the background color // because it covers the most significant area of the squashing layer. - EXPECT_EQ(squashing_layer->background_color(), SK_ColorCYAN); + EXPECT_EQ(squashing_layer->background_color(), SkColors::kCyan); // SafeOpaqueBackgroundColor() returns SK_ColorTRANSPARENT when // background_color() is opaque and contents_opaque() is false. - EXPECT_EQ(squashing_layer->SafeOpaqueBackgroundColor(), SK_ColorTRANSPARENT); + EXPECT_EQ(squashing_layer->SafeOpaqueBackgroundColor(), + SkColors::kTransparent); } // Test that a pleasant checkerboard color is used in the presence of blending. @@ -1481,8 +1483,8 @@ auto* scrolling_contents = ScrollingContentsCcLayerByScrollElementId( RootCcLayer(), MainFrame().GetFrameView()->LayoutViewport()->GetScrollElementId()); - EXPECT_EQ(scrolling_contents->background_color(), SK_ColorWHITE); - EXPECT_EQ(scrolling_contents->SafeOpaqueBackgroundColor(), SK_ColorWHITE); + EXPECT_EQ(scrolling_contents->background_color(), SkColors::kWhite); + EXPECT_EQ(scrolling_contents->SafeOpaqueBackgroundColor(), SkColors::kWhite); } TEST_P(CompositingSimTest, NonDrawableLayersIgnoredForRenderSurfaces) { @@ -2043,7 +2045,8 @@ Compositor().BeginFrame(); - EXPECT_EQ(CcLayerByDOMElementId("target")->background_color(), SK_ColorWHITE); + EXPECT_EQ(CcLayerByDOMElementId("target")->background_color(), + SkColors::kWhite); // Initially, no update is needed. EXPECT_FALSE(paint_artifact_compositor()->NeedsUpdate()); @@ -2060,7 +2063,8 @@ // Though a repaint-only update was done, the background color should still // be updated. - EXPECT_EQ(CcLayerByDOMElementId("target")->background_color(), SK_ColorBLACK); + EXPECT_EQ(CcLayerByDOMElementId("target")->background_color(), + SkColors::kBlack); } // Similar to |BackgroundColorChangeUsesRepaintUpdate| but with multiple paint @@ -2102,7 +2106,7 @@ RootCcLayer(), MainFrame().GetFrameView()->LayoutViewport()->GetScrollElementId()); - EXPECT_EQ(scrolling_contents->background_color(), SK_ColorBLACK); + EXPECT_EQ(scrolling_contents->background_color(), SkColors::kBlack); // Clear the previous update to ensure we record a new one in the next update. paint_artifact_compositor()->ClearPreviousUpdateForTesting(); @@ -2116,7 +2120,7 @@ // Though a repaint-only update was done, the background color should still // be updated. - EXPECT_EQ(scrolling_contents->background_color(), SK_ColorWHITE); + EXPECT_EQ(scrolling_contents->background_color(), SkColors::kWhite); } // Similar to |BackgroundColorChangeUsesRepaintUpdate| but with post-paint
diff --git a/third_party/blink/renderer/core/paint/html_canvas_painter.cc b/third_party/blink/renderer/core/paint/html_canvas_painter.cc index b812c87..f0a56f75 100644 --- a/third_party/blink/renderer/core/paint/html_canvas_painter.cc +++ b/third_party/blink/renderer/core/paint/html_canvas_painter.cc
@@ -52,7 +52,8 @@ if (layout_html_canvas_.DrawsBackgroundOntoContentLayer()) { Color background_color = layout_html_canvas_.ResolveColor(GetCSSPropertyBackgroundColor()); - layer->SetBackgroundColor(background_color.Rgb()); + // TODO(crbug/1308932): Remove FromColor and use just SkColor4f. + layer->SetBackgroundColor(SkColor4f::FromColor(background_color.Rgb())); } // We do not take the foreign layer code path when printing because it // prevents painting canvas content as vector graphics.
diff --git a/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc b/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc index f67aaf3..b5d6a6d6 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_table_painters.cc
@@ -421,7 +421,10 @@ const PaintInfo& paint_info, const PhysicalRect& paint_rect, const BoxDecorationData& box_decoration_data) { - PhysicalRect grid_paint_rect = fragment_.TableGridRect(); + WritingModeConverter converter(fragment_.Style().GetWritingDirection(), + fragment_.Size()); + PhysicalRect grid_paint_rect = + converter.ToPhysical(fragment_.TableGridRect()); grid_paint_rect.offset += paint_rect.offset; // Paint the table background on the grid-rect.
diff --git a/third_party/blink/renderer/core/script/mock_script_element_base.h b/third_party/blink/renderer/core/script/mock_script_element_base.h index dd993ef3..f9c4db08 100644 --- a/third_party/blink/renderer/core/script/mock_script_element_base.h +++ b/third_party/blink/renderer/core/script/mock_script_element_base.h
@@ -42,7 +42,7 @@ MOCK_CONST_METHOD0(GetNonceForElement, const AtomicString&()); MOCK_CONST_METHOD0(ElementHasDuplicateAttributes, bool()); MOCK_CONST_METHOD0(InitiatorName, AtomicString()); - MOCK_CONST_METHOD0(IsExplicitlyRenderBlocking, bool()); + MOCK_CONST_METHOD0(IsPotentiallyRenderBlocking, bool()); MOCK_METHOD3(AllowInlineScriptForCSP, bool(const AtomicString&, const WTF::OrdinalNumber&,
diff --git a/third_party/blink/renderer/core/script/script_element_base.h b/third_party/blink/renderer/core/script/script_element_base.h index eb3f4fe..64534de 100644 --- a/third_party/blink/renderer/core/script/script_element_base.h +++ b/third_party/blink/renderer/core/script/script_element_base.h
@@ -67,8 +67,9 @@ virtual bool HasChildren() const = 0; virtual const AtomicString& GetNonceForElement() const = 0; virtual bool ElementHasDuplicateAttributes() const = 0; - // https://html.spec.whatwg.org/C/#explicitly-render-blocking - virtual bool IsExplicitlyRenderBlocking() const = 0; + + // https://html.spec.whatwg.org/C/#potentially-render-blocking + virtual bool IsPotentiallyRenderBlocking() const = 0; // Whether the inline script is allowed by the CSP. Must be called // synchronously to ensure the correct Javascript world is used for CSP
diff --git a/third_party/blink/renderer/core/script/script_loader.cc b/third_party/blink/renderer/core/script/script_loader.cc index 2629a08..cbf258f 100644 --- a/third_party/blink/renderer/core/script/script_loader.cc +++ b/third_party/blink/renderer/core/script/script_loader.cc
@@ -508,14 +508,10 @@ DCHECK(!prepared_pending_script_); - bool has_render_blocking_attr = - RuntimeEnabledFeatures::BlockingAttributeEnabled() && - element_->IsExplicitlyRenderBlocking(); + bool potentially_render_blocking = element_->IsPotentiallyRenderBlocking(); RenderBlockingBehavior render_blocking_behavior = - !has_render_blocking_attr && (non_blocking_ || dynamic_async_ || - element_->DeferAttributeValue()) - ? RenderBlockingBehavior::kNonBlocking - : RenderBlockingBehavior::kBlocking; + potentially_render_blocking ? RenderBlockingBehavior::kBlocking + : RenderBlockingBehavior::kNonBlocking; // <spec step="22">Let options be a script fetch options whose cryptographic // nonce is cryptographic nonce, integrity metadata is integrity metadata, @@ -611,8 +607,9 @@ return false; } - // If the element is render-blocking, block rendering on the element. - if (has_render_blocking_attr && + // If the element is potentially render-blocking, block rendering on the + // element. + if (potentially_render_blocking && element_document.GetRenderBlockingResourceManager()) { element_document.GetRenderBlockingResourceManager()->AddPendingScript( *element_);
diff --git a/third_party/blink/renderer/core/style/grid_area.h b/third_party/blink/renderer/core/style/grid_area.h index 11cd62f..0798cd6 100644 --- a/third_party/blink/renderer/core/style/grid_area.h +++ b/third_party/blink/renderer/core/style/grid_area.h
@@ -46,10 +46,7 @@ // Legacy grid expands out auto-repeaters, so it has a lower cap than GridNG. // Note that this actually allows a [-999,999] range. const int kLegacyGridMaxTracks = 1000; -// GridNG's cap can be higher than 100k tracks. What would prevent us from -// having an extremely large cap (say, INT_MAX - 1) is rendering tracks but -// being unable to query their computed style. -const int kGridMaxTracks = 100000; +const int kGridMaxTracks = INT_MAX - 1; // A span in a single direction (either rows or columns). Note that |start_line| // and |end_line| are grid lines' indexes.
diff --git a/third_party/blink/renderer/core/svg/svg_script_element.h b/third_party/blink/renderer/core/svg/svg_script_element.h index 1f7fa7a..68f0b9a 100644 --- a/third_party/blink/renderer/core/svg/svg_script_element.h +++ b/third_party/blink/renderer/core/svg/svg_script_element.h
@@ -93,7 +93,7 @@ bool ElementHasDuplicateAttributes() const override { return HasDuplicateAttribute(); } - bool IsExplicitlyRenderBlocking() const override { return false; } + bool IsPotentiallyRenderBlocking() const override { return false; } bool AllowInlineScriptForCSP(const AtomicString& nonce, const WTF::OrdinalNumber&, const String& script_content) override;
diff --git a/third_party/blink/renderer/core/svg/svg_style_element.h b/third_party/blink/renderer/core/svg/svg_style_element.h index 0383df44..f6d7401 100644 --- a/third_party/blink/renderer/core/svg/svg_style_element.h +++ b/third_party/blink/renderer/core/svg/svg_style_element.h
@@ -45,8 +45,6 @@ const AtomicString& media() const override; void setMedia(const AtomicString&); - BlockingAttribute* blocking() const override { return nullptr; } - String title() const override; void setTitle(const AtomicString&);
diff --git a/third_party/blink/renderer/core/timing/performance_observer.cc b/third_party/blink/renderer/core/timing/performance_observer.cc index 51106b30..a37c99c6 100644 --- a/third_party/blink/renderer/core/timing/performance_observer.cc +++ b/third_party/blink/renderer/core/timing/performance_observer.cc
@@ -132,10 +132,12 @@ if (entry_type == PerformanceEntry::kInvalid) { String message = "The entry type '" + entry_type_string + "' does not exist or isn't supported."; - GetExecutionContext()->AddConsoleMessage( - MakeGarbageCollected<ConsoleMessage>( - mojom::ConsoleMessageSource::kJavaScript, - mojom::ConsoleMessageLevel::kWarning, message)); + if (GetExecutionContext()) { + GetExecutionContext()->AddConsoleMessage( + MakeGarbageCollected<ConsoleMessage>( + mojom::ConsoleMessageSource::kJavaScript, + mojom::ConsoleMessageLevel::kWarning, message)); + } } entry_types |= entry_type; } @@ -148,10 +150,12 @@ String message = "The PerformanceObserver does not support buffered flag with " "the entryTypes argument."; - GetExecutionContext()->AddConsoleMessage( - MakeGarbageCollected<ConsoleMessage>( - mojom::ConsoleMessageSource::kJavaScript, - mojom::ConsoleMessageLevel::kWarning, message)); + if (GetExecutionContext()) { + GetExecutionContext()->AddConsoleMessage( + MakeGarbageCollected<ConsoleMessage>( + mojom::ConsoleMessageSource::kJavaScript, + mojom::ConsoleMessageLevel::kWarning, message)); + } } filter_options_ = entry_types; } else { @@ -176,10 +180,12 @@ if (entry_type == PerformanceEntry::kInvalid) { String message = "The entry type '" + observer_init->type() + "' does not exist or isn't supported."; - GetExecutionContext()->AddConsoleMessage( - MakeGarbageCollected<ConsoleMessage>( - mojom::ConsoleMessageSource::kJavaScript, - mojom::ConsoleMessageLevel::kWarning, message)); + if (GetExecutionContext()) { + GetExecutionContext()->AddConsoleMessage( + MakeGarbageCollected<ConsoleMessage>( + mojom::ConsoleMessageSource::kJavaScript, + mojom::ConsoleMessageLevel::kWarning, message)); + } return; } if (observer_init->buffered()) {
diff --git a/third_party/blink/renderer/core/timing/performance_observer_test.cc b/third_party/blink/renderer/core/timing/performance_observer_test.cc index f8787a0..4455236 100644 --- a/third_party/blink/renderer/core/timing/performance_observer_test.cc +++ b/third_party/blink/renderer/core/timing/performance_observer_test.cc
@@ -139,4 +139,24 @@ EXPECT_FALSE(IsRegistered()); EXPECT_EQ(0, NumPerformanceEntries()); } + +// Tests that an observe() call with an argument that triggers a console error +// message does not crash, when such call is made after the ExecutionContext is +// detached. +TEST_F(PerformanceObserverTest, ObserveAfterContextDetached) { + NonThrowableExceptionState exception_state; + { + V8TestingScope scope; + Initialize(scope.GetScriptState()); + } + PerformanceObserverInit* options = PerformanceObserverInit::Create(); + Vector<String> entry_type_vec; + entry_type_vec.push_back("invalid"); + options->setEntryTypes(entry_type_vec); + // The V8TestingScope is out of scope so the observer's ExecutionContext + // should now be null. + EXPECT_FALSE(observer_->GetExecutionContext()); + observer_->observe(options, exception_state); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/timing/profiler_group.cc b/third_party/blink/renderer/core/timing/profiler_group.cc index 60d511cb..88481daa 100644 --- a/third_party/blink/renderer/core/timing/profiler_group.cc +++ b/third_party/blink/renderer/core/timing/profiler_group.cc
@@ -169,12 +169,11 @@ String profiler_id = NextProfilerId(); - v8::CpuProfilingOptions options( - v8::kLeafNodeLineNumbers, init_options.maxBufferSize(), - static_cast<int>(sample_interval_us), script_state->GetContext()); - v8::CpuProfilingStatus status = cpu_profiler_->StartProfiling( - V8String(isolate_, profiler_id), options, + V8String(isolate_, profiler_id), + v8::CpuProfilingOptions( + v8::kLeafNodeLineNumbers, init_options.maxBufferSize(), + static_cast<int>(sample_interval_us), script_state->GetContext()), std::make_unique<DiscardedSamplesDelegate>(this, profiler_id)); switch (status) {
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 6f2ef23..5d2697d 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -3443,9 +3443,6 @@ AXObjectSet& visited, const AXObject* aria_label_or_description_root, bool recursive) const { -#if defined(AX_FAIL_FAST_BUILD) - DCHECK(!is_adding_children_); -#endif if (!CanHaveChildren()) return recursive ? String() : GetElement()->GetInnerTextWithoutUpdate(); @@ -3458,11 +3455,12 @@ // included in tree status change), that we do it now, rather than while // traversing the children. UpdateCachedAttributeValuesIfNeeded(); + + const AXObjectVector& children = ChildrenIncludingIgnored(); #if defined(AX_FAIL_FAST_BUILD) base::AutoReset<bool> auto_reset(&is_computing_text_from_descendants_, true); #endif - - for (AXObject* child : ChildrenIncludingIgnored()) { + for (AXObject* child : children) { constexpr size_t kMaxDescendantsForTextAlternativeComputation = 100; if (visited.size() > kMaxDescendantsForTextAlternativeComputation) break; @@ -4158,6 +4156,10 @@ #endif #if defined(AX_FAIL_FAST_BUILD) + SANITIZER_CHECK(!is_computing_text_from_descendants_) + << "Should not attempt to simultaneously compute text from descendants " + "and add children on: " + << ToString(true, true); SANITIZER_CHECK(!is_adding_children_) << " Reentering method on " << GetNode(); base::AutoReset<bool> reentrancy_protector(&is_adding_children_, true);
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index 7a4d440..1152fd1 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -4911,11 +4911,12 @@ // AccessibilityExposeIgnoredNodes(). // Loop through AXObject children. + #if defined(AX_FAIL_FAST_BUILD) - CHECK(!is_adding_children_) + SANITIZER_CHECK(!is_adding_children_) << "Should not attempt to simultaneously add and clear children on: " << ToString(true, true); - CHECK(!is_computing_text_from_descendants_) + SANITIZER_CHECK(!is_computing_text_from_descendants_) << "Should not attempt to simultaneously compute text from descendants " "and clear children on: " << ToString(true, true);
diff --git a/third_party/blink/renderer/modules/geolocation/geolocation.cc b/third_party/blink/renderer/modules/geolocation/geolocation.cc index d20af60..6a1a7fa6 100644 --- a/third_party/blink/renderer/modules/geolocation/geolocation.cc +++ b/third_party/blink/renderer/modules/geolocation/geolocation.cc
@@ -502,6 +502,16 @@ } else { GeolocationPositionError* position_error = CreatePositionError(position->error_code, position->error_message); + + auto* context = GetExecutionContext(); + DCHECK(context); + if (!position->error_technical.IsEmpty()) { + context->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( + mojom::blink::ConsoleMessageSource::kNetwork, + mojom::blink::ConsoleMessageLevel::kError, + position->error_technical)); + } + if (position_error->code() == GeolocationPositionError::kPermissionDenied) { position_error->SetIsFatal(true); }
diff --git a/third_party/blink/renderer/modules/modules_initializer.cc b/third_party/blink/renderer/modules/modules_initializer.cc index 73e4f0f3..f8c6d977 100644 --- a/third_party/blink/renderer/modules/modules_initializer.cc +++ b/third_party/blink/renderer/modules/modules_initializer.cc
@@ -268,19 +268,16 @@ InspectorDOMAgent* dom_agent, InspectedFrames* inspected_frames, Page* page) const { - session->Append(MakeGarbageCollected<InspectorIndexedDBAgent>( - inspected_frames, session->V8Session())); - session->Append( - MakeGarbageCollected<DeviceOrientationInspectorAgent>(inspected_frames)); - session->Append( - MakeGarbageCollected<InspectorDOMStorageAgent>(inspected_frames)); - session->Append(MakeGarbageCollected<InspectorAccessibilityAgent>( - inspected_frames, dom_agent)); - session->Append(MakeGarbageCollected<InspectorWebAudioAgent>(page)); + session->CreateAndAppend<InspectorIndexedDBAgent>(inspected_frames, + session->V8Session()); + session->CreateAndAppend<DeviceOrientationInspectorAgent>(inspected_frames); + session->CreateAndAppend<InspectorDOMStorageAgent>(inspected_frames); + session->CreateAndAppend<InspectorAccessibilityAgent>(inspected_frames, + dom_agent); + session->CreateAndAppend<InspectorWebAudioAgent>(page); if (allow_view_agents) { - session->Append(MakeGarbageCollected<InspectorDatabaseAgent>(page)); - session->Append( - MakeGarbageCollected<InspectorCacheStorageAgent>(inspected_frames)); + session->CreateAndAppend<InspectorDatabaseAgent>(page); + session->CreateAndAppend<InspectorCacheStorageAgent>(inspected_frames); } }
diff --git a/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc b/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc index 23ef795..82272b2 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/layers_as_json.cc
@@ -56,9 +56,11 @@ if (layer.should_check_backface_visibility()) json->SetString("backfaceVisibility", "hidden"); - if (Color(layer.background_color()).Alpha()) { - json->SetString("backgroundColor", - Color(layer.background_color()).NameForLayoutTreeAsText()); + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. + if (Color(layer.background_color().toSkColor()).Alpha()) { + json->SetString( + "backgroundColor", + Color(layer.background_color().toSkColor()).NameForLayoutTreeAsText()); } if (flags &
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc index 1741107..3b00e8a 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
@@ -842,7 +842,8 @@ Color background_color; for (Color color : base::Reversed(background_colors)) background_color = background_color.Blend(color); - layer.SetBackgroundColor(background_color.Rgb()); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + layer.SetBackgroundColor(SkColor4f::FromColor(background_color.Rgb())); } static void UpdateTouchActionRegion(
diff --git a/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc b/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc index 64bed20c..849cd30 100644 --- a/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc +++ b/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc
@@ -48,7 +48,7 @@ // TODO(lethalantidote): Remove this logic. It should be covered by setting // the layer's opacity to false. solid_color_layer_ = cc::SolidColorLayer::Create(); - solid_color_layer_->SetBackgroundColor(SK_ColorTRANSPARENT); + solid_color_layer_->SetBackgroundColor(SkColors::kTransparent); if (observer_) observer_->RegisterContentsLayer(solid_color_layer_.get()); }
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng index 9efc36c..ff766fb 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng +++ b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng
@@ -482,6 +482,15 @@ crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-005.html [ Failure ] crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-006.html [ Failure ] crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-007.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-008.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-009.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-010.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-011.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-012.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-013.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-014.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-015.html [ Failure ] +crbug.com/1045599 fast/css-grid-layout/grid-auto-repeat-huge-grid-016.html [ Failure ] crbug.com/1045599 fast/css-grid-layout/grid-item-spanning-and-orthogonal-flows.html [ Failure ] crbug.com/1045599 fast/css-grid-layout/grid-track-sizing-with-orthogonal-flows.html [ Failure ] crbug.com/1045599 fast/css-grid-layout/maximize-tracks-definite-indefinite-height.html [ Failure ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 05e95600..8b7255d 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -6821,10 +6821,6 @@ # Sheriff 2022-04-14 crbug.com/1095540 [ Mac ] virtual/threaded-prefer-compositing/fast/scrolling/resize-corner-tracking-touch.html [ Skip ] -# FedCM API test failures -crbug.com/1314987 external/wpt/credential-management/fedcm-logout.sub.https.html [ Skip ] -crbug.com/1314987 external/wpt/credential-management/fedcm-network-requests.sub.https.html [ Skip ] - crbug.com/1313970 virtual/fenced-frame-shadow-dom/wpt_internal/fenced_frame/visual-viewport.https.html [ Failure ] # Sheriff 2022-04-08
diff --git a/third_party/blink/web_tests/editing/pasteboard/copy-standalone-oriented-image.html b/third_party/blink/web_tests/editing/pasteboard/copy-standalone-oriented-image.html index f00ff6e5..81ef9e9a 100644 --- a/third_party/blink/web_tests/editing/pasteboard/copy-standalone-oriented-image.html +++ b/third_party/blink/web_tests/editing/pasteboard/copy-standalone-oriented-image.html
@@ -34,7 +34,7 @@ then click in the red box and paste the image. If the image pastes successfully the test is passed.</p> -<iframe name="imageframe" src="../../external/wpt/css/css-images/image-orientation/support/exif-orientation-5-lu.jpg" onload="editingTest()"> +<iframe name="imageframe" src="support/exif-orientation-5-lu.jpg" onload="editingTest()"> </iframe> <div id="dest" class="editable" contenteditable="true"> </div>
diff --git a/third_party/blink/web_tests/editing/pasteboard/support/exif-orientation-5-lu.jpg b/third_party/blink/web_tests/editing/pasteboard/support/exif-orientation-5-lu.jpg new file mode 100644 index 0000000..06f0f663 --- /dev/null +++ b/third_party/blink/web_tests/editing/pasteboard/support/exif-orientation-5-lu.jpg Binary files differ
diff --git a/third_party/blink/web_tests/external/wpt/.well-known/fedcm.json b/third_party/blink/web_tests/external/wpt/.well-known/fedcm.json new file mode 100644 index 0000000..54175a71 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/.well-known/fedcm.json
@@ -0,0 +1,5 @@ +{ + "provider_urls": [ + "https://web-platform.test:8444/credential-management/support/" + ] +}
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href.html index 76e9576..0c2a43a6 100644 --- a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href.html +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href.html
@@ -1,26 +1,15 @@ <!DOCTYPE HTML> <html> - <head> <meta http-equiv="Content-Security-Policy" content="script-src 'unsafe-hashes' 'nonce-abc' - 'sha256-r5W8SQIDMTbMxAjJ7KzCzFT38dwBy7Y5KF5B+20009g=';"> - <!-- - 'sha256-r5W8SQIDMTbMxAjJ7KzCzFT38dwBy7Y5KF5B+20009g=' ==> 'javascript:t1.done();' - --> - <script src='/resources/testharness.js' nonce='abc'></script> - <script src='/resources/testharnessreport.js' nonce='abc'></script> + 'sha256-l0Wxf12cHMZT6UQ2zsQ7AcFSb6Y198d37Ki8zWITecM=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> </head> - <body> - <div id='log'></div> - <a href='javascript:t1.done();' id='test'> - <script nonce='abc'> - var t1 = async_test("Test that the javascript: src is allowed to run"); - - window.addEventListener('securitypolicyviolation', t1.unreached_func("Should have not raised any event")); - - document.getElementById('test').click(); + <script nonce="abc"> + runTest(true, '<a href>', ''); </script> </body> - </html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank-script-src-attr.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank-script-src-attr.html new file mode 100644 index 0000000..f2b3e1f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank-script-src-attr.html
@@ -0,0 +1,18 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta http-equiv="Content-Security-Policy" content="script-src-attr 'unsafe-hashes' 'nonce-abc' + 'sha256-N5bidCKdNO1nSPa1G7MdL6S7Y7MKZ7UMIS/40JBMSe4=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> +</head> +<body> + <script nonce="abc"> + // script-src-attr CSP should not have effects because navigation CSP + // checks are done against script-src-elem. + // https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check + runTest(true, '<a href target=_blank>', ' (script-src-attr should not be used)'); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank-script-src-elem.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank-script-src-elem.html new file mode 100644 index 0000000..642d9768 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank-script-src-elem.html
@@ -0,0 +1,15 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta http-equiv="Content-Security-Policy" content="script-src-elem 'unsafe-hashes' 'nonce-abc' + 'sha256-N5bidCKdNO1nSPa1G7MdL6S7Y7MKZ7UMIS/40JBMSe4=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> +</head> +<body> + <script nonce="abc"> + runTest(true, '<a href target=_blank>', ''); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank.html index 007338bc..a321521e 100644 --- a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank.html +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_allowed-href_blank.html
@@ -1,26 +1,15 @@ <!DOCTYPE HTML> <html> - <head> <meta http-equiv="Content-Security-Policy" content="script-src 'unsafe-hashes' 'nonce-abc' - 'sha256-WZYVPzLjoxd1Cbc8gcx07ChlPmT3WP+KxkOiY0s4h8g=';"> - <!-- - 'sha256-WZYVPzLjoxd1Cbc8gcx07ChlPmT3WP+KxkOiY0s4h8g=' ==> 'javascript:opener.t1.done();' - --> - <script src='/resources/testharness.js' nonce='abc'></script> - <script src='/resources/testharnessreport.js' nonce='abc'></script> + 'sha256-N5bidCKdNO1nSPa1G7MdL6S7Y7MKZ7UMIS/40JBMSe4=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> </head> - <body> - <div id='log'></div> - <a target="_blank" rel="opener" href='javascript:opener.t1.done();' id='test'> - <script nonce='abc'> - var t1 = async_test("Test that the javascript: src is allowed to run"); - - window.addEventListener('securitypolicyviolation', t1.unreached_func("Should have not raised any event")); - - document.getElementById('test').click(); + <script nonce="abc"> + runTest(true, '<a href target=_blank>', ''); </script> </body> - </html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href.html index 991200a..0f0dc67 100644 --- a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href.html +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href.html
@@ -1,29 +1,15 @@ <!DOCTYPE HTML> <html> - <head> <meta http-equiv="Content-Security-Policy" content="script-src 'nonce-abc' - 'sha256-3MhWOWQJwDMJCRltopqBmDhP4qq569eTDcH+BpbHp0o=';"> - <!-- - 'sha256-3MhWOWQJwDMJCRltopqBmDhP4qq569eTDcH+BpbHp0o=' ==> javascript:t1.unreached_func("Should not have run javascript: URL"); - --> - <script src='/resources/testharness.js' nonce='abc'></script> - <script src='/resources/testharnessreport.js' nonce='abc'></script> + 'sha256-l0Wxf12cHMZT6UQ2zsQ7AcFSb6Y198d37Ki8zWITecM=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> </head> - <body> - <div id='log'></div> - <a href='javascript:t1.unreached_func("Should not have run javascript: URL");' id='test'> - <script nonce='abc'> - var t1 = async_test("Test that the javascript: src is not allowed to run"); - - window.addEventListener('securitypolicyviolation', t1.step_func_done(function(e) { - assert_equals(e.violatedDirective, 'script-src-elem'); - assert_equals(e.blockedURI, 'inline'); - })); - - document.getElementById('test').click(); + <script nonce="abc"> + runTest(false, '<a href>', ' due to missing unsafe-hashes'); </script> </body> - </html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-attr.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-attr.html new file mode 100644 index 0000000..6b863e7a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-attr.html
@@ -0,0 +1,18 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta http-equiv="Content-Security-Policy" content="script-src-attr 'nonce-abc' + 'sha256-N5bidCKdNO1nSPa1G7MdL6S7Y7MKZ7UMIS/40JBMSe4=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> +</head> +<body> + <script nonce="abc"> + // script-src-attr CSP should not have effects because navigation CSP + // checks are done against script-src-elem. + // https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check + runTest(true, '<a href target=_blank>', ' (script-src-attr should not be used)'); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem.html new file mode 100644 index 0000000..23e9bdc1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem.html
@@ -0,0 +1,15 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta http-equiv="Content-Security-Policy" content="script-src-elem 'nonce-abc' + 'sha256-N5bidCKdNO1nSPa1G7MdL6S7Y7MKZ7UMIS/40JBMSe4=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> +</head> +<body> + <script nonce="abc"> + runTest(false, '<a href target=_blank>', ' due to missing unsafe-hashes'); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank.html index 66ec9e1..81805a1 100644 --- a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank.html +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank.html
@@ -1,29 +1,15 @@ <!DOCTYPE HTML> <html> - <head> - <meta http-equiv="Content-Security-Policy" content="script-src 'unsafe-hashes' 'nonce-abc' - 'sha256-r5W8SQIDMTbMxAjJ7KzCzFT38dwBy7Y5KF5B+20009g=';"> - <!-- - 'sha256-3MhWOWQJwDMJCRltopqBmDhP4qq569eTDcH+BpbHp0o=' ==> javascript:t1.unreached_func("Should not have run javascript: URL"); - --> - <script src='/resources/testharness.js' nonce='abc'></script> - <script src='/resources/testharnessreport.js' nonce='abc'></script> + <meta http-equiv="Content-Security-Policy" content="script-src 'nonce-abc' + 'sha256-N5bidCKdNO1nSPa1G7MdL6S7Y7MKZ7UMIS/40JBMSe4=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> </head> - <body> - <div id='log'></div> - <a href='javascript:t1.unreached_func("Should not have run javascript: URL");' id='test'> - <script nonce='abc'> - var t1 = async_test("Test that the javascript: src is not allowed to run"); - - window.addEventListener('securitypolicyviolation', t1.step_func_done(function(e) { - assert_equals(e.violatedDirective, 'script-src-elem'); - assert_equals(e.blockedURI, 'inline'); - })); - - document.getElementById('test').click(); + <script nonce="abc"> + runTest(false, '<a href target=_blank>', ' due to missing unsafe-hashes'); </script> </body> - </html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href.html index 944b727..6558a03 100644 --- a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href.html +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href.html
@@ -1,29 +1,15 @@ <!DOCTYPE HTML> <html> - <head> <meta http-equiv="Content-Security-Policy" content="script-src 'unsafe-hashes' 'nonce-abc' - 'sha256-r5W8SQIDMTbMxAjJ7KzCzFT38dwBy7Y5KF5B+20009g=';"> - <!-- - 'sha256-3MhWOWQJwDMJCRltopqBmDhP4qq569eTDcH+BpbHp0o=' ==> javascript:t1.unreached_func("Should not have run javascript: URL"); - --> - <script src='/resources/testharness.js' nonce='abc'></script> - <script src='/resources/testharnessreport.js' nonce='abc'></script> + 'sha256-wrongwrongwrongwrongwrongwrongwrongwrongwro=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> </head> - <body> - <div id='log'></div> - <a href='javascript:t1.unreached_func("Should not have run javascript: URL");' id='test'> - <script nonce='abc'> - var t1 = async_test("Test that the javascript: src is not allowed to run"); - - window.addEventListener('securitypolicyviolation', t1.step_func_done(function(e) { - assert_equals(e.violatedDirective, 'script-src-elem'); - assert_equals(e.blockedURI, 'inline'); - })); - - document.getElementById('test').click(); + <script nonce="abc"> + runTest(false, '<a href>', ' due to wrong hash'); </script> </body> - </html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-attr.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-attr.html new file mode 100644 index 0000000..fa394b1d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-attr.html
@@ -0,0 +1,18 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta http-equiv="Content-Security-Policy" content="script-src-attr 'unsafe-hashes' 'nonce-abc' + 'sha256-wrongwrongwrongwrongwrongwrongwrongwrongwro=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> +</head> +<body> + <script nonce="abc"> + // script-src-attr CSP should not have effects because navigation CSP + // checks are done against script-src-elem. + // https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check + runTest(true, '<a href target=_blank>', ' (script-src-attr should not be used)'); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem.html new file mode 100644 index 0000000..8ca49da --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem.html
@@ -0,0 +1,15 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta http-equiv="Content-Security-Policy" content="script-src-elem 'unsafe-hashes' 'nonce-abc' + 'sha256-wrongwrongwrongwrongwrongwrongwrongwrongwro=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> +</head> +<body> + <script nonce="abc"> + runTest(false, '<a href target=_blank>', ' due to wrong hash'); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank.html b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank.html index 84491f8..257899af 100644 --- a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank.html +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank.html
@@ -1,29 +1,15 @@ <!DOCTYPE HTML> <html> - <head> - <meta http-equiv="Content-Security-Policy" content="script-src 'nonce-abc' - 'sha256-3MhWOWQJwDMJCRltopqBmDhP4qq569eTDcH+BpbHp0o=';"> - <!-- - 'sha256-3MhWOWQJwDMJCRltopqBmDhP4qq569eTDcH+BpbHp0o=' ==> javascript:t1.unreached_func("Should not have run javascript: URL"); - --> - <script src='/resources/testharness.js' nonce='abc'></script> - <script src='/resources/testharnessreport.js' nonce='abc'></script> + <meta http-equiv="Content-Security-Policy" content="script-src 'unsafe-hashes' 'nonce-abc' + 'sha256-wrongwrongwrongwrongwrongwrongwrongwrongwro=';"> + <script src="/resources/testharness.js" nonce="abc"></script> + <script src="/resources/testharnessreport.js" nonce="abc"></script> + <script src="support/helper.js" nonce="abc"></script> </head> - <body> - <div id='log'></div> - <a target="_blank" href='javascript:t1.unreached_func("Should not have run javascript: URL");' id='test'> - <script nonce='abc'> - var t1 = async_test("Test that the javascript: src is not allowed to run"); - - window.addEventListener('securitypolicyviolation', t1.step_func_done(function(e) { - assert_equals(e.violatedDirective, 'script-src-elem'); - assert_equals(e.blockedURI, 'inline'); - })); - - document.getElementById('test').click(); + <script nonce="abc"> + runTest(false, '<a href target=_blank>', ' due to wrong hash'); </script> </body> - </html>
diff --git a/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/support/helper.js b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/support/helper.js new file mode 100644 index 0000000..26db3289 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/content-security-policy/unsafe-hashes/support/helper.js
@@ -0,0 +1,40 @@ +// Typical CSP hashes are: +// 'sha256-N5bidCKdNO1nSPa1G7MdL6S7Y7MKZ7UMIS/40JBMSe4=' ==> javascript:opener.navigated(); +// 'sha256-l0Wxf12cHMZT6UQ2zsQ7AcFSb6Y198d37Ki8zWITecM=' ==> javascript:navigated(); + +function runTest(navigationShouldAllowed, navigationMethod, description) { + const t1 = async_test( + 'javascript: navigation using ' + navigationMethod + ' should be ' + + (navigationShouldAllowed ? 'allowed' : 'refused') + description); + + if (navigationShouldAllowed) { + window.navigated = () => t1.done(); + window.addEventListener('securitypolicyviolation', + t1.unreached_func('Should have not raised any event')); + } else { + window.navigated = + t1.unreached_func('Should not have run javascript: URL'); + window.addEventListener('securitypolicyviolation', + t1.step_func_done(function(e) { + assert_equals(e.violatedDirective, 'script-src-elem'); + assert_equals(e.blockedURI, 'inline'); + })); + } + + if (navigationMethod === '<a href target=_blank>') { + const a = document.createElement('a'); + a.setAttribute('target', '_blank'); + a.setAttribute('rel', 'opener'); + a.setAttribute('href', 'javascript:opener.navigated();'); + document.body.appendChild(a); + a.click(); + } + else if (navigationMethod === '<a href>') { + const a = document.createElement('a'); + a.setAttribute('href', 'javascript:navigated();'); + document.body.appendChild(a); + a.click(); + } else { + t1.unreached_func('Invalid navigationMethod: ' + navigationMethod)(); + } +}
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-htb-ltr-ref.html b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-htb-ltr-ref.html new file mode 100644 index 0000000..5830aa5f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-htb-ltr-ref.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<style> +.multicol { + inline-size: 400px; + block-size: 100px; + columns: 4; + column-fill: auto; + gap: 0; +} +.pattern { + background: repeating-linear-gradient(orange, orange 25px, dodgerblue 25px, dodgerblue 50px); +} +</style> +<div class="multicol"> + <div style="block-size: 140px; background: lime"></div> + <div class="pattern" style="border: solid 10px; block-size: 225px;"></div> + <div style="block-size: 15px; background: lime"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-htb-ltr.html b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-htb-ltr.html new file mode 100644 index 0000000..e2be9ce1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-htb-ltr.html
@@ -0,0 +1,23 @@ +<!DOCTYPE html> +<link rel="match" href="table-grid-paint-htb-ltr-ref.html"> +<link rel="help" href="https://drafts.csswg.org/css-tables-3/#fragmentation"> +<link rel="help" href="https://drafts.csswg.org/css-tables-3/#rendering"> +<style> +.multicol { + inline-size: 400px; + block-size: 100px; + columns: 4; + column-fill: auto; + gap: 0; +} +.pattern { + background: repeating-linear-gradient(orange, orange 25px, dodgerblue 25px, dodgerblue 50px); +} +</style> +<div class="multicol"> + <table class="pattern" style="inline-size: 100%; border-spacing: 0; border: solid 10px;"> + <caption style="block-size: 140px; background: lime"></caption> + <tbody><td style="padding: 0; block-size: 225px;"></td></tbody> + <caption style="caption-side: bottom; block-size: 15px; background: lime"></caption> + </table> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vlr-rtl-ref.html b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vlr-rtl-ref.html new file mode 100644 index 0000000..5f069ea05 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vlr-rtl-ref.html
@@ -0,0 +1,22 @@ +<!DOCTYPE html> +<style> +body { + writing-mode: vertical-lr; + direction: rtl; +} +.multicol { + inline-size: 400px; + block-size: 100px; + columns: 4; + column-fill: auto; + gap: 0; +} +.pattern { + background: repeating-linear-gradient(to right, orange, orange 25px, dodgerblue 25px, dodgerblue 50px); +} +</style> +<div class="multicol"> + <div style="block-size: 140px; background: lime"></div> + <div class="pattern" style="border: solid 10px; block-size: 225px;"></div> + <div style="block-size: 15px; background: lime"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vlr-rtl.html b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vlr-rtl.html new file mode 100644 index 0000000..b2636305 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vlr-rtl.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<link rel="match" href="table-grid-paint-vlr-rtl-ref.html"> +<link rel="help" href="https://drafts.csswg.org/css-tables-3/#fragmentation"> +<link rel="help" href="https://drafts.csswg.org/css-tables-3/#rendering"> +<style> +body { + writing-mode: vertical-lr; + direction: rtl; +} +.multicol { + inline-size: 400px; + block-size: 100px; + columns: 4; + column-fill: auto; + gap: 0; +} +.pattern { + background: repeating-linear-gradient(to right, orange, orange 25px, dodgerblue 25px, dodgerblue 50px); +} +</style> +<div class="multicol"> + <table class="pattern" style="inline-size: 100%; border-spacing: 0; border: solid 10px;"> + <caption style="block-size: 140px; background: lime"></caption> + <tbody><td style="padding: 0; block-size: 225px;"></td></tbody> + <caption style="caption-side: bottom; block-size: 15px; background: lime"></caption> + </table> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vrl-rtl-ref.html b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vrl-rtl-ref.html new file mode 100644 index 0000000..2080a4e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vrl-rtl-ref.html
@@ -0,0 +1,22 @@ +<!DOCTYPE html> +<style> +body { + writing-mode: vertical-rl; + direction: rtl; +} +.multicol { + inline-size: 400px; + block-size: 100px; + columns: 4; + column-fill: auto; + gap: 0; +} +.pattern { + background: repeating-linear-gradient(to left, orange, orange 25px, dodgerblue 25px, dodgerblue 50px); +} +</style> +<div class="multicol"> + <div style="block-size: 140px; background: lime"></div> + <div class="pattern" style="border: solid 10px; block-size: 225px;"></div> + <div style="block-size: 15px; background: lime"></div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vrl-rtl.html b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vrl-rtl.html new file mode 100644 index 0000000..0d83c6c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-break/table/table-grid-paint-vrl-rtl.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<link rel="match" href="table-grid-paint-vrl-rtl-ref.html"> +<link rel="help" href="https://drafts.csswg.org/css-tables-3/#fragmentation"> +<link rel="help" href="https://drafts.csswg.org/css-tables-3/#rendering"> +<style> +body { + writing-mode: vertical-rl; + direction: rtl; +} +.multicol { + inline-size: 400px; + block-size: 100px; + columns: 4; + column-fill: auto; + gap: 0; +} +.pattern { + background: repeating-linear-gradient(to left, orange, orange 25px, dodgerblue 25px, dodgerblue 50px); +} +</style> +<div class="multicol"> + <table class="pattern" style="inline-size: 100%; border-spacing: 0; border: solid 10px;"> + <caption style="block-size: 140px; background: lime"></caption> + <tbody><td style="padding: 0; block-size: 225px;"></td></tbody> + <caption style="caption-side: bottom; block-size: 15px; background: lime"></caption> + </table> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-writing-modes/crashtests/unicode-bidi-select-crash.html b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/crashtests/unicode-bidi-select-crash.html new file mode 100644 index 0000000..b36a3761 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-writing-modes/crashtests/unicode-bidi-select-crash.html
@@ -0,0 +1,19 @@ +<!DOCTYPE html> +<link rel="help" href="https://crbug.com/1329417"> +<style> + select { + unicode-bidi: bidi-override; + } +</style> +<body> + <select> + <option>Test1</option> + <option id="opt" hidden="hidden">Test2</option> + </select> +</body> +<script> + document.body.offsetTop; + opt.defaultSelected = true; + window.getSelection().selectAllChildren(document.body); + document.vlinkColor = "red"; +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/resources/helper.sub.js b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/resources/helper.sub.js index ff446f5e..4b42d91 100644 --- a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/resources/helper.sub.js +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/resources/helper.sub.js
@@ -187,3 +187,16 @@ } }, description); } + +// Call clients.claim() on the service worker +async function claim(t, worker) { + const channel = new MessageChannel(); + const saw_message = new Promise(function(resolve) { + channel.port1.onmessage = t.step_func(function(e) { + assert_equals(e.data, 'PASS', 'Worker call to claim() should fulfill.'); + resolve(); + }); + }); + worker.postMessage({port: channel.port2}, [channel.port2]); + await saw_message; +}
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/resources/service-worker.js b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/resources/service-worker.js new file mode 100644 index 0000000..60dceb0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/resources/service-worker.js
@@ -0,0 +1,31 @@ +self.addEventListener('message', function(event) { + self.clients.claim() + .then(function(result) { + if (result !== undefined) { + event.data.port.postMessage( + 'FAIL: claim() should be resolved with undefined'); + return; + } + event.data.port.postMessage('PASS'); + }) + .catch(function(error) { + event.data.port.postMessage('FAIL: exception: ' + error.name); + }); + }); + +self.addEventListener('fetch', e => { + if (e.request.url.match(/\/is-controlled/)) { + e.respondWith(new Response('controlled')); + } + else if (e.request.url.match(/\/get-clients-matchall/)) { + const options = { includeUncontrolled: true, type: 'all' }; + e.respondWith( + self.clients.matchAll(options) + .then(clients => { + const client_urls = []; + clients.forEach(client => client_urls.push(client.url)); + return new Response(JSON.stringify(client_urls)); + }) + ); + } + });
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-clients-claim.https.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-clients-claim.https.html new file mode 100644 index 0000000..d9540c2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-clients-claim.https.html
@@ -0,0 +1,71 @@ +<!doctype html> +<meta name="timeout" content="long"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> +<script src="/common/dispatcher/dispatcher.js"></script> +<script src="resources/helper.sub.js"></script> +<script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script> +<script> +// Calling Clients.claim() on the service worker when a controlled page is in +// BFCache should evict the page from BFCache, as per +// https://github.com/w3c/ServiceWorker/issues/1038#issuecomment-291028845. +promise_test(async t => { + const pageA = new RemoteContext(token()); + const pageB = new RemoteContext(token()); + + const urlA = location.origin + executorPath + pageA.context_id; + const urlB = originCrossSite + executorPath + pageB.context_id; + + window.open(urlA, '_blank', 'noopener'); + await pageA.execute_script(waitForPageShow); + + // Register a service worker after `pageA` is loaded to make `pageA` + // uncontrolled at this time. + const workerUrl = + 'resources/service-worker.js?pipe=header(Service-Worker-Allowed,../)'; + const registration = + await service_worker_unregister_and_register(t, workerUrl, './'); + t.add_cleanup(_ => registration.unregister()); + await wait_for_state(t, registration.installing, 'activated'); + + // Navigate to `urlB`. + await pageA.execute_script( + (url) => { + prepareNavigation(() => { location.href = url; }); + }, + [urlB]); + await pageB.execute_script(waitForPageShow); + + // Call Clients.claim() on the service worker when `pageA` is in BFCache. + const controllerChanged = new Promise( + resolve => navigator.serviceWorker.oncontrollerchange = resolve); + await claim(t, registration.active); + await controllerChanged; + + // `pageA` doesn't appear in matchAll(). + const clients1 = await (await fetch('/get-clients-matchall')).json(); + assert_true(clients1.indexOf(urlA) < 0, + '1: matchAll() before back navigation'); + + // Back navigate and check that the page was evicted from BFCache. + await pageB.execute_script( + () => { + prepareNavigation(() => { history.back(); }); + } + ); + await pageA.execute_script(waitForPageShow); + await assert_not_bfcached(pageA); + + // After back navigation, `pageA` appear in matchAll(), because it was newly + // loaded and controlled by the service worker. + const clients2 = await (await fetch('/get-clients-matchall')).json(); + const controlled2 = await pageA.execute_script( + () => (navigator.serviceWorker.controller !== null)); + assert_true(clients2.indexOf(urlA) >= 0, + '2: matchAll() just after back navigation'); + assert_true(controlled2, + '2: pageA should be controlled just after back navigation'); + +}, 'Clients.claim() evicts pages that would be affected from BFCache'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-clients-matchall.https.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-clients-matchall.https.html new file mode 100644 index 0000000..069529db --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-clients-matchall.https.html
@@ -0,0 +1,76 @@ +<!doctype html> +<meta name="timeout" content="long"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> +<script src="/common/dispatcher/dispatcher.js"></script> +<script src="resources/helper.sub.js"></script> +<script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script> +<script> +promise_test(async t => { + // Register a service worker and make this page controlled. + const workerUrl = + 'resources/service-worker.js?pipe=header(Service-Worker-Allowed,../)'; + const registration = + await service_worker_unregister_and_register(t, workerUrl, './'); + t.add_cleanup(_ => registration.unregister()); + await wait_for_state(t, registration.installing, 'activated'); + const controllerChanged = new Promise( + resolve => navigator.serviceWorker.oncontrollerchange = resolve); + await claim(t, registration.active); + await controllerChanged; + + const pageA = new RemoteContext(token()); + const pageB = new RemoteContext(token()); + + const urlA = location.origin + executorPath + pageA.context_id; + const urlB = originCrossSite + executorPath + pageB.context_id; + + // Open `urlA`. + window.open(urlA, '_blank', 'noopener'); + await pageA.execute_script(waitForPageShow); + + // Get Clients.matchAll() and check whether `pageA` is controlled. + // Actual `assert_*()` is called after `assert_bfcached()` below. + const clients1 = await (await fetch('/get-clients-matchall')).json(); + const controlled1 = await pageA.execute_script( + () => (navigator.serviceWorker.controller !== null)); + + // Navigate to `urlB` and get Clients.matchAll() when `urlA` is in BFCache. + await pageA.execute_script( + (url) => prepareNavigation(() => { + location.href = url; + }), + [urlB]); + await pageB.execute_script(waitForPageShow); + const clients2 = await (await fetch('/get-clients-matchall')).json(); + + // Back navigate and check whether the page is restored from BFCache. + await pageB.execute_script( + () => { + prepareNavigation(() => { history.back(); }); + } + ); + await pageA.execute_script(waitForPageShow); + await assert_bfcached(pageA); + + // Get Clients.matchAll() and check whether `pageA` is controlled. + const clients3 = await (await fetch('/get-clients-matchall')).json(); + const controlled3 = await pageA.execute_script( + () => (navigator.serviceWorker.controller !== null)); + + // Clients.matchAll() should not list `urlA` when it is in BFCache. + assert_true(clients1.indexOf(urlA) >= 0, + '1: matchAll() before navigation'); + assert_true(clients2.indexOf(urlA) < 0, + '2: matchAll() before back navigation'); + assert_true(clients3.indexOf(urlA) >= 0, + '3: matchAll() after back navigation'); + + // `pageA` should be controlled before/after BFCached. + assert_true(controlled1, + 'pageA should be controlled before BFCached'); + assert_true(controlled3, + 'pageA should be controlled after restored'); +}, 'Clients.matchAll() should not list pages in BFCache'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-controlled-after-restore.https.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-controlled-after-restore.https.html new file mode 100644 index 0000000..5a63b6e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-controlled-after-restore.https.html
@@ -0,0 +1,54 @@ +<!doctype html> +<meta name="timeout" content="long"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> +<script src="/common/dispatcher/dispatcher.js"></script> +<script src="resources/helper.sub.js"></script> +<script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script> +<script> +promise_test(async t => { + const pageA = new RemoteContext(token()); + const pageB = new RemoteContext(token()); + + const urlA = location.origin + executorPath + pageA.context_id; + const urlB = originCrossSite + executorPath + pageB.context_id; + + // Register a service worker. + const workerUrl = + 'resources/service-worker.js?pipe=header(Service-Worker-Allowed,../)'; + const registration = + await service_worker_unregister_and_register(t, workerUrl, './'); + t.add_cleanup(_ => registration.unregister()); + await wait_for_state(t, registration.installing, 'activated'); + + window.open(urlA, '_blank', 'noopener'); + await pageA.execute_script(waitForPageShow); + + assert_true( + await pageA.execute_script( + () => (navigator.serviceWorker.controller !== null)), + 'pageA should be controlled before navigation'); + + navigateAndThenBack(pageA, pageB, urlB); + await assert_bfcached(pageA); + + assert_true( + await pageA.execute_script( + () => (navigator.serviceWorker.controller !== null)), + 'navigator.serviceWorker.controller should be non-null ' + + 'after restored from BFCache'); + + const isControlled = await pageA.execute_script( + () => fetch('/is-controlled').then(r => r.text())); + + assert_true( + await pageA.execute_script( + () => (navigator.serviceWorker.controller !== null)), + 'navigator.serviceWorker.controller should be non-null ' + + 'after restored from BFCache and after fetch'); + + assert_equals(isControlled, 'controlled', + 'fetch should be intercepted after restored from BFCache'); +}, 'Pages should remain controlled after restored from BFCache'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-unregister.https.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-unregister.https.html new file mode 100644 index 0000000..1c3f811 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-unregister.https.html
@@ -0,0 +1,67 @@ +<!doctype html> +<meta name="timeout" content="long"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/utils.js"></script> +<script src="/common/dispatcher/dispatcher.js"></script> +<script src="resources/helper.sub.js"></script> +<script src="/service-workers/service-worker/resources/test-helpers.sub.js"></script> +<script> +// When a service worker is unregistered when a controlled page is in BFCache, +// the page can be still restored from BFCache and remain controlled by the +// service worker. +promise_test(async t => { + // Register a service worker and make this page controlled. + const workerUrl = + 'resources/service-worker.js?pipe=header(Service-Worker-Allowed,../)'; + const registration = + await service_worker_unregister_and_register(t, workerUrl, './'); + t.add_cleanup(_ => registration.unregister()); + await wait_for_state(t, registration.installing, 'activated'); + const controllerChanged = new Promise( + resolve => navigator.serviceWorker.oncontrollerchange = resolve); + await claim(t, registration.active); + await controllerChanged; + + const pageA = new RemoteContext(token()); + const pageB = new RemoteContext(token()); + + const urlA = location.origin + executorPath + pageA.context_id; + const urlB = originCrossSite + executorPath + pageB.context_id; + + // Open `urlA`. + window.open(urlA, '_blank', 'noopener'); + await pageA.execute_script(waitForPageShow); + + assert_true( + await pageA.execute_script( + () => (navigator.serviceWorker.controller !== null)), + 'pageA should be controlled before navigation'); + + // Navigate to `urlB`. + await pageA.execute_script( + (url) => prepareNavigation(() => { + location.href = url; + }), + [urlB]); + await pageB.execute_script(waitForPageShow); + + // Unregister the service worker when the controlled `pageA` is in BFCache. + await registration.unregister(); + + // Back navigate and check whether the page is restored from BFCache. + await pageB.execute_script( + () => { + prepareNavigation(() => { history.back(); }); + } + ); + await pageA.execute_script(waitForPageShow); + await assert_not_bfcached(pageA); + + assert_true( + await pageA.execute_script( + () => (navigator.serviceWorker.controller === null)), + 'pageA should not be controlled'); + +}, 'Unregister service worker while a controlled page is in BFCache'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/lint.ignore b/third_party/blink/web_tests/external/wpt/lint.ignore index 33aafc9..e6e755b 100644 --- a/third_party/blink/web_tests/external/wpt/lint.ignore +++ b/third_party/blink/web_tests/external/wpt/lint.ignore
@@ -727,6 +727,9 @@ WEB-PLATFORM.TEST:web-bundle/subresource-loading/*.html WEB-PLATFORM.TEST:web-bundle/subresource-loading/resources/*.js +# well-known file has hardcoded URLs +WEB-PLATFORM.TEST: .well-known/fedcm.json + # Tests that depend on resources in /gen/ in Chromium: # https://github.com/web-platform-tests/wpt/issues/16455 # Please consult with ecosystem-infra@chromium.org before adding more.
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/crash-large-positions.html b/third_party/blink/web_tests/fast/css-grid-layout/crash-large-positions.html index 3b3a89e8..2c448e4 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/crash-large-positions.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/crash-large-positions.html
@@ -10,6 +10,6 @@ <script> test(function() { - testGridPositionDefinitionsValues(document.getElementById("item"), "100000", "-100000", "100000", "-100000"); + testGridPositionDefinitionsValues(document.getElementById("item"), "2.14748e+09", "-2.14748e+09", "2.14748e+09", "-2.14748e+09"); }, "Test that setting and getting grid-column|row-start|end to huge values is properly clamped and does not make the renderer crash."); </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-001.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-001.html index 97ec3a9..41817528 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-001.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-001.html
@@ -11,49 +11,17 @@ <script src="resources/grid-tracks-length.js"></script> <div id="wideAutoFillGrid" class="grid wideGrid lotsOfFixedRepeatWithAutoFillCols"></div> -<div id="wideAutoFitGrid" class="grid wideGrid lotsOfFixedRepeatWithAutoFitCols"> - <div>Item1</div> - <div>Item2</div> - <div class="lastColumn">Item3</div> -</div> - -<div id="autoFillGrid" class="grid tallGrid lotsOfFixedRepeatWithAutoFillRows"></div> -<div id="autoFitGrid" class="grid tallGrid lotsOfFixedRepeatWithAutoFitRows"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> <script> test(function() { - var autoFillGrid = testElement("wideAutoFillGrid", "grid-template-columns", 100000); - var autoFitGrid = testElement("wideAutoFitGrid", "grid-template-columns", 100000); + var autoFillGrid = testElement("wideAutoFillGrid", "grid-template-columns", 3570505); - assert_equals(autoFillGrid[100000 - 1], "20px"); - assert_equals(autoFillGrid[100000 - 2], "7px"); + assert_equals(autoFillGrid[3570505 - 1], "1px"); + assert_equals(autoFillGrid[3570505 - 2], "1px"); assert_equals(autoFillGrid[0], "10px"); assert_equals(autoFillGrid[1], "2px"); - assert_equals(autoFitGrid[100000 - 1], "10px"); - assert_equals(autoFitGrid[100000 - 2], "0px"); - assert_equals(autoFitGrid[0], "10px"); - assert_equals(autoFitGrid[1], "2px"); }, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids (normal tracks clamped)."); -test(function() { - var autoFillGrid = testElement("autoFillGrid", "grid-template-rows", 100000); - var autoFitGrid = testElement("autoFitGrid", "grid-template-rows", 100000); - - assert_equals(autoFillGrid[100000 - 1], "20px"); - assert_equals(autoFillGrid[100000 - 2], "7px"); - assert_equals(autoFillGrid[0], "10px"); - assert_equals(autoFillGrid[1], "2px"); - - assert_equals(autoFitGrid[100000 - 1], "10px"); - assert_equals(autoFitGrid[100000 - 2], "0px"); - assert_equals(autoFitGrid[0], "10px"); - assert_equals(autoFitGrid[1], "2px"); -}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids (normal tracks clamped)."); - </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-002.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-002.html index a2e4f3b..d641ec7 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-002.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-002.html
@@ -10,70 +10,21 @@ <script src="resources/grid-definitions-parsing-utils.js"></script> <script src="resources/grid-tracks-length.js"></script> -<div id="wideAutoFillGridFewRepetitions" class="grid wideGrid lotsOfAutoRepeatWithAutoFillCols"></div> -<div id="wideAutoFitGridFewRepetitions" class="grid wideGrid lotsOfAutoRepeatWithAutoFitCols"> +<div id="wideAutoFitGrid" class="grid wideGrid lotsOfFixedRepeatWithAutoFitCols"> <div>Item1</div> <div>Item2</div> <div class="lastColumn">Item3</div> </div> -<div id="tallAutoFillGridFewRepetitions" class="grid tallGrid lotsOfAutoRepeatWithAutoFillRows"></div> -<div id="tallAutoFitGridFewRepetitions" class="grid tallGrid lotsOfAutoRepeatWithAutoFitRows"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> - <script> test(function() { - var fillGridElement = document.getElementById("wideAutoFillGridFewRepetitions"); - var fitGridElement = document.getElementById("wideAutoFitGridFewRepetitions"); + var autoFitGrid = testElement("wideAutoFitGrid", "grid-template-columns", 5034005); - fillGridElement.style.gridGap = "100px"; - fitGridElement.style.gridGap = "100px"; - - var autoFillGrid = testElement("wideAutoFillGridFewRepetitions", "grid-template-columns", 100000); - var autoFitGrid = testElement("wideAutoFitGridFewRepetitions", "grid-template-columns", 100000); - - assert_equals(autoFillGrid[100000 - 1], "20px"); - assert_equals(autoFillGrid[100000 - 2], "7px"); - assert_equals(autoFitGrid[100000 - 1], "10px"); + assert_equals(autoFitGrid[100000 - 1], "0px"); assert_equals(autoFitGrid[100000 - 2], "0px"); - - fillGridElement.style.gridGap = "1000000px"; - fitGridElement.style.gridGap = "1000000px"; - - testElement("wideAutoFillGridFewRepetitions", "grid-template-columns", 30); - testElement("wideAutoFitGridFewRepetitions", "grid-template-columns", 34); - - fillGridElement.style.gridGap = "0px"; - fitGridElement.style.gridGap = "0px"; -}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids with gaps."); - -test(function() { - var autoFillGridElement = document.getElementById("tallAutoFillGridFewRepetitions"); - var autoFitGridElement = document.getElementById("tallAutoFitGridFewRepetitions"); - - autoFillGridElement.style.gridGap = "100px"; - autoFitGridElement.style.gridGap = "100px"; - - var autoFillGrid = testElement("tallAutoFillGridFewRepetitions", "grid-template-rows", 100000); - var autoFitGrid = testElement("tallAutoFitGridFewRepetitions", "grid-template-rows", 100000); - - assert_equals(autoFillGrid[100000 - 1], "20px"); - assert_equals(autoFillGrid[100000 - 2], "7px"); - assert_equals(autoFitGrid[100000 - 1], "10px"); - assert_equals(autoFitGrid[100000 - 2], "0px"); - - autoFillGridElement.style.gridGap = "1000000px"; - autoFitGridElement.style.gridGap = "1000000px"; - - testElement("tallAutoFillGridFewRepetitions", "grid-template-rows", 30); - testElement("tallAutoFitGridFewRepetitions", "grid-template-rows", 34); - - autoFillGridElement.style.gridGap = "0px"; - autoFitGridElement.style.gridGap = "0px"; -}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids with gaps."); + assert_equals(autoFitGrid[0], "10px"); + assert_equals(autoFitGrid[1], "2px"); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids (normal tracks clamped)."); </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-003.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-003.html index e63a2b17..9bcb8716 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-003.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-003.html
@@ -10,15 +10,8 @@ <script src="resources/grid-definitions-parsing-utils.js"></script> <script src="resources/grid-tracks-length.js"></script> -<div id="wideAutoFillGridReversed" class="grid wideGrid lotsOfFixedRepeatWithAutoFillColsReversed"></div> -<div id="wideAutoFitGridReversed" class="grid wideGrid lotsOfFixedRepeatWithAutoFitColsReversed"> - <div>Item1</div> - <div>Item2</div> - <div class="lastColumn">Item3</div> -</div> - -<div id="tallAutoFillGridReversed" class="grid tallGrid lotsOfFixedRepeatWithAutoFillRowsReversed"></div> -<div id="tallAutoFitGridReversed" class="grid tallGrid lotsOfFixedRepeatWithAutoFitRowsReversed"> +<div id="autoFillGrid" class="grid tallGrid lotsOfFixedRepeatWithAutoFillRows"></div> +<div id="autoFitGrid" class="grid tallGrid lotsOfFixedRepeatWithAutoFitRows"> <div>Item1</div> <div>Item2</div> <div class="lastRow">Item3</div> @@ -27,33 +20,18 @@ <script> test(function() { - var autoFillGrid = testElement("wideAutoFillGridReversed", "grid-template-columns", 100000); - var autoFitGrid = testElement("wideAutoFitGridReversed", "grid-template-columns", 100000); + var autoFillGrid = testElement("autoFillGrid", "grid-template-rows", 3570505); + var autoFitGrid = testElement("autoFitGrid", "grid-template-rows", 5034005); - assert_equals(autoFillGrid[100000 - 1], "20px"); - assert_equals(autoFillGrid[100000 - 2], "7px"); - assert_equals(autoFillGrid[0], "1px"); - assert_equals(autoFillGrid[1], "1px"); + assert_equals(autoFillGrid[3570505 - 1], "1px"); + assert_equals(autoFillGrid[3570505 - 2], "1px"); + assert_equals(autoFillGrid[0], "10px"); + assert_equals(autoFillGrid[1], "2px"); - assert_equals(autoFitGrid[100000 - 1], "2px"); - assert_equals(autoFitGrid[100000 - 2], "0px"); - assert_equals(autoFitGrid[0], "1px"); - assert_equals(autoFitGrid[1], "1px"); -}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids (auto repeat tracks clamped)."); - -test(function() { - var autoFillGrid = testElement("tallAutoFillGridReversed", "grid-template-rows", 100000); - var autoFitGrid = testElement("tallAutoFitGridReversed", "grid-template-rows", 100000); - - assert_equals(autoFillGrid[100000 - 1], "20px"); - assert_equals(autoFillGrid[100000 - 2], "7px"); - assert_equals(autoFillGrid[0], "1px"); - assert_equals(autoFillGrid[1], "1px"); - - assert_equals(autoFitGrid[100000 - 1], "2px"); - assert_equals(autoFitGrid[100000 - 2], "0px"); - assert_equals(autoFitGrid[0], "1px"); - assert_equals(autoFitGrid[1], "1px"); -}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids (auto repeat tracks clamped)."); + assert_equals(autoFitGrid[5034005 - 1], "1px"); + assert_equals(autoFitGrid[5034005 - 2], "1px"); + assert_equals(autoFitGrid[0], "10px"); + assert_equals(autoFitGrid[1], "2px"); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids (normal tracks clamped)."); </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-004.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-004.html index 4187f39..1bb70d1 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-004.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-004.html
@@ -10,15 +10,15 @@ <script src="resources/grid-definitions-parsing-utils.js"></script> <script src="resources/grid-tracks-length.js"></script> -<div id="wideAutoFillGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFillCols minSizeWideGrid min-content"></div> -<div id="wideAutoFitGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFitCols minSizeWideGrid min-content"> +<div id="wideAutoFillGridFewRepetitions" class="grid wideGrid lotsOfAutoRepeatWithAutoFillCols"></div> +<div id="wideAutoFitGridFewRepetitions" class="grid wideGrid lotsOfAutoRepeatWithAutoFitCols"> <div>Item1</div> <div>Item2</div> <div class="lastColumn">Item3</div> </div> -<div id="tallAutoFillGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFillRows minSizeTallGrid min-content"></div> -<div id="tallAutoFitGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFitRows minSizeTallGrid min-content"> +<div id="tallAutoFillGridFewRepetitions" class="grid tallGrid lotsOfAutoRepeatWithAutoFillRows"></div> +<div id="tallAutoFitGridFewRepetitions" class="grid tallGrid lotsOfAutoRepeatWithAutoFitRows"> <div>Item1</div> <div>Item2</div> <div class="lastRow">Item3</div> @@ -27,24 +27,53 @@ <script> test(function() { - var autoFillCols = testElement("wideAutoFillGridFewRepetitionsMinSize", "grid-template-columns", 100000); - var autoFitCols = testElement("wideAutoFitGridFewRepetitionsMinSize", "grid-template-columns", 100000); + var fillGridElement = document.getElementById("wideAutoFillGridFewRepetitions"); + var fitGridElement = document.getElementById("wideAutoFitGridFewRepetitions"); - /* Check that clamping auto repetitions does not reduce the amount of the other tracks. */ - assert_equals(autoFillCols[100000 - 1], "20px"); - assert_equals(autoFillCols[100000 - 2], "7px"); - assert_equals(autoFitCols[100000 - 1], "10px"); - assert_equals(autoFitCols[100000 - 2], "0px"); -}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids with gaps and min-width."); + fillGridElement.style.gridGap = "100px"; + fitGridElement.style.gridGap = "100px"; + + var autoFillGrid = testElement("wideAutoFillGridFewRepetitions", "grid-template-columns", 306710); + var autoFitGrid = testElement("wideAutoFitGridFewRepetitions", "grid-template-columns", 314572); + + assert_equals(autoFillGrid[306710 - 1], "1px"); + assert_equals(autoFillGrid[306710 - 2], "1px"); + assert_equals(autoFitGrid[314572 - 1], "1px"); + assert_equals(autoFitGrid[314572 - 2], "1px"); + + fillGridElement.style.gridGap = "1000000px"; + fitGridElement.style.gridGap = "1000000px"; + + testElement("wideAutoFillGridFewRepetitions", "grid-template-columns", 30); + testElement("wideAutoFitGridFewRepetitions", "grid-template-columns", 34); + + fillGridElement.style.gridGap = "0px"; + fitGridElement.style.gridGap = "0px"; +}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids with gaps."); test(function() { - var autoFillRows = testElement("tallAutoFillGridFewRepetitionsMinSize", "grid-template-rows", 100000); - var autoFitRows = testElement("tallAutoFitGridFewRepetitionsMinSize", "grid-template-rows", 100000); + var autoFillGridElement = document.getElementById("tallAutoFillGridFewRepetitions"); + var autoFitGridElement = document.getElementById("tallAutoFitGridFewRepetitions"); - assert_equals(autoFillRows[100000 - 1], "20px"); - assert_equals(autoFillRows[100000 - 2], "7px"); - assert_equals(autoFitRows[100000 - 1], "10px"); - assert_equals(autoFitRows[100000 - 2], "0px"); -}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids with gaps and min-height."); + autoFillGridElement.style.gridGap = "100px"; + autoFitGridElement.style.gridGap = "100px"; + + var autoFillGrid = testElement("tallAutoFillGridFewRepetitions", "grid-template-rows", 306710); + var autoFitGrid = testElement("tallAutoFitGridFewRepetitions", "grid-template-rows", 314572); + + assert_equals(autoFillGrid[306710 - 1], "1px"); + assert_equals(autoFillGrid[306710 - 2], "1px"); + assert_equals(autoFitGrid[314572 - 1], "1px"); + assert_equals(autoFitGrid[314572 - 2], "1px"); + + autoFillGridElement.style.gridGap = "1000000px"; + autoFitGridElement.style.gridGap = "1000000px"; + + testElement("tallAutoFillGridFewRepetitions", "grid-template-rows", 30); + testElement("tallAutoFitGridFewRepetitions", "grid-template-rows", 34); + + autoFillGridElement.style.gridGap = "0px"; + autoFitGridElement.style.gridGap = "0px"; +}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids with gaps."); </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-005.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-005.html index ed10174..30c62d4 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-005.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-005.html
@@ -10,142 +10,18 @@ <script src="resources/grid-definitions-parsing-utils.js"></script> <script src="resources/grid-tracks-length.js"></script> -<div id="twoThousandAutoFillRows" class="grid height25k autoFillRows25px"></div> -<div id="fourThousandAutoFitRows" class="grid height25k autoFitRows25px"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> - -<div id="twoThousandAutoFillCols" class="grid width25k autoFillCols25px"></div> -<div id="fourThousandAutoFitCols" class="grid width25k autoFitCols25px"> - <div>Item1</div> - <div>Item2</div> - <div class="lastColumn">Item3</div> -</div> - -<div id="moreThanAThousandAutoFillAndFixedRows" class="grid height25k autoFillRows205pxFixed5px"></div> -<div id="moreThanAThousandAutoFitAndFixedRows" class="grid height25k autoFitRows205pxFixed5px"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> - -<div id="moreThanAThousandAutoFillAndFixedCols" class="grid width25k autoFillCols205pxFixed5px"></div> -<div id="moreThanAThousandAutoFitAndFixedCols" class="grid width25k autoFitCols205pxFixed5px"> - <div>Item1</div> - <div>Item2</div> - <div class="lastColumn">Item3</div> -</div> - -<div id="aThousandFixedZeroAutoFillRows" class="grid height25k autoFillAndAThousandFixedRows"></div> -<div id="aThousandFixedZeroAutoFitRows" class="grid height25k autoFitAndAThousandFixedRows"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> - -<div id="aThousandFixedZeroAutoFillCols" class="grid width25k autoFillAndAThousandFixedCols"></div> -<div id="aThousandFixedZeroAutoFitCols" class="grid width25k autoFitAndAThousandFixedCols"> - <div>Item1</div> - <div>Item2</div> - <div class="lastColumn">Item3</div> -</div> - -<div id="aHundredThousandFixedZeroAutoFillRowsFreeSpace" class="grid tallGrid autoFillAndAThousandFixedRows"></div> -<div id="aHundredThousandFixedZeroAutoFitRowsFreeSpace" class="grid tallGrid autoFitAndAThousandFixedRows"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> - -<div id="aHundredThousandFixedZeroAutoFillColsFreeSpace" class="grid wideGrid autoFillAndAThousandFixedCols"></div> -<div id="aHundredThousandFixedZeroAutoFitColsFreeSpace" class="grid wideGrid autoFitAndAThousandFixedCols"> - <div>Item1</div> - <div>Item2</div> - <div class="lastColumn">Item3</div> -</div> +<div id="wideAutoFillGridReversed" class="grid wideGrid lotsOfFixedRepeatWithAutoFillColsReversed"></div> <script> test(function() { - var autoFillRows = testElement("twoThousandAutoFillRows", "grid-template-rows", 2000); - var autoFitRows = testElement("fourThousandAutoFitRows", "grid-template-rows", 4000); + var autoFillGrid = testElement("wideAutoFillGridReversed", "grid-template-columns", 3570505); - assert_equals(autoFillRows[2000 - 1], "8px"); - assert_equals(autoFillRows[2000 - 2], "17px"); - assert_equals(autoFitRows[4000 - 1], "5px"); - assert_equals(autoFitRows[4000 - 2], "0px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks auto repeat rows on very tall grids."); + assert_equals(autoFillGrid[3570505 - 1], "20px"); + assert_equals(autoFillGrid[3570505 - 2], "7px"); + assert_equals(autoFillGrid[0], "1px"); + assert_equals(autoFillGrid[1], "1px"); -test(function() { - var autoFillCols = testElement("twoThousandAutoFillCols", "grid-template-columns", 2000); - var autoFitCols = testElement("fourThousandAutoFitCols", "grid-template-columns", 4000); - - assert_equals(autoFillCols[2000 - 1], "23px"); - assert_equals(autoFillCols[2000 - 2], "2px"); - assert_equals(autoFitCols[4000 - 1], "5px"); - assert_equals(autoFitCols[4000 - 2], "0px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks auto repeat columns on very wide grids."); - -test(function() { - var autoFillRows = testElement("moreThanAThousandAutoFillAndFixedRows", "grid-template-rows", 1100); - var autoFitRows = testElement("moreThanAThousandAutoFitAndFixedRows", "grid-template-rows", 1400); - - assert_equals(autoFillRows[1100 - 1], "5px"); - assert_equals(autoFillRows[1100 - 2], "200px"); - assert_equals(autoFitRows[1400 - 1], "72px"); - assert_equals(autoFitRows[1400 - 2], "0px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks (normal and auto-repeat) rows on very tall grids."); - -test(function() { - var autoFillCols = testElement("moreThanAThousandAutoFillAndFixedCols", "grid-template-columns", 1100); - var autoFitCols = testElement("moreThanAThousandAutoFitAndFixedCols", "grid-template-columns", 1400); - - assert_equals(autoFillCols[1100 - 1], "5px"); - assert_equals(autoFillCols[1100 - 2], "200px"); - assert_equals(autoFitCols[1400 - 1], "72px"); - assert_equals(autoFitCols[1400 - 2], "0px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks (normal and auto-repeat) columns on very wide grids."); - -test(function() { - var autoFillGrid = testElement("aThousandFixedZeroAutoFillRows", "grid-template-rows", 1001); - var autoFitGrid = testElement("aThousandFixedZeroAutoFitRows", "grid-template-rows", 1003); - - assert_equals(autoFillGrid[1001 - 1], "37px"); - assert_equals(autoFillGrid[0], "2px"); - assert_equals(autoFitGrid[1003 - 1], "37px"); - assert_equals(autoFitGrid[0], "20px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat rows on very tall grids."); - -test(function() { - var autoFillGrid = testElement("aThousandFixedZeroAutoFillCols", "grid-template-columns", 1001); - var autoFitGrid = testElement("aThousandFixedZeroAutoFitCols", "grid-template-columns", 1003); - - assert_equals(autoFillGrid[1001 - 1], "37px"); - assert_equals(autoFillGrid[0], "2px"); - assert_equals(autoFitGrid[1003 - 1], "37px"); - assert_equals(autoFitGrid[0], "20px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat columns on very wide grids."); - -test(function() { - var autoFillGrid = testElement("aHundredThousandFixedZeroAutoFillRowsFreeSpace", "grid-template-rows", 100000); - var autoFitGrid = testElement("aHundredThousandFixedZeroAutoFitRowsFreeSpace", "grid-template-rows", 100000); - - assert_equals(autoFillGrid[10000 - 1], "2px"); - assert_equals(autoFillGrid[0], "2px"); - assert_equals(autoFitGrid[10000 - 1], "0px"); - assert_equals(autoFitGrid[0], "20px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat rows on very tall grids with enough room for auto repetitions."); - -test(function() { - var autoFillGrid = testElement("aHundredThousandFixedZeroAutoFillColsFreeSpace", "grid-template-columns", 100000); - var autoFitGrid = testElement("aHundredThousandFixedZeroAutoFitColsFreeSpace", "grid-template-columns", 100000); - - assert_equals(autoFillGrid[100000 - 1], "2px"); - assert_equals(autoFillGrid[0], "2px"); - assert_equals(autoFitGrid[100000 - 1], "20px"); - assert_equals(autoFitGrid[0], "20px"); -}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat columns on very wide grids with enough room for auto repetitions."); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids (auto repeat tracks clamped)."); </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-006.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-006.html index 955f49a..f149811 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-006.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-006.html
@@ -10,15 +10,7 @@ <script src="resources/grid-definitions-parsing-utils.js"></script> <script src="resources/grid-tracks-length.js"></script> -<div id="moreThanAThousandFixedZeroAutoFillRows" class="grid height25k autoFillAndMoreThanThousandFixedRows"></div> -<div id="moreThanAThousandFixedZeroAutoFitRows" class="grid height25k autoFitAndMoreThanThousandFixedRows"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> - -<div id="moreThanAThousandFixedZeroAutoFillCols" class="grid width25k autoFillAndMoreThanThousandFixedCols"></div> -<div id="moreThanAThousandFixedZeroAutoFitCols" class="grid width25k autoFitAndMoreThanThousandFixedCols"> +<div id="wideAutoFitGridReversed" class="grid wideGrid lotsOfFixedRepeatWithAutoFitColsReversed"> <div>Item1</div> <div>Item2</div> <div class="lastColumn">Item3</div> @@ -27,23 +19,12 @@ <script> test(function() { - var autoFillGrid = testElement("moreThanAThousandFixedZeroAutoFillRows", "grid-template-rows", 1648); - var autoFitGrid = testElement("moreThanAThousandFixedZeroAutoFitRows", "grid-template-rows", 1630); + var autoFitGrid = testElement("wideAutoFitGridReversed", "grid-template-columns", 5034005); - assert_equals(autoFillGrid[1648 - 1], "6px"); - assert_equals(autoFillGrid[0], "7px"); - assert_equals(autoFitGrid[1630 - 1], "6px"); - assert_equals(autoFitGrid[0], "7px"); -}, "Test that we don't crash when there are more than kGridMaxTracks non auto-repeat rows on very tall grids."); - -test(function() { - var autoFillGrid = testElement("moreThanAThousandFixedZeroAutoFillCols", "grid-template-columns", 1648); - var autoFitGrid = testElement("moreThanAThousandFixedZeroAutoFitCols", "grid-template-columns", 1630); - - assert_equals(autoFillGrid[1648 - 1], "6px"); - assert_equals(autoFillGrid[0], "7px"); - assert_equals(autoFitGrid[1630 - 1], "6px"); - assert_equals(autoFitGrid[0], "7px"); -}, "Test that we don't crash when there are more than kGridMaxTracks non auto-repeat columns on very wide grids."); + assert_equals(autoFitGrid[5034005 - 1], "8px"); + assert_equals(autoFitGrid[5034005 - 2], "0px"); + assert_equals(autoFitGrid[0], "1px"); + assert_equals(autoFitGrid[1], "1px"); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids (auto repeat tracks clamped)."); </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-007.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-007.html index 474bef5b..2530fe5 100644 --- a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-007.html +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-007.html
@@ -10,40 +10,18 @@ <script src="resources/grid-definitions-parsing-utils.js"></script> <script src="resources/grid-tracks-length.js"></script> -<div id="handMadeAutoFillRows" class="grid tallGrid handMadeMoreThanThousandAutoFillRows"></div> -<div id="handMadeAutoFitRows" class="grid tallGrid handMadeMoreThanThousandAutoFitRows"> - <div>Item1</div> - <div>Item2</div> - <div class="lastRow">Item3</div> -</div> - -<div id="handMadeAutoFillCols" class="grid wideGrid handMadeMoreThanThousandAutoFillCols"></div> -<div id="handMadeAutoFitCols" class="grid wideGrid handMadeMoreThanThousandAutoFitCols"> - <div>Item1</div> - <div>Item2</div> - <div class="lastColumn">Item3</div> -</div> +<div id="tallAutoFillGridReversed" class="grid tallGrid lotsOfFixedRepeatWithAutoFillRowsReversed"></div> <script> test(function() { - var autoFillGrid = testElement("handMadeAutoFillRows", "grid-template-rows", 100000); - var autoFitGrid = testElement("handMadeAutoFitRows", "grid-template-rows", 100000); + var autoFillGrid = testElement("tallAutoFillGridReversed", "grid-template-rows", 3570505); - assert_equals(autoFillGrid[100000 - 1], "10px"); - assert_equals(autoFillGrid[0], "10px"); - assert_equals(autoFitGrid[100000 - 1], "10px"); - assert_equals(autoFitGrid[0], "10px"); -}, "Test that we don't crash when there are more than kGridMaxTracks rows in the auto repeat <track-list>."); + assert_equals(autoFillGrid[3570505 - 1], "20px"); + assert_equals(autoFillGrid[3570505 - 2], "7px"); + assert_equals(autoFillGrid[0], "1px"); + assert_equals(autoFillGrid[1], "1px"); -test(function() { - var autoFillGrid = testElement("handMadeAutoFillCols", "grid-template-columns", 100000); - var autoFitGrid = testElement("handMadeAutoFitCols", "grid-template-columns", 100000); - - assert_equals(autoFillGrid[100000 - 1], "10px"); - assert_equals(autoFillGrid[0], "10px"); - assert_equals(autoFitGrid[100000 - 1], "10px"); - assert_equals(autoFitGrid[0], "10px"); -}, "Test that we don't crash when there are more than kGridMaxTracks columns in the auto repeat <track-list>."); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids (auto repeat tracks clamped)."); </script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-008.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-008.html new file mode 100644 index 0000000..9e9d030b --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-008.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="tallAutoFitGridReversed" class="grid tallGrid lotsOfFixedRepeatWithAutoFitRowsReversed"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<script> + +test(function() { + var autoFitGrid = testElement("tallAutoFitGridReversed", "grid-template-rows", 5034005); + + assert_equals(autoFitGrid[5034005 - 1], "8px"); + assert_equals(autoFitGrid[5034005 - 2], "0px"); + assert_equals(autoFitGrid[0], "1px"); + assert_equals(autoFitGrid[1], "1px"); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids (auto repeat tracks clamped)."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-009.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-009.html new file mode 100644 index 0000000..bba078a --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-009.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="wideAutoFillGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFillCols minSizeWideGrid min-content"></div> +<div id="wideAutoFitGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFitCols minSizeWideGrid min-content"> + <div>Item1</div> + <div>Item2</div> + <div class="lastColumn">Item3</div> +</div> + +<script> + +test(function() { + var autoFillCols = testElement("wideAutoFillGridFewRepetitionsMinSize", "grid-template-columns", 3569630); + var autoFitCols = testElement("wideAutoFitGridFewRepetitionsMinSize", "grid-template-columns", 5033170); + + /* Check that clamping auto repetitions does not reduce the amount of the other tracks. */ + assert_equals(autoFillCols[3569630 - 1], "0.390625px"); + assert_equals(autoFillCols[3569630 - 2], "0.390625px"); + assert_equals(autoFitCols[5033170 - 1], "1px"); + assert_equals(autoFitCols[5033170 - 2], "1px"); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very wide grids with gaps and min-width."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-010.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-010.html new file mode 100644 index 0000000..4906f9e --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-010.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="tallAutoFillGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFillRows minSizeTallGrid min-content"></div> +<div id="tallAutoFitGridFewRepetitionsMinSize" class="grid lotsOfAutoRepeatWithAutoFitRows minSizeTallGrid min-content"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<script> + +test(function() { + var autoFillRows = testElement("tallAutoFillGridFewRepetitionsMinSize", "grid-template-rows", 3569630); + var autoFitRows = testElement("tallAutoFitGridFewRepetitionsMinSize", "grid-template-rows", 5033173); + + assert_equals(autoFillRows[3569630 - 1], "0.390625px"); + assert_equals(autoFillRows[3569630 - 2], "0.390625px"); + assert_equals(autoFitRows[5033173 - 1], "1px"); + assert_equals(autoFitRows[5033173 - 2], "1px"); +}, "Test that we don't get more than kGridMaxTracks repetitions even on very tall grids with gaps and min-height."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-011.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-011.html new file mode 100644 index 0000000..3f5a5df --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-011.html
@@ -0,0 +1,143 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="twoThousandAutoFillRows" class="grid height25k autoFillRows25px"></div> +<div id="fourThousandAutoFitRows" class="grid height25k autoFitRows25px"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<div id="twoThousandAutoFillCols" class="grid width25k autoFillCols25px"></div> +<div id="fourThousandAutoFitCols" class="grid width25k autoFitCols25px"> + <div>Item1</div> + <div>Item2</div> + <div class="lastColumn">Item3</div> +</div> + +<div id="moreThanAThousandAutoFillAndFixedRows" class="grid height25k autoFillRows205pxFixed5px"></div> +<div id="moreThanAThousandAutoFitAndFixedRows" class="grid height25k autoFitRows205pxFixed5px"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<div id="moreThanAThousandAutoFillAndFixedCols" class="grid width25k autoFillCols205pxFixed5px"></div> +<div id="moreThanAThousandAutoFitAndFixedCols" class="grid width25k autoFitCols205pxFixed5px"> + <div>Item1</div> + <div>Item2</div> + <div class="lastColumn">Item3</div> +</div> + +<div id="aThousandFixedZeroAutoFillRows" class="grid height25k autoFillAndAThousandFixedRows"></div> +<div id="aThousandFixedZeroAutoFitRows" class="grid height25k autoFitAndAThousandFixedRows"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<div id="aThousandFixedZeroAutoFillCols" class="grid width25k autoFillAndAThousandFixedCols"></div> +<div id="aThousandFixedZeroAutoFitCols" class="grid width25k autoFitAndAThousandFixedCols"> + <div>Item1</div> + <div>Item2</div> + <div class="lastColumn">Item3</div> +</div> + +<div id="aHundredThousandFixedZeroAutoFitRowsFreeSpace" class="grid tallGrid autoFitAndAThousandFixedRows"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<div id="aHundredThousandFixedZeroAutoFitColsFreeSpace" class="grid wideGrid autoFitAndAThousandFixedCols"> + <div>Item1</div> + <div>Item2</div> + <div class="lastColumn">Item3</div> +</div> + +<script> + +test(function() { + var autoFillRows = testElement("twoThousandAutoFillRows", "grid-template-rows", 2000); + var autoFitRows = testElement("fourThousandAutoFitRows", "grid-template-rows", 4000); + + assert_equals(autoFillRows[2000 - 1], "8px"); + assert_equals(autoFillRows[2000 - 2], "17px"); + assert_equals(autoFitRows[4000 - 1], "5px"); + assert_equals(autoFitRows[4000 - 2], "0px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks auto repeat rows on very tall grids."); + +test(function() { + var autoFillCols = testElement("twoThousandAutoFillCols", "grid-template-columns", 2000); + var autoFitCols = testElement("fourThousandAutoFitCols", "grid-template-columns", 4000); + + assert_equals(autoFillCols[2000 - 1], "23px"); + assert_equals(autoFillCols[2000 - 2], "2px"); + assert_equals(autoFitCols[4000 - 1], "5px"); + assert_equals(autoFitCols[4000 - 2], "0px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks auto repeat columns on very wide grids."); + +test(function() { + var autoFillRows = testElement("moreThanAThousandAutoFillAndFixedRows", "grid-template-rows", 1100); + var autoFitRows = testElement("moreThanAThousandAutoFitAndFixedRows", "grid-template-rows", 1400); + + assert_equals(autoFillRows[1100 - 1], "5px"); + assert_equals(autoFillRows[1100 - 2], "200px"); + assert_equals(autoFitRows[1400 - 1], "72px"); + assert_equals(autoFitRows[1400 - 2], "0px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks (normal and auto-repeat) rows on very tall grids."); + +test(function() { + var autoFillCols = testElement("moreThanAThousandAutoFillAndFixedCols", "grid-template-columns", 1100); + var autoFitCols = testElement("moreThanAThousandAutoFitAndFixedCols", "grid-template-columns", 1400); + + assert_equals(autoFillCols[1100 - 1], "5px"); + assert_equals(autoFillCols[1100 - 2], "200px"); + assert_equals(autoFitCols[1400 - 1], "72px"); + assert_equals(autoFitCols[1400 - 2], "0px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks (normal and auto-repeat) columns on very wide grids."); + +test(function() { + var autoFillGrid = testElement("aThousandFixedZeroAutoFillRows", "grid-template-rows", 1001); + var autoFitGrid = testElement("aThousandFixedZeroAutoFitRows", "grid-template-rows", 1003); + + assert_equals(autoFillGrid[1001 - 1], "37px"); + assert_equals(autoFillGrid[0], "2px"); + assert_equals(autoFitGrid[1003 - 1], "37px"); + assert_equals(autoFitGrid[0], "20px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat rows on very tall grids."); + +test(function() { + var autoFillGrid = testElement("aThousandFixedZeroAutoFillCols", "grid-template-columns", 1001); + var autoFitGrid = testElement("aThousandFixedZeroAutoFitCols", "grid-template-columns", 1003); + + assert_equals(autoFillGrid[1001 - 1], "37px"); + assert_equals(autoFillGrid[0], "2px"); + assert_equals(autoFitGrid[1003 - 1], "37px"); + assert_equals(autoFitGrid[0], "20px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat columns on very wide grids."); + +test(function() { + var autoFitGrid = testElement("aHundredThousandFixedZeroAutoFitRowsFreeSpace", "grid-template-rows", 709114); + + assert_equals(autoFitGrid[709114 - 1], "37px"); + assert_equals(autoFitGrid[0], "20px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat rows on very tall grids with enough room for auto repetitions."); + +test(function() { + var autoFitGrid = testElement("aHundredThousandFixedZeroAutoFitColsFreeSpace", "grid-template-columns", 709114); + + assert_equals(autoFitGrid[709114 - 1], "37px"); + assert_equals(autoFitGrid[0], "20px"); +}, "Test that we don't crash when there are exactly kGridMaxTracks non auto-repeat columns on very wide grids with enough room for auto repetitions."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-012.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-012.html new file mode 100644 index 0000000..955f49a --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-012.html
@@ -0,0 +1,49 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="moreThanAThousandFixedZeroAutoFillRows" class="grid height25k autoFillAndMoreThanThousandFixedRows"></div> +<div id="moreThanAThousandFixedZeroAutoFitRows" class="grid height25k autoFitAndMoreThanThousandFixedRows"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<div id="moreThanAThousandFixedZeroAutoFillCols" class="grid width25k autoFillAndMoreThanThousandFixedCols"></div> +<div id="moreThanAThousandFixedZeroAutoFitCols" class="grid width25k autoFitAndMoreThanThousandFixedCols"> + <div>Item1</div> + <div>Item2</div> + <div class="lastColumn">Item3</div> +</div> + +<script> + +test(function() { + var autoFillGrid = testElement("moreThanAThousandFixedZeroAutoFillRows", "grid-template-rows", 1648); + var autoFitGrid = testElement("moreThanAThousandFixedZeroAutoFitRows", "grid-template-rows", 1630); + + assert_equals(autoFillGrid[1648 - 1], "6px"); + assert_equals(autoFillGrid[0], "7px"); + assert_equals(autoFitGrid[1630 - 1], "6px"); + assert_equals(autoFitGrid[0], "7px"); +}, "Test that we don't crash when there are more than kGridMaxTracks non auto-repeat rows on very tall grids."); + +test(function() { + var autoFillGrid = testElement("moreThanAThousandFixedZeroAutoFillCols", "grid-template-columns", 1648); + var autoFitGrid = testElement("moreThanAThousandFixedZeroAutoFitCols", "grid-template-columns", 1630); + + assert_equals(autoFillGrid[1648 - 1], "6px"); + assert_equals(autoFillGrid[0], "7px"); + assert_equals(autoFitGrid[1630 - 1], "6px"); + assert_equals(autoFitGrid[0], "7px"); +}, "Test that we don't crash when there are more than kGridMaxTracks non auto-repeat columns on very wide grids."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-013.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-013.html new file mode 100644 index 0000000..d76d0004 --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-013.html
@@ -0,0 +1,24 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="handMadeAutoFillRows" class="grid tallGrid handMadeMoreThanThousandAutoFillRows"></div> + +<script> + +test(function() { + var autoFillGrid = testElement("handMadeAutoFillRows", "grid-template-rows", 4601597); + + assert_equals(autoFillGrid[4601597 - 1], "999px"); + assert_equals(autoFillGrid[0], "10px"); +}, "Test that we don't crash when there are more than kGridMaxTracks rows in the auto repeat <track-list>."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-014.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-014.html new file mode 100644 index 0000000..77bd7ea --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-014.html
@@ -0,0 +1,28 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="handMadeAutoFitRows" class="grid tallGrid handMadeMoreThanThousandAutoFitRows"> + <div>Item1</div> + <div>Item2</div> + <div class="lastRow">Item3</div> +</div> + +<script> + +test(function() { + var autoFitGrid = testElement("handMadeAutoFitRows", "grid-template-rows", 4601597); + + assert_equals(autoFitGrid[4601597 - 1], "999px"); + assert_equals(autoFitGrid[0], "10px"); +}, "Test that we don't crash when there are more than kGridMaxTracks rows in the auto repeat <track-list>."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-015.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-015.html new file mode 100644 index 0000000..082e562f --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-015.html
@@ -0,0 +1,24 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="handMadeAutoFillCols" class="grid wideGrid handMadeMoreThanThousandAutoFillCols"></div> + +<script> + +test(function() { + var autoFillGrid = testElement("handMadeAutoFillCols", "grid-template-columns", 4601597); + + assert_equals(autoFillGrid[4601597 - 1], "999px"); + assert_equals(autoFillGrid[0], "10px"); +}, "Test that we don't crash when there are more than kGridMaxTracks columns in the auto repeat <track-list>."); + +</script>
diff --git a/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-016.html b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-016.html new file mode 100644 index 0000000..8ae65e64 --- /dev/null +++ b/third_party/blink/web_tests/fast/css-grid-layout/grid-auto-repeat-huge-grid-016.html
@@ -0,0 +1,29 @@ +<!DOCTYPE html> +<title>Test for auto-fit and auto-fill with huge grids (lots of tracks)</title> +<link href="resources/grid.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet"> +<link href="../css-intrinsic-dimensions/resources/height-keyword-classes.css" rel="stylesheet"> +<link href="resources/huge-grids.css" rel="stylesheet"> + +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="resources/grid-definitions-parsing-utils.js"></script> +<script src="resources/grid-tracks-length.js"></script> + +<div id="handMadeAutoFillCols" class="grid wideGrid handMadeMoreThanThousandAutoFillCols"></div> +<div id="handMadeAutoFitCols" class="grid wideGrid handMadeMoreThanThousandAutoFitCols"> + <div>Item1</div> + <div>Item2</div> + <div class="lastColumn">Item3</div> +</div> + +<script> + +test(function() { + var autoFitGrid = testElement("handMadeAutoFitCols", "grid-template-columns", 4601597); + + assert_equals(autoFitGrid[4601597 - 1], "999px"); + assert_equals(autoFitGrid[0], "10px"); +}, "Test that we don't crash when there are more than kGridMaxTracks columns in the auto repeat <track-list>."); + +</script>
diff --git a/third_party/blink/web_tests/fast/mediastream/MediaStreamTrack-getCapabilities.html b/third_party/blink/web_tests/fast/mediastream/MediaStreamTrack-getCapabilities.html index 0f58a3b..7f6181a 100644 --- a/third_party/blink/web_tests/fast/mediastream/MediaStreamTrack-getCapabilities.html +++ b/third_party/blink/web_tests/fast/mediastream/MediaStreamTrack-getCapabilities.html
@@ -57,7 +57,7 @@ test(function() { var video = document.createElement('video'); - video.src = "../../external/wpt/media/test-av-384k-44100Hz-1ch-320x240-30fps-10kfr.webm"; + video.src = "support/test-av-384k-44100Hz-1ch-320x240-30fps-10kfr.webm"; video.play(); video.oncanplay = function() { var stream = video.captureStream();
diff --git a/third_party/blink/web_tests/fast/mediastream/support/test-av-384k-44100Hz-1ch-320x240-30fps-10kfr.webm b/third_party/blink/web_tests/fast/mediastream/support/test-av-384k-44100Hz-1ch-320x240-30fps-10kfr.webm new file mode 100644 index 0000000..8b705db --- /dev/null +++ b/third_party/blink/web_tests/fast/mediastream/support/test-av-384k-44100Hz-1ch-320x240-30fps-10kfr.webm Binary files differ
diff --git a/third_party/blink/web_tests/fast/peerconnection/RTCPeerConnection-addMultipleTracks.html b/third_party/blink/web_tests/fast/peerconnection/RTCPeerConnection-addMultipleTracks.html index cae02d2a..30b4992 100644 --- a/third_party/blink/web_tests/fast/peerconnection/RTCPeerConnection-addMultipleTracks.html +++ b/third_party/blink/web_tests/fast/peerconnection/RTCPeerConnection-addMultipleTracks.html
@@ -4,7 +4,7 @@ <title>RTCPeerConnection.addTrack multiple times</title> <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> -<script src="../../external/wpt/webrtc/RTCPeerConnection-helper.js"></script> +<script src="resources/RTCPeerConnection-helper.js"></script> <script> 'use strict';
diff --git a/third_party/blink/web_tests/fast/peerconnection/resources/RTCPeerConnection-helper.js b/third_party/blink/web_tests/fast/peerconnection/resources/RTCPeerConnection-helper.js new file mode 100644 index 0000000..ac43527 --- /dev/null +++ b/third_party/blink/web_tests/fast/peerconnection/resources/RTCPeerConnection-helper.js
@@ -0,0 +1,715 @@ +'use strict' + +/* + * Helper Methods for testing the following methods in RTCPeerConnection: + * createOffer + * createAnswer + * setLocalDescription + * setRemoteDescription + * + * This file offers the following features: + * SDP similarity comparison + * Generating offer/answer using anonymous peer connection + * Test signalingstatechange event + * Test promise that never resolve + */ + +const audioLineRegex = /\r\nm=audio.+\r\n/g; +const videoLineRegex = /\r\nm=video.+\r\n/g; +const applicationLineRegex = /\r\nm=application.+\r\n/g; + +function countLine(sdp, regex) { + const matches = sdp.match(regex); + if(matches === null) { + return 0; + } else { + return matches.length; + } +} + +function countAudioLine(sdp) { + return countLine(sdp, audioLineRegex); +} + +function countVideoLine(sdp) { + return countLine(sdp, videoLineRegex); +} + +function countApplicationLine(sdp) { + return countLine(sdp, applicationLineRegex); +} + +function similarMediaDescriptions(sdp1, sdp2) { + if(sdp1 === sdp2) { + return true; + } else if( + countAudioLine(sdp1) !== countAudioLine(sdp2) || + countVideoLine(sdp1) !== countVideoLine(sdp2) || + countApplicationLine(sdp1) !== countApplicationLine(sdp2)) + { + return false; + } else { + return true; + } +} + +// Assert that given object is either an +// RTCSessionDescription or RTCSessionDescriptionInit +function assert_is_session_description(sessionDesc) { + if(sessionDesc instanceof RTCSessionDescription) { + return; + } + + assert_not_equals(sessionDesc, undefined, + 'Expect session description to be defined'); + + assert_true(typeof(sessionDesc) === 'object', + 'Expect sessionDescription to be either a RTCSessionDescription or an object'); + + assert_true(typeof(sessionDesc.type) === 'string', + 'Expect sessionDescription.type to be a string'); + + assert_true(typeof(sessionDesc.sdp) === 'string', + 'Expect sessionDescription.sdp to be a string'); +} + + +// We can't do string comparison to the SDP content, +// because RTCPeerConnection may return SDP that is +// slightly modified or reordered from what is given +// to it due to ICE candidate events or serialization. +// Instead, we create SDP with different number of media +// lines, and if the SDP strings are not the same, we +// simply count the media description lines and if they +// are the same, we assume it is the same. +function isSimilarSessionDescription(sessionDesc1, sessionDesc2) { + assert_is_session_description(sessionDesc1); + assert_is_session_description(sessionDesc2); + + if(sessionDesc1.type !== sessionDesc2.type) { + return false; + } else { + return similarMediaDescriptions(sessionDesc1.sdp, sessionDesc2.sdp); + } +} + +function assert_session_desc_similar(sessionDesc1, sessionDesc2) { + assert_true(isSimilarSessionDescription(sessionDesc1, sessionDesc2), + 'Expect both session descriptions to have the same count of media lines'); +} + +function assert_session_desc_not_similar(sessionDesc1, sessionDesc2) { + assert_false(isSimilarSessionDescription(sessionDesc1, sessionDesc2), + 'Expect both session descriptions to have different count of media lines'); +} + +async function generateDataChannelOffer(pc) { + pc.createDataChannel('test'); + const offer = await pc.createOffer(); + assert_equals(countApplicationLine(offer.sdp), 1, 'Expect m=application line to be present in generated SDP'); + return offer; +} + +async function generateAudioReceiveOnlyOffer(pc) +{ + try { + pc.addTransceiver('audio', { direction: 'recvonly' }); + return pc.createOffer(); + } catch(e) { + return pc.createOffer({ offerToReceiveAudio: true }); + } +} + +async function generateVideoReceiveOnlyOffer(pc) +{ + try { + pc.addTransceiver('video', { direction: 'recvonly' }); + return pc.createOffer(); + } catch(e) { + return pc.createOffer({ offerToReceiveVideo: true }); + } +} + +// Helper function to generate answer based on given offer using a freshly +// created RTCPeerConnection object +async function generateAnswer(offer) { + const pc = new RTCPeerConnection(); + await pc.setRemoteDescription(offer); + const answer = await pc.createAnswer(); + pc.close(); + return answer; +} + +// Helper function to generate offer using a freshly +// created RTCPeerConnection object +async function generateOffer() { + const pc = new RTCPeerConnection(); + const offer = await pc.createOffer(); + pc.close(); + return offer; +} + +// Run a test function that return a promise that should +// never be resolved. For lack of better options, +// we wait for a time out and pass the test if the +// promise doesn't resolve within that time. +function test_never_resolve(testFunc, testName) { + async_test(t => { + testFunc(t) + .then( + t.step_func(result => { + assert_unreached(`Pending promise should never be resolved. Instead it is fulfilled with: ${result}`); + }), + t.step_func(err => { + assert_unreached(`Pending promise should never be resolved. Instead it is rejected with: ${err}`); + })); + + t.step_timeout(t.step_func_done(), 100) + }, testName); +} + +// Helper function to exchange ice candidates between +// two local peer connections +function exchangeIceCandidates(pc1, pc2) { + // private function + function doExchange(localPc, remotePc) { + localPc.addEventListener('icecandidate', event => { + const { candidate } = event; + + // Guard against already closed peerconnection to + // avoid unrelated exceptions. + if (remotePc.signalingState !== 'closed') { + remotePc.addIceCandidate(candidate); + } + }); + } + + doExchange(pc1, pc2); + doExchange(pc2, pc1); +} + +// Returns a promise that resolves when a |name| event is fired. +function waitUntilEvent(obj, name) { + return new Promise(r => obj.addEventListener(name, r, {once: true})); +} + +// Returns a promise that resolves when the |transport.state| is |state| +// This should work for RTCSctpTransport, RTCDtlsTransport and RTCIceTransport. +async function waitForState(transport, state) { + while (transport.state != state) { + await waitUntilEvent(transport, 'statechange'); + } +} + +// Returns a promise that resolves when |pc.iceConnectionState| is 'connected' +// or 'completed'. +async function listenToIceConnected(pc) { + await waitForIceStateChange(pc, ['connected', 'completed']); +} + +// Returns a promise that resolves when |pc.iceConnectionState| is in one of the +// wanted states. +async function waitForIceStateChange(pc, wantedStates) { + while (!wantedStates.includes(pc.iceConnectionState)) { + await waitUntilEvent(pc, 'iceconnectionstatechange'); + } +} + +// Returns a promise that resolves when |pc.connectionState| is 'connected'. +async function listenToConnected(pc) { + while (pc.connectionState != 'connected') { + await waitUntilEvent(pc, 'connectionstatechange'); + } +} + +// Returns a promise that resolves when |pc.connectionState| is in one of the +// wanted states. +async function waitForConnectionStateChange(pc, wantedStates) { + while (!wantedStates.includes(pc.connectionState)) { + await waitUntilEvent(pc, 'connectionstatechange'); + } +} + +async function waitForIceGatheringState(pc, wantedStates) { + while (!wantedStates.includes(pc.iceGatheringState)) { + await waitUntilEvent(pc, 'icegatheringstatechange'); + } +} + +// Resolves when RTP packets have been received. +async function listenForSSRCs(t, receiver) { + while (true) { + const ssrcs = receiver.getSynchronizationSources(); + if (Array.isArray(ssrcs) && ssrcs.length > 0) { + return ssrcs; + } + await new Promise(r => t.step_timeout(r, 0)); + } +} + +// Helper function to create a pair of connected data channels. +// On success the promise resolves to an array with two data channels. +// It does the heavy lifting of performing signaling handshake, +// ICE candidate exchange, and waiting for data channel at two +// end points to open. Can do both negotiated and non-negotiated setup. +async function createDataChannelPair(t, options, + pc1 = createPeerConnectionWithCleanup(t), + pc2 = createPeerConnectionWithCleanup(t)) { + let pair = [], bothOpen; + try { + if (options.negotiated) { + pair = [pc1, pc2].map(pc => pc.createDataChannel('', options)); + bothOpen = Promise.all(pair.map(dc => new Promise((r, e) => { + dc.onopen = r; + dc.onerror = ({error}) => e(error); + }))); + } else { + pair = [pc1.createDataChannel('', options)]; + bothOpen = Promise.all([ + new Promise((r, e) => { + pair[0].onopen = r; + pair[0].onerror = ({error}) => e(error); + }), + new Promise((r, e) => pc2.ondatachannel = ({channel}) => { + pair[1] = channel; + channel.onopen = r; + channel.onerror = ({error}) => e(error); + }) + ]); + } + exchangeIceCandidates(pc1, pc2); + await exchangeOfferAnswer(pc1, pc2); + await bothOpen; + return pair; + } finally { + for (const dc of pair) { + dc.onopen = dc.onerror = null; + } + } +} + +// Wait for RTP and RTCP stats to arrive +async function waitForRtpAndRtcpStats(pc) { + // If remote stats are never reported, return after 5 seconds. + const startTime = performance.now(); + while (true) { + const report = await pc.getStats(); + const stats = [...report.values()].filter(({type}) => type.endsWith("bound-rtp")); + // Each RTP and RTCP stat has a reference + // to the matching stat in the other direction + if (stats.length && stats.every(({localId, remoteId}) => localId || remoteId)) { + break; + } + if (performance.now() > startTime + 5000) { + break; + } + } +} + +// Wait for a single message event and return +// a promise that resolve when the event fires +function awaitMessage(channel) { + const once = true; + return new Promise((resolve, reject) => { + channel.addEventListener('message', ({data}) => resolve(data), {once}); + channel.addEventListener('error', reject, {once}); + }); +} + +// Helper to convert a blob to array buffer so that +// we can read the content +async function blobToArrayBuffer(blob) { + const reader = new FileReader(); + reader.readAsArrayBuffer(blob); + return new Promise((resolve, reject) => { + reader.addEventListener('load', () => resolve(reader.result), {once: true}); + reader.addEventListener('error', () => reject(reader.error), {once: true}); + }); +} + +// Assert that two TypedArray or ArrayBuffer objects have the same byte values +function assert_equals_typed_array(array1, array2) { + const [view1, view2] = [array1, array2].map((array) => { + if (array instanceof ArrayBuffer) { + return new DataView(array); + } else { + assert_true(array.buffer instanceof ArrayBuffer, + 'Expect buffer to be instance of ArrayBuffer'); + return new DataView(array.buffer, array.byteOffset, array.byteLength); + } + }); + + assert_equals(view1.byteLength, view2.byteLength, + 'Expect both arrays to be of the same byte length'); + + const byteLength = view1.byteLength; + + for (let i = 0; i < byteLength; ++i) { + assert_equals(view1.getUint8(i), view2.getUint8(i), + `Expect byte at buffer position ${i} to be equal`); + } +} + +// These media tracks will be continually updated with deterministic "noise" in +// order to ensure UAs do not cease transmission in response to apparent +// silence. +// +// > Many codecs and systems are capable of detecting "silence" and changing +// > their behavior in this case by doing things such as not transmitting any +// > media. +// +// Source: https://w3c.github.io/webrtc-pc/#offer-answer-options +const trackFactories = { + // Share a single context between tests to avoid exceeding resource limits + // without requiring explicit destruction. + audioContext: null, + + /** + * Given a set of requested media types, determine if the user agent is + * capable of procedurally generating a suitable media stream. + * + * @param {object} requested + * @param {boolean} [requested.audio] - flag indicating whether the desired + * stream should include an audio track + * @param {boolean} [requested.video] - flag indicating whether the desired + * stream should include a video track + * + * @returns {boolean} + */ + canCreate(requested) { + const supported = { + audio: !!window.AudioContext && !!window.MediaStreamAudioDestinationNode, + video: !!HTMLCanvasElement.prototype.captureStream + }; + + return (!requested.audio || supported.audio) && + (!requested.video || supported.video); + }, + + audio() { + const ctx = trackFactories.audioContext = trackFactories.audioContext || + new AudioContext(); + const oscillator = ctx.createOscillator(); + const dst = oscillator.connect(ctx.createMediaStreamDestination()); + oscillator.start(); + return dst.stream.getAudioTracks()[0]; + }, + + video({width = 640, height = 480, signal} = {}) { + const canvas = Object.assign( + document.createElement("canvas"), {width, height} + ); + const ctx = canvas.getContext('2d'); + const stream = canvas.captureStream(); + + let count = 0; + const interval = setInterval(() => { + ctx.fillStyle = `rgb(${count%255}, ${count*count%255}, ${count%255})`; + count += 1; + ctx.fillRect(0, 0, width, height); + // Add some bouncing boxes in contrast color to add a little more noise. + const contrast = count + 128; + ctx.fillStyle = `rgb(${contrast%255}, ${contrast*contrast%255}, ${contrast%255})`; + const xpos = count % (width - 20); + const ypos = count % (height - 20); + ctx.fillRect(xpos, ypos, xpos + 20, ypos + 20); + const xpos2 = (count + width / 2) % (width - 20); + const ypos2 = (count + height / 2) % (height - 20); + ctx.fillRect(xpos2, ypos2, xpos2 + 20, ypos2 + 20); + // If signal is set (0-255), add a constant-color box of that luminance to + // the video frame at coordinates 20 to 60 in both X and Y direction. + // (big enough to avoid color bleed from surrounding video in some codecs, + // for more stable tests). + if (signal != undefined) { + ctx.fillStyle = `rgb(${signal}, ${signal}, ${signal})`; + ctx.fillRect(20, 20, 40, 40); + } + }, 100); + + if (document.body) { + document.body.appendChild(canvas); + } else { + document.addEventListener('DOMContentLoaded', () => { + document.body.appendChild(canvas); + }, {once: true}); + } + + // Implement track.stop() for performance in some tests on some platforms + const track = stream.getVideoTracks()[0]; + const nativeStop = track.stop; + track.stop = function stop() { + clearInterval(interval); + nativeStop.apply(this); + if (document.body && canvas.parentElement == document.body) { + document.body.removeChild(canvas); + } + }; + return track; + } +}; + +// Get the signal from a video element inserted by createNoiseStream +function getVideoSignal(v) { + if (v.videoWidth < 60 || v.videoHeight < 60) { + throw new Error('getVideoSignal: video too small for test'); + } + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 60; + const context = canvas.getContext('2d'); + context.drawImage(v, 0, 0); + // Extract pixel value at position 40, 40 + const pixel = context.getImageData(40, 40, 1, 1); + // Use luma reconstruction to get back original value according to + // ITU-R rec BT.709 + return (pixel.data[0] * 0.21 + pixel.data[1] * 0.72 + pixel.data[2] * 0.07); +} + +async function detectSignal(t, v, value) { + while (true) { + const signal = getVideoSignal(v).toFixed(); + // allow off-by-two pixel error (observed in some implementations) + if (value - 2 <= signal && signal <= value + 2) { + return; + } + // We would like to wait for each new frame instead here, + // but there seems to be no such callback. + await new Promise(r => t.step_timeout(r, 100)); + } +} + +// Generate a MediaStream bearing the specified tracks. +// +// @param {object} [caps] +// @param {boolean} [caps.audio] - flag indicating whether the generated stream +// should include an audio track +// @param {boolean} [caps.video] - flag indicating whether the generated stream +// should include a video track, or parameters for video +async function getNoiseStream(caps = {}) { + if (!trackFactories.canCreate(caps)) { + return navigator.mediaDevices.getUserMedia(caps); + } + const tracks = []; + + if (caps.audio) { + tracks.push(trackFactories.audio()); + } + + if (caps.video) { + tracks.push(trackFactories.video(caps.video)); + } + + return new MediaStream(tracks); +} + +// Obtain a MediaStreamTrack of kind using procedurally-generated streams (and +// falling back to `getUserMedia` when the user agent cannot generate the +// requested streams). +// Return Promise of pair of track and associated mediaStream. +// Assumes that there is at least one available device +// to generate the track. +function getTrackFromUserMedia(kind) { + return getNoiseStream({ [kind]: true }) + .then(mediaStream => { + const [track] = mediaStream.getTracks(); + return [track, mediaStream]; + }); +} + +// Obtain |count| MediaStreamTracks of type |kind| and MediaStreams. The tracks +// do not belong to any stream and the streams are empty. Returns a Promise +// resolved with a pair of arrays [tracks, streams]. +// Assumes there is at least one available device to generate the tracks and +// streams and that the getUserMedia() calls resolve. +function getUserMediaTracksAndStreams(count, type = 'audio') { + let otherTracksPromise; + if (count > 1) + otherTracksPromise = getUserMediaTracksAndStreams(count - 1, type); + else + otherTracksPromise = Promise.resolve([[], []]); + return otherTracksPromise.then(([tracks, streams]) => { + return getTrackFromUserMedia(type) + .then(([track, stream]) => { + // Remove the default stream-track relationship. + stream.removeTrack(track); + tracks.push(track); + streams.push(stream); + return [tracks, streams]; + }); + }); +} + +// Performs an offer exchange caller -> callee. +async function exchangeOffer(caller, callee) { + await caller.setLocalDescription(await caller.createOffer()); + await callee.setRemoteDescription(caller.localDescription); +} +// Performs an answer exchange caller -> callee. +async function exchangeAnswer(caller, callee) { + // Note that caller's remote description must be set first; if not, + // there's a chance that candidates from callee arrive at caller before + // it has a remote description to apply them to. + const answer = await callee.createAnswer(); + await caller.setRemoteDescription(answer); + await callee.setLocalDescription(answer); +} +async function exchangeOfferAnswer(caller, callee) { + await exchangeOffer(caller, callee); + await exchangeAnswer(caller, callee); +} + +// The returned promise is resolved with caller's ontrack event. +async function exchangeAnswerAndListenToOntrack(t, caller, callee) { + const ontrackPromise = addEventListenerPromise(t, caller, 'track'); + await exchangeAnswer(caller, callee); + return ontrackPromise; +} +// The returned promise is resolved with callee's ontrack event. +async function exchangeOfferAndListenToOntrack(t, caller, callee) { + const ontrackPromise = addEventListenerPromise(t, callee, 'track'); + await exchangeOffer(caller, callee); + return ontrackPromise; +} + +// The resolver extends a |promise| that can be resolved or rejected using |resolve| +// or |reject|. +class Resolver extends Promise { + constructor(executor) { + let resolve, reject; + super((resolve_, reject_) => { + resolve = resolve_; + reject = reject_; + if (executor) { + return executor(resolve_, reject_); + } + }); + + this._done = false; + this._resolve = resolve; + this._reject = reject; + } + + /** + * Return whether the promise is done (resolved or rejected). + */ + get done() { + return this._done; + } + + /** + * Resolve the promise. + */ + resolve(...args) { + this._done = true; + return this._resolve(...args); + } + + /** + * Reject the promise. + */ + reject(...args) { + this._done = true; + return this._reject(...args); + } +} + +function addEventListenerPromise(t, obj, type, listener) { + if (!listener) { + return waitUntilEvent(obj, type); + } + return new Promise(r => obj.addEventListener(type, + t.step_func(e => r(listener(e))), + {once: true})); +} + +function createPeerConnectionWithCleanup(t) { + const pc = new RTCPeerConnection(); + t.add_cleanup(() => pc.close()); + return pc; +} + +async function createTrackAndStreamWithCleanup(t, kind = 'audio') { + let constraints = {}; + constraints[kind] = true; + const stream = await getNoiseStream(constraints); + const [track] = stream.getTracks(); + t.add_cleanup(() => track.stop()); + return [track, stream]; +} + +function findTransceiverForSender(pc, sender) { + const transceivers = pc.getTransceivers(); + for (let i = 0; i < transceivers.length; ++i) { + if (transceivers[i].sender == sender) + return transceivers[i]; + } + return null; +} + +function preferCodec(transceiver, mimeType, sdpFmtpLine) { + const {codecs} = RTCRtpSender.getCapabilities(transceiver.receiver.track.kind); + // sdpFmtpLine is optional, pick the first partial match if not given. + const selectedCodecIndex = codecs.findIndex(c => { + return c.mimeType === mimeType && (c.sdpFmtpLine === sdpFmtpLine || !sdpFmtpLine); + }); + const selectedCodec = codecs[selectedCodecIndex]; + codecs.slice(selectedCodecIndex, 1); + codecs.unshift(selectedCodec); + return transceiver.setCodecPreferences(codecs); +} + +// Contains a set of values and will yell at you if you try to add a value twice. +class UniqueSet extends Set { + constructor(items) { + super(); + if (items !== undefined) { + for (const item of items) { + this.add(item); + } + } + } + + add(value, message) { + if (message === undefined) { + message = `Value '${value}' needs to be unique but it is already in the set`; + } + assert_true(!this.has(value), message); + super.add(value); + } +} + +const iceGatheringStateTransitions = async (pc, ...states) => { + for (const state of states) { + await new Promise((resolve, reject) => { + pc.addEventListener('icegatheringstatechange', () => { + if (pc.iceGatheringState == state) { + resolve(); + } else { + reject(`Unexpected gathering state: ${pc.iceGatheringState}, was expecting ${state}`); + } + }, {once: true}); + }); + } +}; + +const initialOfferAnswerWithIceGatheringStateTransitions = + async (pc1, pc2, offerOptions) => { + await pc1.setLocalDescription( + await pc1.createOffer(offerOptions)); + const pc1Transitions = + iceGatheringStateTransitions(pc1, 'gathering', 'complete'); + await pc2.setRemoteDescription(pc1.localDescription); + await pc2.setLocalDescription(await pc2.createAnswer()); + const pc2Transitions = + iceGatheringStateTransitions(pc2, 'gathering', 'complete'); + await pc1.setRemoteDescription(pc2.localDescription); + await pc1Transitions; + await pc2Transitions; + }; + +const expectNoMoreGatheringStateChanges = async (t, pc) => { + pc.onicegatheringstatechange = + t.step_func(() => { + assert_unreached( + 'Should not get an icegatheringstatechange right now!'); + }); +};
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem-expected.txt new file mode 100644 index 0000000..d9979f1 --- /dev/null +++ b/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_missing_unsafe_hashes-href_blank-script-src-elem-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL javascript: navigation using <a href target=_blank> should be refused due to missing unsafe-hashes assert_unreached: Should not have run javascript: URL Reached unreachable code +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem-expected.txt new file mode 100644 index 0000000..c0ad830 --- /dev/null +++ b/third_party/blink/web_tests/platform/generic/external/wpt/content-security-policy/unsafe-hashes/javascript_src_denied_wrong_hash-href_blank-script-src-elem-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL javascript: navigation using <a href target=_blank> should be refused due to wrong hash assert_unreached: Should not have run javascript: URL Reached unreachable code +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/generic/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-unregister.https-expected.txt b/third_party/blink/web_tests/platform/generic/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-unregister.https-expected.txt new file mode 100644 index 0000000..4e4fb55 --- /dev/null +++ b/third_party/blink/web_tests/platform/generic/external/wpt/html/browsers/browsing-the-web/back-forward-cache/service-worker-unregister.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Unregister service worker while a controlled page is in BFCache assert_implements: Should not be BFCached but actually was undefined +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/wpt_internal/geolocation-api/resources/geolocation-mock.js b/third_party/blink/web_tests/wpt_internal/geolocation-api/resources/geolocation-mock.js index 1e9a588..26eaa34f 100644 --- a/third_party/blink/web_tests/wpt_internal/geolocation-api/resources/geolocation-mock.js +++ b/third_party/blink/web_tests/wpt_internal/geolocation-api/resources/geolocation-mock.js
@@ -112,6 +112,7 @@ timestamp: {internalValue: 0n}, errorMessage: "User has not allowed access to system location.", errorCode: Geoposition_ErrorCode.PERMISSION_DENIED, + errorTechnical: "", }; } @@ -139,9 +140,10 @@ const timestamp = {internalValue: BigInt((new Date().getTime() + epochDeltaInMs) * 1000)}; const errorMessage = ''; + const errorTechnical = ''; const valid = true; return {latitude, longitude, accuracy, altitude, altitudeAccuracy, heading, - speed, timestamp, errorMessage, valid}; + speed, timestamp, errorMessage, valid, errorTechnical}; } /** @@ -166,6 +168,7 @@ timestamp: {internalValue: 0n}, errorMessage: message, errorCode: Geoposition_ErrorCode.POSITION_UNAVAILABLE, + errorTechnical: "", }; }
diff --git a/tools/cast3p/cast_core.version b/tools/cast3p/cast_core.version index 86f6ac2..aba2d5b 100644 --- a/tools/cast3p/cast_core.version +++ b/tools/cast3p/cast_core.version
@@ -1 +1 @@ -cast_20220513_0600_RC00 +cast_20220527_0600_RC00
diff --git a/tools/mac/power/dtrace_scripts/iwakeups.d b/tools/mac/power/dtrace_scripts/iwakeups.d new file mode 100644 index 0000000..b4a5131 --- /dev/null +++ b/tools/mac/power/dtrace_scripts/iwakeups.d
@@ -0,0 +1,66 @@ +// Copyright 2022 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. + +// This script analyzes interrupt wakeups caused by the execution of a process +// and all its children. +// +// Execute like this: +// sudo dtrace -s iwakeups.d $(pgrep -x "Google Chrome") + +// Note on results produced: +// +// This script will produce a data file suitable to be converted to a pprof by +// export_dtrace.py. Care needs to be taken in the analysis of the data. As +// stated in the probe comments, this script emits the stacks of the code that +// ran because of the interrupt wakeup, not the code that triggered the wakeup. +// The iwakeup probe fires in the Darwin kernel +// (see https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/sched_prim.c#L709). +// The first user space thread that will come on-cpu as a result of the wakeup +// will be in the state that made the thread go to sleep in the first place. +// +// Example: +// +// libsystem_kernel.dylib`mach_msg_trap+0xa +// Google Chrome Framework`base::WaitableEvent::TimedWait(base::TimeDelta const&)+0x172 +// Google Chrome Framework`base::internal::WorkerThread::RunWorker()+0x382 +// Google Chrome Framework`base::internal::WorkerThread::RunPooledWorker()+0xd +// Google Chrome Framework`base::(anonymous namespace)::ThreadFunc(void*)+0x75 +// libsystem_pthread.dylib`_pthread_start+0x7d +// libsystem_pthread.dylib`thread_start+0xf +// +// In this example the stack was emitted because the cpu was interrupted to +// allow the code to exit the TimedWait() invocation. This kind of data could +// be called "wakee" stacks. In contrast, the "waker" stack could be captured +// using stack() in the iwakeup probe. It cannot be captured using ustack() +// since the first wakeup is not caused by user space code. + +// This probe fires when the CPU is interrupted to wake up a thread. +sched:::iwakeup +{ + // Make note that the thread's stack should be captured the next time it + // goes on-cpu. + wakees[((thread_t)arg0)->thread_id] = 1; +} + +// This probe fires when a thread begins execution on a cpu. +// Additional conditions are used to execute the body only for threads in our +// processes of interest, when they've previously caused an interrupt wake up. +sched:::on-cpu/(pid == $1 || ppid == $1) && wakees[curthread->thread_id] == 1/ +{ + @wakes[ustack(512)] = count(); + + // Don't monitor this thread again until the next iwakeup. + wakees[curthread->thread_id] = 0; +} + +// This probe fires when a thread begins execution on a cpu. +// Additional conditions are used to execute the body only for threads in +// processes of no interest, when they've previously caused an interrupt wake up. +sched:::on-cpu/pid != $1 && ppid != $1 && wakees[curthread->thread_id] == 1/ +{ + // This thread does not belong to a process of interest. Remove it from |wakees| + // to avoid capturing stacks if thread id reuse causes a thread with the same + // id to go on-cpu on a process of interest. + wakees[curthread->thread_id] = 0; +}
diff --git a/tools/mac/power/dtrace_scripts/profile.d b/tools/mac/power/dtrace_scripts/profile.d index a74c07e..ecf8bf45 100644 --- a/tools/mac/power/dtrace_scripts/profile.d +++ b/tools/mac/power/dtrace_scripts/profile.d
@@ -6,12 +6,26 @@ // Execute like this: // sudo dtrace -s profile.d $(pgrep -x "Google Chrome") +// Note on results produced: +// +// This script will produce a data file suitable to be converted to a pprof by +// export_dtrace.py. The flamegraph generated will present time spent on-cpu as +// a fraction of the total. More time spent on-cpu does not necessarily mean +// more power consumed. A CPU running at a low frequency will take a long time +// to execute work but might do it in a more power-efficient way than if it was +// running at a higher frequency. The same can be said about core selection in +// a big.LITTLE style architecture. + // Profile with a high frequency that is prime to avoid unfortunate alignement // with periods of repeating tasks internal to the process. The frequency was // verified as supported by macOS Monterey running on Intel. See // https://illumos.org/books/dtrace/chp-profile.html#chp-profile-5 for details. - profile-997/(pid == $1 || ppid == $1)/ { - @[ustack(128)] = count(); + @[ustack(512)] = count(); } + +// Future work: +// Currently the frequency data is not filled in within the |curcpu| variable +// on macOS. The |cpu| variable is correctly filled in so applying some notion +// of per-core type weight will be integrated into this script eventually.
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 1a4b452e..4d01194 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -18800,6 +18800,7 @@ <int value="9" label="Excessive reporting origins"/> <int value="10" label="No matching source filter data"/> <int value="11" label="Prohibited by browser policy"/> + <int value="12" label="No matching configurations"/> </enum> <enum name="ConversionStorageSqlInitStatus">
diff --git a/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS b/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS index 0b0d121..0b24669 100644 --- a/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS +++ b/tools/metrics/histograms/metadata/METRIC_REVIEWER_OWNERS
@@ -16,6 +16,7 @@ chadduffin@chromium.org changhaohan@chromium.org ckitagawa@chromium.org +crisrael@google.com csharrison@chromium.org cthomp@chromium.org curranmax@chromium.org
diff --git a/tools/metrics/histograms/metadata/ash/histograms.xml b/tools/metrics/histograms/metadata/ash/histograms.xml index 33efbaa..193fb374 100644 --- a/tools/metrics/histograms/metadata/ash/histograms.xml +++ b/tools/metrics/histograms/metadata/ash/histograms.xml
@@ -951,6 +951,15 @@ <token key="TabletOrClamshell" variants="DisplayModes"/> </histogram> +<histogram name="Ash.CaptureModeController.NumberOfConnectedCameras" + units="connected cameras" expires_after="2023-05-20"> + <owner>conniekxu@chromium.org</owner> + <owner>gzadina@google.com</owner> + <summary> + Records the number of connected cameras to the device whenever it changes. + </summary> +</histogram> + <histogram name="Ash.CaptureModeController.Projector.CaptureConfiguration.{TabletOrClamshell}" enum="CaptureModeConfiguration" expires_after="2022-09-29"> @@ -1828,6 +1837,13 @@ </summary> </histogram> +<histogram name="Ash.DeskTemplate.LaunchSaveAndRecall" enum="BooleanHit" + expires_after="2022-11-24"> + <owner>dandersson@chromium.org</owner> + <owner>janetmac@chromium.org</owner> + <summary>Emitted when a Save and Recall desk is launched.</summary> +</histogram> + <histogram name="Ash.DeskTemplate.LoadTemplateGrid" enum="BooleanHit" expires_after="2022-11-12"> <owner>avynn@google.com</owner> @@ -1862,6 +1878,34 @@ </summary> </histogram> +<histogram name="Ash.DeskTemplate.SaveAndRecallTabCount" units="count" + expires_after="2022-11-24"> + <owner>dandersson@chromium.org</owner> + <owner>janetmac@chromium.org</owner> + <summary> + Records the number of tabs in a Save and Recall desk when it is saved. + </summary> +</histogram> + +<histogram name="Ash.DeskTemplate.SaveAndRecallWindowAndTabCount" units="count" + expires_after="2022-11-24"> + <owner>dandersson@chromium.org</owner> + <owner>janetmac@chromium.org</owner> + <summary> + Records the number of windows and tabs in a Save and Recall desk when it is + saved. + </summary> +</histogram> + +<histogram name="Ash.DeskTemplate.SaveAndRecallWindowCount" units="count" + expires_after="2022-11-24"> + <owner>dandersson@chromium.org</owner> + <owner>janetmac@chromium.org</owner> + <summary> + Records the number of windows in a Save and Recall desk when it is saved. + </summary> +</histogram> + <histogram name="Ash.DeskTemplate.TabCount" units="count" expires_after="2022-10-04"> <owner>richui@chromium.org</owner> @@ -1891,6 +1935,16 @@ </summary> </histogram> +<histogram name="Ash.DeskTemplate.UserSaveAndRecallCount" units="count" + expires_after="2022-11-24"> + <owner>dandersson@chromium.org</owner> + <owner>janetmac@chromium.org</owner> + <summary> + Records the number of Save and Recall desks a user has saved when a desk is + saved or deleted. + </summary> +</histogram> + <histogram name="Ash.DeskTemplate.UserTemplateCount" units="count" expires_after="2022-10-04"> <owner>richui@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/blink/histograms.xml b/tools/metrics/histograms/metadata/blink/histograms.xml index c06114a..97dd6596 100644 --- a/tools/metrics/histograms/metadata/blink/histograms.xml +++ b/tools/metrics/histograms/metadata/blink/histograms.xml
@@ -2106,10 +2106,6 @@ maximum event duration for the keydown, keypress, keyup, pointerdown, pointerup, mousedown, mouseup, and click event is reported."/> - <variant name="ClickOrTap" - summary="of type click or tap. The maximum event duration for the - pointerdown, pointerup, mousedown, mouseup, and click event - is reported."/> <variant name="Drag" summary="of type drag. The maximum event duration for the pointerdown, pointerup, mousedown, mouseup, and click event @@ -2117,6 +2113,10 @@ <variant name="Keyboard" summary="of type keyboard. The maximum event duration for the keydown, keypress, and keyup event is reported."/> + <variant name="TapOrClick" + summary="of type click or tap. The maximum event duration for the + pointerdown, pointerup, mousedown, mouseup, and click event + is reported."/> </token> </histogram>
diff --git a/tools/metrics/histograms/metadata/cross_device/OWNERS b/tools/metrics/histograms/metadata/cross_device/OWNERS index ec425fb..6badf6b 100644 --- a/tools/metrics/histograms/metadata/cross_device/OWNERS +++ b/tools/metrics/histograms/metadata/cross_device/OWNERS
@@ -2,4 +2,5 @@ # Prefer sending CLs to the owners listed below. # Use chromium-metrics-reviews@google.com as a backup. +crisrael@google.com nohle@chromium.org
diff --git a/tools/metrics/histograms/metadata/event/histograms.xml b/tools/metrics/histograms/metadata/event/histograms.xml index ba1fc6b5..1ac4a99 100644 --- a/tools/metrics/histograms/metadata/event/histograms.xml +++ b/tools/metrics/histograms/metadata/event/histograms.xml
@@ -60,16 +60,6 @@ </summary> </histogram> -<histogram name="Event.AsyncTargeting.AsyncClientDepth" units="clients" - expires_after="2021-08-09"> - <owner>sadrul@chromium.org</owner> - <owner>event-targeting@chromium.org</owner> - <summary> - Tracks how many clients were queried (asynchronously) to determine the - target for an input event. - </summary> -</histogram> - <histogram name="Event.AsyncTargeting.ResponseTime" units="ms" expires_after="2022-10-09"> <owner>sadrul@chromium.org</owner> @@ -559,17 +549,6 @@ </summary> </histogram> -<histogram name="Event.Latency.ScrollBegin.TopControlsMoved" enum="Boolean" - expires_after="2020-12-06"> - <owner>sadrul@chromium.org</owner> - <owner>chrome-gpu-metrics@google.com</owner> - <summary> - Records whether the browser top-controls (i.e. omnibox, toolbar) moved - because of the scroll-begin event (i.e. the first scroll-update event of - that sequence). - </summary> -</histogram> - <histogram name="Event.Latency.ScrollBegin.Touch.AverageLagPresentation" units="pixels" expires_after="2022-05-01"> <owner>flackr@chromium.org</owner> @@ -1143,17 +1122,6 @@ </summary> </histogram> -<histogram name="Event.Latency.ScrollUpdate.TopControlsMoved" enum="Boolean" - expires_after="2020-08-02"> - <owner>sadrul@chromium.org</owner> - <owner>chrome-gpu-metrics@google.com</owner> - <summary> - Records whether the browser top-controls (i.e. omnibox, toolbar) moved - because of the scroll-update event (other than the first update event in the - sequence). - </summary> -</histogram> - <histogram name="Event.Latency.ScrollUpdate.TotalDuration" units="ms" expires_after="2022-09-25"> <owner>ddrone@google.com</owner> @@ -1772,26 +1740,6 @@ </token> </histogram> -<histogram name="Event.VizHitTest.AsyncHitTestReasons" - enum="AsyncHitTestReasons" expires_after="2021-10-10"> - <owner>sadrul@chromium.org</owner> - <owner>event-targeting@chromium.org</owner> - <summary> - Tracks the reasons why sychronous hit testing could not be done for each hit - test requests processd by HitTestQuery. - </summary> -</histogram> - -<histogram name="Event.VizHitTest.HitTestDataIsEqualAccuracy" - enum="BooleanAccuracy" expires_after="2021-01-03"> - <owner>zandershah@google.com</owner> - <owner>event-targeting@chromium.org</owner> - <summary> - Tracks the result of AsyncLayerTreeFrameSink calls to - HitTestRegionList::IsEqual. - </summary> -</histogram> - <histogram name="Event.WaylandDragDrop.IncomingDataTransferTime" units="ms" expires_after="M90"> <owner>rjkroege@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/nearby/OWNERS b/tools/metrics/histograms/metadata/nearby/OWNERS index ec425fb..6badf6b 100644 --- a/tools/metrics/histograms/metadata/nearby/OWNERS +++ b/tools/metrics/histograms/metadata/nearby/OWNERS
@@ -2,4 +2,5 @@ # Prefer sending CLs to the owners listed below. # Use chromium-metrics-reviews@google.com as a backup. +crisrael@google.com nohle@chromium.org
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index af921a5..0aff374 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -3448,6 +3448,10 @@ <histogram name="Conversions.CreateReportStatus2" enum="ConversionStorageCreateReportStatus" expires_after="2022-10-04"> + <obsolete> + Replaced with Conversions.CreateReportStatus3 due to enum value change, + 05/2022. + </obsolete> <owner>apaseltiner@chromium.org</owner> <owner>johnidel@chromium.org</owner> <owner>measurement-api-dev+metrics@google.com</owner> @@ -3458,6 +3462,18 @@ </summary> </histogram> +<histogram name="Conversions.CreateReportStatus3" + enum="ConversionStorageCreateReportStatus" expires_after="2022-10-04"> + <owner>apaseltiner@chromium.org</owner> + <owner>johnidel@chromium.org</owner> + <owner>measurement-api-dev+metrics@google.com</owner> + <summary> + Measures how often event-level triggers are stored successfully or rejected + and why. Recorded once for each conversion event processed by the + attribution storage layer. + </summary> +</histogram> + <histogram name="Conversions.DeleteSentReportOperation" enum="ConversionPostSendReportDeleteEvent" expires_after="M105"> <obsolete>
diff --git a/tools/metrics/histograms/metadata/phonehub/OWNERS b/tools/metrics/histograms/metadata/phonehub/OWNERS index ec425fb..6badf6b 100644 --- a/tools/metrics/histograms/metadata/phonehub/OWNERS +++ b/tools/metrics/histograms/metadata/phonehub/OWNERS
@@ -2,4 +2,5 @@ # Prefer sending CLs to the owners listed below. # Use chromium-metrics-reviews@google.com as a backup. +crisrael@google.com nohle@chromium.org
diff --git a/tools/metrics/histograms/metadata/power/histograms.xml b/tools/metrics/histograms/metadata/power/histograms.xml index 5acfdc9..842a7e2 100644 --- a/tools/metrics/histograms/metadata/power/histograms.xml +++ b/tools/metrics/histograms/metadata/power/histograms.xml
@@ -134,38 +134,6 @@ but there was in the last 2 minutes"/> </variants> -<histogram name="PerformanceMonitor.AverageCPU2.Total{UsageScenario}" - units="1/100 %" expires_after="2022-11-30"> - <owner>fdoray@chromium.org</owner> - <owner>catan-team@chromium.org</owner> - <summary> - See definitioin of PerformanceClass.AverageCPU2.ProcessName. This is - recorded for {UsageScenario} (see go/chrome_power_use_per_scenario). - </summary> - <token key="UsageScenario" variants="UsageScenario"/> -</histogram> - -<histogram name="PerformanceMonitor.AverageCPU2.{ProcessName}" units="1/100 %" - expires_after="2022-11-30"> - <owner>fdoray@chromium.org</owner> - <owner>catan-team@chromium.org</owner> - <summary> - Average CPU utilization of process type {ProcessName}, read out at each - two-minute interval. The utilization is in the 0-100% range per CPU, which - is then summed up and multiplied by 100. The histogram is capped at 20000 - (equivalent to 2 cores fully loaded). I.e. 4 cores busy at 25% each will - read as 25 * 4 * 100 = 10000. - - NOTE: This metric has one signigicant limitation, it doesn't report the CPU - usage of processes that terminate before the end of the interval. This means - that short lived processes will rarely be included in the data. Furthermore, - we know that short-lived processes are very common (see - Renderer.ProcessLifetime). A future version of this metric will address this - limitation. - </summary> - <token key="ProcessName" variants="ProcessName"/> -</histogram> - <histogram name="PerformanceMonitor.AverageCPU3.Total{UsageScenario}" units="1/100 %" expires_after="2022-11-30"> <owner>fdoray@chromium.org</owner> @@ -174,8 +142,6 @@ <summary> See definition of PerformanceClass.AverageCPU3.ProcessName. This is recorded for {UsageScenario} (see go/chrome_power_use_per_scenario). - - Only recorded on Windows. </summary> <token key="UsageScenario" variants="UsageScenario"/> </histogram> @@ -192,10 +158,7 @@ (equivalent to 2 cores fully loaded). I.e. 4 cores busy at 25% each will read as 25 * 4 * 100 = 10000. - Only recorded on Windows, and is more precise than AverageCPU2 because it - uses `QueryProcessCycleTime` instead of `GetProcessTimes`. - - NOTE: This metric has one signigicant limitation, it doesn't report the CPU + NOTE: This metric has one significant limitation, it doesn't report the CPU usage of processes that terminate before the end of the interval. This means that short lived processes will rarely be included in the data. Furthermore, we know that short-lived processes are very common (see
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 9a9aed8..76e1b2a 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,24 +5,24 @@ "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm64/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "win": { - "hash": "0f0f7c039258a6034f576ed6a7054cfa9d1ee0bc", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/fecea55a5bc59c274e8200d06cd68260832d5591/trace_processor_shell.exe" + "hash": "6dbca97e80dcaeed2cdce3bcd4c7f1ed43d3ac70", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/a2ba21403c0a958883480c4191c8b5d48a350806/trace_processor_shell.exe" }, "linux_arm": { "hash": "58893933be305d3bfe0a72ebebcacde2ac3ca893", "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux_arm/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "mac": { - "hash": "b4aca317482f24db77dd1027f8c5a9a25d42edac", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/fecea55a5bc59c274e8200d06cd68260832d5591/trace_processor_shell" + "hash": "9c416e7a683a5ff76551bcd9c32d023d27154d76", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/mac/a2ba21403c0a958883480c4191c8b5d48a350806/trace_processor_shell" }, "mac_arm64": { "hash": "e1ad4861384b06d911a65f035317914b8cc975c6", "full_remote_path": "perfetto-luci-artifacts/v25.0/mac-arm64/trace_processor_shell" }, "linux": { - "hash": "a69c29ff4a09e03fde1c602209535753632a1965", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/fecea55a5bc59c274e8200d06cd68260832d5591/trace_processor_shell" + "hash": "6af362a53a155fdc10bfd52b59057fcfc75a5428", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/26f1ca3b42a13a5dc179334f972ad8847aded023/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/ui/accessibility/ax_node_data.cc b/ui/accessibility/ax_node_data.cc index 77ad61e..7b25bc69 100644 --- a/ui/accessibility/ax_node_data.cc +++ b/ui/accessibility/ax_node_data.cc
@@ -450,7 +450,7 @@ for (const std::pair<std::string, std::string>& html_attribute : html_attributes) { const std::string& attr = html_attribute.first; - if (base::LowerCaseEqualsASCII(attr, attribute)) { + if (base::EqualsCaseInsensitiveASCII(attr, attribute)) { *value = html_attribute.second; return true; }
diff --git a/ui/android/delegated_frame_host_android.cc b/ui/android/delegated_frame_host_android.cc index 2d47a4b3..42492a88 100644 --- a/ui/android/delegated_frame_host_android.cc +++ b/ui/android/delegated_frame_host_android.cc
@@ -217,7 +217,7 @@ if (pre_navigation_local_surface_id_.is_valid() && !first_local_surface_id_after_navigation_.is_valid()) { EvictDelegatedFrame(); - content_layer_->SetBackgroundColor(SK_ColorTRANSPARENT); + content_layer_->SetBackgroundColor(SkColors::kTransparent); } content_layer_->SetOldestAcceptableFallback( @@ -322,8 +322,8 @@ content_layer_->SetOldestAcceptableFallback(new_primary_surface_id); // We default to black background for fullscreen case. - content_layer_->SetBackgroundColor(is_fullscreen ? SK_ColorBLACK - : SK_ColorTRANSPARENT); + content_layer_->SetBackgroundColor( + is_fullscreen ? SkColors::kBlack : SkColors::kTransparent); } }
diff --git a/ui/base/models/dialog_model.cc b/ui/base/models/dialog_model.cc index 6ca513aa..7b906fe4a3 100644 --- a/ui/base/models/dialog_model.cc +++ b/ui/base/models/dialog_model.cc
@@ -110,11 +110,13 @@ params)); } -void DialogModel::AddCombobox(std::u16string label, +void DialogModel::AddCombobox(ElementIdentifier id, + std::u16string label, std::unique_ptr<ui::ComboboxModel> combobox_model, const DialogModelCombobox::Params& params) { AddField(std::make_unique<DialogModelCombobox>( - GetPassKey(), this, std::move(label), std::move(combobox_model), params)); + GetPassKey(), this, id, std::move(label), std::move(combobox_model), + params)); } void DialogModel::AddSeparator() { @@ -129,11 +131,12 @@ std::move(callback))); } -void DialogModel::AddTextfield(std::u16string label, +void DialogModel::AddTextfield(ElementIdentifier id, + std::u16string label, std::u16string text, const DialogModelTextfield::Params& params) { AddField(std::make_unique<DialogModelTextfield>( - GetPassKey(), this, std::move(label), std::move(text), params)); + GetPassKey(), this, id, std::move(label), std::move(text), params)); } void DialogModel::AddCustomField(
diff --git a/ui/base/models/dialog_model.h b/ui/base/models/dialog_model.h index e22f066a..6f0a594 100644 --- a/ui/base/models/dialog_model.h +++ b/ui/base/models/dialog_model.h
@@ -227,11 +227,13 @@ } // Adds a combobox. See DialogModel::AddCombobox(). - Builder& AddCombobox(std::u16string label, + Builder& AddCombobox(ElementIdentifier id, + std::u16string label, std::unique_ptr<ui::ComboboxModel> combobox_model, const DialogModelCombobox::Params& params = DialogModelCombobox::Params()) { - model_->AddCombobox(std::move(label), std::move(combobox_model), params); + model_->AddCombobox(id, std::move(label), std::move(combobox_model), + params); return *this; } @@ -251,11 +253,12 @@ } // Adds a textfield. See DialogModel::AddTextfield(). - Builder& AddTextfield(std::u16string label, + Builder& AddTextfield(ElementIdentifier id, + std::u16string label, std::u16string text, const DialogModelTextfield::Params& params = DialogModelTextfield::Params()) { - model_->AddTextfield(std::move(label), std::move(text), params); + model_->AddTextfield(id, std::move(label), std::move(text), params); return *this; } @@ -297,7 +300,8 @@ DialogModelCheckbox::Params()); // Adds a labeled combobox (label: [model]) at the end of the dialog model. - void AddCombobox(std::u16string label, + void AddCombobox(ElementIdentifier id, + std::u16string label, std::unique_ptr<ui::ComboboxModel> combobox_model, const DialogModelCombobox::Params& params = DialogModelCombobox::Params()); @@ -311,7 +315,8 @@ void AddSeparator(); // Adds a labeled textfield (label: [text]) at the end of the dialog model. - void AddTextfield(std::u16string label, + void AddTextfield(ElementIdentifier id, + std::u16string label, std::u16string text, const DialogModelTextfield::Params& params = DialogModelTextfield::Params());
diff --git a/ui/base/models/dialog_model_field.cc b/ui/base/models/dialog_model_field.cc index 04c91e9..79fa7a9 100644 --- a/ui/base/models/dialog_model_field.cc +++ b/ui/base/models/dialog_model_field.cc
@@ -205,14 +205,6 @@ DialogModelCombobox::Params::Params() = default; DialogModelCombobox::Params::~Params() = default; -DialogModelCombobox::Params& DialogModelCombobox::Params::SetId( - ElementIdentifier id) { - DCHECK(!id_); - DCHECK(id); - id_ = id; - return *this; -} - DialogModelCombobox::Params& DialogModelCombobox::Params::SetCallback( base::RepeatingClosure callback) { callback_ = std::move(callback); @@ -228,14 +220,11 @@ DialogModelCombobox::DialogModelCombobox( base::PassKey<DialogModel> pass_key, DialogModel* model, + ElementIdentifier id, std::u16string label, std::unique_ptr<ui::ComboboxModel> combobox_model, const DialogModelCombobox::Params& params) - : DialogModelField(pass_key, - model, - kCombobox, - params.id_, - params.accelerators_), + : DialogModelField(pass_key, model, kCombobox, id, params.accelerators_), label_(std::move(label)), accessible_name_(params.accessible_name_), selected_index_(combobox_model->GetDefaultIndex()), @@ -282,14 +271,6 @@ DialogModelTextfield::Params::Params() = default; DialogModelTextfield::Params::~Params() = default; -DialogModelTextfield::Params& DialogModelTextfield::Params::SetId( - ElementIdentifier id) { - DCHECK(!id_); - DCHECK(id); - id_ = id; - return *this; -} - DialogModelTextfield::Params& DialogModelTextfield::Params::AddAccelerator( Accelerator accelerator) { accelerators_.insert(std::move(accelerator)); @@ -299,14 +280,11 @@ DialogModelTextfield::DialogModelTextfield( base::PassKey<DialogModel> pass_key, DialogModel* model, + ElementIdentifier id, std::u16string label, std::u16string text, const ui::DialogModelTextfield::Params& params) - : DialogModelField(pass_key, - model, - kTextfield, - params.id_, - params.accelerators_), + : DialogModelField(pass_key, model, kTextfield, id, params.accelerators_), label_(label), accessible_name_(params.accessible_name_), text_(std::move(text)) {}
diff --git a/ui/base/models/dialog_model_field.h b/ui/base/models/dialog_model_field.h index 2de0a8f..0516de5 100644 --- a/ui/base/models/dialog_model_field.h +++ b/ui/base/models/dialog_model_field.h
@@ -298,8 +298,6 @@ Params& operator=(const Params&) = delete; ~Params(); - Params& SetId(ElementIdentifier id); - Params& AddAccelerator(Accelerator accelerator); Params& SetAccessibleName(std::u16string accessible_name) { @@ -327,6 +325,7 @@ // fields. DialogModelCombobox(base::PassKey<DialogModel> pass_key, DialogModel* model, + ElementIdentifier id, std::u16string label, std::unique_ptr<ui::ComboboxModel> combobox_model, const Params& params); @@ -415,8 +414,6 @@ Params& operator=(const Params&) = delete; ~Params(); - Params& SetId(ElementIdentifier id); - Params& AddAccelerator(Accelerator accelerator); Params& SetAccessibleName(std::u16string accessible_name) { @@ -436,6 +433,7 @@ // fields. DialogModelTextfield(base::PassKey<DialogModel> pass_key, DialogModel* model, + ElementIdentifier id, std::u16string label, std::u16string text, const Params& params);
diff --git a/ui/compositor/layer.cc b/ui/compositor/layer.cc index 173b922..7b5519c 100644 --- a/ui/compositor/layer.cc +++ b/ui/compositor/layer.cc
@@ -262,9 +262,10 @@ clone->SetAlphaShape(std::make_unique<ShapeRects>(*alpha_shape_)); // cc::Layer state. + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. if (surface_layer_) { clone->SetShowSurface(surface_layer_->surface_id(), frame_size_in_dip_, - surface_layer_->background_color(), + surface_layer_->background_color().toSkColor(), surface_layer_->deadline_in_frames() ? cc::DeadlinePolicy::UseSpecifiedDeadline( *surface_layer_->deadline_in_frames()) @@ -1003,8 +1004,11 @@ CreateSurfaceLayerIfNecessary(); surface_layer_->SetSurfaceId(surface_id, deadline_policy); - surface_layer_->SetBackgroundColor(default_background_color); - surface_layer_->SetSafeOpaqueBackgroundColor(default_background_color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + surface_layer_->SetBackgroundColor( + SkColor4f::FromColor(default_background_color)); + surface_layer_->SetSafeOpaqueBackgroundColor( + SkColor4f::FromColor(default_background_color)); surface_layer_->SetStretchContentToFillBounds(stretch_content_to_fill_bounds); frame_size_in_dip_ = frame_size_in_dip; @@ -1042,8 +1046,8 @@ surface_layer_->SetSurfaceId(surface_id, cc::DeadlinePolicy::UseInfiniteDeadline()); - surface_layer_->SetBackgroundColor(SK_ColorBLACK); - surface_layer_->SetSafeOpaqueBackgroundColor(SK_ColorBLACK); + surface_layer_->SetBackgroundColor(SkColors::kBlack); + surface_layer_->SetSafeOpaqueBackgroundColor(SkColors::kBlack); surface_layer_->SetStretchContentToFillBounds(true); surface_layer_->SetIsReflection(true); @@ -1128,11 +1132,13 @@ if (animator_ && animator_->IsAnimatingProperty( LayerAnimationElement::COLOR)) return animator_->GetTargetColor(); - return cc_layer_->background_color(); + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. + return cc_layer_->background_color().toSkColor(); } SkColor Layer::background_color() const { - return cc_layer_->background_color(); + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. + return cc_layer_->background_color().toSkColor(); } bool Layer::SchedulePaint(const gfx::Rect& invalid_rect) { @@ -1512,8 +1518,9 @@ void Layer::SetColorFromAnimation(SkColor color, PropertyChangeReason reason) { DCHECK_EQ(type_, LAYER_SOLID_COLOR); - cc_layer_->SetBackgroundColor(color); - cc_layer_->SetSafeOpaqueBackgroundColor(color); + // TODO(crbug/1308932): Remove FromColor and make all SkColor4f. + cc_layer_->SetBackgroundColor(SkColor4f::FromColor(color)); + cc_layer_->SetSafeOpaqueBackgroundColor(SkColor4f::FromColor(color)); SetFillsBoundsOpaquelyWithReason(SkColorGetA(color) == 0xFF, reason); } @@ -1577,8 +1584,10 @@ SkColor Layer::GetColorForAnimation() const { // The NULL check is here since this is invoked regardless of whether we have // been configured as LAYER_SOLID_COLOR. - return solid_color_layer_.get() ? - solid_color_layer_->background_color() : SK_ColorBLACK; + // TODO(crbug/1308932): Remove toSkColor and make all SkColor4f. + return solid_color_layer_.get() + ? solid_color_layer_->background_color().toSkColor() + : SK_ColorBLACK; } gfx::Rect Layer::GetClipRectForAnimation() const { @@ -1643,7 +1652,7 @@ } cc_layer_->SetTransformOrigin(gfx::Point3F()); cc_layer_->SetContentsOpaque(true); - cc_layer_->SetSafeOpaqueBackgroundColor(SK_ColorWHITE); + cc_layer_->SetSafeOpaqueBackgroundColor(SkColors::kWhite); cc_layer_->SetIsDrawable(type_ != LAYER_NOT_DRAWN); cc_layer_->SetHitTestable(IsHitTestableForCC()); cc_layer_->SetElementId(cc::ElementId(cc_layer_->id()));
diff --git a/ui/events/blink/blink_event_util.h b/ui/events/blink/blink_event_util.h index e0f3d38..ed105fc 100644 --- a/ui/events/blink/blink_event_util.h +++ b/ui/events/blink/blink_event_util.h
@@ -29,6 +29,10 @@ struct GestureEventDetails; class MotionEvent; +// The scroll percentage per mousewheel tick. Used to determine scroll delta +// if percent based scrolling is enabled. +const float kScrollPercentPerLineOrChar = 0.05f; + blink::WebTouchEvent CreateWebTouchEventFromMotionEvent( const MotionEvent& event, bool may_cause_scrolling,
diff --git a/ui/events/blink/web_input_event.cc b/ui/events/blink/web_input_event.cc index 7143fb6..1b7d11a6 100644 --- a/ui/events/blink/web_input_event.cc +++ b/ui/events/blink/web_input_event.cc
@@ -22,10 +22,6 @@ namespace { -// The scroll percentage per mousewheel tick. Used to determine scroll delta -// if percent based scrolling is enabled. -const float kScrollPercentPerLineOrChar = 0.05; - gfx::PointF GetScreenLocationFromEvent(const LocatedEvent& event) { return event.target() ? event.target()->GetScreenLocationF(event) : event.root_location_f();
diff --git a/ui/events/blink/web_input_event_builders_win.cc b/ui/events/blink/web_input_event_builders_win.cc index fdaef04..6d8d63a7 100644 --- a/ui/events/blink/web_input_event_builders_win.cc +++ b/ui/events/blink/web_input_event_builders_win.cc
@@ -21,7 +21,6 @@ static const unsigned long kDefaultScrollLinesPerWheelDelta = 3; static const unsigned long kDefaultScrollCharsPerWheelDelta = 1; -static const unsigned long kScrollPercentPerLineOrChar = 5; // WebMouseEvent -------------------------------------------------------------- @@ -313,7 +312,7 @@ // the percentage amount (out of 1, i.e. 1 == 100%) the targeted scroller // should scroll. This percentage will be resolved against the size of // the scroller in the renderer process. - scroll_delta *= kScrollPercentPerLineOrChar / 100.f; + scroll_delta *= kScrollPercentPerLineOrChar; result.delta_units = ui::ScrollGranularity::kScrollByPercentage; } else { // Convert wheel delta amount to a number of pixels to scroll.
diff --git a/ui/events/keycodes/DEPS b/ui/events/keycodes/DEPS index d974f6c..4feb273f 100644 --- a/ui/events/keycodes/DEPS +++ b/ui/events/keycodes/DEPS
@@ -7,8 +7,19 @@ "-third_party", "-ui", - "+third_party/abseil-cpp/absl", "+ui/base/buildflags.h", # Doesn't bring in all of UI. "+ui/gfx/x", "+ui/events", + + # Abseil features must be allowlisted explicitly for now. See + # //styleguide/c++/c++11.html. Allowed features' headers will be listed + # explicitly here. + # Please keep this section in sync with //DEPS. + '-absl', + '-third_party/abseil-cpp', + '+third_party/abseil-cpp/absl/base/attributes.h', + "+third_party/abseil-cpp/absl/numeric/int128.h", + '+third_party/abseil-cpp/absl/types/optional.h', + '+third_party/abseil-cpp/absl/types/variant.h', + '+third_party/abseil-cpp/absl/utility/utility.h', ]
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.cc b/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.cc index 7971290..4068429 100644 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.cc +++ b/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.cc
@@ -503,11 +503,11 @@ // Parse a boolean value keyword (e.g., on/off, true/false). int ParseBooleanKeyword(const std::string& value) { for (size_t i = 0; i < std::size(kTrue); ++i) { - if (base::LowerCaseEqualsASCII(value, kTrue[i])) + if (base::EqualsCaseInsensitiveASCII(value, kTrue[i])) return 1; } for (size_t i = 0; i < std::size(kFalse); ++i) { - if (base::LowerCaseEqualsASCII(value, kFalse[i])) + if (base::EqualsCaseInsensitiveASCII(value, kFalse[i])) return -1; } return 0;
diff --git a/ui/latency/latency_tracker.cc b/ui/latency/latency_tracker.cc index ef6fed7..c28238eb 100644 --- a/ui/latency/latency_tracker.cc +++ b/ui/latency/latency_tracker.cc
@@ -306,11 +306,7 @@ UMA_HISTOGRAM_INPUT_LATENCY_5_SECONDS_MAX_MICROSECONDS( metric_name, original_timestamp, gpu_swap_begin_timestamp); - // Report whether the top-controls visible height changed from this scroll - // event. - UMA_HISTOGRAM_BOOLEAN("Event.Latency.ScrollBegin.TopControlsMoved", - top_controls_visible_height_changed); - // Also report the latency metric separately for the scrolls that caused the + // Report the latency metric separately for the scrolls that caused the // top-controls to scroll and the ones that didn't. if (top_controls_visible_height_changed) base::StrAppend(&metric_name, {".TopControlsMoved"}); @@ -346,11 +342,6 @@ UMA_HISTOGRAM_INPUT_LATENCY_5_SECONDS_MAX_MICROSECONDS( metric_name, original_timestamp, gpu_swap_begin_timestamp); - // Report whether the top-controls visible height changed from this scroll - // event. - UMA_HISTOGRAM_BOOLEAN("Event.Latency.ScrollUpdate.TopControlsMoved", - top_controls_visible_height_changed); - // Also report the latency metric separately for the scrolls that caused the // top-controls to scroll and the ones that didn't. if (top_controls_visible_height_changed)
diff --git a/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc b/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc index 6b4aafb9..3384dbf 100644 --- a/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc +++ b/ui/ozone/platform/drm/gpu/gbm_surface_factory.cc
@@ -199,7 +199,7 @@ // Skip the virtual graphics memory manager device. ScopedDrmVersionPtr version(drmGetVersion(dev_path_file.GetPlatformFile())); - if (!version || base::LowerCaseEqualsASCII(version->name, "vgem")) { + if (!version || base::EqualsCaseInsensitiveASCII(version->name, "vgem")) { continue; }
diff --git a/ui/ozone/platform/wayland/BUILD.gn b/ui/ozone/platform/wayland/BUILD.gn index b0b9ad00..b5dbeea 100644 --- a/ui/ozone/platform/wayland/BUILD.gn +++ b/ui/ozone/platform/wayland/BUILD.gn
@@ -407,6 +407,8 @@ "test/mock_zaura_shell.h", "test/mock_zcr_extended_text_input.cc", "test/mock_zcr_extended_text_input.h", + "test/mock_zcr_touch_stylus.cc", + "test/mock_zcr_touch_stylus.h", "test/mock_zwp_linux_dmabuf.cc", "test/mock_zwp_linux_dmabuf.h", "test/mock_zwp_text_input.cc", @@ -469,6 +471,8 @@ "test/test_wp_pointer_gestures.h", "test/test_xdg_popup.cc", "test/test_xdg_popup.h", + "test/test_zcr_stylus.cc", + "test/test_zcr_stylus.h", "test/test_zcr_text_input_extension.cc", "test/test_zcr_text_input_extension.h", "test/test_zwp_linux_buffer_params.cc", @@ -501,6 +505,7 @@ "//third_party/wayland-protocols:pointer_gestures_protocol", "//third_party/wayland-protocols:presentation_time_protocol", "//third_party/wayland-protocols:primary_selection_protocol", + "//third_party/wayland-protocols:stylus_protocol", "//third_party/wayland-protocols:text_input_extension_protocol", "//third_party/wayland-protocols:text_input_protocol", "//third_party/wayland-protocols:viewporter_protocol",
diff --git a/ui/ozone/platform/wayland/host/wayland_event_source.cc b/ui/ozone/platform/wayland/host/wayland_event_source.cc index 1deef5fe..8178bd55 100644 --- a/ui/ozone/platform/wayland/host/wayland_event_source.cc +++ b/ui/ozone/platform/wayland/host/wayland_event_source.cc
@@ -346,7 +346,7 @@ return; } - PointerDetails details(EventPointerType::kTouch, id); + PointerDetails details(PointerDetailsForDispatching(id)); TouchEvent event(ET_TOUCH_PRESSED, location, location, timestamp, details, keyboard_modifiers_); DispatchEvent(&event); @@ -384,6 +384,11 @@ HandleTouchFocusChange(touch_point->window, false, id); touch_points_.erase(it); + + // Clean up stylus touch tracking, if any. + const auto stylus_it = last_touch_stylus_tool_.find(id); + if (stylus_it != last_touch_stylus_tool_.end()) + last_touch_stylus_tool_.erase(stylus_it); } void WaylandEventSource::OnTouchMotionEvent(const gfx::PointF& location, @@ -396,7 +401,7 @@ return; } it->second->last_known_location = location; - PointerDetails details(EventPointerType::kTouch, id); + PointerDetails details(PointerDetailsForDispatching(id)); TouchEvent event(ET_TOUCH_MOVED, location, location, timestamp, details, keyboard_modifiers_); DispatchEvent(&event); @@ -420,6 +425,7 @@ HandleTouchFocusChange(touch_point.second->window, false); } touch_points_.clear(); + last_touch_stylus_tool_.clear(); } void WaylandEventSource::OnTouchFocusChanged(WaylandWindow* window) { @@ -433,6 +439,12 @@ return pointer_ids; } +void WaylandEventSource::OnTouchStylusToolChanged( + PointerId pointer_id, + EventPointerType pointer_type) { + last_touch_stylus_tool_[pointer_id] = pointer_type; +} + const WaylandWindow* WaylandEventSource::GetTouchTarget(PointerId id) const { const auto it = touch_points_.find(id); return it == touch_points_.end() ? nullptr : it->second->window; @@ -580,4 +592,15 @@ return PointerDetails(*last_pointer_stylus_tool_); } +PointerDetails WaylandEventSource::PointerDetailsForDispatching( + PointerId pointer_id) const { + const auto it = last_touch_stylus_tool_.find(pointer_id); + if (it == last_touch_stylus_tool_.end() || !it->second || + it->second == EventPointerType::kTouch) { + return PointerDetails(EventPointerType::kTouch, pointer_id); + } + + return PointerDetails(it->second.value(), pointer_id); +} + } // namespace ui
diff --git a/ui/ozone/platform/wayland/host/wayland_event_source.h b/ui/ozone/platform/wayland/host/wayland_event_source.h index 6fa56f0..bca4682 100644 --- a/ui/ozone/platform/wayland/host/wayland_event_source.h +++ b/ui/ozone/platform/wayland/host/wayland_event_source.h
@@ -127,6 +127,8 @@ void OnTouchFocusChanged(WaylandWindow* window) override; std::vector<PointerId> GetActiveTouchPointIds() override; const WaylandWindow* GetTouchTarget(PointerId id) const override; + void OnTouchStylusToolChanged(PointerId pointer_id, + EventPointerType pointer_type) override; // WaylandZwpPointerGesture::Delegate: void OnPinchEvent(EventType event_type, @@ -175,8 +177,12 @@ bool SurfaceSubmissionInPixelCoordinates() const; + // For pointer events. PointerDetails PointerDetailsForDispatching() const; + // For touch events. + PointerDetails PointerDetailsForDispatching(PointerId pointer_id) const; + WaylandWindowManager* const window_manager_; WaylandConnection* const connection_; @@ -202,9 +208,14 @@ // Time of the last pointer frame event. base::TimeTicks last_pointer_frame_time_; - // Last known pointer stylus type (eg mouse, pointer, eraser, touch). + // Last known pointer stylus type (eg mouse, pen, eraser or touch). absl::optional<EventPointerType> last_pointer_stylus_tool_; + // Last known touch stylus type (eg touch, pen or eraser). + // absl::optional<PointerId, EventPointerType> last_touch_stylus_tool_; + base::flat_map<PointerId, absl::optional<EventPointerType>> + last_touch_stylus_tool_; + // Recent pointer frames to compute fling scroll. // Front is newer, and back is older. std::deque<PointerFrame> recent_pointer_frames_;
diff --git a/ui/ozone/platform/wayland/host/wayland_touch.cc b/ui/ozone/platform/wayland/host/wayland_touch.cc index ca3e9837..36cf00d7 100644 --- a/ui/ozone/platform/wayland/host/wayland_touch.cc +++ b/ui/ozone/platform/wayland/host/wayland_touch.cc
@@ -115,8 +115,22 @@ void WaylandTouch::Tool(void* data, struct zcr_touch_stylus_v2* obj, uint32_t id, - uint32_t type) { - NOTIMPLEMENTED_LOG_ONCE(); + uint32_t stylus_type) { + auto* pointer = static_cast<WaylandTouch*>(data); + + ui::EventPointerType pointer_type = ui::EventPointerType::kTouch; + switch (stylus_type) { + case ZCR_TOUCH_STYLUS_V2_TOOL_TYPE_PEN: + pointer_type = EventPointerType::kPen; + break; + case ZCR_TOUCH_STYLUS_V2_TOOL_TYPE_ERASER: + pointer_type = ui::EventPointerType::kEraser; + break; + case ZCR_POINTER_STYLUS_V2_TOOL_TYPE_TOUCH: + break; + } + + pointer->delegate_->OnTouchStylusToolChanged(id, pointer_type); } // static
diff --git a/ui/ozone/platform/wayland/host/wayland_touch.h b/ui/ozone/platform/wayland/host/wayland_touch.h index 3b36e4ab..b988a769 100644 --- a/ui/ozone/platform/wayland/host/wayland_touch.h +++ b/ui/ozone/platform/wayland/host/wayland_touch.h
@@ -96,6 +96,8 @@ virtual void OnTouchFocusChanged(WaylandWindow* window) = 0; virtual std::vector<PointerId> GetActiveTouchPointIds() = 0; virtual const WaylandWindow* GetTouchTarget(PointerId id) const = 0; + virtual void OnTouchStylusToolChanged(PointerId pointer_id, + EventPointerType pointer_type) = 0; }; } // namespace ui
diff --git a/ui/ozone/platform/wayland/host/wayland_touch_unittest.cc b/ui/ozone/platform/wayland/host/wayland_touch_unittest.cc index 9d0664b..7007f30 100644 --- a/ui/ozone/platform/wayland/host/wayland_touch_unittest.cc +++ b/ui/ozone/platform/wayland/host/wayland_touch_unittest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include <linux/input.h> +#include <stylus-unstable-v2-server-protocol.h> #include <wayland-server.h> #include <cstdint> #include <memory> @@ -14,6 +15,7 @@ #include "ui/events/event_constants.h" #include "ui/ozone/platform/wayland/host/wayland_window.h" #include "ui/ozone/platform/wayland/test/mock_surface.h" +#include "ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.h" #include "ui/ozone/platform/wayland/test/test_keyboard.h" #include "ui/ozone/platform/wayland/test/test_touch.h" #include "ui/ozone/platform/wayland/test/test_wayland_server_thread.h" @@ -58,12 +60,15 @@ } protected: - void CheckEventType(ui::EventType event_type, ui::Event* event) { + void CheckEventType( + ui::EventType event_type, + ui::Event* event, + ui::EventPointerType pointer_type = ui::EventPointerType::kTouch) { ASSERT_TRUE(event); ASSERT_TRUE(event->IsTouchEvent()); - auto* key_event = event->AsTouchEvent(); - EXPECT_EQ(event_type, key_event->type()); + auto* touch_event = event->AsTouchEvent(); + EXPECT_EQ(event_type, touch_event->type()); } wl::TestTouch* touch_; @@ -91,6 +96,33 @@ CheckEventType(ui::ET_TOUCH_RELEASED, event.get()); } +// Tests that touch events with stylus pen work. +TEST_P(WaylandTouchTest, TouchPressAndMotionWithStylus) { + std::unique_ptr<Event> event; + EXPECT_CALL(delegate_, DispatchEvent(_)).WillRepeatedly(CloneEvent(&event)); + + zcr_touch_stylus_v2_send_tool(touch_->touch_stylus()->resource(), 0 /* id */, + ZCR_TOUCH_STYLUS_V2_TOOL_TYPE_PEN); + Sync(); + + wl_touch_send_down(touch_->resource(), 1, 0, surface_->resource(), 0 /* id */, + wl_fixed_from_int(50), wl_fixed_from_int(100)); + + Sync(); + CheckEventType(ui::ET_TOUCH_PRESSED, event.get(), ui::EventPointerType::kPen); + + wl_touch_send_motion(touch_->resource(), 500, 0 /* id */, + wl_fixed_from_int(100), wl_fixed_from_int(100)); + + Sync(); + CheckEventType(ui::ET_TOUCH_MOVED, event.get(), ui::EventPointerType::kPen); + + wl_touch_send_up(touch_->resource(), 1, 1000, 0 /* id */); + + Sync(); + CheckEventType(ui::ET_TOUCH_RELEASED, event.get()); +} + // Tests that touch focus is correctly set and released. TEST_P(WaylandTouchTest, CheckTouchFocus) { uint32_t serial = 0;
diff --git a/ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.cc b/ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.cc new file mode 100644 index 0000000..e096694 --- /dev/null +++ b/ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.cc
@@ -0,0 +1,18 @@ +// Copyright 2022 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 "ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.h" + +namespace wl { + +const struct zcr_touch_stylus_v2_interface kMockZcrTouchStylusImpl = { + &DestroyResource, // destroy +}; + +MockZcrTouchStylus::MockZcrTouchStylus(wl_resource* resource) + : ServerObject(resource) {} + +MockZcrTouchStylus::~MockZcrTouchStylus() = default; + +} // namespace wl
diff --git a/ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.h b/ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.h new file mode 100644 index 0000000..458ffa8 --- /dev/null +++ b/ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.h
@@ -0,0 +1,28 @@ +// Copyright 2022 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 UI_OZONE_PLATFORM_WAYLAND_TEST_MOCK_ZCR_TOUCH_STYLUS_H_ +#define UI_OZONE_PLATFORM_WAYLAND_TEST_MOCK_ZCR_TOUCH_STYLUS_H_ + +#include <stylus-unstable-v2-server-protocol.h> + +#include "ui/ozone/platform/wayland/test/server_object.h" + +namespace wl { + +extern const struct zcr_touch_stylus_v2_interface kMockZcrTouchStylusImpl; + +class MockZcrTouchStylus : public ServerObject { + public: + explicit MockZcrTouchStylus(wl_resource* resource); + + MockZcrTouchStylus(const MockZcrTouchStylus&) = delete; + MockZcrTouchStylus& operator=(const MockZcrTouchStylus&) = delete; + + ~MockZcrTouchStylus() override; +}; + +} // namespace wl + +#endif // UI_OZONE_PLATFORM_WAYLAND_TEST_MOCK_ZCR_TOUCH_STYLUS_H_
diff --git a/ui/ozone/platform/wayland/test/test_touch.h b/ui/ozone/platform/wayland/test/test_touch.h index dc202f4..7da0520 100644 --- a/ui/ozone/platform/wayland/test/test_touch.h +++ b/ui/ozone/platform/wayland/test/test_touch.h
@@ -15,6 +15,8 @@ extern const struct wl_pointer_interface kTestTouchImpl; +class MockZcrTouchStylus; + class TestTouch : public ServerObject { public: explicit TestTouch(wl_resource* resource); @@ -23,6 +25,14 @@ TestTouch& operator=(const TestTouch&) = delete; ~TestTouch() override; + + void set_touch_stylus(MockZcrTouchStylus* touch_stylus) { + touch_stylus_ = touch_stylus; + } + MockZcrTouchStylus* touch_stylus() const { return touch_stylus_; } + + private: + MockZcrTouchStylus* touch_stylus_ = nullptr; }; } // namespace wl
diff --git a/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc b/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc index a8f78c1..00860dd7 100644 --- a/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc +++ b/ui/ozone/platform/wayland/test/test_wayland_server_thread.cc
@@ -93,6 +93,8 @@ if (!xdg_shell_.Initialize(display_.get())) return false; } + if (!zcr_stylus_.Initialize(display_.get())) + return false; if (!zcr_text_input_extension_v1_.Initialize(display_.get())) return false; if (!zwp_text_input_manager_v1_.Initialize(display_.get()))
diff --git a/ui/ozone/platform/wayland/test/test_wayland_server_thread.h b/ui/ozone/platform/wayland/test/test_wayland_server_thread.h index c14d2c03..b08b191 100644 --- a/ui/ozone/platform/wayland/test/test_wayland_server_thread.h +++ b/ui/ozone/platform/wayland/test/test_wayland_server_thread.h
@@ -28,6 +28,7 @@ #include "ui/ozone/platform/wayland/test/test_surface_augmenter.h" #include "ui/ozone/platform/wayland/test/test_viewporter.h" #include "ui/ozone/platform/wayland/test/test_wp_pointer_gestures.h" +#include "ui/ozone/platform/wayland/test/test_zcr_stylus.h" #include "ui/ozone/platform/wayland/test/test_zcr_text_input_extension.h" #include "ui/ozone/platform/wayland/test/test_zwp_linux_explicit_synchronization.h" #include "ui/ozone/platform/wayland/test/test_zwp_text_input_manager.h" @@ -174,6 +175,7 @@ TestSeat seat_; MockXdgShell xdg_shell_; MockZxdgShellV6 zxdg_shell_v6_; + TestZcrStylus zcr_stylus_; TestZcrTextInputExtensionV1 zcr_text_input_extension_v1_; TestZwpTextInputManagerV1 zwp_text_input_manager_v1_; TestZwpLinuxExplicitSynchronizationV1 zwp_linux_explicit_synchronization_v1_;
diff --git a/ui/ozone/platform/wayland/test/test_zcr_stylus.cc b/ui/ozone/platform/wayland/test/test_zcr_stylus.cc new file mode 100644 index 0000000..806d708 --- /dev/null +++ b/ui/ozone/platform/wayland/test/test_zcr_stylus.cc
@@ -0,0 +1,50 @@ +// Copyright 2022 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 "ui/ozone/platform/wayland/test/test_zcr_stylus.h" + +#include "base/notreached.h" +#include "ui/ozone/platform/wayland/test/mock_zcr_touch_stylus.h" +#include "ui/ozone/platform/wayland/test/server_object.h" +#include "ui/ozone/platform/wayland/test/test_touch.h" + +namespace wl { + +namespace { + +constexpr uint32_t kZcrStylusVersion = 2; + +void GetTouchStylus(wl_client* client, + wl_resource* resource, + uint32_t id, + wl_resource* touch_resource) { + wl_resource* touch_stylus_resource = + CreateResourceWithImpl<MockZcrTouchStylus>( + client, &zcr_touch_stylus_v2_interface, + wl_resource_get_version(resource), &kMockZcrTouchStylusImpl, id); + GetUserDataAs<TestTouch>(touch_resource) + ->set_touch_stylus( + GetUserDataAs<MockZcrTouchStylus>(touch_stylus_resource)); +} + +void GetPointerStylus(wl_client* client, + wl_resource* resource, + uint32_t id, + wl_resource* touch_resource) { + NOTIMPLEMENTED(); +} + +const struct zcr_stylus_v2_interface kTestZcrStylusImpl = {&GetTouchStylus, + &GetPointerStylus}; + +} // namespace + +TestZcrStylus::TestZcrStylus() + : GlobalObject(&zcr_stylus_v2_interface, + &kTestZcrStylusImpl, + kZcrStylusVersion) {} + +TestZcrStylus::~TestZcrStylus() = default; + +} // namespace wl
diff --git a/ui/ozone/platform/wayland/test/test_zcr_stylus.h b/ui/ozone/platform/wayland/test/test_zcr_stylus.h new file mode 100644 index 0000000..1f89122 --- /dev/null +++ b/ui/ozone/platform/wayland/test/test_zcr_stylus.h
@@ -0,0 +1,26 @@ +// Copyright 2022 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 UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_ZCR_STYLUS_H_ +#define UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_ZCR_STYLUS_H_ + +#include <stylus-unstable-v2-server-protocol.h> + +#include "ui/ozone/platform/wayland/test/global_object.h" + +namespace wl { + +class TestZcrStylus : public GlobalObject { + public: + TestZcrStylus(); + + TestZcrStylus(const TestZcrStylus&) = delete; + TestZcrStylus& operator=(const TestZcrStylus&) = delete; + + ~TestZcrStylus() override; +}; + +} // namespace wl + +#endif // UI_OZONE_PLATFORM_WAYLAND_TEST_TEST_ZCR_STYLUS_H_
diff --git a/ui/views/bubble/bubble_dialog_delegate_view.h b/ui/views/bubble/bubble_dialog_delegate_view.h index b3884ad..aa2cf0f7 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view.h +++ b/ui/views/bubble/bubble_dialog_delegate_view.h
@@ -293,15 +293,6 @@ // anchor, while retaining the other anchor view logic. virtual gfx::Rect GetBubbleBounds(); - // Update the button highlight, which may be the anchor view or an explicit - // view set in |highlighted_button_tracker_|. This can be overridden to - // provide different highlight effects. - // - // TODO(ellyjones): Remove this; it is only used in one place, to disable - // highlighting the button, but this is trivial to achieve using other - // methods. - virtual void UpdateHighlightedButton(bool highlight); - // Override this to perform initialization after the Widget is created but // before it is shown. // TODO(pbos): Turn this into a (Once?)Callback and add set_init(cb). @@ -376,6 +367,8 @@ // after losing it. void NotifyAnchoredBubbleIsPrimary(); + void UpdateHighlightedButton(bool highlight); + void SetAnchoredDialogKey(); gfx::Insets title_margins_;
diff --git a/ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_list.ts b/ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_list.ts index 70f6550..6044a0b 100644 --- a/ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_list.ts +++ b/ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_list.ts
@@ -113,6 +113,8 @@ this.previousAnchor_ = detail.anchor; this.showProvisioningDetailsDialog_ = true; event.stopPropagation(); + CertificateProvisioningBrowserProxyImpl.getInstance() + .refreshCertificateProvisioningProcesses(); }); }
diff --git a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.js b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.js index 67768a25..b212670c 100644 --- a/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.js +++ b/ui/webui/resources/cr_components/chromeos/bluetooth/bluetooth_pairing_ui.js
@@ -242,8 +242,6 @@ ready() { super.ready(); - getBluetoothConfig().observeSystemProperties( - this.systemPropertiesObserverReceiver_.$.bindNewPipeAndPassRemote()); // If there's a specific device to pair with, immediately go to the spinner // page. @@ -252,12 +250,28 @@ } } + connectedCallback() { + super.connectedCallback(); + + getBluetoothConfig().observeSystemProperties( + this.systemPropertiesObserverReceiver_.$.bindNewPipeAndPassRemote()); + } + disconnectedCallback() { super.disconnectedCallback(); + if (this.systemPropertiesObserverReceiver_) { + this.systemPropertiesObserverReceiver_.$.close(); + } if (this.bluetoothDiscoveryDelegateReceiver_) { this.bluetoothDiscoveryDelegateReceiver_.$.close(); } + if (this.pairingDelegateReceiver_) { + this.pairingDelegateReceiver_.$.close(); + } + if (this.keyEnteredReceiver_) { + this.keyEnteredReceiver_.close(); + } } /** @override */
diff --git a/weblayer/browser/permissions/geolocation_permission_context_delegate.cc b/weblayer/browser/permissions/geolocation_permission_context_delegate.cc index e77fbe0..1cc75b4 100644 --- a/weblayer/browser/permissions/geolocation_permission_context_delegate.cc +++ b/weblayer/browser/permissions/geolocation_permission_context_delegate.cc
@@ -15,7 +15,6 @@ namespace weblayer { bool GeolocationPermissionContextDelegate::DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture,
diff --git a/weblayer/browser/permissions/geolocation_permission_context_delegate.h b/weblayer/browser/permissions/geolocation_permission_context_delegate.h index afb6185..0f236b09 100644 --- a/weblayer/browser/permissions/geolocation_permission_context_delegate.h +++ b/weblayer/browser/permissions/geolocation_permission_context_delegate.h
@@ -22,7 +22,6 @@ // GeolocationPermissionContext::Delegate: bool DecidePermission( - content::WebContents* web_contents, const permissions::PermissionRequestID& id, const GURL& requesting_origin, bool user_gesture,